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

Ship v0.2.9: the Case Sheet, multi-point proofs, and the audit pass (#60)

OsintMeThatfb8f7747a622
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 740497d..1abfc7f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -30,47 +30,81 @@ jobs:
# Windows exe was a guess; this is what makes "works everywhere" checkable.
# Filesystem behaviour is where they actually differ — engine/scrapers.py
# swaps directories, and Windows won't delete an open file.
+ #
+ # `tests` is what each box runs. Everywhere but Windows that is the whole
+ # suite in one job, because -n auto finishes it in about three minutes.
+ # Windows pays roughly eight times as much per test — every one of these
+ # builds a case, and a case is a database, folders and files — so it is the
+ # one box that runs the suite in pieces, and the pieces are cut on measured
+ # cost rather than on the alphabet. Neither signal predicts Windows alone:
+ # by CPU seconds the heaviest range finished first, by test count the
+ # lightest finished last, so the weight is both.
+ #
+ # Then measured again, because the box itself is not a constant: the same
+ # range ran 11 minutes one hour and 24 the next, and `test_repository.py`
+ # alone is half of it. That range is split rather than trusted, since a
+ # slow hour on the 30-minute timeout is a red run for no reason.
+ #
+ # The ranges have to leave no gap: one stopping at test_sc* beside one
+ # starting at test_se* runs everything except the test_sd* somebody adds
+ # next year, and says nothing. `tests/test_ci_shards.py` reads them back
+ # out of this file and fails if they stop covering the directory.
include:
- name: Backend (ubuntu-latest, py3.12)
os: ubuntu-latest
python: "3.12"
- tests: all
+ tests: tests
- name: Backend (macos-latest, py3.12)
os: macos-latest
python: "3.12"
- tests: all
- # Five fresh Windows processes retain the complete suite while making
- # progress visible and keeping every shard well below the timeout.
- - name: Backend (windows-latest, py3.12, A-F)
+ tests: tests
+ - name: Backend (windows-latest, py3.12, 1/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[a-f]*.py
- - name: Backend (windows-latest, py3.12, G-L)
+ tests: tests/test_[a-d]*.py tests/test_e[a-n]*.py
+ - name: Backend (windows-latest, py3.12, 2/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[g-l]*.py
- - name: Backend (windows-latest, py3.12, M-O)
+ tests: tests/test_e[o-z]*.py tests/test_[f-i]*.py
+ - name: Backend (windows-latest, py3.12, 3/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[m-o]*.py
- - name: Backend (windows-latest, py3.12, P-R)
+ tests: tests/test_[j-o]*.py tests/test_p[a-l]*.py
+ - name: Backend (windows-latest, py3.12, 4/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[p-r]*.py
- - name: Backend (windows-latest, py3.12, S-Z)
+ tests: tests/test_p[m-z]*.py
+ - name: Backend (windows-latest, py3.12, 5/7)
os: windows-latest
python: "3.12"
- tests: tests/test_[s-z]*.py
+ tests: tests/test_[q-r]*.py tests/test_s[a-d]*.py
+ - name: Backend (windows-latest, py3.12, 6/7)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_s[e-h]*.py
+ - name: Backend (windows-latest, py3.12, 7/7)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_s[i-z]*.py tests/test_[t-z]*.py
- name: Backend (ubuntu-latest, py3.11)
os: ubuntu-latest
python: "3.11" # the floor in requires-python
- tests: all
+ tests: tests
- name: Backend (ubuntu-latest, py3.13)
os: ubuntu-latest
python: "3.13" # the ceiling we've tested against
- tests: all
+ tests: tests
steps:
- uses: actions/checkout@v7
+ # Defender reads every file as it is written, and this suite writes a whole
+ # case per test. Excluding the three directories the run works in is the
+ # difference between a Windows job that fits the timeout and one that does
+ # not. Best-effort: a runner that refuses the call is slow, not broken.
+ - name: Keep Defender out of the directories the suite writes
+ if: runner.os == 'Windows'
+ shell: pwsh
+ continue-on-error: true
+ run: Add-MpPreference -ExclusionPath $env:RUNNER_TEMP, $env:TEMP, $env:GITHUB_WORKSPACE
- uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
enable-cache: true
@@ -81,13 +115,13 @@ jobs:
# --check fails if uv.lock drifted from pyproject.toml (forgot `uv lock`).
- run: uv lock --check
- run: uv sync --frozen --extra dev
+ # -n auto spreads the work over the runner's cores. Every test builds its
+ # case under `tmp_path` (see tests/conftest.py) and nothing is scoped wider
+ # than a test, so there is nothing for two workers to collide over. bash on
+ # every OS so the Windows ranges glob the same way they do here.
- name: Run backend suite
- if: matrix.tests == 'all'
- run: uv run pytest -q --durations=20 --durations-min=1
- - name: Run Windows shard with per-test progress
- if: matrix.tests != 'all'
shell: bash
- run: uv run pytest -vv ${{ matrix.tests }} --durations=20 --durations-min=1
+ run: uv run pytest -q -n auto ${{ matrix.tests }} --durations=20 --durations-min=1
lint:
name: Lint & type-check (backend)
@@ -97,6 +131,11 @@ jobs:
# everywhere, so matrix runs would just be identical verdicts. Python
# 3.12 on purpose — mypy parses numpy's 2.x stubs, which use 3.12 syntax a
# 3.11 target chokes on. The 3.11 floor stays covered by the pytest matrix.
+ #
+ # Both read `scripts/` and `packaging/` as well as the package. The job's name
+ # says "backend" and it used to mean "src and tests": `packaging/entry.py` is the
+ # script PyInstaller analyses, so it ships inside all three binaries, and nothing
+ # checked it. mypy's own scope is in pyproject; ruff's is spelled out here.
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
@@ -105,7 +144,7 @@ jobs:
prune-cache: true
python-version: "3.12"
- run: uv sync --frozen --extra dev
- - run: uv run ruff check src tests
+ - run: uv run ruff check src tests scripts packaging
- run: uv run mypy
backend-floating:
@@ -122,7 +161,7 @@ jobs:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
- run: uv sync --upgrade --extra dev
- - run: uv run pytest -q --durations=20 --durations-min=1
+ - run: uv run pytest -q -n auto --durations=20 --durations-min=1
frontend:
name: Frontend tests + build
@@ -144,9 +183,18 @@ jobs:
- run: npm run build
browser:
- name: Browser canvas interactions
+ name: Browser canvas interactions (${{ matrix.browser }})
runs-on: ubuntu-latest
timeout-minutes: 20
+ # One job per browser rather than one job running both. The specs stay at a
+ # single Playwright worker on purpose — canvas startup times out when Leaflet
+ # and Konva compete for a runner's cores — so the only way to shorten this
+ # job is to stop making Firefox wait for Chromium. Each job also installs
+ # only the browser it runs.
+ strategy:
+ fail-fast: false
+ matrix:
+ browser: [chromium, firefox]
defaults:
run:
working-directory: frontend
@@ -158,5 +206,11 @@ jobs:
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- - run: npx playwright install --with-deps chromium firefox
- - run: npm run test:e2e
+ # The browser, not its system libraries: `--with-deps` runs apt as root, and
+ # three of the four browser jobs one afternoon died at the 20-minute timeout
+ # inside `apt-get update` with azure.archive.ubuntu.com answering nothing. The
+ # runner image already carries Chrome and Firefox, so the libraries a Playwright
+ # build links against are there. If one ever is not, the browser fails to launch
+ # and says so in a minute, which is the better failure of the two.
+ - run: npx playwright install ${{ matrix.browser }}
+ - run: npm run test:e2e -- --project=${{ matrix.browser }}
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 954b056..5ebcf0c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -180,6 +180,13 @@ jobs:
permissions:
contents: write # create the GitHub release + upload assets
id-token: write # PyPI Trusted Publishing (OIDC) — no token secret needed
+ # This is the only job holding a publishing identity, and the only one running
+ # third-party actions on a **mutable** ref: a tag can be moved and a branch moves by
+ # design, where `setup-uv` above is pinned by commit. Kept, and recorded as an accepted
+ # risk in docs/SPEC.md §9 rather than left implicit — `@release/v1` is the form PyPA
+ # documents for its own action, and pinning it by digest means tracking their releases
+ # by hand to keep Trusted Publishing working. Pin both by SHA the day that trade stops
+ # being worth it; do not change one without the other.
steps:
- uses: actions/checkout@v7
- uses: actions/download-artifact@v8
diff --git a/README.md b/README.md
index e0534a3..d7ff256 100644
--- a/README.md
+++ b/README.md
@@ -52,16 +52,17 @@ to fix a point on the map.*
| Tool | What it does |
|------|--------------|
-| **Board** | The whole case as one sortable table: typed identity fields per entity, one filter bar whose values are all taken from the case, and shared Details. |
-| **Graph** | The same case drawn. Lenses pick what a reading is about, nodes cluster, edges carry their verb, and a click opens what a node connects to without losing the picture you were reading. |
+| **Board** | The whole case as one sortable table: typed identity fields per entity, one filter bar whose values are all taken from the case, shared Details, and a ticked selection deleted as one recoverable act. |
+| **Graph** | The same case drawn. Lenses pick what a reading is about, nodes cluster, edges carry their verb, and a click opens what a node connects to without losing the picture you were reading. Graph and Timeline both export a reading as an SVG or PNG plate carrying its question, period and legend. |
| **Timeline** | The same case on a time axis. Dated statements and media stack in coloured tracks, the ruler reads in any zone or at a saved place, date quality is drawn instead of flattened, and the window can be handed to Board, Graph or the map. |
+| **Sheet** | The case's own CSVs in a plain grid: a comparison table, a worklist with its own state, or the half-facts too soft to be entities. Columns can be typed, a workbook arrives one sheet per tab, and a declared sheet promotes into entities, places and dated statements. A worklist can also be built back out of what the case holds. |
| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Public media is fetched cookie-less; a login-walled post prompts once for a browser session or an exported `cookies.txt`. Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
| **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. Nothing uploads on its own. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
-| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default, plus Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. |
+| **Satellite** | Coordinates or a place name become an imagery crop. The search bar proposes matches as you type: saved work, coordinates and a bundled city list answer offline, and the geocoder fills in the rest once you pause. Select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default, plus Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. |
| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |
-| **Geo Proof** | Start a named proof from a reusable house style, select case panels with search, compose them in a grid or free layout, annotate with colored shapes/freehand/text, and export `proof.png` plus a re-editable spec. |
+| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, annotate with colored shapes, fills, symbols, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X, Bluesky, or Mastodon: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
| **Notebook** | Tabbed Markdown notes with local media, Mermaid diagrams, linked case evidence, broken-reference markers, and PDF export of one note or a whole selection. |
@@ -72,27 +73,32 @@ extension, and cross-platform binaries with a bundled ffmpeg.
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
-## New in v0.2.8
-
-Entities, graph and timeline:
-
-- Read the whole case as a table, with one filter bar whose values and counts all
- come from the case, and file a person, an account or a statement by hand.
-- Draw the same question in the Graph: lenses, clustered nodes, verbs on the
- edges, sources folded onto the edge they stand for, and an undo for the drawing
- that never writes to the case.
-- Put dated statements and media on a Timeline, in coloured tracks, on any zone's
- clock, with daylight under the ruler at a saved place.
-- Create and edit dates on the axis itself, and measure two entries without
- pretending a coarse date is an exact one.
-- Hand one period from Timeline to Board, Graph and a session-only map layer.
- Fact time never mixes with the date something was filed.
-- Keep statement confidence and source reliability apart, with support and
- contradiction stated as their own links.
-- Date a statement through a guided editor for a year, a day, a bounded range or
- a zoned time range, with the raw syntax still accepted.
-- Existing cases upgrade to SQLite schema 17 when they open, and bundles exported
- by v0.2.7 still import.
+## New in v0.2.9
+
+A table you can work in, and a proof that can argue more than one point.
+
+- **Sheet**, a new tool: the case's own CSV files in a spreadsheet-style grid.
+ They still open in Excel, and the grid notices when they change on disk.
+- Type a column (state, list, yes/no, number, coordinates, date, image) and the
+ sheet sorts, filters and maps it properly. Excel workbooks import one tab per
+ sheet.
+- Turn a prepared sheet into entities, places and dated statements after reading
+ a row-by-row plan, or build a worklist out of what the case already holds.
+- Geocode a column of addresses, check a column of links, list every proof in the
+ case, or build one proof per row from columns of links and coordinates.
+- A proof can state several points, name them, mark the camera position, and list
+ several sources, downloading supporting files for a link the case lacks.
+- Import a published post as a proof: its pictures become panels and its text is
+ read for coordinates, with a preview to approve first.
+- Fill shapes at a chosen opacity, stamp ready-made symbols, and move or recolour
+ several at once.
+- Export a Graph or Timeline view as an SVG or PNG plate carrying the case, the
+ question, the period and a legend.
+- The map's search box suggests as you type from saved places, pasted coordinates
+ and 34,000 bundled cities, and only calls the geocoder once you stop.
+- Saved views can be renamed and sorted, Board rows delete as one undoable batch,
+ and removing a relation or an imported entity photo now asks first.
+- Existing cases open unchanged, and older bundles still import.
## Cases on disk
@@ -201,8 +207,8 @@ cd frontend && npm run dev # UI on :5173
Checks (CI runs these on every push):
```bash
-uv run ruff check src tests # lint
-uv run mypy # type-check the backend
+uv run ruff check src tests scripts packaging # lint
+uv run mypy # type-check the package, scripts and packaging
cd frontend && npm run check # svelte-check (blocks on errors)
```
@@ -263,6 +269,11 @@ Raising an upper bound is a deliberate act: bump it in `pyproject.toml`, run
"latest deps" CI job re-resolves past the lock, so upstream breakage shows up
as a red run of ours rather than a broken install for someone else.
+The map's offline city list is data, not a dependency:
+`src/azimut/engine/data/cities.tsv.gz`, about 770 KiB, trimmed from GeoNames
+(CC BY 4.0) by `python scripts/build_cities.py`. Rebuild it when it goes stale;
+nothing else reads it.
+
**yt-dlp and gallery-dl are deliberately unbounded**: they track sites that
change, so pinning them just schedules a breakage. They can also be updated
from inside the app (Settings → System → Downloaders), which is what keeps a
@@ -274,7 +285,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, and
publishes to PyPI. **Don't publish by hand.**
```bash
-git tag v0.2.8 && git push origin v0.2.8
+git tag v0.2.9 && git push origin v0.2.9
```
One-time setup: register the repo as a
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 6f324e5..8aef85c 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -76,6 +76,12 @@ presents it as this logical shape:
SQLite browse index mirrors searchable fields, plus whether that position
exists. Entities retain only what the graph needs for identity, links and
deduplication.
+- A media's origin is `source.url`, mirrored onto `attrs.source_url`, and
+ `source.type` says how it was come by: a `download` fetched that address, while
+ an `upload`, a `clipboard` paste or an adopted `manual` file carries what the
+ analyst stated for it. Only those three can be given or corrected one; what a
+ tool recorded is never written over, since a case that cannot tell a fetched
+ address from a stated one is holding neither.
## 2. Entity
@@ -124,7 +130,7 @@ to one clause — no full stop, no em-dash, under a hundred characters.
| `class` | a model the case counts with, never one particular object | `equipment-type` |
| `identifier` | a handle on a system | `account`, `email`, `phone`, `domain`, `ip`, `network` |
| `collected` | bytes gathered into the case rather than written, so one may depict a place | `media`, `capture` |
-| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `inspect-session`, `bookmark` |
+| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `sheet`, `inspect-session`, `bookmark` |
| `place` | a point, never a thing | `place` |
| `claim` | a statement about the graph, carrying its own reasoning | `claim` |
@@ -153,7 +159,7 @@ picture of the case is about it. The line that matters is between the first two
|---|---|---|---|
| `subject` | the case is about it | `person`, `organization`, `vehicle`, `vessel`, `aircraft`, `structure`, `equipment-type`, `account`, `email`, `phone`, `domain`, `ip`, `network`, `media`, `place`, `claim` | a node |
| `attestation` | a wrapper around something the case already holds | `bookmark`, `proof`, `capture` | folded into the edge that carries its provenance, drawn or not (below) |
-| `annex` | consulted rather than seen, hanging off one node | `note`, `inspect-session` | out of the case readings, drawn by **My work** |
+| `annex` | consulted rather than seen, hanging off one node | `note`, `sheet`, `inspect-session` | out of the case readings, drawn by **My work** |
| `deliverable` | what the case produced | `post` | out of the case readings, drawn by **My work** |
A bookmark stays drawn because it is not a leaf: *this account posted it, this
@@ -176,6 +182,7 @@ answer by omission (`tests/test_entities.py`).
| `post` | document | deliverable | ✅ | post-composer | `draft` (json) | yes |
| `inspect-session` | document | annex | ✅ | inspect | `spec` (json) | yes |
| `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
+| `sheet` | document | annex | ✅ | sheet | `path` (csv) | yes (CSV + sidecar) |
| `bookmark` | document | attestation | ✅ | capture extension | `url`, `fetched_at?`, `archive_url?`, `reliability?` | no (a URL) |
| `person` | actor | subject | ✅ | analyst | `aliases`, `role`, `nationality` | no |
| `organization` | actor | subject | ✅ | analyst | `echelon`, `country` | no |
@@ -512,7 +519,7 @@ a narrowing can only remove a type, never smuggle one in from elsewhere.
| `at` | claim → place | where the statement puts its subject | ✅ |
| `cites` | claim → bookmark/note/proof/media/capture/claim | what the statement rests on | ✅ |
| `contradicts` | claim → claim | the two statements cannot both hold | ✅ |
-| `mentions` | note/post/proof/bookmark → any other declared entity | the document refers to the entity | ✅ |
+| `mentions` | note/post/proof/bookmark/sheet → any other declared entity | the document refers to the entity | ✅ |
Every manual connector is validated by the API and offered only by its own picker.
`same-image-as` is machine-only. `part-of`, `in-network`, `cites` and the derivation
@@ -569,7 +576,10 @@ an edge.
**`mentions` is a pointer, not a derivation.** A document *refers to* something,
where `derived-from` says the file was built from it; both may sit on the same pair,
and deleting the target drops the mention with no tombstone. The author is a note,
-post, proof or bookmark; the target is any other declared entity, a Claim included.
+post, proof, bookmark or sheet; the target is any other declared entity, a Claim
+included. A sheet states its mentions from the cells the analyst pointed at an
+entity, restated on every save, so a row naming a subject is visible from that
+subject's side too.
It is the one verb served as its own **action** (`RelationType.action`, `"mention"`)
under its own heading (`RelationType.group`). A pointer must not borrow the weight of
@@ -577,6 +587,70 @@ a finding, so the split is the registry's and every surface obeys it: **Add rela
never turns into **mentions**, **Add mention** has its own target search, an edge is
only reworded inside its action, and a mention carries no rating (`ratable: false`).
+### Promotion, which is how a sheet reaches all of this ✅
+
+A sheet says what is being **checked**; the graph says what the case **believes**.
+Promotion is the one road between them and it runs one way: nothing reads the graph
+back into a cell. **One declaration, one press** (`engine/sheetpass.py`): a binder's line
+holds several of these at once, and only the first is one row per thing
+(`engine/sheetpromote.py`, `engine/sheetclaims.py`).
+
+| Mode | What it makes | Why it is its own answer |
+|---|---|---|
+| a **row** | one entity of the chosen type | the ordinary case |
+| a **group of rows** | one entity, one place per point | a cross-border event is two lines, one point per country; row by row that is two events |
+| a **column's words** | one entity per distinct **word** | four hundred rows hold forty pieces of equipment, and a cell may hold three |
+| a column of **addresses** | a `bookmark` per URL | a cell holds an address, so it becomes the thing that claims to be one |
+| a column of **row names** | `part-of` / `member-of` edges | an order of battle held as text, with a validation that has already decayed |
+| a column of **times** | a `claim` per row | the binder holds a *reasoning about* a time across three columns, not a time |
+
+**And the edges between the columns**, which is what no single-column road could draw: for
+each pair the analyst joined, the vocabulary is asked what it allows between their two
+types (`pair_verbs`), only the pairs with an answer are offered, and the verb is re-checked
+against the registry before anything is written. They enter `confirmed` — the analyst chose
+the reading and pressed the button — and carry the pass's one confidence where the edge is
+`ratable`. An edge is drawn only where **both** ends resolved: a row whose unit is ambiguous
+keeps its entities and loses its edges, with the reason.
+
+Six rules hold across the modes, and they are the reason it is safe to press twice.
+
+**Nothing that owns a file is born from a cell.** A `media`, a `capture`, a `proof`, a
+`post`, an `inspect-session` hold bytes; a cell holds an address. They exist only where the
+app itself fetched the file — the proof import's road (`engine/proofimport.py`), and the
+build a geolocation index presses (`engine/sheetproofs.py`), which is that same road driven
+a row at a time. The rule is not about where the request came from but about who fetched
+the bytes: the build downloads them, so it may state `derived-from`, and the pass never
+touches the network, so it may not.
+
+**A name is not an identity.** Two people share a name, so a label the case already
+holds is *offered* and never merged into on its own. The exception is the
+`identifier` family, where the value **is** the identity (§2).
+
+**The sidecar remembers what came from here.** A promoted cell points at the entity it
+made (`links`), a promoted word points at what it means (`values`), so the second
+press updates instead of minting a twin. What the cell **said** at that moment is kept
+too (`promoted`), which is what lets a row say it has moved on since — a link alone
+cannot, being the same link after the label is rewritten.
+
+**Only the columns asked for travel.** The label, the mapped fields, the point. A
+promotion that swept every column into the graph would put a worklist's private notes
+into the case's own record of a subject.
+
+**A point is a second entity unless the row *is* a place.** Writing a latitude onto a
+structure would put a field on it that nothing in the app declares, shows or edits, so
+the coordinates become a `place` joined by whichever verb the vocabulary allows
+(`sited-at` for a structure), and a type it allows none for is refused at the door.
+
+**An inferred time is a Claim, never a cell.** Ten videos carrying an offset against
+one **sync point** get an absolute time the moment that point is dated — `probable`,
+with the reasoning naming it. Writing that timestamp into a `when` cell would present a
+deduction as an observation. An estimated hour is likewise recorded one rung below an
+established one, because the binder kept two columns for exactly that difference.
+
+**Deleting a sheet keeps what it established.** Its `mentions` edges go with it and
+the entities stay: throwing the worklist away is throwing the worklist away, not the
+subjects it settled.
+
### The claim, and how sure it is ✅
A `claim` is a statement node. It points `about` at subjects, `at` at places and
@@ -682,18 +756,20 @@ subject removes it transitively.
- It is also read backwards, as geography. The Saved panel counts the proofs
hanging off each saved point through this edge, and a proof with no point of
its own is placed at the point of every capture it composes, one hop back.
- A proof does carry its own point first, though: `coordsText` (what the analyst
- typed, in any supported format) then `coords` (what the panels gave it, frozen
- at save). That is what keeps a proof on the map once its capture is deleted —
- a tombstone records the path, the sha256 and the URL, never coordinates.
+ A proof does carry its own points first, though: `spec.points[]` (what the
+ analyst typed, in any supported format, one entry per point) then `coords`
+ (what the panels gave it, frozen at save). That is what keeps a proof on the
+ map once its capture is deleted — a tombstone records the path, the sha256 and
+ the URL, never coordinates.
- **Placement reads the same edges further, and in both directions**
(`satellite.placements`, `GET /entities/{id}/placement`): a video reaches its
capture three hops away, through the proof that composed a frame of it. Only
`capture` and `proof` carry a point, and **the artifact carrying one ends the
walk**. Points deduplicate on the exact pair, never a rounded one, and the nearest
- hop wins a repeat. Bounded at four hops, 200 entities read and 15 points reported,
- each with the entity it was read off; a `capture` reports none, its point being its
- own rather than one the chain placed it at.
+ hop wins a repeat. A proof reports every point it states, so the footage behind a
+ three-point proof answers for all three. Bounded at four hops, 200 entities read
+ and 15 points reported, each with the entity it was read off; a `capture` reports
+ none, its point being its own rather than one the chain placed it at.
- `attrs.lost_sources[]` stores `{label, type, path, sha256, source_url, at}`.
Tombstones are keyed by path and never stacked.
- Every UI deletion uses the same dependency-aware service. The confirmation
@@ -752,10 +828,18 @@ It answers with resolved type lists, so a client never has to know what a family
### Where a geolocation becomes a point ✅
-Saving a proof files the point it carries as a `place` and states
-`proof --depicts--> place` (`satellite.place_for_proof`). The point is what the
-analyst typed into the composer, or what its panels froze and they left standing
-(`own_point`, §3 placement).
+Saving a proof files the points it carries as `place`s and states
+`proof --depicts--> place` for each (`satellite.place_for_proof`). They are what
+the analyst typed into the composer, or what its panels froze and they left
+standing (`spec_points`, §3 placement).
+
+**A proof states as many points as it argues.** Three impacts, a building, the
+camera that filmed it: each is a point somebody concluded on, and they are peers,
+in the order they were typed. **The first is the conclusion** — the map mark, the
+coordinate a post cites, the place a save files first — and nothing else takes
+that rank, POV included: a list that reordered itself would take a coordinate out
+of a tweet without saying so. A point may carry a name, which becomes the `place`'s
+label: "impact 2" reads better in the tree than `64.148100, -21.940100`.
**A capture files nothing.** Ten are taken while hunting one roof and each frames
a slightly different centre, so filing each would pin the search rather than the
@@ -776,13 +860,18 @@ the moment somebody commits to it. That moment is the proof.
- **A save restates the point rather than adding one**
(`satellite.restate_proof_point`), the rule the proof's panels already follow.
Reopening a proof and correcting the coordinates is an answer withdrawn: the old
- edges go, or the case reads as two geolocations. Toggling POV changes the verb
- the last save wrote, and an emptied coordinate field withdraws the point
- entirely. Only what the composer itself wrote is reconciled — an edge stated by
- hand in Details, or proposed by import enrichment, is a separate claim about the
- same file — and a point another proof still concludes on keeps its material.
- A place the proof let go of that nothing else holds is **offered for deletion,
- never swept**: it is on the map, and dropping it is the analyst's call.
+ edges go, or the case reads as two geolocations. It reconciles the **whole list**
+ by difference, so a point taken off it rends its place exactly as an emptied
+ field once did, and POV moved to another line changes both verbs. The proof's own
+ edge to a place is reconciled **whoever filed it**: it has one reading, and it is
+ the list the composer opens on, so a row another road filed is a row the analyst
+ can delete. Its **material** is the narrower question — a media reaching a place is
+ one claim among several about that file — so only the two roads that pose a proof's
+ point are restated there (`satellite.POINT_ROADS`), and an edge stated by hand in
+ Details or proposed by import enrichment stays. A point another proof still
+ concludes on keeps its material. A place the proof let go of that nothing else
+ holds is **offered for deletion, never swept**: it is on the map, and dropping it
+ is the analyst's call.
- **The material the proof composes states the same point**, over the derivation
closure — the frame, the collage, the video two hops up, the capture. Confirmed,
because **composing is the assertion**: putting a frame beside a capture and
@@ -790,18 +879,69 @@ the moment somebody commits to it. That moment is the proof.
their own act is the review everybody clicks through, which is what makes
`suggested` stop meaning anything where it is real. Being wrong costs one
removal, since a relation drops alone.
-- **`spec.pov` picks the verb for the material, because the composition cannot.**
+- **POV picks the verb for the material, because the composition cannot.**
Recorded-at and shows are independent — a rooftop shot was recorded somewhere it
never shows, a skyline is shown from kilometres away — and a match between a
frame and an imagery says only that they meet, not whether the camera or its
- subject was located. The composer asks once (**POV**), and the answer travels in
- the spec: set, the media are `located-at` the point; unset, they `depicts` it. A
+ subject was located. So it rides on the **point**, not on the proof, and **at
+ most one point carries it**: a camera stood in one place, and two would have one
+ video recorded twice. Set, the media are `located-at` that point; unset, they
+ `depicts` it. A
`capture` shows it either way, since orbital imagery was recorded nowhere on the
ground, and so does the proof, which was composed. POV is also the only reading
that reaches an audio file, which has a place it was made and nothing it shows.
+**A point another road filed for the proof is one of its points too.** A sheet
+row states a second position about a picture it already built, under its own
+provenance rather than by composing that picture twice (`sheetproofs._added_point`).
+The graph then holds a point the spec never learned, so everything that asks what
+a proof concludes on reads both (`satellite.proof_points`): the map draws it, and
+the composer **opens on it** instead of beside it. Saving is what makes the spec
+agree; until then, reopening never rewrites what the analyst typed. It arrives as a
+row like any other, which cuts both ways: a save that keeps it states it, and one
+that deletes it withdraws it. Its POV is read off **this** proof's own footage — a
+second proof's clip recorded at the same place answers for that proof and not this
+one.
+
`proof_place_auto` (Settings → General → Proofs, on by default) decides whether
-the save files it or the composer asks first. Both write the same thing.
+the save files them or the composer asks first. Both write the same thing, and the
+question is plural when the list is.
+
+**Only the conclusion is looked up at save.** Geography is a paced Nominatim call
+(`engine/geo._pace`, 1.1 s apart under one lock), so resolving three points would
+hold the save for three seconds to answer what the Locate pass answers for free.
+The rest are born unlocated, exactly as an offline save already is.
+
+**A proof is derived from what it composes and from what it rests on.** Its panels are
+the pictures laid out on the canvas; its `material` is the footage behind them, brought
+into the case from an address the analyst stated in the composer's Source list. Both are
+restated on every save (`links.sync`), so an address taken off the list drops its edge
+the way a dropped panel does, and the point follows the derivation closure rather than a
+second rule — `restate_proof_point` already poses a proof's place on everything in its
+chain.
+
+**An imported proof is filed by the same rules** (`engine/proofimport.py`). A
+post that publishes a geolocation is a proof and its material written in prose,
+so the import files every file the post points at as `media`, each picture it
+published as a `media` that proof composes, and writes their spec through the
+composer's own save route — one panel per published picture, since a post
+publishing a set published one geolocation. **Both halves are plural, and for
+opposite reasons**: a set of published pictures is one composition, while a thread
+states one point and hangs the photos and the clips it rests on off several posts.
+
+**The proof is the node they all hang off.** It composes the pictures and rests on the
+material, and both are its own `derived-from` edges — the same shape the composer writes
+by hand, and the reading somebody opening the graph is after, since the proof is the
+finding and a published picture is one file among the several it was read from. Hanging
+the material off the *picture* instead made a media node the centre of a geolocation and
+left the proof a leaf beside it. It also asked the import to say which photo of four a
+composite was laid out from, which is not something a post says.
+
+Nothing about the vocabulary changes: the proof `depicts`, the material takes the verb
+POV picks, and the point deduplicates on `COORD_KEY` like any other. The material reaches
+the point because the proof records `derived-from` it — the derivation closure is what the
+placement reads, so a source that is merely named in the text and never downloaded is a
+proof with no material rather than an edge stated about a file the case does not hold.
### Lenses ✅
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index 4fa6127..2cdd97a 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -1,105 +1,98 @@
-# Azimut v0.2.8
-
-## OSINT toolkit at a glance
-
-- **Sources:** import or download media, preserve hashes and provenance, inspect
- frames, crops, collages, panoramas and ELA, then prepare reverse-image
- searches.
-- **Maps and sky:** convert coordinates, geocode places, capture and compare
- imagery, review AOI grids, and calculate local sun and moon conditions
- offline.
-- **Evidence:** organise media, places, proofs and notes in portable cases with
- folders, relations, Markdown notebooks and PDF exports.
-- **Analysis:** read the same case as a table, as a drawing or on a time axis,
- with statements, sources and confidence kept apart.
-- **Publishing:** build annotated Geo Proofs and prepare evidence-linked Geo
- Reports for X, Bluesky or Mastodon without posting automatically.
-
-## What changed in v0.2.8
-
-The case stops being only a pile of files. Everything it holds is a typed
-entity, and three surfaces now read the same case: a table, a drawing and a
-time axis.
-
-### Board
-
-- **A row per entity, whatever its type.** A person, an account or a statement
- had no screen before.
-- **One filter bar:** a search, a **+ Filter** menu and a removable chip per
- term. Every value offered comes from the case, with its count.
-- **Search+ names the field that matched** under the row, so a vehicle found by
- its plate is not an unexplained result. Totals read against the whole case.
-- **New entity builds its form from the type registry** and flags an identifier
- the case already holds, with the existing row one click away.
-- **Board and Graph share one filter and one family of saved views.** Timeline
- keeps its own, because tracks and a clock are not something a table can draw.
-
-### Graph
-
-- **Lenses decide what the drawing is about.** Nodes cluster, and every edge
- states its direction and its verb.
-- **Expand, Collapse and Hide are explicit acts**, with `Ctrl+Z` on the drawing
- and no writes to the case.
-- **A question worked out in the Board is drawn here.** The filter travels
- rather than the rows it matched.
-- **Sources fold onto the edge they stand for**, and derivation, support, source
- and account counts sit on the node.
-
-### Timeline
-
-- **A windowed UTC axis**, read 200 entries at a time, with a density histogram
- keeping the whole chronology visible underneath.
-- **Any zone's clock**, named rather than offered as an offset, plus daylight
- under the ruler for a place the case has saved.
-- **Date quality is drawn, not flattened:** points, bars, reduced dates over the
- period their precision covers, dashed edges for approximate ones.
-- **Tracks** come from editable presets or a Search+ question, with colours,
- folds, reordering and grouping.
-- **Dates can be created and edited on the axis**, and two entries measured
- without turning a coarse date into an exact one.
-- **Views keep a reading.** Live autosaves its window, clock and tracks; a
- Snapshot freezes up to 5,000 rows and opens read-only.
-- **Undated work stays visible**, and the date a fact entered Azimut never
- masquerades as the date of the fact.
-
-### One period, four surfaces
-
-- **A window travels.** Timeline hands its period to Board, Graph and a
- session-only map layer, which state it with the way back and a Clear.
-- **Fact time never mixes with filing time.** The window narrows the page, the
- totals and a saved view alike, and leaves the "when was this filed" filters
- alone.
-
-### Statements, sources and confidence
-
-- **Relations, Mentions, Claims and lineage stay separate** in Details, under
- one validated verb registry.
-- **How sure and how reliable are two controls that never merge**, with the
- source's Admiralty grade stated beside the name it belongs to.
-- **Sources, Supports and Contradictions read from the right end**, and
- statements about a row add up before they list.
-- **A guided editor dates a statement**, from a year to a bounded or zoned
- range, choosing precision, certainty and timezone separately. The raw syntax
- is still accepted.
-
-### Storage
-
-- **Cases upgrade to SQLite schema 17 when they open**, including the derived
- time projection Case Doctor checks.
-- **A case bundle exported by v0.2.7 still imports** and lands on the current
- schema.
+# Azimut v0.2.9
+
+Azimut is a local OSINT workspace: media, geolocation work, proofs and notes in
+one portable case folder, on your own machine.
+
+This release adds a table you can work in, and lets a proof argue more than one
+point.
+
+## Sheet, a new tool
+
+A spreadsheet-style grid over the case's own CSV files.
+
+- Each sheet is a plain `.csv` in the case folder, so it also opens in Excel or
+ LibreOffice. If you edit it there while Azimut has it open, the grid tells you
+ and asks whether to reload or overwrite.
+- Sort, filter, rename, merge, pin or hide a column from its own heading, and
+ clean up a pasted column (trim, lowercase, de-duplicate, split) after seeing
+ how many cells it would change.
+- Give a column a type: state, list, yes/no, number, coordinates, date or image.
+ The sheet then sorts and filters it correctly, and can show it on the map, on
+ the Timeline or as a progress count.
+- Import an Excel workbook, one sheet per tab.
+- A cell can point at a person, a place or a media item already in the case.
+- Copy the rows you are looking at as a Markdown table, or save them as a CSV.
+
+### From a sheet into the case, and back
+
+- Turn a prepared sheet into entities, places, bookmarks and dated statements in
+ one go. You see a row-by-row plan first, and nothing is written until you
+ accept it.
+- Or the other way round: build a worklist from what the case already holds, for
+ example forty places to check with a column for your verdict.
+- Geocode a column of addresses, check a column of links, or send a column of
+ coordinates to the map.
+- List every proof in the case, one per row, and build one proof per row out of
+ columns holding links and coordinates.
+
+## Geo Proof
+
+- A proof can now state several points, not one. Name them, mark which one is
+ the camera position, and the first row stays the proof's conclusion.
+- It can also list several sources. For a link the case has nothing from, Azimut
+ offers to download its files as supporting material.
+- Import a published post as a proof: its pictures become the panels, its text
+ is read for coordinates, and any video it links is downloaded. You approve a
+ preview before anything is saved.
+- New drawing options: filled boxes and ellipses with adjustable opacity, a set
+ of ready-made symbols, and multi-select to recolour or move several shapes at
+ once.
+
+## Elsewhere
+
+- Export a Graph or Timeline view as an SVG or PNG plate, with the case name,
+ the question, the period and a legend around the drawing.
+- The map's search box now suggests as you type, from your saved places, from
+ coordinates you paste and from a list of 34,000 cities bundled with the app.
+ It only calls the online geocoder once you stop typing.
+- Saved views can be renamed and sorted, and each says when it was last changed.
+- Select several rows in the Board and delete them in one step, undoable from
+ the toast.
+- Downloads behind a login explain what the site actually asked for, and offer
+ to reuse your browser session.
+- Removing a relation, or deleting a photo you imported into an entity, now asks
+ for confirmation, because neither can be undone.
+
+## Fixes and hardening
+
+- A sheet no longer removes a relation you stated yourself. Clicking a filter
+ dropped the entities you had linked to the sheet by hand, and promoting the
+ same rows a second time dropped the sources you had added to a statement.
+- A point that a batch build filed for a proof can now be taken off it, and its
+ camera marker is read from that proof's own footage. Deleting the row used to
+ do nothing, and the point came back the next time you opened the proof.
+- A camera position marked on a coordinate written twice is kept, instead of
+ being dropped with the repeated line.
+- A batch proof build no longer overwrites an existing proof that happens to
+ share its title; it stops and tells you about the name clash.
+- Large uploads are refused by size before being read, including the proof
+ composer's save.
+- A malformed extension pairing token is rejected properly instead of returning
+ a server error.
+- Filing several downloads at once no longer fails one of them on a locked
+ database, which mostly affected Windows.
## Install or upgrade
-Download the ready-to-run asset for Windows x86_64, Linux x86_64 or Apple
-Silicon macOS and run it. Each binary includes the browser UI, `ffmpeg`,
-`ffprobe` and the fonts used for note PDFs.
+Download the ready-to-run file for Windows x86_64, Linux x86_64 or Apple
+Silicon macOS and run it. Each one includes the interface, `ffmpeg` and the
+fonts used for PDF export.
-Intel Macs require macOS 14 or newer and the Python package:
+On Intel Macs (macOS 14 or newer), install the Python package instead:
`pipx install azimut` or `pip install azimut`.
-The binaries are unsigned. Follow the operating system prompt described in the
-README on first launch.
+The downloads are unsigned, so your system will warn you the first time. The
+README explains the prompt for each platform.
-Existing cases upgrade in place when they open. Older case bundles remain
-importable, and no manual export or migration is required.
+Your existing cases open as they are. No export, migration or manual step is
+needed, and older case bundles still import.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index c8d47f4..09bce46 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -1,6 +1,6 @@
# Azimut product overview
-Status: **spec v0.3** (2026-08-03). Read in order: Done → Roadmap → Loose ideas.
+Status: **spec v0.3** (2026-08-21). Read in order: Done → Roadmap → Loose ideas.
Implementation detail belongs in code and tests; see
[IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), [UI.md](UI.md),
[ONTOLOGY.md](ONTOLOGY.md) and
@@ -51,10 +51,11 @@ azimut/ # everything Azimut owns; the rest of the folder is yours
case.json # small manifest: name, dates, storage format + schema
notes.md # free-form case notes (markdown)
notes/ # note bodies, named after their title, filed as in the notebook
+ sheets/ # case sheets as plain CSV; .meta/ holds the grid's own state
media/ # source + captured + extracted media; .meta/ holds the sidecars
proofs/ # exported PNGs; .meta/ holds the specs and pasted images
- exports/ # notes exported to PDF, and yours to fill
- .data/ # case.db: authoritative SQLite graph
+ exports/ # notes as PDF, analysis plates, and yours to fill
+ .data/ # case.db, the authoritative SQLite graph, and entity photos
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
.search/ # saved Grid Search state
@@ -126,26 +127,33 @@ proof for publication.
| ✅ **Research helpers** | Prepares media for keyless reverse search and saves keyboard-reviewed AOI grids. |
| ✅ **Reports & templates** | Stores reusable proof and post structures, then prepares sourced Markdown for X, Bluesky or Mastodon. |
| ✅ **Case Notebook** | Edits linked Markdown notes with local media, Mermaid diagrams, PDF output and remembered export folders. |
-| ✅ **Media at scale** | Handles login-gated downloads, bounded search, searchable pickers, local metadata enrichment and GPS handoff to the map. |
+| ✅ **Media at scale** | Downloads behind a login with a session named once, plus bounded search, searchable pickers, local metadata enrichment and GPS handoff to the map. |
| ✅ **Storage & recovery** | Uses per-case SQLite and durable jobs, with whole-case bundles, Trash and portable settings backups. |
| ✅ **Case utilities** | Opens case folders, reports scrubbed diagnostics, keeps filenames in sync and offers explicit Doctor repairs. |
+| ✅ **Workspace portability** | Moves or adopts a workspace safely, recovers hand-added cases and prevents two live instances from sharing it silently. |
+| ✅ **Updates & paste** | Reports available app, downloader and extension updates, then files supported clipboard content from the main case surfaces. |
| ✅ **Evidence on the map** | Places proofs and derived media through their evidence chain, with stated point uncertainty and traced footprints. |
+| ✅ **Map search** | Answers the search box while typing from saved work, a coordinate parse and a bundled gazetteer, and asks the geocoder only once typing stops. |
| ✅ **Ontology connections** | Keeps Relations, Mentions, Claim connectors and artifact lineage separate under one validated verb registry. |
-| ✅ **Board & entities** | Provides the sortable Case Board, shared Details, typed creation and primary entity photos. |
-| ✅ **Case graph** | Draws registry-backed lenses with clustered nodes, readable edges, previews and an explicit view budget. |
+| ✅ **Board & entities** | Provides the sortable Case Board, shared Details, typed creation, primary entity photos and a ticked selection deleted as one recoverable act. |
+| ✅ **Case graph** | Draws registry-backed lenses with clustered nodes, readable edges, previews, a view budget and sources folded onto their edges. |
| ✅ **Working the graph** | Expands, folds, hides, searches and pins nodes per lens, with undo and no case mutation. |
-| ✅ **Graph evidence** | Folds sources onto their edges and exposes derivation, support, source and account counts. |
-| ✅ **Shared analysis views** | Shares one filter and saved-view family between Board and Graph while Timeline keeps readings built for tracks. |
| ✅ **Claim assessment** | Keeps statement confidence, relation confidence and source reliability separate, with explicit support and contradiction links. |
| ✅ **Structured findings** | Records associations, duplicate identifiers, asset condition, equipment models and statement totals without inventing missing values. |
| ✅ **Temporal Claims** | Dates a Claim with guided point, timestamp or interval input and files its subjects, places and evidence atomically. |
-| ✅ **Case Timeline** | Aligns dated statements and media on a windowed UTC axis with uncertainty, density, direct edits and Undated work. |
+| ✅ **Case Timeline** | Aligns dated statements and media on a windowed axis read in UTC or a civil zone, with uncertainty, density, direct edits and Undated work. |
| ✅ **Timeline readings** | Builds coloured tracks from presets or Search+, then saves a changing Live view or a fixed Snapshot. |
-| ✅ **Timeline clocks & comparison** | Reads the axis in UTC or a chosen civil zone, adds daylight context and compares exact or uncertain entries. |
-| ✅ **Shared fact time** | Passes one fact-time window between Timeline, Board, Graph and a session-only Map layer without mixing in filing dates. |
-| ✅ **Workspace portability** | Moves or adopts a workspace safely, recovers hand-added cases and prevents two live instances from sharing it silently. |
-| ✅ **Updates & paste** | Reports available app, downloader and extension updates, then files supported clipboard content from the main case surfaces. |
-
+| ✅ **Shared analysis views** | Shares one filter, saved-view family and fact-time window between Board, Graph and Map, while Timeline keeps readings built for tracks. |
+| ✅ **Analysis view export** | Writes the Graph or the Timeline out as a vector plate carrying its lens, question, window, clock and legend, or copies it as an image. |
+| ✅ **Case Sheet** | Opens and builds case CSVs in a plain grid: keyed rows, sorts, filters, row colour, clipboard both ways, bulk fill, undo, cells that point at case entities, and a reading handed out as CSV or Markdown. |
+| ✅ **Typed columns** | Types a column in the sidecar as a state, a list, a yes/no, a number, a point, a date or a picture, and lets the sort, the filters, the vocabulary, the map, the Timeline, the progress and the link check read it. |
+| ✅ **A family of sheets** | Files a workbook one sheet per tab, forks a sheet, moves ticked rows under a column mapping, and confirms a reload or an overwrite when the file changed on disk. |
+| ✅ **A sheet into the case, both ways** | Promotes a declared sheet into entities, places, bookmarks, vocabularies, row edges and dated Claims in one transaction, read as a plan first, and builds a worklist back out of what the case holds. |
+| ✅ **Geolocation index** | Lays the case's proofs out one per row with their media, place and coordinates, and builds one proof per row back out of two address columns and a coordinate column, as a stoppable job. |
+| ✅ **Imported proofs** | Turns a published post into a composed proof: every picture a panel, its text read for a position, the addresses it points at fetched as material, and nothing filed before the preview is approved. |
+| ✅ **Import origin** | States one origin for a whole import, offers it to a batch that landed without one, and corrects any file later from Details. |
+| ✅ **Drawing on a proof** | Stamps a fixed set of marks, fills boxes and ellipses at a chosen opacity, keeps every shape tool in hand, and recolours, restyles, nudges, drags or deletes a picked family at once. |
+| ✅ **A proof of several points** | States every place a proof argues, each optionally named and one of them the camera's, files them as places under one title, and carries them into the tweet and onto the exported picture. |
---
@@ -155,18 +163,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from
§7. New tools become tabs or modes in an existing workspace (see
[UI.md](UI.md)). Releases ship as GitHub `v0.x` tags.
-### v2: still to finish (next `v0.2.x`)
-
-| Tool | What it does |
-|------|--------------|
-| **Case Sheet** | Adds editable free columns and CSV/GeoJSON round trips to the shipped Board. Imported loose rows stay outside the graph until promoted. |
-| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
-| **Saved view management** | Renames and sorts Board, Graph and Timeline views, with their surface and last modification clearly shown. |
-| **Analysis view export** | Copies or exports the visible Graph or Timeline as a PNG with its lens, question, time window, clock and legend. |
-
-Toward v2: split Satellite.svelte into `lib/` modules, before the map engine
-changes under it.
-
### v3: GEOINT expansion
| Tool | What it does |
@@ -191,7 +187,10 @@ changes under it.
| **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: shape fill + 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, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
+| **Detached tool windows** | Opens a tool in its own browser window for a second screen, greyed out in the tab it left and taken back when that window closes. Cross-tool handoffs route to wherever the tool now lives, and the open case follows every window. Read surfaces open as many copies as wanted; the document editors allow one window per document. |
+| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
+| **Help and tips** | A mark the analyst clicks for the open tool's own guide: what it is for, the controls whose icon does not say it, and its shortcuts. Clicking an entry points at the real button. One panel, one entry per tool. |
Edit Provenance rests on three facts about Adobe renders, kept here so the tool
can be rebuilt from the spec alone:
@@ -210,7 +209,8 @@ can be rebuilt from the spec alone:
The result is one track per source file over the render's timecode, with
GPS-tagged clips promotable to places.
-Toward v3: GIF maker; curated tool links; full-text case search; clipboard
+Toward v3: split Satellite.svelte into `lib/` modules, before the map engine
+changes under it; GIF maker; curated tool links; full-text case search; clipboard
image/URL capture with provenance; EXIF/GPS import suggestions for place and
time; sun and moon times read against the terrain horizon the 3D map's DEM
supplies, since a ridge ends the day well before the flat horizon does.
@@ -275,7 +275,6 @@ stops making sense.
- **Count a statement's independence by origin, not by wrapper:** three collages made from one video are three sources today, and are arguably one. The graph already answers this for a place; changing it for a statement changes a published number.
- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and Inspect collage.
- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
-- **Guided companion:** a mark the analyst clicks for a legend of the open tool, covering what it is for and the controls whose icon does not say it. Clicking an entry points at the real button.
- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.
## 8. Explicit non-goals
@@ -283,8 +282,6 @@ stops making sense.
- No cloud, accounts, hosted service, or telemetry.
- No automated geolocation verdict; Azimut files facts for the analyst.
- No rebuilding specialized OSINT services; Azimut orchestrates them.
-- No spreadsheet engine. The Case Sheet is a view of the graph, not a workbook:
- no formulas, no cell types, no second copy of the case.
- No block-evasion scraping. User session cookies are in scope; third-party
downloader proxies are not because they re-encode media and expose targets.
- No auto-posting by default. An optional, opt-in X/Twitter API key (Settings,
@@ -320,12 +317,29 @@ stops making sense.
- **Security posture** (single-user localhost): `127.0.0.1` bind + Host/Origin
guard (DNS rebinding), 0600/0700 perms, hard 100 MP Pillow limit, content-hashed
names for images pasted into a proof (no client-chosen path), token-gated
- ingest island for the extension. The workspace pointer is the one file written
+ ingest island for the extension. A case id and an artifact name each address
+ one directory entry, checked against POSIX *and* Windows path rules so the
+ separator only one of them honours cannot walk out of the workspace. The workspace pointer is the one file written
outside the workspace, 0600 and holding a path; deleting the copy a move set
aside acts on this process's own memory, never on a path from the request.
Accepted risks recorded here: cleartext keys over
- localhost, the hash-verified scraper updater, and tile/media URL fetches (SSRF
- only matters if the localhost assumption breaks). The startup update check is
+ localhost, the hash-verified scraper updater, the release workflow's publish job
+ running `softprops/action-gh-release` and `pypa/gh-action-pypi-publish` on mutable
+ refs while it holds the PyPI OIDC identity (the branch ref is the form PyPA
+ documents; every other action in both workflows is pinned by tag or by commit),
+ tile/media URL fetches (SSRF
+ only matters if the localhost assumption breaks), and a download that fails
+ saying only that the content is unavailable being retried with the stored
+ browser session, so a merely deleted post gets the analyst's cookies — kept
+ because a hundred-row press cannot stop on a question and the first attempt is
+ always cookie-less. A sheet's link check refuses a literal loopback, private or
+ link-local address on the first hop and on every redirect; a hostname that
+ resolves to one is not looked up to find out, and what such a hop could learn is
+ "this port answered" and never a body. An imported workbook is bounded on its
+ compressed bytes and on the size its own directory declares once unzipped. 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. The startup update check is
the one on-mount network call: opt-out, and read-only against GitHub's
releases feed plus PyPI's JSON for the two downloaders, both governed by the
same switch. Release notes are rendered through the Notebook's
@@ -335,11 +349,18 @@ stops making sense.
about that behavior and local Case media avoids it. Notebook diagrams are the
one markup DOMPurify does not clear: Mermaid draws its SVG into the preview
after sanitizing, under its own `strict` level, which escapes labels and drops
- click handlers. The PDF export is the one place a picture drawn in the browser
- is posted back: the request, each diagram and their decoded total are bounded
- before rendering, and every diagram is read as an image,
- and the note's own text is re-read from disk rather than trusted from the
- request. Case imports extract only unique, non-symlink members declared
+ click handlers. Three routes take a picture drawn in the browser back: the note
+ PDF export, whose request, diagrams and decoded total are bounded before
+ rendering, every diagram read as an image and the note's own text re-read from
+ disk rather than trusted from the request; the analysis plate, bounded the
+ same way and inspected before it is written, since a plate lands where documents
+ are opened — it must start as an SVG and carry no script, event handler,
+ embedded document or reference leaving the file; and saving a proof, which posts
+ the composer's rendered export and the images pasted into it, bounded as a
+ request and again as a decoded picture. Every body the browser assembles whole —
+ a table, a note, a picture — is refused by size before it is parsed, and the
+ routes are not trusted to a list: `tests/test_hardening.py` walks them.
+ Case imports extract only unique, non-symlink members declared
by the manifest and matching its SHA-256. Password-protected bundles seal the
complete ZIP with chunked AES-256-GCM and a scrypt-derived key; filenames stay
encrypted and the password is never persisted in a job. Import temporarily
diff --git a/docs/UI.md b/docs/UI.md
index 10a137a..c291d05 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -19,7 +19,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| Workspace | Tools today | Future tools land here |
|---|---|---|
-| **Case** (topbar) | Board, Graph, Timeline | Sheet; v5: Orchestrator |
+| **Case** (topbar) | Board, Graph, Timeline, Sheet | v5: Orchestrator |
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
| **Map** | Satellite, Coords & Sky | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
@@ -151,6 +151,28 @@ row's Details.
case when opened. Every
later filter, sort, fold, hiding, expansion, camera move and graph drag autosaves;
the badge says **saving…**, **saved** or **save failed**.
+- **Each surface restores only what it saved.** Opening a Graph view from the Board puts
+ its question on the rows and leaves the analyst where they are; the lens, the folds and
+ the arrangement wait for the Graph, which restores them off the same active view. The
+ row names the surface, so a reading made elsewhere is recognised before it is opened.
+- **Export writes the reading out as a plate**, from Graph and from Timeline alike.
+ A plate is a page rather than a screenshot: a header naming the case, the view, the
+ lens, the question, the window and the clock, the drawing itself, and a legend for
+ its hues and strokes. **SVG** is the default — the drawing is rebuilt as vectors from
+ the same geometry the screen uses, so it zooms without softening and its text stays
+ text — with **PNG** for an image and **Copy image** for the clipboard, which takes no
+ SVG. The image states the scale it will really have, since a wide reading rasterises
+ under twice the page. The page is always drawn on the daylight palette whatever the app
+ is set to, and a Timeline plate is laid out at its own width rather than the browser's,
+ so two analysts export the same file. The header states what the drawing holds and what
+ it leaves out: how many nodes and links are on it, entries with no date, nodes a fold or
+ a focus is holding back, verbs dropped where the drawing is too dense to carry them.
+- **The menu is where a list of readings is kept in order.** Every row states its mode,
+ its surface where the family holds two, and when it was last written — a distance up
+ to a week, then the date, with the exact UTC minute in the tooltip. Past one saved
+ view, **Sort** offers recently updated, name or surface, remembered per family in the
+ browser. **Rename** edits the name in the row itself and is the one edit a snapshot
+ accepts, since a label is not evidence.
- **A snapshot freezes a reading, not a second case.** It keeps up to 2,000 captured
entities, their fields and provenance, the relations among them and bounded photo
previews. Its Search+ controls and every case write are disabled, and its own
@@ -167,11 +189,22 @@ row's Details.
gesture either way: which of the two it is belongs to the column, not to a second
control the analyst has to find.
- **Columns** are the four every entity has — identity, type, folder, created — plus
- the chosen type's declared fields once a single type is picked. Read-only: editing
- cells and CSV belong to the Case Sheet. A primary entity photo replaces the type
+ the chosen type's declared fields once a single type is picked. Read-only: a value is
+ edited in that row's Details, and the Case Sheet works on the case's CSV files rather
+ than on these rows. A primary entity photo replaces the type
icon in the identity column; without one, the icon remains.
- **A row is a control**: focusable, opened with Enter, and the review clicks inside
it never open it.
+- **A box per row deletes several at once.** A mistake is rarely one row — a folder
+ imported twice, a scraper run that filed forty of the wrong thing, a paste into the
+ case next door — and undoing that one Details panel at a time is what made a slip
+ expensive. Shift ticks a run and unticks it the same way, and the bar above the table
+ says how many are going. The heading box reads the selection: empty, it takes the
+ rows loaded; part-ticked, it shows a dash and **clears** — completing a selection
+ would tick the row deliberately left out of it. The dialog is the
+ organizer's, word for word, and the delete lands as **one** trash group, so the Undo
+ in the toast takes the whole act back rather than the last row of it. A frozen
+ snapshot has no boxes, since every case write is off there.
**The vocabulary explains itself on hover.** A family, a type, a verb, a rating and a
declared field each carry one clause from the registry that declares them, shown
@@ -533,7 +566,12 @@ single root to expand from. Expansion is the drill-down.
away in Details. Each control appears because the **registry** declares it, not
because the edge holds a value: a ratable verb gets the rating, a verb that takes a
qualifier gets the word. A proposal gets neither, since reviewing a machine's claim
- and grading it are two gestures and the API refuses the second first. Nothing may be
+ and grading it are two gestures and the API refuses the second first. **Removing a
+ stated edge is asked for**, in red and in the same words Details uses: the panel is
+ opened to read an edge, *Remove* sat beside two controls that write nothing, and
+ nothing holds a removed edge — re-filing one mints a new id, a new date and a new
+ author. Dismissing a proposal stays one click, because that is the review this panel
+ is for and nothing of the analyst's goes with it. Nothing may be
written to a line that stands for several, which is why a folded edge offers only its
sources back.
- **Folder** draws one of the analyst's own buckets instead of the whole case, read the
@@ -653,7 +691,8 @@ remembered per workspace for the current session. Reloading restores the default
- **Details** — a drawer over the sidebar, closed with the back arrow or Escape, so
selecting a row never pushes the case out of view. Every entity uses the same three
tabs. **Info** holds identity, declared profile fields, file metadata, notes and
- folder. **Connections** holds placement, relations, mentions, Claims and the
+ folder. An entity that sits on a point shows it, read off the point itself and
+ written in the coordinate format Settings chose. **Connections** holds placement, relations, mentions, Claims and the
collapsed **Made from & used by** block. **Time** holds dated statements, intrinsic
media dates and a collapsed Case activity section. A field declared as holding
sentences is a box that grows, not a line. A
@@ -662,8 +701,11 @@ remembered per workspace for the current session. Reloading restores the default
form. It accepts several images from the computer or the Media Library, keeps the
main preview to a normal panel height, and lets one image become primary. A
computer import stays private to the entity and never enters the Media Library;
- choosing from Media only stores a reference. Removing a private photo deletes its
- dedicated copy, while removing a Media choice leaves the media in the case. With
+ choosing from Media only stores a reference. **The two are not one act and are not
+ called one thing.** *Remove* takes a Media choice off the entity and leaves the media
+ in the case, on the click. *Delete this copy* is the other, because a private photo
+ exists nowhere else and is not an artifact, so no Trash holds it and no toast can undo
+ it: it is asked for, in red. One word for both read as the harmless one. With
no photo, only the two add actions remain and other surfaces keep the entity icon.
The same two actions appear while creating a supported entity. Photos are staged
in the form, where one can be chosen as primary, then attached after creation.
@@ -680,8 +722,8 @@ remembered per workspace for the current session. Reloading restores the default
fields.
- **Delete** — deleting an artifact moves its registered files and cascade into
Trash and shows an **Undo** toast. The confirmation uses the neutral tone and
- states what can be restored. Red is reserved for deleting a case, purging a
- trash group and emptying Trash.
+ states what can be restored. Red is for what nothing holds afterwards: deleting a
+ case, purging a trash group, emptying Trash, and deleting an entity's private photo.
## Case switcher
@@ -740,8 +782,8 @@ process, warned once and never presented as the ordinary way out.
## Export folders and backup
-Settings → Storage remembers one destination each for note PDFs, media copies
-and proof PNGs. **Change…** opens the shared folder browser, which lists folders
+Settings → Storage remembers one destination each for note PDFs, media copies,
+proof PNGs, analysis plates and sheet CSVs. **Change…** opens the shared folder browser, which lists folders
only and can create one; the case's `exports/` stays the default. Media Details,
saved proofs and Notebook use those same destinations. Files already outside a
case are never overwritten, and concurrent exports reserve distinct numbered
@@ -761,7 +803,9 @@ generic History list.
Ordinary relations render through one component wherever they appear. Two lines carry
the neighbour's name, then what the edge states and how sure of it. A suggested row
-can be confirmed; any row can be removed. Where a pair supports several verbs or both
+can be confirmed; any row can be removed, and a row the analyst stated asks first — the
+question is written once and read by Details, a Claim's connectors and the Graph's edge
+alike. Where a pair supports several verbs or both
directions, the reading is selectable. An older out-of-matrix row stays visible and
removable but cannot be restated. Past six rows the list hides the rest behind one
click, suggestions first. The registry's headings only appear where a list runs
@@ -905,8 +949,8 @@ autosaves its window, display timezone, display mode, categories, ordered tracks
their colours, folds, hidden and pinned entries, grouping and entity scope. A Snapshot
stores up to 5,000 matching
temporal rows with their exact track assignments and opens read-only. It does not query
-the current case when reopened. Timeline views can be duplicated, deleted through
-Trash, restored and carried in a complete case bundle.
+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
tracks cannot. Clicking empty space creates a point; dragging creates a bounded range.
@@ -998,6 +1042,22 @@ files beyond the loaded page after a case import. Thumbnail failures are scoped
to their case, so switching cases always reloads previews even when relative
paths match. Enrich respects an existing confirmed GPS relation during backfill.
+**Import asks where the files came from.** A file fetched by hand elsewhere and
+then dropped here carries no address of its own, so a drop or a pick opens one
+field for the whole batch, and stating nothing is a real answer. The last address
+stated prefills the next dialog, since one thread's worth of files rarely arrives
+in a single drop. A batch that landed without one keeps the offer on its toast:
+**Set source** states one for every file that just entered. Later, the Source URL
+field in Details corrects any of them one at a time, and a link on the row reaches
+whatever the file came from, fetched or stated.
+
+An origin is a link, refused when it is not one — on all three doors that take one: an
+upload, a later correction in Details, and the file hand-attached to a proof import, which
+is the one where it is typed rather than carried. It is recorded as **stated, not
+fetched**: the source type stays `upload`, the file stays under **Imports**, and
+only a file brought in by hand takes one — a download already carries the address
+it was pulled from, and a frame's origin is the video it came out of.
+
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.
@@ -1010,6 +1070,17 @@ remote ids in provenance instead of appending them to the visible name.
## Map
+The search bar in the header proposes matches as you type, in the order they can
+answer: the coordinates the text parses to, saved work in this case, cities from
+a gazetteer shipped with the app (GeoNames, credited under the list), and last
+the geocoder's streets and hamlets. The first three cost no network and appear on
+the keystroke; the geocoder is asked once typing stops, from three characters up,
+and a request it cannot pace is dropped rather than queued, so the list keeps
+what it had. Arrows walk the list, Enter takes the highlighted row, and Enter on
+nothing parses or geocodes the raw text the way the plain box always did. A city
+lands at zoom 12 and a street at 15; a saved item reopens at its own view and
+bearing. Picks are remembered locally and offered back when the bar is empty.
+
Saved work — places, captures and screenshots filed by the extension — lives in
one right-hand **Saved** panel, grouped by geography rather than by date. The
tree's depth follows the case: one country opens straight on its regions, a
@@ -1037,15 +1108,18 @@ spelling. Proofs and posts keep the native name only.
Saving a place or a capture resolves its country as part of the save, so the item
appears already grouped. Offline it lands under Unlocated for a later Locate.
-Saving a proof turns the coordinates it carries into a place, which is where a
-geolocation stops being text in a spec and joins the map (ONTOLOGY §3). The
-composer's **POV** box beside the coordinates says what the point is: ticked, the
-footage was recorded there; left alone, the footage shows it. Nothing in a
-composition can answer that, which is why it is asked rather than guessed. A capture
-files nothing: ten are taken while hunting one roof, and the point is worth
-minting once, where somebody commits to it. Settings → General → Proofs saves it
-outright or has the composer ask; a point the case already holds is neither
-filed twice nor asked about.
+Saving a proof turns the coordinates it carries into places, which is where a
+geolocation stops being text in a spec and joins the map (ONTOLOGY §3). A proof
+stating three points draws three marks and files three rows under one title,
+told apart by the name each point was given. The marker beside a row says that
+point is where the camera stood, at most one per proof; the others are what the
+footage shows. Nothing in a composition can answer that, which is why it is asked
+rather than guessed. A capture files nothing: ten are taken while hunting one
+roof, and the point is worth minting once, where somebody commits to it.
+Settings → General → Proofs saves them outright or has the composer ask; a point
+the case already holds is neither filed twice nor asked about. Only the first
+point is looked up at save — the rest wait for Locate rather than holding the
+save for a lookup each.
A row the enrichment proposed from a file's GPS carries a `suggested` chip and an
**accept** action, on the row and in the search modal, so the point is settled
@@ -1120,10 +1194,925 @@ content hash, travels with a rename, and goes when the proof does. A proof needs
a panel first, since the panels are what give the document its size — moving an
overlay never resizes the export.
+**Coordinates and sources.** Both sit above the panels and both fill themselves in:
+the coordinates from the first panel that carries them, the sources from the address
+each panel's media traces back to.
+
+**Coordinates are a list too**, one row per point, with a `+` to add one. A proof
+often shows more than one place — three impacts, a building, the camera — and each
+row takes an optional name and the marker that says the camera stood there. **The
+first row is the proof's point**: the map mark, the coordinate a post cites, the
+one the export prints. An arrow moves a row up to make it the conclusion; the
+marker never reorders anything, or ticking it would take a coordinate out of a
+tweet without saying so. A single-point proof is the field it has always been.
+The exported picture prints them only when asked (Advanced → Show coordinates):
+unnamed points share one line, a named one takes its own, and the plate grows by
+what it prints. **Show text** switches the credit line off beside it, so a plate
+can carry its points and nothing else; with both off the band takes no height at
+all. A saved house style carries both, and one saved before they existed leaves a
+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
+`+` 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
+means retyping the three the panels already knew. The reset arrow hands the list back
+to the panels, and it is the only way back: **an emptied list is an answer**, not a
+blank to fill in. A proof whose boxes have all been cleared says it has no public
+source — the footage was handed over privately — and the `!` says so rather than the
+panels quietly putting their addresses back and carrying them into the post.
+
+**An address the case holds nothing from** shows a download arrow beside it. Pressing
+it brings the files in as ordinary media and records them as the proof's *material*:
+in its chain, and through the chain on its point, without ever becoming panels. An
+address holding several files asks which, ticked by default, since an address stated
+as material holds material. Only stated addresses offer it — one traced off a panel is
+already in the case by construction.
+
+Wherever a source is *read* rather than edited — the post it is handed to, the Markdown
+report — it is one address per line, and a report renders one link each.
+
**Frames.** Any panel or overlay takes a coloured border, its own colour and
thickness, drawn inset so the layout does not shift. A frame is decoration: it
stays out of the legend, which is still built from annotation colours alone.
+**Drawing.** A tool in hand holds the canvas alone. Nothing already drawn answers
+the pointer, so a stroke started inside a box draws a new element instead of
+dragging the old one, and the colour and width you pick set the next element
+rather than repainting the last. The selection stays where it was and its handles
+come back with Select. A box or an ellipse also takes a fill, in its own colour at
+an opacity you choose. Shapes start hollow: a fill hides what is under it, so it
+is asked for rather than given. Fill and outline share one colour, since the
+legend reads colour as the feature. Every shape tool stays in hand, so three
+boxes is three drags. Text is the one that puts the pen down: the editor opens
+where the label was placed, because placing it and saying what it says are one
+act. A label holds more than one line — Shift+Enter opens the second, Enter ends
+the edit.
+
+**What a picked element offers.** A box, an ellipse or a freehand stroke resizes
+from any handle and rotates; a line, an arrow or a curve gets a handle per vertex
+instead, so any point can be re-placed. A stroke is the exception among the
+points-based kinds: it has too many samples to show, so it takes the frame and
+the handles rather than a canvas full of dots.
+
+**Symbols.** A grid of fixed marks — a pin, an impact, vehicles, a building, a
+drone, a camera, an antenna, a north arrow — stamped with one click. The tool
+stays in hand afterwards, since marking six vehicles is one act rather than six.
+A symbol takes the active colour like anything else drawn, so it joins the legend
+by colour and claims no vocabulary the legend cannot say. It resizes from its
+corners with the ratio locked: the box is square and there is one side to change,
+so a squashed symbol is not expressible. The pin hangs from its tip rather than
+its middle, which is what keeps it on its pixel while it is resized. The solid
+marks carry no outline and the width control stays away for them. Fill on a
+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.
+
+**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
+panel too, since the grid decides where a panel sits and the drag cannot be
+moving it. In free layout that same drag moves the panel, so the rectangle starts
+on the page around it. What a family answers to: colour, stroke width, fill,
+arrow keys, Delete, and a drag from any one of them, which carries the rest.
+Resizing, rotating and copying still want one element, and the handles say so —
+several picked at once show the border and no anchors.
+
+**The gestures.** Escape unwinds one level per press: the draft in hand first,
+then whatever is picked, and only with nothing left to drop does it put the pen
+down. Only the primary button draws. A release the canvas never sees still lands:
+letting go over the side column commits the stroke and applies the rectangle
+rather than leaving either one following a bare pointer. Space or the middle
+button pans, and so does a drag that starts where no tool has anything to draw
+on. A row picked in the side column takes the hand back to Select, since a row
+cannot mean "draw here" — which is also why the rows stop lighting up while a
+drawing tool is in hand: a pick nothing answers to is not shown as one. A dialog
+over the composer keeps the one-letter keys, so `r` never changes the tool
+underneath it.
+
+### Import
+
+**Import** is the third way into the tool, beside composing a proof and opening a
+saved one, and it lives at the foot of the **Create proof** dialog. Paste the address of a post and the picture is downloaded, its text
+read for a position and for the links it points at. Both fill the form and say
+where they came from; neither is applied on its own, and a post that spells
+nothing out leaves the fields empty for you to type into. **Use an image** skips
+the post entirely and opens the same form. A post carrying several attachments
+asks which one, each shown with the poster frame its extractor reported and its
+kind — nothing has been downloaded at that point, so the picture is chosen by
+looking at it. The **pictures arrive ticked and several can be**: a post publishing a
+geolocation as a set — the overhead, the ground shot, the match — published one proof,
+and keeping the first of three keeps a third of it. They become the panels of one
+composition, which is what a proof already is. The footage slot stays single: which
+clip is the source is not something a rule knows. A login wall gives the Media
+Library's cookie prompt — including the one X gives, which reads as a tombstone
+(*Unavailable*) rather than as a refusal, and used to be read as a plain failure, so the
+prompt never appeared on the site that needs it most. *No video could be found in this
+tweet* is deliberately **not** among them: it is also what a perfectly public photo-only
+post gets, and it is the ordinary road to the picture extractor. The prompt opens on **the browser this page is in**, read off the user agent:
+the tab is the analyst's browser, so it is almost always the session being asked for,
+and defaulting to Firefox made a Chrome user answer a question whose answer was on
+screen. **And it is asked once.** Reading a browser's cookie store is reading
+credentials for every site, so it is asked for and stored rather than taken — but a
+session already stored is then *used*, on a wall, without the question coming back. What
+a still-walled line means is therefore one of two things, and it says which: no session
+named, or the named one refused.
+
+The left of the dialog shows **the set the proof will compose**, in order, as a strip
+above the file being looked at. Not the render — laying panels out is the composer's
+canvas — but what is going in, which is the part worth checking before pressing Create.
+The footage sits in that list as its own entry rather than as a page of the proof.
+
+The proof's picture is **asked for as a picture**. The video extractor reads a post
+for its footage, so a post that publishes a geolocation beside a quoted clip hands
+back the clip and the published picture is invisible to it. The image extractor is
+the one that can reach it, and it used to be tried only when nothing at all was
+found — so the panel filled with fifty seconds of video and said so two screens
+later, at the preview. Now a result of the wrong kind counts as nothing found.
+
+Coordinates and a source are required, and **a source is one box per address**.
+A geolocation thread states its point in the post that published it and hangs the
+photos and the clips it rests on off the ones after it, so the addresses the post's
+text pointed at all arrive as boxes and **Add a source** opens another. Each box is
+fetched on its own, says underneath itself what it holds or that it was not
+downloaded, and offers **Attach it** for that one address. Two addresses typed into
+one box is refused: a box is the address its own file comes from, and nothing can be
+downloaded from a pair.
+
+Pressing **Preview** downloads what the boxes point at — the left of the dialog then
+holds every file, the proof picture and the material, with arrows to step between
+them and a video playable before anything is filed — and lists what the import would
+write: each entity marked new or reused, the edges between them, and whatever is
+worth saying first — a point already on the map, a picture the case already holds,
+this post imported before, or a file whose own metadata sits more than 150 m from the
+coordinates entered. A source that could not be downloaded is a warning, not a
+blockage: the proof is created without that file and the address stays on it. An
+address taken off the list leaves its download behind rather than filing it.
+**Create** appears only once the preview comes back clean, and editing a field
+withdraws it.
+
+**The proof is what everything hangs off.** It composes the pictures and rests on the
+material, and both are its own edges, so the graph draws one node for the geolocation
+rather than a media node with the rest strung from it. Which photo of four a composite
+was laid out from is not something a post says, and a guessed pairing would state one
+edge right and the rest wrong.
+
+**One picture exports itself; a set waits for the composer.** A published panel is
+already a rendered proof, so a single-picture import files it as `proofs/<name>.png`
+and is done. Several panels have no render — laying them out is the composer's canvas,
+in the browser — and a second renderer on the server would drift from it at the first
+change to a layout. So a set is filed **without an export**, borrowing the first
+picture's thumbnail so the proof still draws in the graph rather than being the only
+blank node of its own constellation, and the first save in the composer writes the real
+one. Until then it has nothing to export and nothing to carry into a bundle, which is
+the honest cost of a composition nobody composed.
+
+Until then nothing is in the case. Both downloads wait in a staging directory
+under `media/.dl/`, which bundles skip and the Doctor ignores; closing the dialog
+deletes it, and one left behind goes when the next import opens. What Create
+writes is a normal proof: it lists, travels in a bundle, and reopens in the
+composer as a composition to annotate — one panel per picture taken.
+
+## Sheet
+
+A table the analyst works in, which **is** a CSV in the case folder. Three uses no
+other tool covers: a comparison grid, candidates down and criteria across; a worklist
+carrying its own state and a count; and the half-facts that are too soft to be
+entities and too valuable to lose. The graph says what the case believes, a sheet
+says what it is checking.
+
+- **The file is the artifact.** `sheets/<name>.csv`, readable in any spreadsheet, written
+ with a byte-order mark so Excel on Windows reads its accents instead of the machine's
+ legacy codepage, and replaced by **rename rather than in place** so a save that dies
+ half way leaves the previous table whole. A file the system will not take — a
+ spreadsheet holding it open on Windows, a read-only folder — is said in a sentence
+ naming it rather than a 500. A finding is a column of it — a status, a verdict, the reason — so handing the file
+ to someone else hands them the work. Presentation lives in a sidecar
+ (`sheets/.meta/<name>.json`): widths, hidden columns, the sort, row colours, which
+ column stays in view, **what the app knows about each column**, which entity a cell
+ points at, and what a cell said when the case took it. Losing the sidecar costs chips
+ and colours, never a finding.
+- **Two writers on one file, and the grid does not win.** Because the CSV is the
+ artifact, it may be open in a spreadsheet at the same time. A read hands out a
+ stamp of the file and every save presents it back; a save that would write over
+ work the grid never saw is refused. The stamp is also **checked whenever the window
+ comes back** — it is a stat, so it is cheap enough to ask every time — and that one is
+ a warning rather than a refusal: nothing has been stopped, so the banner says the file
+ moved on and waits. Both banners offer to **read the file first**: how many rows it
+ holds that the grid has not, how many cells differ and the first few of them, either
+ way round. Reload and overwrite are each irreversible in the direction that matters,
+ and choosing between them over one sentence made three rows a colleague added and one
+ stray cell the same press. **Both are confirmed**, and reload is the one that needed it
+ most: it looked like the safe way out and it is the analyst's own unsaved edits that it
+ drops, with the undo stack. A file rewritten byte for byte and otherwise unchanged says
+ so and the banner goes.
+- **The sheet's own ceiling is refused at the gesture.** 20 000 rows and 64 columns, which
+ is where a worklist becomes a dataset and a grid in a browser is the wrong tool. Those
+ are the file's bounds, so they used to be answered only by the save — the analyst pasted
+ eight hundred rows over the line, the grid took them, and every autosave from that
+ moment on was refused with the work on screen and unsaved. The paste, the append, the
+ duplicate and the split are refused now, and say how much room is left.
+- **Persistence is the file plus its sidecar, and nothing else.** No named views, no
+ exported plate: a sheet *is* its own saved reading, and a second frozen copy of its
+ state would be a duplicate that drifts. Another reading of the same rows is another
+ sheet — and **duplicating a sheet** forks the work rather than the headings, sidecar
+ and all, which is the button that answer had been missing. Both live in a **footer of the
+ sheet list that does not scroll**, the way the case switcher's own do: they make a sheet
+ out of the one that is open, and a case holding fourteen of them must not scroll them out
+ of reach. The **other** fork takes the
+ columns and leaves the rows, which is what a binder is actually built out of: an inbox, a
+ worklist and a reference table at one schema, and a row that has been worked out **moves
+ up a floor**. **Moving rows asks twice before it writes**: the first screen
+ lists them and lets any be taken back out, because the grid's selection is a drag away
+ from being every row on screen, and the second lines the columns up — one of this sheet's
+ against one of that one's, identical names taken as the answer and a near spelling marked
+ as a guess. What lands carries the rows' colour, their links and what they had already
+ promoted, which is exactly what copying by hand loses; a column pointed at nothing stays
+ behind, said on that screen rather than in the toast afterwards, because the destination's
+ shape is its own and a silent loss reads as a clean move. Both sheets are written by one
+ call and the grid's own undo reaches neither, so the toast carries **Undo**: this sheet
+ goes back as it stood and the rows come out of the other one, refused if the sheet has
+ been typed into since. The reading itself is part
+ of what is written down: **the search and the filters live in the sidecar** with the
+ sort and the hidden columns, so a sheet reopens on the question it was left on rather
+ than on all four hundred rows. Everything that is the grid rather than the table —
+ a filter, a colour, a width, a hidden column, the pinned row — goes out through a
+ **route that writes the sidecar alone and leaves the CSV byte-identical**, because
+ rewriting the file to record that a funnel was clicked moved the modification time the
+ stamp is made of: the analyst's own next save then answered a conflict nobody caused,
+ and a spreadsheet open on the same file was told it had been overwritten. For the same
+ reason a view change never enters the undo stack — `Ctrl+Z` is for what was written,
+ not for what was asked. Undo follows that logic throughout: a typed cell records the
+ cells that changed, not a copy of the table, so a long afternoon on a long sheet stays
+ undoable.
+- **Rows are keyed by an `id` column, in the file.** Nothing hangs on a row's
+ position, because a file sorted in someone else's spreadsheet would move every
+ colour and link one row down. An import that already carries an `id` keeps it
+ rather than being given a second one; a file edited outside and stripped of it is
+ re-keyed in the grid, said so in one line, and written back only on the next save.
+- **A new sheet starts from one of four worklists, or plain.** A verification worklist, a
+ geolocation index, a list of accounts, a run of events: the tables an analyst rebuilds by
+ hand every case, ten minutes of naming columns before any work happens — and each one
+ slightly different, which is why two of their sheets never compare. A template is columns
+ **and** what the app should know about them, so the status column arrives as a state with
+ its four words painted and the coordinates as a point. Renamed and dropped like any others
+ the moment the sheet exists. The five ways of getting rows in — blank, a file, a paste, the
+ case's own entities, rows into the sheet already open — sit under **one `New` button**,
+ because each is asked once per sheet and as five buttons they crowded a header that also
+ carries the title, the subtitle, the sheet list, the export and the delete.
+- **The browser neither reads nor writes CSV.** One parser and one writer, both in
+ `engine/sheets.py`, so an imported file and a saved grid cannot disagree. Import
+ posts the text of a file dropped on the grid, picked from a dialog or pasted into
+ one, and the delimiter is guessed — a semicolon export is a table, not an error. A
+ **workbook** cannot go that way — it is a zip holding several tables — so it goes up whole
+ and comes back as **one sheet per tab under the tabs' own names**, which is how a binder
+ arrives; asking the analyst to export six tabs by hand is asking them not to bother, and
+ the one that gets skipped is always the "How to use" tab saying what the others mean. A
+ tab holding nothing but pasted screenshots reads as empty, and it is **named rather than
+ filed**: two empty sheets nobody asked for are worse than the sentence. A workbook cell
+ has no words, only a number and a display format, so dates land as ISO — the one spelling
+ that means the same thing in every locale, carrying the seconds when a cell has them,
+ because a timecode column is what an offset is counted in — and a cleaning pass restyles
+ the column for anyone who wants it otherwise. **What did not fit is named too**: the tabs
+ past the twenty-fourth, and any tab read only to the twenty-thousandth row or the
+ sixty-fourth column. A thirty thousand row export arriving as twenty thousand under a
+ toast reading *5 tabs filed* is a sheet that looks whole. An import is also all of the
+ tabs or none of them: a tab the filesystem refuses takes the ones already filed back out
+ with it, so the retry does not land a second copy of half a binder.
+- **A clipboard block is not a file, so it is read here.** It is TSV, and a paste is a
+ patch into a selection whose geometry only the browser knows. `Ctrl+V` lands a block
+ from the cursor: rows grow to fit it, columns never do — a block wider than the
+ sheet is clipped and says by how much, because a heading nobody chose is worse than
+ a cell lost — and the key column is never written. A wall of links with no tabs is
+ read as an inbox instead: one row per link. `Ctrl+C` copies the selected rectangle
+ back out, quoted so a spreadsheet reads it whole.
+- **Editing is a grid's.** Press a cell and pull to select a rectangle, shift-click a far
+ corner to do the same in two clicks, typing
+ starts an edit on that character, Enter and Tab commit and move, Escape backs out one
+ step at a time — what is open, then the edit, then the cell itself —
+ arrows walk the cursor in the order the screen shows. `Ctrl+F` reaches the search,
+ `Ctrl+A` ticks every row on screen, `Ctrl+Enter` adds a row, `Ctrl+D` copies the top of
+ the selection down, Home, End and the page keys cross a long sheet, Delete empties the
+ selection. Deep undo, and the sheet autosaves.
+- **A bar above the headings holds the cell under the cursor.** A cell is thirty pixels
+ tall and as wide as its column, and the sentences an analyst writes into a `Title` are
+ neither: the bar is the same cell, full width, where a long value can be read and
+ rewritten. Enter commits and steps down, Escape lets go of what was typed, and the corner
+ pulls the bar open as far as the value needs. It is drawn whether or not a cell is picked
+ — a bar that arrived with the first click pushed the grid down under the pointer, and the
+ drag that click had started painted a selection nobody aimed at. The key column and the
+ columns the app writes are shown and refused, for the reason their cells are.
+- **The grid always ends on an empty line, and writing in it is what makes it a row.**
+ What a spreadsheet does, and Tab off the last cell grows the sheet the same way. A
+ `+ Row` button in the footer stood in for this: a trip to the bottom of the screen and
+ then back to the column being filled, for the most ordinary thing a grid does. The
+ editor opens where the click landed.
+- **The list of gestures has a door.** The grid keeps its power under a right-click, which
+ is right — and a right-click nobody tries is a feature nobody has. `?`, or the `i` in the
+ header, opens one list naming the keys and the gestures. It is not a tour and blocks
+ nothing.
+- **A row can be kept under the heading while the rest scrolls.** A comparison grid is read
+ *against* something — the confirmed case, the sample that sets the standard — and at row
+ twelve that reference had scrolled away, which is the point of the grid gone. Pinned from
+ the gutter, drawn a second time rather than moved, and not drawn at all while the filter
+ leaves it out: a reference the count says is not on screen would be the grid disagreeing
+ with itself.
+- **Rows are thirty pixels, or four lines.** Right for a worklist and wrong for the column
+ the reasoning is written in, so the sheet says which it is and remembers.
+- **A line beside the sheet's name says what the table is for.** The binders carried a
+ whole "How to use" tab of annotated screenshots; most of what it said belongs on the
+ columns it was about, which is what a column's note is, and what is left is a subtitle —
+ so it sits where a subtitle sits, next to the name, and is written in place rather than
+ in a dialog. A pencil beside the name when there is none, since the `i` in that header is
+ the help; no menu row for it anywhere.
+- **A colour can be told what it means.** Six colours and no legend is six colours whose
+ meaning lives in one analyst's head, on a case that gets handed over. Only the ones the
+ sheet actually paints with are worth naming; they are named in a panel and read back in
+ a strip under the rows.
+- **The gutter carries the row's number and its own menu.** The number, because the key is
+ a handle (`r7a3f…`) and nobody says "row r7a3f" out loud; the tick box takes its place on
+ hover or once anything is ticked, since two controls in 34 pixels would be neither. A
+ right-click there inserts a row above or below — where the analyst is reading, rather than
+ four hundred rows below — duplicates rows, paints them, opens one field by field, or
+ deletes them. A duplicate is keyed anew and carries no colour or link of its own: the
+ gesture is a candidate that turns out to be two, and the second one has had no work done
+ on it yet. Every gesture made on one row acts on **the batch when that row is in it**, and
+ the menu's heading says which it is.
+- **Many rows at once, off one selection.** Shift-click in the gutter ticks a range in
+ the order the grid draws; a box in the header ticks everything shown, and only what is
+ shown. Painting, deleting, filling a column and promoting all act on **what is ticked,
+ or failing that on the rows dragged across** — one rule, said in the bar, because two
+ selections that disagreed meant a screenful selected by dragging could not be painted
+ and forty ticked rows could not be copied. The bulk fill leaves out the columns the app
+ writes itself: a value put in one of those is gone by the next save. What those rows can
+ become is **a bar drawn over the last of them** rather than ten more controls in the
+ question bar, where ticking one row wrapped that bar onto a second line and pushed the
+ table down a row height under the pointer that had just done the ticking.
+- **Columns are the analyst's.** Drag a heading to move it, which moves it **in the
+ file** where a collaborator will see it. Insert one on either side of the one being worked
+ on — a verdict next to the claim it judges — and it lands in rename, ready to be named.
+ Duplicate one and the copy carries its cells, its width, its role and its note, but none of
+ its links: a link is the case's answer about one cell, and two cells claiming it would state
+ one edge twice. Rename in the heading itself on a double-click. One column can be kept
+ beside the key while the table scrolls sideways. A URL in a cell is a link, shown as its host: a hundred
+ and twenty characters of query string in a row thirty pixels tall says nothing.
+- **A row can be read down instead of across.** Fourteen columns do not read by
+ scrolling sideways, so a panel shows one row field by field, every box editable, its
+ links live, and how much of it is filled. It walks the rows on screen, not the file's
+ own order. Each field **offers what its column knows**, as the grid's own editor does: a
+ state or a set of values draws its words to click, a yes/no field is a toggle, a date
+ field carries its picker, and a column the app fills is shown rather than typed into.
+ A panel that put a bare box on all fourteen was a worse place to work than the row it
+ was showing, on exactly the columns somebody had set up.
+- **Everything that opens over the grid closes on Escape or a click beside it** —
+ the heading menu, the gutter menu, the filter, the columns list, the sheet list, the export
+ menu, the fill bar, the row panel. Every row of a menu **acts and then closes**, in that
+ order: closing first clears the column the menu was opened about.
+- **Six passes fix a column that came from somewhere else**, and each says what it would do
+ before it does it — how many cells, and the first few as they would come out. Find and
+ replace, on this column or every one, whole-cell or inside the words; the spacing taken out,
+ because `Kherson ` and `Kherson` are two values in every menu and the difference is a
+ character nothing can draw; the casing; a split into as many columns as the separator makes,
+ keeping the original unless told otherwise, and up to eight — a cell that breaks into more
+ is prose with punctuation in it, so the eighth column keeps the whole tail rather than the
+ pass dropping what it could not place; a merge of several into one, empties left out;
+ and the links lifted into a column of their own, as addresses or as bare hosts — eleven rows
+ sourced to one channel is a finding, and it is invisible while the hosts sit inside
+ sentences. They read the rows **on screen**, filter and all, and the count says which. There
+ is no regular-expression box: a pattern with no preview is how a sheet loses a column.
+- **Sort is three states on one control**: up, down, off. A blank cell sinks to the
+ bottom whichever way the arrow points, because blank is "no answer yet" and it must
+ not bury the rows that have one. A **second column breaks the first one's ties** —
+ *by status, then by date* is how a worklist is read, and one key meant re-sorting by
+ hand every time the first tied. It is offered in the heading menu rather than as a
+ fourth state on the heading's own click, since "sort by this" and "sort by this too"
+ one gesture apart would be a trap, and the heading it breaks ties on carries a smaller
+ mark.
+- **Two rows can be folded into one, and one row split into many.** The grid could already
+ find the values said twice and paint them, and then left retyping one row out of three by
+ hand — on an inbox where the same address arrives from three channels, that is the whole
+ job. Merging keeps the fullest answer per column and the first row's key, so its colour,
+ its links and its promotion record survive. The other direction is the shape every "to be
+ sorted" inbox arrives in: a cell holding five links, or `Buk-M2E, ZU23-2, S-300` in a
+ worklist that wants a line each, becomes a row per value with the rest of the row copied
+ down. Splitting a column into *columns* is a different question and lives in the cleaning
+ passes.
+- **A batch of rows can be added to the sheet already open.** Import files a new sheet,
+ which is right the first time and wrong every time after it: the daily batch of links
+ belongs in the worklist that already carries the statuses. Which incoming column lands
+ where is proposed by name and then the analyst's, and **what would be dropped is said
+ before the press** — "40 rows added" over three silently discarded columns is the kind of
+ import somebody finds out about a week later. It lands as one undoable step.
+- **A heading has three doors, split by how often each is wanted.** The **funnel** asks
+ something of the rows and stays lit whether or not the heading is hovered — hiding the
+ gesture made a hundred times a day behind a hover is how an analyst concludes a grid
+ cannot filter. The **short menu**, on the `...` and on a **right-click anywhere on the
+ heading**, is the frequent list: sort either way, filter, insert a column left or right,
+ duplicate it, rename it, the cleaning passes, point its cells at the case, keep it in
+ view, hide, delete. And its last row opens the **setup panel**, which is the rare half.
+ Before the menu existed the `...` opened the panel straight away, so declaring a role had
+ a door and inserting a column beside the one being worked on had none.
+- **The setup panel is what a column *is*, with room.** A name, a role with its own
+ vocabulary, a line of instruction and the readings the role earns do not fit in a popover,
+ and scrolling a menu is how you lose your place in it. So it takes the same right-hand slot
+ the row panel uses — you are either reading a row across its fields or working on a column
+ down the rows — and it **stays open and follows the next heading clicked**, which is what
+ makes declaring six roles six clicks. Escape closes it; a click in the grid does not,
+ because working on a column means clicking cells of it. Nothing the short menu offers is
+ offered here twice: one screen saying a thing in two places is how the two come to
+ disagree.
+- **A column can be told what it holds, and the file keeps the words.** A role lives in
+ the sidecar — a state, a set of values, a point, a date, a picture, and the two the app
+ fills itself — and it is a **lens, never a validator**: `To be found` in a coordinates column
+ and `OK en cours` outside a status vocabulary are what a real binder holds on every
+ page, so they are shown as written and the filter still finds them. The role is
+ suggested from the column and confirmed by hand, never applied on a guess. What the
+ column is shows **in its heading**, and the cells its lens cannot read carry a mark and
+ are reachable as a filter — a column that accepts anything and says nothing about what
+ it skipped is a column whose total nobody can check.
+ - **The sort follows the role**, which is the most visible thing one buys: without it a
+ `dd/MM/yyyy` column puts 1 February before 31 January. A date sorts by the moment, a
+ state by its own vocabulary's order, a counting column by the count, and a cell the
+ role cannot read goes to the end rather than into the middle of January.
+ - A **set of values** draws one chip per value, and clicking one filters on **that
+ value** — `Buk-M2E, ZU23-2` is two answers, so the filter reads them apart rather than
+ comparing the whole cell. Whether a cell may hold several is a question with a box for
+ the separator under it, rather than one box whose placeholder was the word "no". The
+ value menu counts how many rows hold each, which is what the filter hands back. Reading
+ `2x S-125` as two of `S-125` was offered here once and is gone: it kept a **count inside
+ a column of words**, where nothing could total it — a count belongs in a number column
+ beside a column naming what is counted.
+ - The **vocabulary is edited as rows**, not as text: the word, the colour it carries
+ picked from the palette, how many rows use it, and two buttons to move it — because
+ the order *is* the ranking the sort reads, and `to do → in progress → done` is the
+ order of the work rather than the alphabet. A → Z and Z → A are offered and never
+ applied on their own. The panel also says which declared values nothing uses, and
+ offers to take in the words the cells hold that the list has never heard of.
+ - A **state** column starts on four words already painted — to do grey, in progress blue,
+ done green, ruled out red — because that is what makes the grid readable at a glance.
+ A vocabulary the column brought itself is left unpainted: `done` among an imported
+ binder's own words means what the binder meant.
+ - **Yes / no** is two words the column chooses, and a click on the cell flips between
+ them. Two answers is a toggle, not a menu.
+ - A **number** gives **one** answer in the footer, over the rows on screen, and the
+ column says which: nothing, how many were read, a total, an average, or the range it
+ covers. The footer **names the reading it gives** — `total 52 km over 2` — because a
+ total and an average are the same digits from down there. On screen and not in the
+ sheet: filtering to the twelve rows left to check and then being told the total of all
+ four hundred answers a question nobody asked. The column also carries a **unit** —
+ `%`, `€`, `km` — written beside the heading, once, since the cells keep the digits the
+ file holds. It can be repeated after every cell on request, which a column of shares
+ wants and a column of distances mostly does not. `1 200` and `12,5` are read, and
+ `~9` is read because an estimate is
+ still a number; a digit buried in prose is not, because extracting it would also turn
+ `AB-123` into 123. What it could not read is counted beside the answer and is one
+ click from being the only rows on screen.
+ - **A comma is a decimal mark, everywhere and without a switch.** `12,5` is twelve and a
+ half, `1 200` and `1'200` are twelve hundred, and `1,234,567` is refused rather than
+ read as a million: two commas cannot both be decimal marks, and guessing would put a
+ value a thousand times out into a typed field with nothing said. The same reading
+ settles a point, so `48,8` is one number and not a pair of coordinates — a pair needs a
+ separator the comma cannot be mistaken for (`48,8566; 2,3522`, `48,8566 2,3522`) or a
+ full stop already doing the job. Unlike the day-or-month order of a date, which a column
+ carries its own answer to, this one is not configurable: a binder is written in one
+ convention and it is the European one.
+ - **The editor offers what the column knows, and never only that.** A state or a set of
+ values offers its vocabulary beside the box, **narrowed to what is being typed** — on a
+ multi-value column, to the value after the last separator, because that is the one
+ being written. ↑ and ↓ move through it and Enter or Tab takes what is lit; clicking
+ stays a toggle, which is how a list is built and unbuilt with the mouse. A word the
+ column has never heard of can be **taken into its vocabulary from the cell**, which is
+ where the decision is actually made. A date column offers a calendar that writes the
+ form the column already uses, keeping an hour the cell had. The free text box always
+ stays: `OK en cours`, `AFTER` and `To be found` are what the binders write, and an
+ editor offering only a closed list would refuse exactly the cells that carry the
+ reasoning.
+ - A **point** is checked as it is read: two decimals is about a kilometre and says so,
+ and a transposed pair is flagged rather than refused. The column can be put on the
+ map as a session layer, where a coarse point is drawn as the circle it actually
+ claims, and **one cell can go over on its own** from the row being read, which is
+ what a worklist asks far more often; it can be swept for pairs too close to be two
+ places; and it can be
+ rewritten in one form on request — the one action that touches the file, because a
+ role by itself never improves it.
+ - A **date** column says which of three things it holds — a date, a time, or both — and
+ the cell offers the picker made for it. Declared rather than guessed, so a column that
+ is still empty can be told it holds times. A bare `hh:mm` stays a time of day: the
+ binder writes `01:57` for an event whose date is in the sheet's title, and inventing
+ that date would be inventing evidence. The column can **open the Timeline on the
+ period it covers**, which is what that does — it files nothing there.
+ - A **picture** column draws each cell as the picture it names, in the row, with the full
+ size one click away. Two things count as one: an address, and **a file this case
+ already holds**, written as the case-relative path a collaborator reads the same way in
+ a spreadsheet (`media/quai-sud.jpg`). The case's own files are the common case — a
+ geolocation index is worked on the images in the case folder — so **an image dropped on
+ a row** goes into the case's `media/`, the cell cites it by path, and the cell points at
+ the media entity so the graph knows the row rests on it. Only the address kind reaches
+ the network, which the panel says before the role is chosen. A cell holding neither is
+ shown as written and marked, never refused; an absolute path names a disk this case does
+ not travel with, so nothing is drawn for it.
+ - A **source** column declares where the pages a row rests on are written. Links are
+ already live in any cell without a role, so what declaring one buys is a promotion that
+ knows which column to file as bookmarks.
+ - **Another row** says the cells name other rows of this sheet, and which column's words
+ do the naming. Names and not keys, because the file is what a collaborator reads.
+ - An **offset** says the cell is a time either side of a **sync point**, and which one.
+ `-00:01:50` before it, `00:04:04` after; the column sorts by that, which is the order
+ the videos actually run in and is usable long before the sync point has a time. Naming
+ and dating the sync points is one press from here, because a column of offsets is where
+ anybody wants them.
+ - Three columns are written **by the app, into the CSV**: the date a row first appeared,
+ once and never again, a column the app answers, and a column the case holds. All three
+ are in the file rather than beside it because `On map: YES/NO` is exactly the column a
+ collaborator opening the spreadsheet reads. `Added on` dates every empty cell on the next save, including rows
+ already in the sheet, and the panel says so before it is chosen. The answered column
+ holds one of three readings, and the heading says which — a heading drawing a globe over
+ a column counting criteria would lie about it:
+ - **on the map**, whether what the row points at has a place. Restated on every **read**
+ as well as every save, so a place added an hour ago does not leave the sheet reading
+ NO; the read still writes nothing.
+ - **how complete**, how many of the columns it was told to watch are answered, and
+ **score**, how many of them say yes — the one kind of formula this tool has, and the
+ number a comparison grid is built to end each row with. A yes is spelled the way each
+ watched column spells one: a declared yes/no column answers with its own first word,
+ and a tick column somebody typed by hand holds `x`. The cells hold the **bare number**
+ so a spreadsheet can total them; the denominator is said once, in the heading and the
+ panel, rather than four hundred times in cells thirty pixels tall. A column told to
+ watch nothing writes nothing, because a score over the whole sheet would change under
+ the analyst every time a column was added.
+ - **its point** and **what it is joined to**, which are what the case *knows* rather
+ than whether it knows: the coordinates of the entity one named column points at, and
+ the far end of that entity's edges. One hop, and blank where the answer is not one
+ thing.
+ - **still in the case**, whether the case still holds what the row was **built** from.
+ The only one that reads where the row came from rather than what its cells point at,
+ because it is the only one asking about something that may be gone: a link naming a
+ deleted entity is dropped on the next read, so by then the cell that would have
+ answered is already blank. Rows somebody typed themselves stay empty — they were
+ never built from anything.
+ - **Held by the case** is the third, and it is the one role the app writes that still
+ carries a **link**: the cell opens the entity it was filled from. Typing in it is
+ refused, because a refresh rewrites it — a view somebody can type over is a view that
+ starts lying the first time they do.
+ - Losing a role is **said out loud**. Renaming a column in a spreadsheet takes its role
+ and its map layer with it, and a lens configured in ten minutes is not a colour.
+- **A sheet can be built out of the proofs the case already holds, and kept level with
+ them.** The template that fetches and this shape carry almost the same columns and run in
+ opposite directions, so the modal asks which **before** anything else: *one row per
+ entity* takes a type and its fields, *my geolocations* takes neither. The
+ outgoing one is one row per proof, carrying the media it rests on, the place it puts on
+ the map and coordinates read off the graph. Those three columns are the case's and are
+ read-only; Status, Notes and any column added are the analyst's. It offers no *Build
+ proofs* button, because the proofs already exist and there is nothing left to fetch.
+ - **Refresh is a press, never automatic.** A sheet that rewrote itself when it was opened
+ would move a file under somebody who came to read it, and it would fight the stamp that
+ keeps two readers of one file from overwriting each other. It files the proofs added
+ since, restates the columns the case owns, and says what it did.
+ - **It adds and never removes.** A proof deleted since the build keeps its row, its notes
+ and its colour, and answers NO under *In case*. Filtering on that column groups them so
+ they can be deleted in one gesture — but that is the analyst's call, because the notes
+ on those rows are theirs and nothing in the app wrote them.
+- **A column of sources can be asked whether it still answers.** Most of a worklist is
+ links, they rot, and nothing said which ones already had — so a finding could be
+ published on a source gone for a month, and the only way to know was to open four hundred
+ tabs. This is the one part of a sheet that reaches the network and it goes on a press,
+ over the rows on screen, in batches so the count moves. Distinct addresses rather than
+ rows, because eleven rows sourced to one channel hold one address eleven times. Five
+ answers, and keeping them apart is the point: it answered, it answered *not here* (404,
+ 410), it answered something else — a login wall, a rate limit — which says nothing about
+ whether the page is there, nothing answered at all, which says as much about the
+ connection, or it was never asked because the sweep ran out of its own time budget. That
+ last one is counted beside the others rather than folded into them: nobody asked, so
+ nothing was learnt about the page. The dead ones are chips that paint their rows. An
+ address on this machine or its own network is refused unasked, and so is a redirect onto
+ one — the addresses come from the sheet, and a sheet arrives by import, by paste or as a
+ workbook somebody sent.
+- **A column of place names can be read into coordinates, and back.** Both directions
+ existed elsewhere in the app and the sheet, which is where a geolocation index is
+ actually worked, could reach neither — so four hundred rows of `Kherson, Ukraine` were
+ typed in by hand. Reading names into points has two halves, and the case comes first:
+ a row whose cell points at an entity the case has placed is answered off the graph,
+ exactly and at once, and only the words left over reach the geocoder. An entity two
+ different points reach is left alone rather than resolved. Two rules hold the rest:
+ **nothing is applied on its own**, since a geocoder's first hit is a guess and a guess
+ written unattended into a column of evidence is indistinguishable from a coordinate
+ somebody read off a photograph; and **only where the target cell is empty**. Distinct
+ values one way — forty places out of four hundred rows — and row by row the other,
+ because five decimals is a metre and rounding two readings together would put one row's
+ answer on another row's ground. The lookups are paced, so they run one at a time with a
+ count and a Stop.
+- **How far along the work is, off whichever column carries it.** One column per sheet,
+ chosen or accepted from a suggestion, never imposed: the footer reads *312 filled · 156
+ left* on any column, or the tally per bucket when that column is a state. It needs no
+ role at all, which is the point — the binder this most has to replace is a geolocation
+ index with no status column, and its question is the fill rate of one column. The count
+ of rows left is **a link**, so those rows are one click away and the chip that appears
+ was asked for. A sheet opens on the question it was left on and on nothing else: posting
+ that filter automatically could not tell a cleared question from one never asked — both
+ are an empty table in the sidecar — so it came back on every reopen, which reads as a
+ filter appearing from nowhere.
+- **A worklist can be built out of what the case already believes.** Promotion runs one way
+ — rows become entities — and until this existed an analyst holding forty places in the graph
+ had two answers, both bad: retype the forty, or work in a Board with nowhere to write a
+ verdict. Say which type and which of its declared fields deserve a column, and the sheet
+ arrives as one row per entity plus the two the work needs, a status and a note. Nothing else
+ travels: a sheet holding every attribute would be a second copy of the graph, and the second
+ copy is the one that goes stale. Each row **points back at what it came from**, in the same
+ place a promotion writes a link, so editing the rows and promoting them again updates those
+ entities rather than minting twins. The sheet gains its `mentions` edges in the same write.
+- **A sheet goes into the case in one declaration and one press.** There were six roads out
+ of a sheet — rows, a column's words, pointing a column at what the case already held, a
+ column of hours, a column of row names — and none of them could draw an edge, because an
+ edge needs *two* columns and each road only ever saw one. A line of a binder says *this
+ person, in that unit, with these sources, at that point*; the case got the nodes and lost
+ the sentence. So: **a mode per column**, then the joins, one plan, one press.
+ - **The mode is offered only where the column's role carries it.** *Ignore* by default,
+ because only what was asked for travels; *one entity per row* for the subject; *one
+ entity per value* for a column of words; and, where the role says so, *Place
+ (coordinates)*, *Bookmark (links)*, *Claim (hours)*, *edges to other rows*. The three
+ that mint one type and only that type are named after it, in the vocabulary's own word,
+ with what the column has to hold beside it.
+ - **The grain of a column of words is the word**, split on the column's own separator, so
+ `Buk-M2E, ZU23-2, S-125` in one cell is three. Forty pieces of kit out of four hundred
+ rows, created where the case has nothing under that word and attached where it has
+ exactly one. What a word *means* is kept on the column rather than on a cell, because
+ one cell cannot hold three links; on a column with no separator each row also points at
+ what its own word means, which is what the answering columns read.
+ - **The joins are not drawn by hand.** For every pair of columns that designates
+ something, the vocabulary is asked what it allows between their two types, and only the
+ pairs with an answer are offered. A person and a point have no verb between them, so
+ that pair never appears at all. The select shows the registry's own *readings* — "is a
+ member of", "has member" — which settles the direction without asking a question about
+ direction, and a pair the vocabulary leaves no choice about arrives filled in. One
+ confidence for the whole pass, applied to the edges that can carry one; the edges enter
+ **confirmed**, because the analyst chose the verb and pressed the button.
+ - **The scope is one for every mode: the ticked rows**, or the visible ones when nothing
+ is ticked, said in those words on the screen. A pass whose halves disagreed about scope
+ is a pass whose count never adds up.
+ - **The plan is read first, and it is the same code the press runs.** Row by row and word
+ by word: a new entity, one attached to something the case already holds, one already
+ sent updated, a row left alone, or a cell that cannot be read at all — then the edges,
+ with the rows that have only one end and why. The button says how much it will write
+ over both layers.
+ - **A name is not an identity.** Two people share a name, so a row matching an entity
+ already in the case is *offered* it, never merged into it behind the analyst's back;
+ attaching is a choice made in the plan. The one exception is the identifier family,
+ where the value is the identity — one address is one email.
+ - **A field is checked before it is stored.** A column mapped onto a declared field goes
+ through the same readings a typed form does, so `about 12` in a number field stops that
+ row and says why instead of landing as text in a field nothing can sum. Nothing else
+ travels: a pass that swept every column would put a worklist's private notes into the
+ case's record of a subject.
+ - **Pressing twice is safe.** The row keeps a link to what it made, so the second press
+ updates it — and only while that link still points at something of the promoted type,
+ since a cell pointing at a place is not a person waiting to be overwritten. An edge
+ already stated is restated rather than stacked.
+ - **A column of coordinates makes places**, with the uncertainty radius the cell's own
+ precision claims: two decimals is about a kilometre, and a place stored without saying
+ so reads on the map as a pinpoint somebody established. Points on their own are that
+ column as the *subject*, typed Place — it is its own point, and nothing asks a second
+ time — and a place is **named by whichever column is the subject**, so a geolocation
+ index names its points by making the title column the subject and this one the point. The verb joining the row to its
+ point is read out of the vocabulary — a structure is *sited at* its ground, a media *was
+ recorded at* its own — and a type the vocabulary puts nowhere is refused at the door
+ rather than given a latitude nothing in the app would show. A **column of addresses**
+ files its pages as bookmarks that mention the row's subject, one per URL however many
+ rows cite it.
+ - **Nothing that owns a file is born from a cell.** A media, a capture, a proof, a post
+ hold bytes and a cell holds an address, so those types are not on offer here at all.
+ Going to fetch the file is the proof import's road, and it is the only one that may.
+ - A **Claim is not something a bare row can become**: a statement carries what it is
+ about, when it applies and what it rests on, and a row promoted on its own would be a
+ statement about nothing. It is a mode of its own, on a column of hours.
+ - **The press is all or nothing.** The file is checked before the first entity is written,
+ the graph and the sheet's own save happen in one transaction, and a file that moved
+ under the analyst takes the whole pass back — where entities without the links that make
+ a second press an update would be minted twice by the retry.
+ - Afterwards the row says whether it still agrees with the case: the sidecar keeps what
+ the cell said when it was taken, and a cell edited since carries a mark. The sheet gains
+ a `mentions` edge per promoted row.
+ - **A sync point with no time is dated from where the hours are declared.** A column of
+ offsets carries its rows' order straight away and their hours only once the shot itself
+ is dated, so the mode that reads them says which sync point it counts from and offers to
+ date it. The sync points open **over** the declaration rather than instead of it: what is
+ on screen is what sent the analyst there, and closing it to ask for one date would be
+ asking them to declare the whole pass twice. Escape answers the dialog on top.
+ - **Ticked rows can be one thing rather than one thing each.** The only shape row-by-row
+ gets wrong by construction, and it is a common one: the binder's geolocation index puts
+ a cross-border event on two lines, one point per country, same title, same source.
+ Promoted separately that is two events and the second is the copy nobody corrects. As a
+ group it is one entity with a place per point, every row pointing at it — so either of
+ them can say it is already in the case. Where two rows disagree about a field the first
+ answer is kept and the preview says which field that was, because rows grouped on
+ purpose differ in the detail; that is why there are two of them.
+- **A geolocation index builds its proofs, which is the one road that fetches files.** Its
+ own button, offered only on a sheet that can feed it — two columns of addresses and one of
+ coordinates — because it is not a mode of the press above: that one is a single transaction
+ precisely because nothing in it touches the network, and this one is a hundred downloads.
+ Three columns and a note say what a row is, and how much of that the row holds decides what
+ it becomes: coordinates alone pin a place, coordinates and the footage pose that media on
+ its ground, and all three write the whole constellation a hand-made proof import writes —
+ the two files, the proof composed of the published picture, and the point they all state.
+ `derived-from` is honest here and only here: the app fetched the bytes and composed the
+ proof, so it observed the derivation. A proof with no footage is **refused**, stricter than
+ importing one post by hand, because a binder holds dozens of those and nobody re-reads them
+ one by one. So is a geolocation with no point, and a proof with no name — a proof's name is
+ its filename.
+ - **The plan downloads nothing.** The three refusals come out of the cells and the three
+ "already there" answers out of the case, so the analyst reads what a hundred downloads
+ would do before one of them starts. Rows ruled out on their status are dropped by default
+ and handed back with one click, because a filter nobody can see is the app deciding which
+ lines of a binder count.
+ - **A source cell may list several addresses.** There is no `+` in a spreadsheet, so a
+ cell holding them separated by spaces is how a hundred rows say what the import dialog
+ says with boxes: one proof, one point, and every file it rests on. The published
+ picture stays one — a row builds one proof, and a second picture would be a second.
+ A row counts as already there only when every one of its addresses is already
+ downloaded, since half a row is a row to run.
+ - **A post with several attachments is answered, not asked about.** That is the ordinary
+ shape here — a published geolocation is a picture and the post carries the material
+ beside it — so a picker would fire on nearly every row, and a hundred rows cannot each
+ raise one. Each slot takes **everything it can use and the extractor vouches for**:
+ the proof takes every picture, since a post publishing a set published one proof of
+ several panels, and the material takes every picture, clip and recording, since a post
+ carrying two photos of the scene carries two things that were shot there. Keeping the
+ first of them keeps half. What is *not* vouched for is left: the video extractor reads
+ a post's media and the media of the post it quotes into one list, and past the first it
+ cannot say whose a clip is. Taking it would file a stranger's video on this row's
+ point, which is a wrong statement where a missing one is only incomplete — and the two
+ screens with somebody in front of them list it instead.
+ A row behind a login wall says the next move rather than the platform's own wording,
+ which is a tombstone nobody can act on: no browser picked in Settings, one picked that
+ is not signed in to that site, or Windows refusing to hand over a Chromium cookie store
+ at all — three different instructions, not one sentence.
+ The two still differ on what happens when nothing matches, because their contents do:
+ a post carrying no picture holds no proof and is a row to do by hand, while the
+ material takes a still photographed on the spot as readily as a clip.
+ - **A hundred rows a press**, against five hundred for the press above, and the door says
+ how many are left over: a cap that only refuses reads as a breakdown where the same cap
+ naming the remainder reads as the queue it is.
+ - **Atomic per row, not over the batch** — the opposite of the press above and for the
+ opposite reason. Failing at row 47 is no reason to hand back the 46 that worked, so the
+ files are fetched into a staging directory first and nothing enters the case until they
+ are held. A row behind a login wall ends as the words **needs a login** rather than as a
+ prompt nobody can answer a hundred times; naming a browser in Settings is what unblocks
+ it, and the next press walks through on its own.
+ - **It runs as a job with a bar and a stop**, because two minutes of downloads is
+ something to watch rather than wait out. Counted in rows, not in bytes: a row is the
+ unit this road is atomic in, and how far down the binder it has got is what the analyst
+ is actually watching. Stopping keeps every row it finished and leaves nothing of the
+ row in flight: that row's bytes are still outside the case. When it ends the screen
+ **says so** — past tense, each row carrying what it turned out to be rather than what
+ it was going to be, and a way out called *Done* rather than a Close that reads as
+ walking away. It also names the one loose end: a proof composed of several pictures has
+ no export until somebody opens it.
+ - **Pressing twice is safe without the sheet remembering anything.** A proof is found by
+ **where it was published**, a media by the page it was downloaded from, a place by its
+ point — so a second press refreshes the point, the note and the name, and downloads
+ nothing. Identity is the address and never the name, because the name is a cell
+ somebody corrects: keyed on it, a corrected title built a second proof beside the first
+ and left the old one standing, which is the duplicate nobody notices since both look
+ right in the list. Corrected, the title now *moves* the proof, spec and export with it.
+ What the sheet keeps is the chips: each cell ends up pointing at what it produced.
+ - **One picture published about two places is one proof.** The binder's cross-border
+ shape — a strike written on two lines, one point per country, same video, same
+ published picture. Row by row that filed two exports of one image under two names and
+ fetched both files twice. Now the rows sharing a published address are one proof: the
+ first composes it, and the others add their point to the **material and to the proof
+ itself** — the published picture is what establishes both positions, and saying so is
+ the whole reason two lines were written about it. The composer's own coordinate field
+ goes on stating one point, and only the edges it wrote are reconciled by a later save:
+ an edge stated by another hand is a separate claim about the same file, so these stand.
+ The proof always `depicts`, whatever POV says, having been composed and recorded
+ nowhere. Two rows under one *name* at two different addresses are still refused: that
+ is a collision over one filename, not one proof. And a row that joins one that did not
+ build — a dead link, a login wall — **fails with that reason** rather than writing a
+ point onto nothing: reported as done, the second position of a cross-border strike
+ disappeared with no red line and no later press to take it again.
+- **The reading is handed over three ways.** The rows on screen as a CSV, the rows ticked as a
+ CSV, or the whole view **copied as a Markdown table** — which is what goes into a note, a
+ ticket or a message, and retyping twelve rows into the Notebook is where citing a sheet
+ stops. The Markdown carries a **quoted header** saying where it came from: the case, the
+ sheet, the filter that was on, the sort, how many rows of how many, and the hour. That is
+ the one thing a sheet plate would have carried and the only part worth keeping — twelve
+ rows pasted with no filter named are a sample presented as a set, and *12 of 468* read
+ without seeing why is worse than no number. A CSV is **written into the folder this case files sheets in** (Settings → Storage,
+ the case's own `exports/` until another is picked), the way a note's PDF and an analysis
+ plate are. Where it lands is named **in the export menu and changed from there** — sending
+ the analyst to Settings to file a table somewhere else was the one export in the app that
+ did that — and the sentence saying where it went carries a button that opens the folder,
+ because a folder nobody finds is a file exported twice. A download instead was the one
+ export nobody could find twice. Inside the case a re-export overwrites so the folder is
+ refreshed in one click; outside it nothing is ever overwritten, because those files are
+ the analyst's.
+- **A column naming other rows of the same sheet becomes real edges.** The binders wrote an
+ order of battle in a column called `Links with others` — a brigade listing its companies,
+ each company naming its brigade back — held together by a spreadsheet validation that
+ cannot survive a row moving, and in the real file it had already decayed to `#REF!`. Here
+ the cell keeps the **words**, because a file whose links read `r7f3a` is one the
+ collaborator opening it cannot follow, and the link is re-read from those words every
+ time: a name points at a row when exactly one other row spells it that way. A name that
+ reaches none, or two, is shown rather than guessed at — the same decay becomes a list of
+ what to fix. The row panel shows the other direction, **who points at this row**, derived
+ rather than kept in a second column that would drift. As a mode of the press it draws
+ `part-of` or `member-of` between the entities both rows are, and an order of battle lands
+ in the one press that makes its units: the modes run in the order their answers depend on
+ each other, so the edges see the subjects the same press just wrote. A row whose end is
+ outside the pass and not in the case yet is said so rather than invented.
+- **An answering column can give the case's answer rather than a yes or no.** `On map`
+ says *whether* the case knows the row's subject and nothing about what it knows, so the
+ coordinates and the parent unit went on being retyped into the column alongside. Two more
+ readings close that: the **point** the case holds for what one named column points at, and
+ **what it is joined to** — the far end of that entity's edges, one hop, written with the
+ column's own separator. The column is named rather than swept, since a sheet may point at
+ the case from a subject column and a place column both. Blank where the case has nothing
+ to say, and blank where two different points reach the same entity: choosing one would be
+ the silent merge the app refuses everywhere.
+- **A column of hours becomes dated statements, not a date field.** The binders do not hold
+ dates. They hold a *reasoning about* one across three or four columns: the hour that was
+ established, the hour that was estimated, and how it was worked out — "the author gave me
+ this time", "a private video shows 1:57", "between 2:00 and 2:10". Copied into one field
+ that is one number and three lost columns, and a Timeline fed that way is a Timeline
+ nobody believes. So each ticked row becomes a **Claim**: about what its subject cell
+ points at, carrying when, how sure, the reasoning, the place its own column names and the
+ sources its links are. A row with no established hour falls back to its estimate **one
+ rung lower in confidence** and the reasoning says which it was, because the binder kept
+ two columns for exactly that difference; a note reading *between 02:00 and 02:10* becomes
+ an interval. Two things are asked for rather than guessed, since guessing either moves
+ evidence in time: which **day** a column of bare clocks belongs to — the binder keeps it
+ in the sheet's title — and which **zone** it is written in, where local is the default and
+ is honest, because a column called `Local time` stamped `Z` is off by however far away the
+ event happened. Pressing again updates the statements rather than filing them twice, and
+ the hours ride in the same press as the subjects they are about.
+- **Rows lined up on a sync point inherit an absolute time from it.** A **sync point** is
+ one moment visible in several rows — a launch, an impact, a shot heard in every video —
+ and each row carries its offset against it: `-00:01:50`, `00:04:04`, which is exactly
+ what the binder's `start synchro` column held. Their **relative order is usable straight
+ away**, before anybody knows what time anything happened; the moment the shot itself is
+ dated, every one of them has a time to the second. Sync points are named and dated on the
+ sheet rather than on the columns, because one serves several of them and a time restated
+ per column will disagree with itself — and a sheet holds more than one, since the binder
+ already had a start and an end. They are reached from the column that uses one, which is
+ the only place anybody wants them. Staying undated is the normal state and costs only the
+ absolute times. What it produces is a **statement**
+ whose reasoning names the moment, never a timestamp written into a cell: that is an
+ inference, and presenting one as an observation is the thing the whole ontology is built
+ to prevent.
+- **A row can carry case files of its own.** The proof of an hour — the screenshot of the
+ message, the emailed reply — sat in two whole tabs of pasted images beside the work it was
+ the proof of, because a spreadsheet has nowhere to put it. Attached to the row from its
+ panel and **referenced, never copied**: the file is already the case's, so nothing new is
+ filed, no artifact is owned twice and the bundle does not drift. The sheet mentions it, so
+ it is reachable from the file's own side too. A row holding links can also ask **what the
+ library already downloaded from them** — matched on the source URL the download recorded,
+ never on a title resembling a filename — which is the two halves of one page that nothing
+ had ever joined.
+- **The question is a search, a chip per clause and a count** — *23 of 1 204*, the
+ denominator being the whole sheet. What the search found is **marked in the cells**, since
+ on a fourteen-column binder the match is often in a column that is off screen. A column is
+ asked four things, and they hold together: which values, whether it is empty or filled, a
+ word it must or must not hold, and — on a column that says it holds numbers or dates — a
+ **bound at either end**, which is the question a list of values cannot ask: *before this
+ date*, *under five kilometres*. The value menu **pages** rather than giving up: it lists the
+ commonest, says how many there are in all, and a box narrows against the whole column, so a
+ column of a hundred and twenty cities is walkable instead of answering "too many to list".
+- **A cell can point at an entity, where that means anything.** The `@` is drawn on a text
+ column and on a point — a yes/no cell, a date, a number and a value out of a vocabulary are
+ not things the case holds an entity for, and an `@` on them read as an offer to point a
+ status at a person. A cell that already carries a link keeps its `@` whatever its column
+ became. It opens the picker, which leads with what the case holds — a count per type — because the analyst usually does not
+ know the label: the cell says `3rd Bde` and the case holds `3rd Separate Brigade`. A
+ bare search bar only works when the answer is already known. Narrowing by type is one
+ click and says how big each answer is first; the arrows and Enter pick without the
+ mouse. The list is **paged, not capped**: it says how many of the matching set are on
+ screen and loads the rest on a press, and the ordering — name or newest, either way —
+ is applied to the whole matching set on the server, because sorting the forty rows
+ already loaded answers a different question. The link is recorded beside the table and
+ the cell takes the entity's name when it was empty, so the CSV still says in words
+ what the graph says in an edge. Each of those becomes a `mentions` edge on save, and
+ clicking the mark opens that entity's Details. **A link does not outlive what it points
+ at.** No sheet shows or saves a link the case cannot answer for: the rule runs on every
+ read and every save, so a sidecar carried in from another case or written against older
+ ids heals itself rather than showing a cell that reads as work already done. Deleting an
+ entity clears it eagerly in every sheet of the case, and an open grid drops it as soon as
+ it hears the case changed, saying how many went — otherwise the next save would write the
+ dead id back over the file the delete had just cleared. The words in the cell stay, since
+ the file has to say in words what the graph said in an edge. Restoring from the trash
+ brings the entity back, not the link.
+- Rows are ticked in the gutter, painted from the annotation palette, and deleted
+ together. Amber is not in that palette: it means selection, so a tick marks the
+ gutter rather than washing the row and hiding the colour just painted on it.
+- **The grid draws its own scrollbars**, one per axis, in a strip beside the table
+ rather than over it. The app's chrome is thin everywhere, which is right for a
+ panel hinting there is more below and wrong here, where the bar is how a wide
+ table is crossed; and on Linux the native ones are overlays that fade out. Drag
+ the thumb, or click the track to jump a panel. The tick column, the row's key and
+ the column kept in view stay put while the table scrolls sideways.
+- Only the rows on screen are in the DOM, so a sheet of twenty thousand scrolls. Row
+ height is fixed: a cell holding sentences shows one line and opens into a box that
+ grows.
+
## Notebook
The Notebook places a GitHub-flavored Markdown editor beside its preview. The
diff --git a/extension/manifest.json b/extension/manifest.json
index 31bd11f..18dad25 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Azimut Capture",
- "version": "0.2.5",
+ "version": "0.2.9",
"description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],
diff --git a/extension/popup.js b/extension/popup.js
index ba06e31..d6cf162 100644
--- a/extension/popup.js
+++ b/extension/popup.js
@@ -119,8 +119,11 @@ async function init() {
$("state-nomap").hidden = false;
if (tab.title) $("bm-title").value = tab.title;
const paired = await loadCases($("bm-case"), stored);
+ // Azimut down or unpaired: loadCases has already said so above. Leaving the
+ // button live would answer that message with a click that does nothing, and
+ // the analyst reads it as the extension being broken.
+ $("save-bookmark").disabled = !paired;
$("save-bookmark").addEventListener("click", async () => {
- if (!paired) return;
$("save-bookmark").disabled = true;
const body = new FormData();
body.append("url", tab.url);
@@ -195,8 +198,10 @@ async function init() {
}
});
+ // Same reason as Save place just above: unreachable is shown, not swallowed.
+ $("capture-area").disabled = !paired;
+
$("capture-area").addEventListener("click", async () => {
- if (!paired) return;
// half a coordinate would 422 server-side; catch it where it's fixable
if ((numOrNull("lat") === null) !== (numOrNull("lon") === null)) {
status("Latitude and longitude go together. Fill both or neither.", "error");
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 2e52640..78dcc3a 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -73,6 +73,17 @@ const settings = {
month: '2026-07',
};
+// The offline gazetteer, cut down to what a spec needs: two cities that share a
+// prefix, so ranking is visible, and one street only the geocoder knows about.
+const GAZETTEER = [
+ { name: 'Kramatorsk', region: 'Donetsk', country: 'ua', country_name: 'Ukraine', lat: 48.7311, lon: 37.5678, population: 147145 },
+ { name: 'Kraków', region: 'Lesser Poland', country: 'pl', country_name: 'Poland', lat: 50.0614, lon: 19.9366, population: 755050 },
+];
+
+const GEOCODED = [
+ { lat: 48.8534, lon: 37.6067, display_name: 'Kramatorska Street, Sloviansk, Donetsk Oblast, Ukraine', kind: 'road' },
+];
+
// A workspace that is present and nobody else's, so the app runs instead of
// showing the stopped screen (GET /settings/workspace), and no folder in it is
// waiting to become a case (GET /workspace/folders).
@@ -609,6 +620,9 @@ export async function installAppFixture(page, options = {}) {
...settings,
export_dirs: { ...settings.export_dirs, ...(options.exportDirs ?? {}) },
};
+ // What the search bar asked for, and in which layer: a spec has to be able to
+ // prove the geocoder was left alone while the analyst was still typing.
+ const geoQueries = { suggest: [], places: [] };
const settingsWrites = [];
const folderWrites = [];
const exportWrites = [];
@@ -664,6 +678,52 @@ export async function installAppFixture(page, options = {}) {
const uploads = [];
const pastes = [];
const revealed = [];
+ const mediaDownloadWrites = [];
+
+ /**
+ * The sheets this case holds, in memory, behaving the way the engine does.
+ *
+ * Enough of the real thing for the grid to be exercised for real: a stamp handed out
+ * by every read and checked by every save, the sidecar written by its own route
+ * without touching the table, and the key column filled in on create. `sheetStamp`
+ * moves on its own when a test wants to play the spreadsheet that edited the file
+ * underneath.
+ */
+ const fixtureSheets = new Map();
+ const sheetWrites = [];
+ let sheetTick = 1000;
+ const nextStamp = () => `${(sheetTick += 1)}-70`;
+ const makeSheet = (title, columns, rows = [], meta = null) => {
+ const id = `sheet-${fixtureSheets.size + 1}`;
+ const held = {
+ id,
+ title,
+ path: `sheets/${title}.csv`,
+ columns: ['id', ...columns],
+ rows: rows.map((row, at) => [`r${at + 1}`, ...row]),
+ // A sheet may arrive with a sidecar: the roles are what make a column offer a
+ // vocabulary, and a spec about that list cannot set one up through the panel.
+ meta: { version: 5, ...(meta ?? {}) },
+ stamp: nextStamp(),
+ };
+ fixtureSheets.set(id, held);
+ return held;
+ };
+ const sheetPayload = (held) => ({
+ id: held.id,
+ title: held.title,
+ path: held.path,
+ columns: [...held.columns],
+ rows: held.rows.map((row) => [...row]),
+ meta: structuredClone(held.meta),
+ stamp: held.stamp,
+ assigned: false,
+ dropped_roles: [],
+ pieces: {},
+ });
+ for (const [title, columns, rows, meta] of options.sheets ?? []) {
+ makeSheet(title, columns, rows, meta);
+ }
const timelineEntity = (id) => fixtureCatalog.find((entity) => entity.id === id)
?? fixtureChains[id]?.entity
@@ -1534,6 +1594,18 @@ export async function installAppFixture(page, options = {}) {
if (!result.duplicate && result.entity) fixtureCatalog.push(result.entity);
return json(route, result);
}
+ if (
+ options.mediaDownloadJob &&
+ caseId &&
+ path === `/api/cases/${caseId}/media/download` &&
+ request.method() === 'POST'
+ ) {
+ mediaDownloadWrites.push(request.postDataJSON());
+ return json(route, { job_id: 'media-download-job' });
+ }
+ if (options.mediaDownloadJob && path === '/api/jobs/media-download-job') {
+ return json(route, options.mediaDownloadJob);
+ }
if (path === `/api/cases/${CASE_ID}/media/page`) {
return json(route, {
items: fixtureMedia,
@@ -1605,7 +1677,81 @@ export async function installAppFixture(page, options = {}) {
if (path === `/api/cases/${CASE_ID}/proofs` && request.method() === 'POST') {
const payload = request.postDataJSON();
proofSaves.push(payload);
- return json(route, { name: 'browser-proof', png: 'proofs/browser-proof.png' });
+ // The title comes back the way the backend answers, canonicalised: the
+ // composer writes it straight into the header, so dropping it here left
+ // the saved document holding a title the composer never gave it.
+ return json(route, {
+ name: 'browser-proof',
+ title: payload.title,
+ png: 'proofs/browser-proof.png',
+ });
+ }
+
+ if (path === `/api/cases/${caseId}/sheets` && request.method() === 'GET') {
+ return json(route, {
+ sheets: [...fixtureSheets.values()].map((held) => ({
+ id: held.id,
+ title: held.title,
+ rows: held.rows.length,
+ columns: held.columns.length,
+ })),
+ });
+ }
+ if (path === `/api/cases/${caseId}/sheets` && request.method() === 'POST') {
+ const body = request.postDataJSON();
+ const made = makeSheet(body.title, body.columns ?? ['Subject', 'Status', 'Notes']);
+ return json(route, { id: made.id, label: made.title, type: 'sheet', attrs: { path: made.path } });
+ }
+ const sheetMatch = path.match(new RegExp(`^/api/cases/${caseId}/sheets/([^/]+)(/meta|/stamp)?$`));
+ if (sheetMatch && fixtureSheets.has(sheetMatch[1])) {
+ const held = fixtureSheets.get(sheetMatch[1]);
+ if (sheetMatch[2] === '/stamp') return json(route, { stamp: held.stamp });
+ if (request.method() === 'GET') return json(route, sheetPayload(held));
+ const body = request.postDataJSON();
+ // The sidecar's own route: it never touches the table, so it never moves the stamp.
+ if (sheetMatch[2] === '/meta') {
+ held.meta = body.meta ?? {};
+ sheetWrites.push({ id: held.id, kind: 'meta' });
+ return json(route, { status: 'saved', meta: structuredClone(held.meta) });
+ }
+ if (body.stamp !== undefined && body.stamp !== held.stamp) {
+ return json(route, { detail: 'this file changed on disk since it was opened' }, 409);
+ }
+ held.columns = body.columns;
+ held.rows = body.rows;
+ held.meta = body.meta ?? {};
+ held.stamp = nextStamp();
+ sheetWrites.push({ id: held.id, kind: 'table', rows: body.rows.length });
+ return json(route, { status: 'saved', ...sheetPayload(held) });
+ }
+
+ // The search bar's two layers. The offline one answers coordinates and a
+ // handful of cities; the geocoder answers streets, and only ever late.
+ if (path === '/api/geo/suggest') {
+ const q = url.searchParams.get('q') ?? '';
+ geoQueries.suggest.push(q);
+ const decimal = /^\s*(-?\d{1,3}(?:\.\d+)?)\s*,\s*(-?\d{1,3}(?:\.\d+)?)\s*$/.exec(q);
+ const cities = decimal
+ ? []
+ : GAZETTEER.filter((city) => city.name.toLowerCase().startsWith(q.trim().toLowerCase()));
+ return json(route, {
+ coords: decimal ? { lat: Number(decimal[1]), lon: Number(decimal[2]) } : null,
+ cities,
+ attribution: cities.length ? '© GeoNames (CC BY 4.0)' : null,
+ });
+ }
+ if (path === '/api/geo/places') {
+ const q = url.searchParams.get('q') ?? '';
+ geoQueries.places.push(q);
+ const places = GEOCODED.filter((place) =>
+ place.display_name.toLowerCase().includes(q.trim().toLowerCase())
+ );
+ return json(route, {
+ places,
+ busy: false,
+ throttled: false,
+ attribution: places.length ? '© OpenStreetMap contributors (Nominatim)' : null,
+ });
}
unexpected.push(`${request.method()} ${path}`);
@@ -1626,8 +1772,19 @@ export async function installAppFixture(page, options = {}) {
uploads,
pastes,
revealed,
+ mediaDownloadWrites,
+ sheetWrites,
+ /** Play the spreadsheet that edited the CSV underneath the grid. */
+ moveSheetOnDisk: (id, change = {}) => {
+ const held = fixtureSheets.get(id);
+ Object.assign(held, change);
+ held.stamp = nextStamp();
+ return held.stamp;
+ },
+ sheetOnDisk: (id) => fixtureSheets.get(id),
trashWrites,
bundleCalls,
+ geoQueries,
settingsWrites,
folderWrites,
exportWrites,
diff --git a/frontend/e2e/board.spec.js b/frontend/e2e/board.spec.js
index 718e5ef..27acbcf 100644
--- a/frontend/e2e/board.spec.js
+++ b/frontend/e2e/board.spec.js
@@ -84,12 +84,18 @@ async function ask(page, question) {
.click();
}
-/** The identity cell, excluding the action cell whose accessible name repeats it. */
+/**
+ * The identity cell, which is the one that opens Details.
+ *
+ * Not simply the first cell: the tick box sits in front of it and swallows the click
+ * that lands on it, which is the whole point of a selection column. Excluding the
+ * action cell too, whose accessible name repeats the entity's.
+ */
function entityCell(page, name) {
return page
.locator('tbody tr')
.filter({ has: page.locator('.name', { hasText: name }) })
- .locator('td')
+ .locator('td:not(.pick)')
.first();
}
@@ -415,8 +421,9 @@ test('keeps both readings when relation endpoints share a type', async ({ page }
test('sorts on a heading, and reverses on a second click', async ({ page }) => {
await openBoard(page);
+ // The cell after the tick box, rather than the first one, which the tick box is.
const names = async () =>
- (await page.locator('tbody tr td:first-child').allInnerTexts()).map((t) => t.trim());
+ (await page.locator('tbody tr td.pick + td').allInnerTexts()).map((t) => t.trim());
await page.getByRole('button', { name: 'Name' }).click();
@@ -442,7 +449,7 @@ test('sorts by type too, so a mixed case can be read a family at a time', async
await page.getByRole('button', { name: 'Type' }).click();
- expect(await page.locator('tbody tr td:nth-child(2)').allInnerTexts()).toEqual([
+ expect(await page.locator('tbody tr td.pick + td + td').allInnerTexts()).toEqual([
'Bookmark', 'Media', 'Place',
]);
});
@@ -659,7 +666,7 @@ test('draws a document as a document, never as a photograph', async ({ page }) =
await openBoard(page, { catalog: [catalog[0], plan] });
await expect(page.locator('tbody tr')).toHaveCount(2);
- const icons = await page.locator('tbody tr td:first-child svg path').evaluateAll((nodes) =>
+ const icons = await page.locator('tbody tr td.pick + td svg path').evaluateAll((nodes) =>
nodes.map((node) => node.getAttribute('d'))
);
diff --git a/frontend/e2e/graph.spec.js b/frontend/e2e/graph.spec.js
index 3347873..2a25ceb 100644
--- a/frontend/e2e/graph.spec.js
+++ b/frontend/e2e/graph.spec.js
@@ -1895,7 +1895,13 @@ test('folds and unfolds from the canvas, where the switch is', async ({ page })
await expect(page.getByText('6 of 7')).toBeVisible();
await expect(page.getByRole('button', { name: '1 folded' })).toBeVisible();
- await page.mouse.dblclick(at.x, at.y);
+ // Found again rather than clicked at the same pixel. Folding rebuilds the drawing —
+ // Konva throws its layer away and makes a new one — and re-runs the arrangement over
+ // what is left, so the count in the toolbar can be right while the node is neither
+ // where it was nor yet listening. Asking for it back waits for both.
+ const back = await nodeAt(page, 'harbourwatch');
+ await page.getByLabel('Find a node').fill('');
+ await page.mouse.dblclick(back.x, back.y);
await expect(page.getByText('7 of 7')).toBeVisible();
await expect(page.getByRole('button', { name: /folded/ })).toHaveCount(0);
});
diff --git a/frontend/e2e/media-download.spec.js b/frontend/e2e/media-download.spec.js
new file mode 100644
index 0000000..a805be9
--- /dev/null
+++ b/frontend/e2e/media-download.spec.js
@@ -0,0 +1,35 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+test('explains when a large video must be saved from Telegram', async ({ page }) => {
+ const target = 'https://t.me/example_channel/104333';
+ const fixture = await installAppFixture(page, {
+ mediaDownloadJob: {
+ id: 'media-download-job',
+ kind: 'download',
+ status: 'done',
+ progress: {},
+ result: { telegram_only: true },
+ },
+ });
+
+ await page.goto('/#media');
+ await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();
+ await page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)').fill(target);
+ await page.getByRole('button', { name: 'Download', exact: true }).click();
+
+ const dialog = page.getByRole('dialog', { name: 'This video needs Telegram' });
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toContainText('Save it in Telegram, then import the file here.');
+ await expect(dialog.getByRole('link', { name: 'Open in Telegram' }))
+ .toHaveAttribute('href', target);
+ await expect(dialog.getByRole('link', { name: 'Open in Telegram' }))
+ .toHaveAttribute('target', '_blank');
+ expect(fixture.mediaDownloadWrites).toEqual([{
+ url: target,
+ index: null,
+ title: null,
+ use_cookies: false,
+ }]);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.js
index 2214083..b475a10 100644
--- a/frontend/e2e/proof-canvas.spec.js
+++ b/frontend/e2e/proof-canvas.spec.js
@@ -98,6 +98,9 @@ test('a picked colour becomes the default for the next drawn shape', async ({ pa
await expect.poll(() => fixture.proofSaves.length).toBe(1);
const shapes = fixture.proofSaves[0].spec.shapes;
expect(shapes[1].color).toBe('#40c4ff');
+ // …and the first box keeps the colour it was drawn with: a pick made with a
+ // drawing tool in hand sets the next shape, never repaints the last one.
+ expect(shapes[0].color).toBe('#ff5252');
fixture.expectNoUnexpectedRequests();
});
@@ -132,6 +135,7 @@ test('a picked stroke width becomes the default for the next drawn shape', async
await expect.poll(() => fixture.proofSaves.length).toBe(1);
const shapes = fixture.proofSaves[0].spec.shapes;
expect(shapes[1].strokeWidth).toBe(11);
+ expect(shapes[0].strokeWidth).toBe(4);
fixture.expectNoUnexpectedRequests();
});
@@ -335,3 +339,728 @@ test('leaving the window hands Ctrl+V back to the system clipboard', async ({ pa
await expect(page.locator('.shape-row')).toHaveCount(1); // the shape was not duplicated
fixture.expectNoUnexpectedRequests();
});
+
+// Konva ends a corner-resize on a window mouseup and on nothing else. A release
+// the page never sees — the button let go outside the window, the tab alt-tabbed
+// away mid-drag — used to leave the resize running: the panel kept growing under
+// a pointer with no button held, and the scale never reached the document, so the
+// drawn panel, its selection frame and the sidebar percentage all disagreed.
+test('a resize whose release the window never sees still lands, and stops there', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await page.locator('.panel-thumb').click();
+ await expect(page.locator('.panel-row')).toHaveClass(/selected/);
+ await expect(page.locator('.scale-val')).toHaveText('100%');
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+
+ // The selection frame is drawn on the canvas, so its corner has no DOM handle
+ // to click; ask the stage where it put it.
+ const anchor = await page.evaluate(() => {
+ const tr = window.Konva.stages[0].find('Transformer')[0];
+ return { x: tr.x() + tr.width(), y: tr.y() + tr.height() };
+ });
+ const canvas = await page.locator('.konva canvas').first().boundingBox();
+ const ax = canvas.x + anchor.x;
+ const ay = canvas.y + anchor.y;
+
+ await page.mouse.move(ax, ay);
+ await page.mouse.down();
+ await page.mouse.move(ax + 60, ay + 40, { steps: 8 });
+ await page.evaluate(() => window.dispatchEvent(new Event('blur'))); // the release that never arrives
+
+ await expect(page.locator('.scale-val')).not.toHaveText('100%');
+ const committed = await page.locator('.scale-val').innerText();
+
+ // The pointer wanders on with no button held. Nothing may follow it.
+ await page.mouse.move(ax + 240, ay + 170, { steps: 10 });
+ await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 100)));
+ await expect(page.locator('.scale-val')).toHaveText(committed);
+
+ await page.mouse.up();
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const saved = fixture.proofSaves[0].spec.panels[0];
+ expect(`${Math.round(saved.scale * 100)}%`).toBe(committed);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a stroke started inside a shape draws, and leaves that shape where it was', 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 + Math.min(180, box.height / 3);
+
+ // A box wide enough that the next gesture starts well inside it.
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(cx - 70, cy - 45);
+ await page.mouse.down();
+ await page.mouse.move(cx + 70, cy + 45, { 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 drawnBox = fixture.proofSaves[0].spec.shapes[0];
+
+ // Konva fills a shape's hit canvas whether or not the shape has a fill, so
+ // this press lands on the box. With a line in hand it must draw anyway.
+ await page.getByTitle('Line (l)').click();
+ await page.mouse.move(cx - 40, cy - 20);
+ await page.mouse.down();
+ await page.mouse.move(cx + 40, cy + 20, { steps: 8 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ const shapes = fixture.proofSaves[1].spec.shapes;
+ expect(shapes[1].kind).toBe('line');
+ expect(shapes[0]).toEqual(drawnBox); // the box neither moved nor resized
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a fill is opt-in, rides the shape colour and survives the save', 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 + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+
+ // Drawn before touching the control: hollow, like every shape starts.
+ await page.mouse.move(cx - 70, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx - 12, cy + 10, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ await page.getByTitle('Fill', { exact: true }).click();
+ await page.getByLabel('fill opacity').fill('40');
+
+ await page.mouse.move(cx + 12, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx + 70, cy + 10, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const shapes = fixture.proofSaves[0].spec.shapes;
+ expect(shapes[0].fillOpacity).toBeUndefined();
+ expect(shapes[1].fillOpacity).toBe(0.4);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the fill control is out for the kinds that cannot hold one', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await page.getByTitle('Ellipse (e)').click();
+ await expect(page.getByTitle('Fill', { exact: true })).toBeVisible();
+ await page.getByTitle('Arrow (a)').click();
+ await expect(page.getByTitle('Fill', { exact: true })).toBeHidden();
+ fixture.expectNoUnexpectedRequests();
+});
+
+/** Two boxes side by side on the panel, drawn with the Box tool. */
+async function drawTwoBoxes(page) {
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(cx - 80, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx - 20, cy + 10, { steps: 6 });
+ await page.mouse.up();
+ await page.mouse.move(cx + 20, cy - 40);
+ await page.mouse.down();
+ await page.mouse.move(cx + 80, cy + 10, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+ await page.getByTitle('Select / move (v)').click();
+ return { cx, cy };
+}
+
+test('shift-click picks a second annotation, and both take one colour', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ await drawTwoBoxes(page);
+
+ const rows = page.locator('.shape-row');
+ await rows.nth(0).click();
+ await rows.nth(1).click({ modifiers: ['Shift'] });
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+
+ await page.getByTitle('Annotation colour').click();
+ await page.getByLabel('color #40c4ff').click();
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const shapes = fixture.proofSaves[0].spec.shapes;
+ expect(shapes.map((s) => s.color)).toEqual(['#40c4ff', '#40c4ff']);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a marquee dragged over the panel picks what it touches, and Delete takes them all', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const { cx, cy } = await drawTwoBoxes(page);
+
+ // Grid layout pins the panel, so a drag across it picks rather than moves.
+ // Start beside the left box, inside the panel, and sweep across both.
+ await page.mouse.move(cx - 110, cy - 30);
+ await page.mouse.down();
+ await page.mouse.move(cx + 110, cy + 5, { steps: 10 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+ await expect(page.locator('.panel-row')).not.toHaveClass(/selected/);
+
+ await page.keyboard.press('Delete');
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a marquee that touches nothing clears the selection', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const { cx, cy } = await drawTwoBoxes(page);
+
+ await page.locator('.shape-row').first().click();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+
+ await page.mouse.move(cx - 100, cy + 60);
+ await page.mouse.down();
+ await page.mouse.move(cx - 60, cy + 90, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('dragging one of several moves the whole family', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const { cx, cy } = await drawTwoBoxes(page);
+
+ const rows = page.locator('.shape-row');
+ await rows.nth(0).click();
+ await rows.nth(1).click({ modifiers: ['Shift'] });
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+
+ 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;
+
+ // Press inside the first box and drag: the second must travel the same way.
+ await page.mouse.move(cx - 50, cy - 15);
+ await page.mouse.down();
+ await page.mouse.move(cx - 50, cy + 25, { steps: 8 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(2);
+ const after = fixture.proofSaves[1].spec.shapes;
+ const moved = after.map((s, i) => s.y - before[i].y);
+ expect(moved[0]).toBeGreaterThan(1);
+ expect(moved[1]).toBeCloseTo(moved[0], 1);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('clicking one of several collapses to it, but dragging does not', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ const { cx, cy } = await drawTwoBoxes(page);
+
+ const rows = page.locator('.shape-row');
+ await rows.nth(0).click();
+ await rows.nth(1).click({ modifiers: ['Shift'] });
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+
+ // A press inside a picked box that turns into a drag keeps the family, so the
+ // whole of it travels; only a press that stays put narrows the selection.
+ await page.mouse.move(cx - 50, cy - 15);
+ await page.mouse.down();
+ await page.mouse.move(cx - 50, cy + 5, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(2);
+
+ // The drag rebuilds the document, and Konva redraws its hit canvas a frame
+ // behind the scene: a press landing inside that frame is tested against the
+ // canvas from before, so let the redraw land before clicking.
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+ await page.mouse.click(cx - 50, cy + 5);
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('stamps a symbol, keeps the tool in hand, and saves it', 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 + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Symbol (s)').click();
+ await page.getByRole('button', { name: 'Tank', exact: true }).click();
+
+ await page.mouse.click(cx - 60, cy);
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ // the stamp stays armed, so a second mark is a second click and nothing else
+ await page.mouse.click(cx + 60, cy);
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+ await expect(page.locator('.shape-row').first()).toContainText('Tank');
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ const stamped = fixture.proofSaves[0].spec.shapes.filter((s) => s.kind === 'icon');
+ expect(stamped).toHaveLength(2);
+ expect(stamped[0].name).toBe('tank');
+ expect(Number.isFinite(stamped[0].size)).toBe(true);
+ expect(Number.isFinite(stamped[0].x)).toBe(true);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a solid symbol takes a colour and offers no stroke width', async ({ page }) => {
+ await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ await page.getByTitle('Symbol (s)').click();
+ await page.getByRole('button', { name: 'Point', exact: true }).click();
+ // a silhouette has no outline, so the control goes away rather than lying
+ await expect(page.getByTitle('Stroke width')).toHaveCount(0);
+ await expect(page.getByTitle('Annotation colour')).toBeVisible();
+
+ await page.getByTitle('Symbol (s)').click();
+ await page.getByRole('button', { name: 'Vehicle', exact: true }).click();
+ await expect(page.getByTitle('Stroke width')).toBeVisible();
+});
+
+test('panels stay resizable and movable once a symbol tool exists', async ({ page }) => {
+ await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ // A reference to selKind above its declaration once threw inside the effect
+ // that wires the transformer, taking the panel handles and the row-move
+ // arrows down with it. Nothing in the unit suite could see that.
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+
+ await page.locator('.panel-thumb').click();
+ await expect(page.locator('.panel-row')).toHaveClass(/selected/);
+ await expect(page.locator('.konva canvas').first()).toBeVisible();
+
+ await page.getByTitle('Symbol (s)').click();
+ await page.getByRole('button', { name: 'Drone', exact: true }).click();
+ await page.getByTitle('Select / move (v)').click();
+ await page.locator('.panel-thumb').click();
+
+ expect(errors).toEqual([]);
+});
+
+// ---- gestures the composer runs itself, released where Konva cannot hear ----
+// Konva binds pointerup to its container and to nothing else, so letting go over
+// the annotations column — which touches the right edge of the canvas, and is
+// where the pointer lands whenever a stroke is drawn near a panel's right side —
+// never reached the handlers that settle a draft, a marquee or a pan.
+
+/** The size of the one committed annotation, read off the drawn node. */
+const drawnSize = (page) => page.evaluate(() => {
+ const node = window.Konva.stages[0].find('Rect').find((rect) => rect.id());
+ return node ? { w: Math.round(node.width()), h: Math.round(node.height()) } : null;
+});
+
+/** Marquee rectangles still on the ui layer, found by the fill only it uses. */
+const marqueeGhosts = (page) => page.evaluate(() => window.Konva.stages[0]
+ .find('Rect')
+ .filter((rect) => rect.fill() === 'rgba(232, 163, 61, 0.12)').length);
+
+const stagePos = (page) => page.evaluate(() => {
+ const stage = window.Konva.stages[0];
+ return { x: Math.round(stage.x()), y: Math.round(stage.y()) };
+});
+
+test('a stroke let go off the canvas lands, and stops following the pointer', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const side = await page.locator('aside.side').boundingBox();
+ const x = box.x + box.width / 2 - 40;
+ const y = box.y + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 90, y + 60, { steps: 6 });
+ await page.mouse.move(side.x + 20, y, { steps: 4 }); // over the side column
+ await page.mouse.up();
+
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ // The settle runs a frame after the release and the rebuild a frame after
+ // that, so let both land before reading the drawn node.
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+ const committed = await drawnSize(page);
+ expect(committed).not.toBeNull();
+
+ // The pointer wanders on with no button held. Nothing may follow it.
+ await page.mouse.move(x + 260, y + 190, { steps: 10 });
+ await page.mouse.move(x - 100, y + 30, { steps: 10 });
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ expect(await drawnSize(page)).toEqual(committed);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ expect(fixture.proofSaves[0].spec.shapes).toHaveLength(1);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a marquee let go off the canvas selects what it caught and leaves nothing behind', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const side = await page.locator('aside.side').boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(cx - 30, cy - 20);
+ await page.mouse.down();
+ await page.mouse.move(cx + 30, cy + 20, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ // The shape drawn a moment ago comes back into reach with the hand; Escape
+ // lets go of it, so what the rectangle below catches is the rectangle's own.
+ await page.getByTitle('Select / move (v)').click();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.shape-row.selected')).toHaveCount(0);
+
+ // A rectangle dragged over that annotation, released over the side column.
+ // Grid layout pins the panel, so a drag across it picks rather than moves.
+ await page.mouse.move(cx - 110, cy - 30);
+ await page.mouse.down();
+ await page.mouse.move(cx + 60, cy + 30, { steps: 8 });
+ await page.mouse.move(side.x + 20, cy, { steps: 4 });
+ await page.mouse.up();
+
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ expect(await marqueeGhosts(page)).toBe(0);
+
+ // The next press used to orphan the old rectangle on the ui layer, where
+ // nothing would ever destroy it.
+ await page.mouse.move(cx - 110, cy - 30);
+ await page.mouse.down();
+ await page.mouse.move(cx - 90, cy - 10, { steps: 4 });
+ await page.mouse.up();
+ expect(await marqueeGhosts(page)).toBe(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a pan let go off the canvas stops there', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const side = await page.locator('aside.side').boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + Math.min(180, box.height / 3);
+
+ await page.mouse.move(cx, cy);
+ await page.mouse.down({ button: 'middle' });
+ await page.mouse.move(cx + 70, cy + 40, { steps: 6 });
+ await page.mouse.move(side.x + 20, cy, { steps: 4 });
+ await page.mouse.up({ button: 'middle' });
+
+ const settled = await stagePos(page);
+ await page.mouse.move(cx - 150, cy + 120, { steps: 10 });
+ await page.mouse.move(cx + 200, cy - 60, { steps: 10 });
+ expect(await stagePos(page)).toEqual(settled);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the right button neither draws nor drops what is picked', 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 + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(cx - 30, cy - 20);
+ await page.mouse.down({ button: 'right' });
+ await page.mouse.move(cx + 40, cy + 30, { steps: 6 });
+ await page.mouse.up({ button: 'right' });
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+
+ // Same in Select: the drag used to clear the selection and open a marquee.
+ await page.mouse.move(cx - 30, cy - 20);
+ await page.mouse.down();
+ await page.mouse.move(cx + 40, cy + 30, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ await page.locator('.shape-row').click();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+
+ await page.mouse.move(cx, cy);
+ await page.mouse.down({ button: 'right' });
+ await page.mouse.move(cx + 30, cy + 20, { steps: 4 });
+ await page.mouse.up({ button: 'right' });
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ expect(await marqueeGhosts(page)).toBe(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Escape unwinds one level per press', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const x = box.x + box.width / 2 - 40;
+ const y = box.y + Math.min(180, box.height / 3);
+
+ // Mid-draft: the stroke goes and the pen stays, because cancelling a stroke
+ // is no reason to put the pen down.
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 60, y + 40, { steps: 4 });
+ await page.keyboard.press('Escape');
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+ await expect(page.getByTitle('Box (r)')).toHaveClass(/active/);
+
+ // Nothing left in hand: now the pen goes down.
+ await page.keyboard.press('Escape');
+ await expect(page.getByTitle('Select / move (v)')).toHaveClass(/active/);
+
+ // A pick that shows is its own rung, ahead of the tool.
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 60, y + 40, { steps: 4 });
+ await page.mouse.up();
+ await page.locator('.shape-row').click();
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.shape-row.selected')).toHaveCount(0);
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a row picked in the side column takes the hand back to Select', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const x = box.x + box.width / 2 - 40;
+ const y = box.y + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 60, y + 40, { steps: 4 });
+ await page.mouse.up();
+
+ // Drawn with the Box still in hand: no row lights up, because nothing on the
+ // canvas would answer to it.
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ await expect(page.locator('.shape-row.selected')).toHaveCount(0);
+
+ await page.locator('.shape-row').click();
+ await expect(page.getByTitle('Select / move (v)')).toHaveClass(/active/);
+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);
+ // and Delete now reaches it, which is what the lit row promises
+ await page.keyboard.press('Delete');
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+
+ // A panel row reads the same way.
+ await page.getByTitle('Box (r)').click();
+ await page.locator('.panel-thumb').click();
+ await expect(page.getByTitle('Select / move (v)')).toHaveClass(/active/);
+ await expect(page.locator('.panel-row')).toHaveClass(/selected/);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a placed label opens its editor on the spot, and holds two lines', 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 + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Text (t)').click();
+ await page.mouse.click(cx - 40, cy);
+ const editor = page.locator('textarea.text-edit');
+ await expect(editor).toBeFocused();
+
+ await page.keyboard.type('north');
+ await page.keyboard.press('Shift+Enter');
+ await page.keyboard.type('wall');
+ await page.keyboard.press('Enter');
+ await expect(editor).toHaveCount(0);
+
+ 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.text)).toEqual(['north\nwall']);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the room around the page pans with a drawing tool in hand', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const before = await stagePos(page);
+
+ // Same room, same drag as in Select: the press used to be lost entirely while
+ // the crosshair promised a stroke.
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height - 8);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2 + 90, box.y + box.height - 58, { steps: 6 });
+ await page.mouse.up();
+
+ const after = await stagePos(page);
+ expect(after.x).toBeGreaterThan(before.x);
+ expect(after.y).toBeLessThan(before.y);
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('undoing back to the saved document takes the unsaved badge with it', async ({ page }) => {
+ // The saved proof has to be findable in the catalog afterwards, or the
+ // composer rightly decides it was deleted out from under it and marks the
+ // document unsaved again.
+ const fixture = await installAppFixture(page, {
+ lookupEntities: { 'proofs/.meta/browser-proof.json': { id: 'proof-1' } },
+ });
+ await openProofWithPanel(page);
+
+ await page.getByRole('button', { name: 'Save proof', exact: true }).click();
+ await expect.poll(() => fixture.proofSaves.length).toBe(1);
+ await expect(page.getByText('unsaved')).toHaveCount(0);
+ // outlast the history capture debounce, so the save's own document is on the stack
+ await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 500)));
+
+ await drawBox(page);
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ await expect(page.getByText('unsaved')).toHaveCount(1);
+
+ await page.getByTitle('Undo (Ctrl+Z)').click();
+ await expect(page.locator('.shape-row')).toHaveCount(0);
+ await expect(page.getByText('unsaved')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a freehand stroke resizes from its handles, and its samples take the change', async ({ page }) => {
+ // It is the one kind with neither vertex handles nor a width to write a resize
+ // into, so the whole transform is folded into the samples themselves.
+ 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 + Math.min(180, box.height / 3);
+
+ await page.getByTitle('Freehand (d)').click();
+ await page.mouse.move(cx - 60, cy - 20);
+ await page.mouse.down();
+ await page.mouse.move(cx - 20, cy + 10, { steps: 6 });
+ await page.mouse.move(cx + 30, cy - 10, { steps: 6 });
+ await page.mouse.up();
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ await page.locator('.shape-row').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[0];
+ expect(before.kind).toBe('freehand');
+
+ // The frame is drawn on the canvas, so ask the stage where it put its corner.
+ await page.evaluate(() => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+ const anchor = 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 + anchor.x, box.y + anchor.y);
+ await page.mouse.down();
+ await page.mouse.move(box.x + anchor.x + 70, box.y + anchor.y + 50, { 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 after = fixture.proofSaves[1].spec.shapes[0];
+ const span = (points, axis) => {
+ const values = points.filter((_, i) => i % 2 === axis);
+ return Math.max(...values) - Math.min(...values);
+ };
+ expect(span(after.points, 0)).toBeGreaterThan(span(before.points, 0));
+ expect(span(after.points, 1)).toBeGreaterThan(span(before.points, 1));
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a finished curve leaves the tool in hand', 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 + Math.min(180, box.height / 3);
+ const curve = page.getByTitle(/^Curve/);
+
+ // Konva calls any two clicks inside its 400 ms window a double-click, whatever
+ // the distance between them, so vertices are dropped at a human's pace here.
+ const vertex = async (x, y) => {
+ await page.mouse.click(x, y);
+ await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 450)));
+ };
+
+ await curve.click();
+ await vertex(cx - 40, cy);
+ await vertex(cx, cy - 20);
+ await page.mouse.dblclick(cx + 40, cy);
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+ await expect(curve).toHaveClass(/active/);
+
+ // Three curves in a row is three drags, not three presses on `c` as well.
+ await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 450)));
+ await vertex(cx - 40, cy + 25);
+ await vertex(cx, cy + 10);
+ await page.mouse.dblclick(cx + 40, cy + 25);
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/satellite-search.spec.js b/frontend/e2e/satellite-search.spec.js
new file mode 100644
index 0000000..b14a828
--- /dev/null
+++ b/frontend/e2e/satellite-search.spec.js
@@ -0,0 +1,125 @@
+import { test, expect } from '@playwright/test';
+import { installAppFixture } from './app.fixture.js';
+
+const SAVED = [
+ {
+ id: 'p1',
+ kind: 'place',
+ title: 'Kramatorsk checkpoint',
+ lat: 48.74,
+ lon: 37.57,
+ notes: '',
+ fetched_at: '2026-07-20T09:12:04Z',
+ geo: { state: 'ok', country: 'Україна', country_code: 'ua', region: 'Donetsk' },
+ country_en: 'Ukraine',
+ continent: 'Europe',
+ folder: '',
+ },
+];
+
+const bar = (page) => page.getByRole('combobox', { name: 'Search a place or coordinates' });
+
+test('proposes cities from the first letters, without asking the geocoder', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('kr');
+ await expect(page.getByRole('option', { name: /Kramatorsk/ })).toBeVisible();
+ await expect(page.getByRole('option', { name: /Kraków/ })).toBeVisible();
+ await expect(page.getByText('Cities from GeoNames, CC BY 4.0')).toBeVisible();
+
+ // two letters is under the floor: the geocoder is not asked, however long we wait
+ await page.waitForTimeout(1200);
+ expect(fixture.geoQueries.places).toEqual([]);
+ expect(fixture.geoQueries.suggest).toContain('kr');
+});
+
+test('asks the geocoder once typing stops, and puts its matches last', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('kramatorsk');
+ // the city is there straight away; the street arrives after the pause
+ await expect(page.getByRole('option', { name: /Kramatorsk Donetsk/ })).toBeVisible();
+ await expect(page.getByRole('option', { name: /Kramatorska Street/ })).toBeVisible();
+
+ const groups = await page.locator('#sat-suggestions .head').allTextContents();
+ expect(groups).toEqual(['Cities', 'Places']);
+ expect(fixture.geoQueries.places).toEqual(['kramatorsk']);
+});
+
+test('offers saved work in this case above anything looked up', async ({ page }) => {
+ const fixture = await installAppFixture(page, { savedIndex: SAVED });
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('kram');
+ await expect(page.locator('#sat-suggestions .head').first()).toHaveText('Saved in this case');
+ await expect(page.getByRole('option', { name: /Kramatorsk checkpoint/ })).toBeVisible();
+
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('flies the map to the row the arrows land on', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+ await expect(page.locator('.hud-coords')).toContainText('48.85'); // the home view, Paris
+
+ await bar(page).fill('kramatorsk');
+ await expect(page.getByRole('option', { name: /Kramatorsk Donetsk/ })).toBeVisible();
+ await bar(page).press('ArrowDown');
+ await bar(page).press('Enter');
+
+ await expect(page.locator('.hud-coords')).toContainText('48.73');
+ await expect(page.locator('.hud-coords')).toContainText('37.56');
+ await expect(page.locator('#sat-suggestions')).toHaveCount(0);
+});
+
+test('recognises coordinates as they are typed', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('50.4501, 30.5234');
+ await expect(page.locator('#sat-suggestions .head').first()).toHaveText('Coordinates');
+ await bar(page).press('ArrowDown');
+ await bar(page).press('Enter');
+ await expect(page.locator('.hud-coords')).toContainText('50.45');
+
+ // a coordinate is nobody's place name: the geocoder is never troubled with one
+ expect(fixture.geoQueries.places).toEqual([]);
+});
+
+test('remembers where it was sent, and offers it back on an empty bar', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('kramatorsk');
+ await page.getByRole('option', { name: /Kramatorsk Donetsk/ }).first().click();
+ await expect(page.locator('.hud-coords')).toContainText('48.73');
+
+ await bar(page).fill('');
+ await bar(page).click();
+ await expect(page.locator('#sat-suggestions .head').first()).toHaveText('Recent');
+ await expect(page.getByRole('option', { name: /Kramatorsk/ })).toBeVisible();
+});
+
+test('closes on Escape and on a press elsewhere', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+
+ await bar(page).fill('kram');
+ await expect(page.locator('#sat-suggestions')).toBeVisible();
+ await bar(page).press('Escape');
+ await expect(page.locator('#sat-suggestions')).toHaveCount(0);
+
+ await bar(page).click();
+ await expect(page.locator('#sat-suggestions')).toBeVisible();
+ await page.getByRole('heading', { name: 'Satellite' }).click();
+ await expect(page.locator('#sat-suggestions')).toHaveCount(0);
+});
diff --git a/frontend/e2e/settings.spec.js b/frontend/e2e/settings.spec.js
index a9f0ab7..b7c76d9 100644
--- a/frontend/e2e/settings.spec.js
+++ b/frontend/e2e/settings.spec.js
@@ -103,3 +103,58 @@ test('chooses a real export folder and uses it from Media Library', async ({ pag
await expect(page.getByText('panel.svg copied to Field reports')).toBeVisible();
fixture.expectNoUnexpectedRequests();
});
+
+// The template preview hangs its commits off transformend, the same way the
+// composer does, so a release the page never sees left the signature resizing
+// under a bare pointer and never wrote the size back into the template.
+test('a signature resize whose release the window never sees still lands, and stops there', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#settings');
+ const rail = page.getByRole('navigation', { name: 'Settings sections' });
+ await rail.getByRole('button', { name: 'Templates' }).click();
+ await page.getByRole('button', { name: 'New proof template' }).click();
+
+ await page.getByLabel('Stamp the logo').check();
+ const size = page.getByRole('slider', { name: 'Size' });
+ const before = await size.inputValue();
+ const canvas = page.locator('.preview-frame canvas').first();
+ await expect(canvas).toBeVisible();
+
+ // Select the logo, then take its frame's corner. Both live on the canvas,
+ // where there is no DOM handle to aim at; ask the stage where it put them.
+ const preview = () => page.evaluate(() => {
+ const stage = window.Konva.stages[window.Konva.stages.length - 1];
+ const k = stage.scaleX();
+ const tr = stage.find('Transformer')[0];
+ const logo = stage.find((n) => n.draggable())[0];
+ const r = logo.getClientRect({ relativeTo: stage });
+ return {
+ logo: { x: (r.x + r.width / 2) * k, y: (r.y + r.height / 2) * k },
+ anchor: tr ? { x: tr.x() + tr.width(), y: tr.y() + tr.height() } : null,
+ };
+ });
+
+ const box = await canvas.boundingBox();
+ const { logo } = await preview();
+ await page.mouse.click(box.x + logo.x, box.y + logo.y);
+ const { anchor } = await preview();
+ expect(anchor).not.toBeNull();
+
+ const ax = box.x + anchor.x;
+ const ay = box.y + anchor.y;
+ await page.mouse.move(ax, ay);
+ await page.mouse.down();
+ await page.mouse.move(ax + 14, ay + 9, { steps: 6 });
+ await page.evaluate(() => window.dispatchEvent(new Event('blur'))); // the release that never arrives
+
+ await expect(size).not.toHaveValue(before);
+ const committed = await size.inputValue();
+
+ // The pointer wanders on with no button held. Nothing may follow it.
+ await page.mouse.move(ax + 120, ay + 90, { steps: 10 });
+ await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 100)));
+ await expect(size).toHaveValue(committed);
+
+ await page.mouse.up();
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/sheet.spec.js b/frontend/e2e/sheet.spec.js
new file mode 100644
index 0000000..c649cb6
--- /dev/null
+++ b/frontend/e2e/sheet.spec.js
@@ -0,0 +1,232 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+/**
+ * The Case Sheet, in a real browser.
+ *
+ * The grid is the one tool here whose behaviour is mostly *gestures* — a cell entered on
+ * a keystroke, a selection pulled with the arrows, an autosave nobody pressed, a banner
+ * that appears because a file moved on disk. None of that is reachable from a unit test
+ * with a fake DOM: the render tests drive the component's own functions, so they prove
+ * the model and say nothing about whether typing into the screen reaches the file.
+ *
+ * So these run for real, and they are deliberately about the seams:
+ * the keyboard reaching the table, the autosave presenting the stamp it read, the
+ * sidecar going out on its own route, and the refusal an analyst meets when a
+ * spreadsheet has the same file open.
+ */
+
+const SHEETS = [
+ ['Candidates', ['Subject', 'Status', 'Notes'], [
+ ['Quai sud', 'To check', ''],
+ ['Pont nord', 'Seen', 'two frames'],
+ ['Rue basse', 'Ruled out', ''],
+ ]],
+];
+
+async function openSheet(page) {
+ await page.goto('/#sheet');
+ await expect(page.getByRole('heading', { name: 'Sheet', exact: true })).toBeVisible();
+ await expect(page.getByRole('grid', { name: 'Sheet rows' })).toBeVisible();
+}
+
+const cell = (page, row, column) => page.locator(`#sheet-cell-${row}-${column}`);
+
+/** Put the cursor in a cell and wait until the grid says so, before anything is typed.
+ * Under a loaded machine the click and the first keystroke can otherwise cross. */
+async function focusCell(page, row, column) {
+ const target = cell(page, row, column);
+ await target.click();
+ await expect(target).toHaveClass(/cursor/);
+ return target;
+}
+
+/** Type into the cell under the cursor and commit, waiting for the editor to exist so a
+ * slow mount cannot swallow the run. */
+async function typeInto(page, row, column, text) {
+ await focusCell(page, row, column);
+ await page.keyboard.press(text[0]);
+ await expect(cell(page, row, column).locator('textarea')).toBeVisible();
+ if (text.length > 1) await page.keyboard.type(text.slice(1));
+ await page.keyboard.press('Enter');
+}
+
+test('types into a cell and autosaves it, presenting the stamp it read', async ({ page }) => {
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ await typeInto(page, 0, 2, 'Seen');
+
+ // Nobody pressed save. The grid writes on its own, and what it writes is the table.
+ await expect.poll(() => fixture.sheetWrites.filter((write) => write.kind === 'table').length)
+ .toBeGreaterThan(0);
+ await expect(cell(page, 0, 2)).toContainText('Seen');
+ expect(fixture.sheetOnDisk('sheet-1').rows[0][2]).toBe('Seen');
+ await fixture.expectNoUnexpectedRequests();
+});
+
+test('Tab off the last cell grows the sheet', async ({ page }) => {
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ const before = fixture.sheetOnDisk('sheet-1').rows.length;
+ await focusCell(page, 2, 3);
+ await page.keyboard.press('Tab');
+ await page.keyboard.type('Pont vieux');
+ await page.keyboard.press('Enter');
+
+ await expect.poll(() => fixture.sheetOnDisk('sheet-1').rows.length).toBe(before + 1);
+});
+
+/**
+ * The vocabulary a column offers opens **downwards**, so on the last row of a short sheet
+ * it lands right across the empty line the grid ends on. Both lists are moved with a
+ * transform — a stacking context each — and the empty line, drawn last, simply painted on
+ * top: a click meant for a word added a row instead, and the word was never written.
+ */
+test('a word offered over the empty last line is the thing that is clicked', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ sheets: [['Candidates', ['Subject', 'Status'], [
+ ['Quai sud', ''],
+ ['Pont nord', ''],
+ ['Rue basse', ''],
+ ], { roles: { Status: { kind: 'choice', values: ['to check', 'seen', 'ruled out'] } } }]],
+ });
+ await openSheet(page);
+
+ const rowsBefore = fixture.sheetOnDisk('sheet-1').rows.length;
+ await focusCell(page, 2, 2);
+ await page.keyboard.press('Enter');
+ const offers = page.locator('.offers');
+ await expect(offers).toBeVisible();
+
+ // Whichever word happens to land over the empty line, taken by a click on the word.
+ const ghost = await page.locator('.rows.ghost .row').boundingBox();
+ const words = await offers.getByRole('button').all();
+ let over = null;
+ for (const word of words) {
+ const box = await word.boundingBox();
+ if (box.y < ghost.y + ghost.height && box.y + box.height > ghost.y) over = word;
+ if (over) break;
+ }
+ expect(over).not.toBeNull();
+ const chosen = (await over.textContent()).trim();
+ await over.click();
+
+ await expect(cell(page, 2, 2)).toContainText(chosen);
+ expect(fixture.sheetOnDisk('sheet-1').rows.length).toBe(rowsBefore);
+});
+
+test('the search narrows the rows and is remembered without rewriting the CSV', async ({ page }) => {
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ await expect(page.locator('.count')).toContainText('3 of 3');
+ await page.getByPlaceholder('Search these rows').fill('pont');
+ await expect(page.locator('.count')).toContainText('1 of 3');
+
+ // The question is the sidecar's, and the sidecar has a route of its own: asking it
+ // must not rewrite the file, because that moves the stamp a save is made of.
+ await expect.poll(() => fixture.sheetWrites.filter((write) => write.kind === 'meta').length)
+ .toBeGreaterThan(0);
+ expect(fixture.sheetWrites.filter((write) => write.kind === 'table')).toHaveLength(0);
+ expect(fixture.sheetOnDisk('sheet-1').meta.query).toBe('pont');
+});
+
+test('a file changed underneath is noticed, and reading it is asked about first', async ({ page }) => {
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ // An edit the grid is holding, then the spreadsheet writes over the same file.
+ await typeInto(page, 0, 2, 'mine');
+ await expect.poll(() => fixture.sheetWrites.length).toBeGreaterThan(0);
+
+ await fixture.moveSheetOnDisk('sheet-1', {
+ rows: [['r1', 'Quai sud', 'theirs', ''], ['r2', 'Pont nord', 'Seen', 'two frames']],
+ });
+ await typeInto(page, 1, 2, 'again');
+
+ const banner = page.locator('.notice.danger');
+ await expect(banner).toBeVisible();
+ await expect(banner).toContainText('changed on disk');
+
+ // Reload drops the analyst's own unsaved work, so it asks before it does.
+ await banner.getByRole('button', { name: 'Reload' }).click();
+ const dialog = page.getByRole('alertdialog');
+ await expect(dialog).toContainText('lose your edits');
+ await dialog.getByRole('button', { name: 'Reload' }).click();
+
+ await expect(banner).toBeHidden();
+ await expect(cell(page, 0, 2)).toContainText('theirs');
+});
+
+test('overwriting is asked about too, and then sends no stamp', async ({ page }) => {
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ await typeInto(page, 0, 2, 'mine');
+ await expect.poll(() => fixture.sheetWrites.length).toBeGreaterThan(0);
+
+ await fixture.moveSheetOnDisk('sheet-1', {});
+ await typeInto(page, 1, 2, 'again');
+
+ const banner = page.locator('.notice.danger');
+ await expect(banner).toBeVisible();
+ await banner.getByRole('button', { name: 'Overwrite' }).click();
+ const dialog = page.getByRole('alertdialog');
+ await expect(dialog).toContainText('loses them');
+ await dialog.getByRole('button', { name: 'Overwrite' }).click();
+
+ await expect(banner).toBeHidden();
+ await expect.poll(() => fixture.sheetOnDisk('sheet-1').rows[0][2]).toBe('mine');
+});
+
+test('a drag chooses cells and paints no text, and the block copies and pastes', async ({ page }) => {
+ // A press on a cell used to start the browser's own text selection as well, so pulling
+ // a rectangle painted the headings and whatever sat past the table blue, and left that
+ // highlight behind as the thing the next Ctrl+C would have taken. Only a real browser
+ // has a text selection to get wrong, so this seam lives here.
+ const fixture = await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ const from = await cell(page, 0, 1).boundingBox();
+ const to = await cell(page, 1, 2).boundingBox();
+ await page.mouse.move(from.x + 6, from.y + 6);
+ await page.mouse.down();
+ await page.mouse.move(to.x + 6, to.y + 6, { steps: 8 });
+ await page.mouse.up();
+
+ await expect(page.locator('.foot')).toContainText('2 × 2 selected');
+ expect(await page.evaluate(() => window.getSelection().toString())).toBe('');
+
+ // Two rows by two columns, taken from the top of the sheet and put down on the last one.
+ await page.keyboard.press('Control+c');
+ await focusCell(page, 2, 1);
+ await page.keyboard.press('Control+v');
+
+ await expect(cell(page, 2, 1)).toContainText('Quai sud');
+ await expect(cell(page, 2, 2)).toContainText('To check');
+ await expect.poll(() => fixture.sheetOnDisk('sheet-1').rows[2][1]).toBe('Quai sud');
+ await fixture.expectNoUnexpectedRequests();
+});
+
+test('names every key and gesture behind ?', async ({ page }) => {
+ await installAppFixture(page, { sheets: SHEETS });
+ await openSheet(page);
+
+ await page.locator('#sheet-grid').click();
+ await page.keyboard.press('?');
+
+ const help = page.getByRole('dialog');
+ await expect(help).toContainText('Ctrl+S');
+ await expect(help).toContainText('Right-click a heading');
+});
+
+test('the empty case says what a sheet is for', async ({ page }) => {
+ await installAppFixture(page, { sheets: [] });
+ await page.goto('/#sheet');
+
+ await expect(page.getByText('No sheet in this case.')).toBeVisible();
+ await expect(page.getByText('A worklist that counts what is left')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'New sheet' })).toBeVisible();
+});
diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.js
index 52a7609..5ccd583 100644
--- a/frontend/e2e/timeline.spec.js
+++ b/frontend/e2e/timeline.spec.js
@@ -175,7 +175,7 @@ async function openTimeline(page, options = {}) {
test('draws a clear chronology with density, uncertainty and an inspector', async ({ page }, testInfo) => {
const fixture = await openTimeline(page);
- await expect(page.locator('.tabstrip').getByRole('button')).toHaveText(['Board', 'Graph', 'Timeline']);
+ await expect(page.locator('.tabstrip').getByRole('button')).toHaveText(['Board', 'Graph', 'Timeline', 'Sheet']);
await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media']);
await expect(page.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
await expect(page.getByRole('button', { name: /Vehicle remained/ }).locator('..')).toHaveClass(/period.*approximate.*uncertain/);
@@ -620,7 +620,7 @@ test('keeps entity history in the same three-tab Details model', async ({ page }
},
});
await page.goto('/#board');
- await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
const details = page.getByRole('dialog', { name: 'Details' });
await expect(details.getByRole('tab')).toHaveText(['Info', 'Connections', 'Time']);
await details.getByRole('tab', { name: 'Time' }).click();
@@ -641,7 +641,7 @@ test('opens the row handed over from the Time tab', async ({ page }) => {
},
});
await page.goto('/#board');
- await page.locator('tbody tr').filter({ hasText: mediaEntity.label }).locator('td').first().click();
+ await page.locator('tbody tr').filter({ hasText: mediaEntity.label }).locator('td:not(.pick)').first().click();
const details = page.getByRole('dialog', { name: 'Details' });
await details.getByRole('tab', { name: 'Time' }).click();
await details.getByRole('button', { name: `Open ${mediaEntity.label} in Timeline` }).click();
@@ -667,7 +667,7 @@ test('edits an existing assessment from the Time tab', async ({ page }) => {
},
});
await page.goto('/#board');
- await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
const details = page.getByRole('dialog', { name: 'Details' });
await details.getByRole('tab', { name: 'Time' }).click();
@@ -698,7 +698,7 @@ test('starts a new assessment from an empty form after editing one', async ({ pa
},
});
await page.goto('/#board');
- await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td:not(.pick)').first().click();
const details = page.getByRole('dialog', { name: 'Details' });
await details.getByRole('tab', { name: 'Time' }).click();
@@ -721,7 +721,7 @@ test('shows an undated Claim as a missing statement date, not an existing assess
},
});
await page.goto('/#board');
- await page.locator('tbody tr').filter({ hasText: undatedClaim.label }).locator('td').first().click();
+ await page.locator('tbody tr').filter({ hasText: undatedClaim.label }).locator('td:not(.pick)').first().click();
const details = page.getByRole('dialog', { name: 'Details' });
await details.getByRole('tab', { name: 'Time' }).click();
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 3dcf2a0..58b89a2 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -42,6 +42,7 @@
{ id: 'board', label: TOOL_LABELS.board, load: () => import('./tools/Board.svelte') },
{ id: 'graph', label: TOOL_LABELS.graph, load: () => import('./tools/Graph.svelte') },
{ id: 'timeline', label: TOOL_LABELS.timeline, load: () => import('./tools/Timeline.svelte') },
+ { id: 'sheet', label: TOOL_LABELS.sheet, load: () => import('./tools/Sheet.svelte') },
{ id: 'media', label: TOOL_LABELS.media, load: () => import('./tools/MediaLibrary.svelte') },
{ id: 'files', label: TOOL_LABELS.files, load: () => import('./tools/Files.svelte') },
{ id: 'reverse', label: TOOL_LABELS.reverse, load: () => import('./tools/ReverseSearch.svelte') },
diff --git a/frontend/src/app.css b/frontend/src/app.css
index e703aed..f352037 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -735,3 +735,15 @@ a:hover {
font-size: var(--fs-sm);
font-style: italic;
}
+
+/* Row and value marks, from the annotation palette. Global because three components
+ paint with them — the grid's rows and chips, the cell editor's offers, the column
+ panel's vocabulary — and a scoped copy per component is three lists that drift. The
+ amber accent is not in here: it means selection, and a row painted with it would read
+ as a selected row. */
+.c-red { --mark: var(--anno-1); --row-tint: rgba(255, 82, 82, 0.1); }
+.c-orange { --mark: var(--anno-6); --row-tint: rgba(255, 158, 64, 0.1); }
+.c-yellow { --mark: var(--anno-3); --row-tint: rgba(255, 215, 64, 0.1); }
+.c-green { --mark: var(--anno-4); --row-tint: rgba(105, 240, 174, 0.1); }
+.c-blue { --mark: var(--anno-2); --row-tint: rgba(64, 196, 255, 0.1); }
+.c-grey { --mark: var(--text-3); --row-tint: rgba(160, 160, 160, 0.08); }
diff --git a/frontend/src/components/AnalysisViews.render.test.js b/frontend/src/components/AnalysisViews.render.test.js
new file mode 100644
index 0000000..2ee1d84
--- /dev/null
+++ b/frontend/src/components/AnalysisViews.render.test.js
@@ -0,0 +1,184 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/** Rows whose three orderings all differ, so a sort choice can be told apart. */
+const VIEWS = [
+ {
+ id: 'v_ports', name: 'ports', mode: 'live', surface: 'board',
+ snapshot_count: 0, created_at: '2026-08-12T09:00:00Z', updated_at: '2026-08-12T09:00:00Z',
+ },
+ {
+ id: 'v_ammo', name: 'Ammunition', mode: 'snapshot', surface: 'graph',
+ snapshot_count: 340, created_at: '2026-08-11T18:30:00Z', updated_at: '2026-08-11T18:30:00Z',
+ },
+ {
+ id: 'v_bridge', name: 'Bridges', mode: 'live', surface: 'graph',
+ snapshot_count: 0, created_at: '2026-08-13T07:15:00Z', updated_at: '2026-08-13T07:15:00Z',
+ },
+];
+
+const patch = vi.fn((url, body) => {
+ const id = url.split('/').pop();
+ const row = VIEWS.find((view) => view.id === id);
+ return Promise.resolve({ ...row, name: body.name, updated_at: '2026-08-13T11:00:00Z' });
+});
+
+vi.mock('../lib/api.js', () => ({
+ api: {
+ get: () => Promise.resolve({ views: VIEWS }),
+ post: vi.fn(),
+ put: vi.fn(),
+ patch,
+ del: vi.fn(),
+ },
+}));
+
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('./views.fixture.svelte.js');
+ return { caseState, registerCaseChangeGuard: () => () => {}, toast };
+});
+vi.mock('../lib/trash.js', () => ({ restoreGroup: vi.fn() }));
+
+const { caseState } = await import('./views.fixture.svelte.js');
+const { activateAnalysisView, catalogViews, openAnalysisCase } =
+ await import('../lib/analysisSearch.svelte.js');
+const { default: AnalysisViews } = await import('./AnalysisViews.svelte');
+
+let live = null;
+
+async function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AnalysisViews, { target, props: { surface: 'board', ...props } });
+ flushSync();
+ await settle();
+ target.querySelector('button[aria-expanded]').click();
+ flushSync();
+ return target;
+}
+
+async function settle() {
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+const labelled = (root, label) => root.querySelector(`[aria-label="${label}"]`);
+const names = (root) => [...root.querySelectorAll('.open strong')].map((el) => el.textContent);
+const row = (root, name) =>
+ [...root.querySelectorAll('.open')].find((el) => el.querySelector('strong').textContent === name);
+
+function sortBy(root, order) {
+ const select = root.querySelector('select');
+ select.value = order;
+ // Svelte 5 delegates `change` from the root, so a non-bubbling event never lands.
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ return select;
+}
+
+beforeEach(() => {
+ vi.stubGlobal('localStorage', {
+ getItem: () => null,
+ setItem: () => {},
+ removeItem: () => {},
+ });
+ caseState.current = { id: 'case-a', name: 'Renaming' };
+ openAnalysisCase(null);
+ patch.mockClear();
+ toast.mockClear();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('managing saved views', () => {
+ it('states each reading with its surface and when it was last written', async () => {
+ const root = await open();
+
+ expect(row(root, 'Ammunition').textContent.replace(/\s+/g, ' '))
+ .toContain('340 captured · graph · ');
+ expect(row(root, 'Ammunition').querySelector('time').getAttribute('title'))
+ .toBe('2026-08-11 18:30 UTC');
+ expect(row(root, 'ports').textContent.replace(/\s+/g, ' ')).toContain('live · board · ');
+ });
+
+ it('opens on the order the case wrote, and re-sorts on request', async () => {
+ const root = await open();
+ expect(names(root)).toEqual(['Bridges', 'ports', 'Ammunition']);
+
+ const select = sortBy(root, 'name');
+ expect([...select.options].map((option) => option.value))
+ .toEqual(['recent', 'name', 'surface']);
+ expect(names(root)).toEqual(['Ammunition', 'Bridges', 'ports']);
+
+ sortBy(root, 'surface');
+ expect(names(root)).toEqual(['ports', 'Ammunition', 'Bridges']);
+ });
+
+ it('offers no ordering for a list with nothing to order', async () => {
+ const root = await open({ surface: 'timeline' });
+
+ expect(root.querySelector('select')).toBeNull();
+ expect(root.querySelector('.empty').textContent).toContain('No saved timeline views yet.');
+ });
+
+ it('renames a frozen capture in place, without sending its spec back', async () => {
+ const root = await open();
+ labelled(root, 'Rename Ammunition').click();
+ flushSync();
+
+ const input = labelled(root, 'New name for Ammunition');
+ expect(document.activeElement).toBe(input);
+ input.value = ' Ammunition depot ';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ await settle();
+
+ expect(patch).toHaveBeenCalledWith(
+ '/api/cases/case-a/analysis-views/v_ammo', { name: 'Ammunition depot' }
+ );
+ expect(names(root)).toContain('Ammunition depot');
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it('carries the new name onto the reading being held, so an autosave keeps it', async () => {
+ const root = await open();
+ activateAnalysisView('case-a', {
+ id: 'v_ports', name: 'ports', mode: 'live', surface: 'board',
+ spec: { query: { filter: {} } },
+ });
+ flushSync();
+
+ labelled(root, 'Rename ports').click();
+ flushSync();
+ const input = labelled(root, 'New name for ports');
+ input.value = 'Port berths';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ labelled(root, 'Save name').click();
+ await settle();
+
+ expect(catalogViews.activeView.name).toBe('Port berths');
+ });
+
+ it('leaves a name alone when the edit is abandoned', async () => {
+ const root = await open();
+ labelled(root, 'Rename ports').click();
+ flushSync();
+ const input = labelled(root, 'New name for ports');
+ input.value = 'Discarded';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ flushSync();
+
+ expect(patch).not.toHaveBeenCalled();
+ expect(names(root)).toContain('ports');
+ });
+});
diff --git a/frontend/src/components/AnalysisViews.svelte b/frontend/src/components/AnalysisViews.svelte
index fa58137..319d828 100644
--- a/frontend/src/components/AnalysisViews.svelte
+++ b/frontend/src/components/AnalysisViews.svelte
@@ -6,10 +6,19 @@
activateAnalysisView,
adoptSavedAnalysisView,
leaveAnalysisView,
+ renameAnalysisView,
viewFamily,
viewSlot,
} from '../lib/analysisSearch.svelte.js';
- import { copyName } from '../lib/analysisViews.js';
+ import {
+ copyName,
+ exactStamp,
+ readViewOrder,
+ sortViews,
+ timeAgo,
+ viewOrders,
+ writeViewOrder,
+ } from '../lib/analysisViews.js';
import { closeOnOutsidePointer } from '../lib/dismiss.js';
import { restoreGroup } from '../lib/trash.js';
import { caseState, registerCaseChangeGuard, toast } from '../lib/state.svelte.js';
@@ -41,6 +50,17 @@
let mode = $state('live');
let busy = $state(false);
let loadedFor = null;
+ /** The chosen ordering, remembered per family. */
+ let order = $state('recent');
+ let orderedFor = null;
+ const orders = $derived(viewOrders(family));
+ const rows = $derived(sortViews(views, order));
+ /** Read when the menu opens: a popover is not open long enough for "5 min ago"
+ * to drift, and a ticking clock would redraw the list under the pointer. */
+ let now = $state(Date.now());
+ /** The row being relabelled, and the name being typed into it. */
+ let renaming = $state(null);
+ let draft = $state('');
let readRun = 0;
let autoTimer = 0;
let activeSave = null;
@@ -81,9 +101,27 @@
loadedFor = caseId;
menu = false;
saving = false;
+ renaming = null;
void read();
});
+ $effect(() => {
+ if (family === orderedFor) return;
+ orderedFor = family;
+ order = readViewOrder(family);
+ });
+
+ function chooseOrder(value) {
+ order = value;
+ writeViewOrder(family, value);
+ }
+
+ function openMenu() {
+ now = Date.now();
+ renaming = null;
+ menu = !menu;
+ }
+
function updateSummary(view) {
stored = stored.map((row) => row.id === view.id
? {
@@ -227,6 +265,41 @@
}
}
+ function startRename(view) {
+ renaming = view.id;
+ draft = view.name;
+ }
+
+ /** Relabel one reading. Both modes accept it: a snapshot's capture is evidence,
+ * its name is not, so `PATCH` never touches the spec. */
+ async function rename(view) {
+ const caseId = caseState.current?.id;
+ const next = draft.trim();
+ if (!caseId || !next || busy) return;
+ if (next === view.name) {
+ renaming = null;
+ return;
+ }
+ busy = true;
+ try {
+ const saved = await api.patch(
+ `/api/cases/${caseId}/analysis-views/${view.id}`, { name: next }
+ );
+ updateSummary(saved);
+ renameAnalysisView(caseId, view.id, saved.name);
+ renaming = null;
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ function focusInput(node) {
+ node.focus();
+ node.select();
+ }
+
async function duplicate(viewId) {
const caseId = caseState.current?.id;
if (!caseId) return;
@@ -245,6 +318,7 @@
async function remove(view) {
const caseId = caseState.current?.id;
if (!caseId) return;
+ if (renaming === view.id) renaming = null;
try {
const result = await api.del(`/api/cases/${caseId}/analysis-views/${view.id}`);
if (slot.activeView?.id === view.id) {
@@ -296,7 +370,7 @@
class="btn btn-sm"
aria-expanded={menu}
disabled={!caseState.current}
- onclick={() => (menu = !menu)}
+ onclick={openMenu}
>
<Icon name="layers" size={13} /> Views{views.length ? ` ${views.length}` : ''}
</button>
@@ -313,24 +387,69 @@
>
<Icon name="save" size={12} /> Save view
</button>
+ {#if views.length > 1}
+ <label class="sort">
+ Sort
+ <select
+ class="input"
+ value={order}
+ onchange={(event) => chooseOrder(event.currentTarget.value)}
+ >
+ {#each orders as choice (choice.id)}
+ <option value={choice.id}>{choice.label}</option>
+ {/each}
+ </select>
+ </label>
+ {/if}
</div>
{#if views.length}
<ul>
- {#each views as view (view.id)}
- <li>
- <button class="open" disabled={busy} onclick={() => open(view.id)}>
- <strong>{view.name}</strong>
- <span>
- {view.mode === 'snapshot' ? `${view.snapshot_count} captured` : 'live'}
- {#if family === 'catalog'}· {view.surface}{/if}
- </span>
- </button>
- <button title="Duplicate view" aria-label="Duplicate {view.name}" onclick={() => duplicate(view.id)}>
- <Icon name="copy" size={12} />
- </button>
- <button title="Delete view" aria-label="Delete {view.name}" onclick={() => remove(view)}>
- <Icon name="trash" size={12} />
- </button>
+ {#each rows as view (view.id)}
+ <li class:editing={renaming === view.id}>
+ {#if renaming === view.id}
+ <input
+ class="input"
+ use:focusInput
+ bind:value={draft}
+ maxlength="80"
+ aria-label="New name for {view.name}"
+ onkeydown={(event) => {
+ if (event.key === 'Enter') rename(view);
+ if (event.key === 'Escape') renaming = null;
+ }}
+ />
+ <button
+ title="Save name"
+ aria-label="Save name"
+ disabled={!draft.trim() || busy}
+ onclick={() => rename(view)}
+ >
+ <Icon name="check" size={12} />
+ </button>
+ <button title="Cancel" aria-label="Cancel rename" onclick={() => (renaming = null)}>
+ <Icon name="x" size={12} />
+ </button>
+ {:else}
+ <button class="open" disabled={busy} onclick={() => open(view.id)}>
+ <strong>{view.name}</strong>
+ <span>
+ {view.mode === 'snapshot' ? `${view.snapshot_count} captured` : 'live'}
+ {#if family === 'catalog'}· {view.surface}{/if}
+ · <time datetime={view.updated_at} title={exactStamp(view.updated_at)}>
+ {timeAgo(view.updated_at, now)}
+ </time>
+ </span>
+ </button>
+ <button title="Rename view" aria-label="Rename {view.name}" onclick={() => startRename(view)}>
+ <Icon name="edit" size={12} />
+ </button>
+ <button title="Duplicate view" aria-label="Duplicate {view.name}" onclick={() => duplicate(view.id)}>
+ <Icon name="copy" size={12} />
+ </button>
+ <button title="Delete view" aria-label="Delete {view.name}" onclick={() => remove(view)}>
+ <Icon name="trash" size={12} />
+ </button>
+ {/if}
</li>
{/each}
</ul>
@@ -385,11 +504,18 @@
padding: 8px; border: 1px solid var(--border-strong); border-radius: var(--r-md);
background: var(--bg-1); box-shadow: var(--shadow-2);
}
- .menu-actions { display: flex; gap: 6px; padding-bottom: 7px; border-bottom: 1px solid var(--border); }
+ .menu-actions {
+ display: flex; align-items: center; justify-content: space-between; gap: 6px;
+ padding-bottom: 7px; border-bottom: 1px solid var(--border);
+ }
+ .sort { display: flex; align-items: center; gap: 5px; color: var(--text-3); font-size: var(--fs-xs); }
+ .sort select { padding: 3px 5px; font-size: var(--fs-xs); }
/* The list's own reset: without it the browser's 40px marker gutter left an empty
column down the left of every row. */
ul { max-height: 310px; margin: 6px 0 0; padding: 0; list-style: none; overflow: auto; }
- li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 2px; }
+ li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; align-items: center; gap: 2px; }
+ li.editing { grid-template-columns: minmax(0, 1fr) auto auto; padding: 4px 5px; }
+ li.editing input { width: 100%; }
li:hover { background: var(--bg-2); }
li > button:not(.open) { display: flex; padding: 7px 5px; color: var(--text-3); }
.open { min-width: 0; padding: 7px; text-align: left; }
diff --git a/frontend/src/components/AnalysisViews.test.js b/frontend/src/components/AnalysisViews.test.js
index 4945203..dcc6f9e 100644
--- a/frontend/src/components/AnalysisViews.test.js
+++ b/frontend/src/components/AnalysisViews.test.js
@@ -67,5 +67,22 @@ describe('saved analysis views', () => {
it('keeps a snapshot immutable instead of recapturing it under the same name', () => {
expect(source).toContain("disabled={slot.activeView?.mode === 'snapshot'}");
expect(source).toContain('Duplicate the snapshot to keep another copy.');
+ // A label is not a capture: the rename route takes both modes and no spec.
+ expect(source).toContain('api.patch(');
+ expect(source).toContain("{ name: next }");
+ });
+
+ it('reads the list in a remembered order, and only where there is one to read', () => {
+ expect(source).toContain('sortViews(views, order)');
+ expect(source).toContain('order = readViewOrder(family)');
+ expect(source).toContain('writeViewOrder(family, value)');
+ expect(source).toContain('{#if views.length > 1}');
+ expect(source).toContain('{#each orders as choice (choice.id)}');
+ });
+
+ it('dates every row and spells the exact minute out of the way', () => {
+ expect(source).toContain('timeAgo(view.updated_at, now)');
+ expect(source).toContain('title={exactStamp(view.updated_at)}');
+ expect(source).toContain('now = Date.now()');
});
});
diff --git a/frontend/src/components/CaseSwitcher.test.js b/frontend/src/components/CaseSwitcher.test.js
index 41f90fb..d20bad4 100644
--- a/frontend/src/components/CaseSwitcher.test.js
+++ b/frontend/src/components/CaseSwitcher.test.js
@@ -149,7 +149,7 @@ describe('refreshCaseList', () => {
await refreshCaseList({ q: ' ' });
expect(get).toHaveBeenNthCalledWith(1, '/api/cases');
vi.doUnmock('../lib/api.js');
- });
+ }, 20_000);
it('loads the workspace folders alongside the cases, unfiltered', async () => {
vi.resetModules();
@@ -163,7 +163,7 @@ describe('refreshCaseList', () => {
// the folder list is not a case list: the name query does not apply to it
expect(get).toHaveBeenNthCalledWith(2, '/api/workspace/folders');
vi.doUnmock('../lib/api.js');
- });
+ }, 20_000);
it('still lists the cases when the folder scan fails', async () => {
vi.resetModules();
@@ -179,7 +179,7 @@ describe('refreshCaseList', () => {
expect(caseState.list).toHaveLength(1);
expect(caseState.folders).toEqual([]);
vi.doUnmock('../lib/api.js');
- });
+ }, 20_000);
});
describe('workspace folders', () => {
@@ -217,7 +217,7 @@ describe('workspace folders', () => {
expect(get).toHaveBeenLastCalledWith('/api/cases/Oceanside match');
expect(caseState.current).toBeTruthy();
vi.doUnmock('../lib/api.js');
- });
+ }, 20_000);
});
describe('open case folder', () => {
diff --git a/frontend/src/components/ClaimConnections.svelte b/frontend/src/components/ClaimConnections.svelte
index ccca94a..7c83b85 100644
--- a/frontend/src/components/ClaimConnections.svelte
+++ b/frontend/src/components/ClaimConnections.svelte
@@ -1,8 +1,9 @@
<script>
import { api } from '../lib/api.js';
- import { saveRelation } from '../lib/relations.svelte.js';
+ import { retractionWarning, saveRelation } from '../lib/relations.svelte.js';
import { toast } from '../lib/state.svelte.js';
import { entityIcon } from '../lib/entityIcon.js';
+ import ConfirmDialog from './ConfirmDialog.svelte';
import Icon from './Icon.svelte';
import RelationPicker from './RelationPicker.svelte';
@@ -42,6 +43,8 @@
let adding = $state(null);
let busy = $state(false);
let busyId = $state(null);
+ //: The connector waiting on an answer before it is taken back: `{ link, words }`.
+ let retracting = $state(null);
/** A group's rows. `way` narrows to one reading; without it both are listed, which
* is what a symmetric verb wants. */
@@ -65,9 +68,20 @@
}
}
+ /** A connector is a statement too: `about`, `at` and `cites` are what the Claim rests
+ * on, and dropping one is not held anywhere. Asked for in the same words the Details
+ * relations and the Graph's edge use (`retractionWarning`). */
+ function askRemove(link) {
+ if (busyId) return;
+ const words = retractionWarning(link);
+ if (words) retracting = { link, words };
+ else remove(link);
+ }
+
async function remove(link) {
if (busyId) return;
busyId = link.id;
+ retracting = null;
try {
await api.del(`/api/cases/${caseId}/links/${link.id}`);
await onchanged?.();
@@ -108,7 +122,7 @@
class="btn btn-ghost btn-sm remove"
title="Remove"
disabled={busyId === row.link.id}
- onclick={() => remove(row.link)}
+ onclick={() => askRemove(row.link)}
><Icon name="x" size={12} /></button>
</div>
{/each}
@@ -132,6 +146,19 @@
{/each}
</div>
+{#if retracting}
+ <ConfirmDialog
+ title={retracting.words.title}
+ message={retracting.words.message}
+ detail={retracting.words.detail}
+ confirmLabel={retracting.words.confirmLabel}
+ tone="danger"
+ busy={busyId === retracting.link.id}
+ onconfirm={() => remove(retracting.link)}
+ oncancel={() => (retracting = null)}
+ />
+{/if}
+
<style>
.claim-connections {
display: grid;
diff --git a/frontend/src/components/ClaimConnections.test.js b/frontend/src/components/ClaimConnections.test.js
index 71034a5..562a4ea 100644
--- a/frontend/src/components/ClaimConnections.test.js
+++ b/frontend/src/components/ClaimConnections.test.js
@@ -61,4 +61,14 @@ describe('Claim connections', () => {
expect(references).not.toContain('api.patch');
expect(references).not.toContain('api.del');
});
+
+ it('asks before a connector goes, in the words every surface uses', () => {
+ // `about`, `at` and `cites` are what a statement rests on. Dropping one is a write
+ // nothing holds, so it is the same question the Details relations and the Graph's edge
+ // ask, read out of one place rather than worded here.
+ expect(editor).toContain('const words = retractionWarning(link);');
+ expect(editor).toContain('if (words) retracting = { link, words };');
+ expect(editor).toContain('<ConfirmDialog');
+ expect(editor).toContain('onclick={() => askRemove(row.link)}');
+ });
});
diff --git a/frontend/src/components/ConfirmDialog.render.test.js b/frontend/src/components/ConfirmDialog.render.test.js
new file mode 100644
index 0000000..45987bc
--- /dev/null
+++ b/frontend/src/components/ConfirmDialog.render.test.js
@@ -0,0 +1,124 @@
+// @vitest-environment happy-dom
+/**
+ * The confirmation dialog, actually mounted.
+ *
+ * This dialog is a guard rail, and the two ways a guard rail fails are invisible in the
+ * source: the key that dismisses it also dismissing the window behind it, and the key that
+ * raised it answering it. Both need a real DOM and real key events.
+ */
+import { describe, expect, it, afterEach, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: ConfirmDialog } = await import('./ConfirmDialog.svelte');
+const { default: Modal } = await import('./Modal.svelte');
+
+const live = [];
+
+function open(Component, props) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const app = mount(Component, { target, props });
+ live.push(app);
+ flushSync();
+ return app;
+}
+
+const press = (key, init = {}) =>
+ window.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, ...init }));
+
+const cancelButton = () =>
+ [...document.querySelectorAll('[role="alertdialog"] button')].find(
+ (b) => b.textContent.trim() === 'Cancel'
+ );
+
+afterEach(() => {
+ while (live.length) unmount(live.pop());
+ document.body.innerHTML = '';
+});
+
+describe('escape', () => {
+ it('steps back one overlay, leaving the window that raised the dialog open', () => {
+ const onclose = vi.fn();
+ const oncancel = vi.fn();
+ open(Modal, { title: 'Details', onclose });
+ open(ConfirmDialog, { title: 'Remove relation', message: 'It comes back.', oncancel });
+
+ press('Escape');
+
+ expect(oncancel).toHaveBeenCalledTimes(1);
+ expect(onclose).not.toHaveBeenCalled();
+ });
+
+ it('reaches the window again once the dialog is gone', () => {
+ const onclose = vi.fn();
+ open(Modal, { title: 'Details', onclose });
+ const dialog = open(ConfirmDialog, { title: 'Remove', message: 'x', oncancel: () => {} });
+
+ unmount(live.pop() === dialog ? dialog : dialog);
+ flushSync();
+ press('Escape');
+
+ expect(onclose).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('focus', () => {
+ it('moves into the dialog, onto the half that takes nothing away', () => {
+ open(ConfirmDialog, { title: 'Delete', message: 'x', tone: 'danger', oncancel: () => {} });
+ expect(document.activeElement).toBe(cancelButton());
+ });
+
+ it('goes back to the button that raised the dialog when it closes', () => {
+ const trigger = document.createElement('button');
+ document.body.append(trigger);
+ trigger.focus();
+
+ const dialog = open(ConfirmDialog, { title: 'Delete', message: 'x', oncancel: () => {} });
+ expect(document.activeElement).not.toBe(trigger);
+
+ live.splice(live.indexOf(dialog), 1);
+ unmount(dialog);
+ flushSync();
+
+ expect(document.activeElement).toBe(trigger);
+ });
+});
+
+describe('enter', () => {
+ it('is not answered by the window, so a stray press cannot confirm', () => {
+ const onconfirm = vi.fn();
+ open(ConfirmDialog, { title: 'Delete', message: 'x', onconfirm, oncancel: () => {} });
+
+ press('Enter');
+
+ expect(onconfirm).not.toHaveBeenCalled();
+ });
+
+ it('ignores the repeats of a key still held down from the click that opened it', () => {
+ open(ConfirmDialog, { title: 'Delete', message: 'x', oncancel: () => {} });
+
+ const held = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ cancelButton().dispatchEvent(held);
+
+ expect(held.defaultPrevented).toBe(true);
+ });
+
+ it('still lets a fresh press through to the focused button', () => {
+ open(ConfirmDialog, { title: 'Delete', message: 'x', oncancel: () => {} });
+
+ const fresh = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ repeat: false,
+ bubbles: true,
+ cancelable: true,
+ });
+ cancelButton().dispatchEvent(fresh);
+
+ expect(fresh.defaultPrevented).toBe(false);
+ });
+});
diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelte
index 673ad18..d895b27 100644
--- a/frontend/src/components/ConfirmDialog.svelte
+++ b/frontend/src/components/ConfirmDialog.svelte
@@ -1,6 +1,7 @@
<script>
import Icon from './Icon.svelte';
import { portal } from '../lib/fullscreen.js';
+ import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';
// A small, styled confirmation dialog — replaces the browser confirm() popup.
// Tone drives the accent so an irreversible action reads differently from one
@@ -27,9 +28,34 @@
oncancel,
} = $props();
+ // Escape belongs to the overlay on top. This dialog usually opens from inside an
+ // entity window, and answering the same press as the window behind it would close
+ // both: the analyst asked to step back one, not to lose the window.
+ const self = {};
+ let cancelBtn = $state(null);
+
+ $effect(() => joinOverlays(self));
+
+ // An alertdialog that leaves the focus behind the veil is unreachable by keyboard, so
+ // move it in. Cancel and not the confirm button: this dialog exists to be read before
+ // it is answered, and the safe half is the one a blind Enter should reach.
+ $effect(() => {
+ const returnTo = document.activeElement;
+ cancelBtn?.focus();
+ return () => {
+ if (returnTo?.isConnected) returnTo.focus?.();
+ };
+ });
+
function onkeydown(e) {
- if (e.key === 'Escape') oncancel?.();
- else if (e.key === 'Enter') onconfirm?.();
+ if (e.key === 'Escape' && isTopOverlay(self)) oncancel?.();
+ }
+
+ // Enter held down on the button that opened this dialog keeps firing keydown, and the
+ // repeats land on whatever now holds the focus — answering the dialog with the very
+ // press that raised it. Only a fresh press counts.
+ function ondialogkeydown(e) {
+ if (e.repeat && (e.key === 'Enter' || e.key === ' ')) e.preventDefault();
}
</script>
@@ -41,7 +67,14 @@
onclick={(e) => e.target === e.currentTarget && oncancel?.()}
role="presentation"
>
- <div class="dialog" class:danger={tone === 'danger'} role="alertdialog" aria-label={title}>
+ <div
+ class="dialog"
+ class:danger={tone === 'danger'}
+ role="alertdialog"
+ aria-label={title}
+ tabindex="-1"
+ onkeydown={ondialogkeydown}
+ >
<div class="head">
<span class="badge" class:danger={tone === 'danger'}>
<Icon name={icon} size={18} />
@@ -89,7 +122,7 @@
</div>
{/if}
<div class="actions">
- <button class="btn" onclick={oncancel} disabled={busy}>Cancel</button>
+ <button class="btn" bind:this={cancelBtn} onclick={oncancel} disabled={busy}>Cancel</button>
<button
class="btn {tone === 'danger' ? 'btn-danger' : 'btn-primary'}"
onclick={onconfirm}
diff --git a/frontend/src/components/EntityDetails.render.test.js b/frontend/src/components/EntityDetails.render.test.js
index 952cc59..d6595c2 100644
--- a/frontend/src/components/EntityDetails.render.test.js
+++ b/frontend/src/components/EntityDetails.render.test.js
@@ -39,14 +39,22 @@ const registryLanded = new Promise((resolve) => {
landRegistry = resolve;
});
+// Hoisted with the mock factory that closes over it, so the spy exists before the
+// panel's first import pulls the mocked module in.
+const { patch } = vi.hoisted(() => ({ patch: vi.fn() }));
+
vi.mock('../lib/api.js', async () => {
// The panel reads its entity off the bounded chain endpoint, never off the case.
- const { entity } = await import('./details.fixture.svelte.js');
+ const { entity, mediaItem } = await import('./details.fixture.svelte.js');
const chain = { entity, sources: [], lost: [], dependents: [], relations: [], empty: true };
return {
api: {
- get: (url) => (url.includes('entity-types') ? registryLanded : Promise.resolve(chain)),
- patch: vi.fn(),
+ get: (url) => {
+ if (url.includes('entity-types')) return registryLanded;
+ if (url.includes('/media/item')) return Promise.resolve({ ...mediaItem });
+ return Promise.resolve(chain);
+ },
+ patch,
post: vi.fn(),
del: vi.fn(),
},
@@ -70,9 +78,16 @@ vi.mock('../lib/navigate.js', () => ({
vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'pin' }));
vi.mock('../lib/filing.js', () => ({ assignFolder: vi.fn() }));
vi.mock('../lib/poll.js', () => ({ pollWhile: () => () => {} }));
-vi.mock('../lib/trash.js', () => ({ deletedToast: () => {}, RESTORABLE: [] }));
+vi.mock('../lib/trash.js', () => ({
+ deletedToast: () => {},
+ FILE_BACKED: new Set(['media']),
+ RESTORABLE: [],
+}));
const { default: EntityDetails } = await import('./EntityDetails.svelte');
+// The same module instance the mocks hand the panel, so a test can change what the
+// entity and its file are between mounts.
+const { entity, mediaItem } = await import('./details.fixture.svelte.js');
let live = null;
@@ -103,6 +118,19 @@ afterEach(() => {
live = null;
});
+describe('EntityDetails coordinates', () => {
+ it('says where a point is, from the pair rather than the string a tool wrote', async () => {
+ // The fixture place holds `lat`/`lon` and no `coords`, which is what a sheet
+ // promotion mints: the row used to be keyed on the string, so a promoted place
+ // showed no coordinate anywhere in the panel.
+ const target = await open();
+ const row = [...target.querySelectorAll('.info-row')].find(
+ (el) => el.querySelector('.info-k')?.textContent === 'Coords'
+ );
+ expect(row?.textContent).toContain('1.000000, 2.000000');
+ });
+});
+
describe('EntityDetails field seeding', () => {
it('carries the stored values when the registry lands after the panel opened', async () => {
let dirty = false;
@@ -125,3 +153,71 @@ describe('EntityDetails field seeding', () => {
expect(dirty).toBe(false);
});
});
+
+describe('the source of a file the analyst brought in', () => {
+ const PLACE = { ...entity, attrs: { ...entity.attrs } };
+
+ function asMedia(id, source) {
+ Object.assign(entity, {
+ id,
+ type: 'media',
+ label: 'shot',
+ attrs: { path: 'media/shot.png' },
+ });
+ mediaItem.source = source;
+ }
+
+ afterEach(() => {
+ Object.assign(entity, PLACE, { attrs: { ...PLACE.attrs } });
+ mediaItem.source = { type: 'upload', original_name: 'shot.png' };
+ patch.mockClear();
+ });
+
+ it('is a field to type into, seeded with what the sidecar holds', async () => {
+ asMedia('m1', { type: 'upload', original_name: 'shot.png', url: 'https://t.me/c/42' });
+ const target = await open({ entityId: 'm1' });
+ expect(target.querySelector('#ed-source')?.value).toBe('https://t.me/c/42');
+ // and not repeated as a fact above: one Source on screen, the one that can be edited
+ const rows = [...target.querySelectorAll('.info-row .info-k')].map((el) => el.textContent);
+ expect(rows).not.toContain('Source');
+ });
+
+ it('is saved through the media route, beside the title and the notes', async () => {
+ asMedia('m2', { type: 'upload', original_name: 'shot.png' });
+ const target = await open({ entityId: 'm2' });
+ const field = target.querySelector('#ed-source');
+ field.value = 'https://example.org/post/7';
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Save').click();
+ await Promise.resolve();
+ expect(patch).toHaveBeenCalledWith(
+ '/api/cases/c1/media',
+ expect.objectContaining({ source_url: 'https://example.org/post/7' })
+ );
+ });
+
+ it('refuses to save an origin that is not an address', async () => {
+ asMedia('m3', { type: 'upload', original_name: 'shot.png' });
+ const target = await open({ entityId: 'm3' });
+ const field = target.querySelector('#ed-source');
+ field.value = 'a friend sent it';
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ const save = [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Save');
+ expect(save.disabled).toBe(true);
+ expect(target.textContent).toContain('The source must be an http(s) address.');
+ });
+
+ it('is never offered for what a tool fetched — that address is a fact', async () => {
+ asMedia('m4', {
+ type: 'download',
+ url: 'https://x.com/user/status/1',
+ webpage_url: 'https://x.com/user/status/1',
+ });
+ const target = await open({ entityId: 'm4' });
+ expect(target.querySelector('#ed-source')).toBe(null);
+ const rows = [...target.querySelectorAll('.info-row .info-k')].map((el) => el.textContent);
+ expect(rows).toContain('Source');
+ });
+});
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index c9b38cb..a121b10 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -12,7 +12,7 @@
*/
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
- import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import { caseState, fmtCoords, reloadCase, toast, uiState } from '../lib/state.svelte.js';
import { buildTree, flattenPaths, folderOf } from '../lib/folderTree.js';
import { assignFolder as fileEntity } from '../lib/filing.js';
import {
@@ -41,7 +41,8 @@
ENTITY_TOOL,
} from '../lib/navigate.js';
import { pollWhile } from '../lib/poll.js';
- import { deletedToast, RESTORABLE } from '../lib/trash.js';
+ import { canStateSource, sourceProblem } from '../lib/statedSource.js';
+ import { deletedToast, FILE_BACKED, RESTORABLE } from '../lib/trash.js';
import Icon from './Icon.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import FolderSelect from './FolderSelect.svelte';
@@ -102,8 +103,6 @@
const allFolders = $derived(flattenPaths(buildTree(caseState.current?.folders ?? [], [])));
- // Entity types backed by a file on disk — deleting them drops the file.
- const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);
// Every type gets the title/notes editor — a list of which ones did was a list
// that drifted: none of the hand-made types were on it, so a claim created on the
// board opened with a title nobody could correct. A capture and a media commit
@@ -116,6 +115,9 @@
let infoTitle = $state('');
let infoNotes = $state('');
let infoFolder = $state('');
+ // Only ever shown for a file the analyst brought in: an origin the bytes cannot
+ // state, and that the import may have gone past without anyone typing.
+ let infoSource = $state('');
let infoSaving = $state(false);
let seededId = null; // the id whose fields are currently loaded
let seededFields = 0; // declared fields the registry knew when they were loaded
@@ -135,6 +137,7 @@
title: infoTitle,
notes: infoNotes,
folder: infoFolder,
+ source: infoSource,
attrs: { ...infoAttrs },
};
}
@@ -144,6 +147,7 @@
if (infoTitle !== baseline.title) return true;
if (infoNotes !== baseline.notes) return true;
if (infoFolder !== baseline.folder) return true;
+ if (infoSource !== baseline.source) return true;
const keys = new Set([...Object.keys(baseline.attrs), ...Object.keys(infoAttrs)]);
for (const key of keys) {
if ((baseline.attrs[key] ?? null) !== (infoAttrs[key] ?? null)) return true;
@@ -179,6 +183,11 @@
// so the one action that helps is the folder it sits in.
const inFileManager = $derived(opensInFileManager(entity));
+ // A file the analyst brought in gets a Source field; one a tool fetched or made
+ // shows the origin it recorded, as a fact, in the rows above.
+ const sourceEditable = $derived(entity?.type === 'media' && canStateSource(infoData));
+ const sourceIssue = $derived(sourceEditable ? sourceProblem(infoSource) : '');
+
$effect(() => {
const e = entity;
caseState.rev; // re-resolve preview/metadata after a reload…
@@ -203,6 +212,7 @@
infoTitle = e.label ?? '';
infoNotes = e.attrs?.notes ?? '';
infoFolder = folderOf(e) ?? '';
+ infoSource = '';
infoData = null;
}
infoAttrs = Object.fromEntries(fields.map((f) => [f.key, e.attrs?.[f.key] ?? null]));
@@ -240,6 +250,7 @@
if (infoData && seedFields) {
infoTitle = infoData.title ?? e.label ?? '';
infoNotes = infoData.notes ?? infoNotes;
+ infoSource = canStateSource(infoData) ? (infoData.source?.url ?? '') : '';
// the sidecar is what the fields now hold, so it is what they are compared
// against — otherwise the panel would open already reading as edited
snapshot();
@@ -294,6 +305,19 @@
const identityPlaceholder = $derived(
entity ? entityIdentityPlaceholder(entity.type) : 'What to call it'
);
+
+ /**
+ * The point this entity sits on, for the types that carry one.
+ *
+ * Read off `lat`/`lon` rather than off the `coords` string the map save wrote:
+ * that string only exists when a tool minted it, so a place promoted from a
+ * sheet column held its point and showed nothing. Reading the pair also renders
+ * it in the format the analyst chose, where the stored string is frozen decimal
+ * degrees. The string is still the fallback, for a record that has one and no pair.
+ */
+ const coordText = $derived(
+ fmtCoords(entity?.attrs?.lat, entity?.attrs?.lon) || entity?.attrs?.coords || ''
+ );
const ordinaryRelations = $derived(
(chain?.relations ?? []).filter((row) => relationAction(row.link.type) === 'relation')
);
@@ -381,7 +405,7 @@
/** One point, written the way every other coordinate row in this panel writes one. */
function pointText(point) {
- return `${Number(point.lat).toFixed(6)}, ${Number(point.lon).toFixed(6)}`;
+ return fmtCoords(point.lat, point.lon);
}
$effect(() => {
@@ -498,6 +522,9 @@
} else if (entity.type === 'media') {
await api.patch(`/api/cases/${cid}/media`, {
path: entity.attrs.path, title: infoTitle.trim(), notes: infoNotes,
+ // Sent only where it can be stated, so a Save on a download or a
+ // derivative never asks the route to touch what a tool recorded.
+ ...(sourceEditable ? { source_url: infoSource.trim() } : {}),
});
} else {
await api.patch(`/api/cases/${cid}/entities/${entity.id}`, {
@@ -577,9 +604,10 @@
return bytes + ' B';
}
- function formatCoords(gps) {
- if (gps?.lat == null || gps?.lon == null) return '';
- return `${Number(gps.lat).toFixed(6)}, ${Number(gps.lon).toFixed(6)}`;
+ /** The pair EXIF or a video probe carried, read on the same terms as every other
+ * coordinate in this panel. */
+ function gpsText(gps) {
+ return fmtCoords(gps?.lat, gps?.lon);
}
</script>
@@ -651,7 +679,7 @@
id="ed-title"
class="input"
bind:value={infoTitle}
- placeholder={entity.attrs?.coords ?? identityPlaceholder}
+ placeholder={coordText || identityPlaceholder}
/>
{#if twin}
@@ -688,7 +716,9 @@
{#if infoData.source?.duration}
<div class="info-row"><span class="info-k">Duration</span><span>{infoData.source.duration}s</span></div>
{/if}
- {#if infoData.source?.webpage_url ?? infoData.source?.url}
+ <!-- What a tool fetched, read as a fact. A file whose origin is the
+ analyst's to state carries it as a field below instead. -->
+ {#if !sourceEditable && (infoData.source?.webpage_url ?? infoData.source?.url)}
<div class="info-row">
<span class="info-k">Source</span>
<a class="mono src" href={infoData.source.webpage_url ?? infoData.source.url} target="_blank" rel="noreferrer">
@@ -735,8 +765,8 @@
</div>
{/if}
{/if}
- {#if entity.attrs?.coords}
- <div class="info-row"><span class="info-k">Coords</span><span class="mono">{entity.attrs.coords}</span></div>
+ {#if coordText}
+ <div class="info-row"><span class="info-k">Coords</span><span class="mono">{coordText}</span></div>
{/if}
</div>
@@ -756,7 +786,7 @@
<div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.taken_at}</span></div>
{/if}
{#if infoData.gps}
- <div class="info-row"><span class="info-k">GPS</span><span class="mono">{formatCoords(infoData.gps)}</span></div>
+ <div class="info-row"><span class="info-k">GPS</span><span class="mono">{gpsText(infoData.gps)}</span></div>
{/if}
{#each Object.entries(infoData.exif ?? {}) as [key, value] (key)}
<div class="info-row"><span class="info-k">{key}</span><span class="exif-value">{value}</span></div>
@@ -773,7 +803,7 @@
<div class="info-row"><span class="info-k">Captured</span><span class="mono">{infoData.taken_at}</span></div>
{/if}
{#if infoData.gps}
- <div class="info-row"><span class="info-k">GPS</span><span class="mono">{formatCoords(infoData.gps)}</span></div>
+ <div class="info-row"><span class="info-k">GPS</span><span class="mono">{gpsText(infoData.gps)}</span></div>
{/if}
{#each Object.entries(infoData.video_metadata) as [key, value] (key)}
<div class="info-row"><span class="info-k">{key}</span><span class="exif-value">{value}</span></div>
@@ -782,6 +812,17 @@
</details>
{/if}
+ {#if sourceEditable}
+ <label class="modal-label" for="ed-source">Source URL</label>
+ <input
+ id="ed-source"
+ class="input"
+ placeholder="https://…"
+ bind:value={infoSource}
+ />
+ <p class="field-help">Where you got this file. Recorded as stated, not as fetched.</p>
+ {/if}
+
<label class="modal-label" for="ed-notes">Notes</label>
<textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
@@ -1083,7 +1124,12 @@
<Icon name="trash" size={13} /> Delete
</button>
<div style="flex:1"></div>
- <button class="btn btn-primary btn-sm" onclick={saveInfo} disabled={infoSaving}>
+ {#if sourceIssue}<span class="save-problem">{sourceIssue}</span>{/if}
+ <button
+ class="btn btn-primary btn-sm"
+ onclick={saveInfo}
+ disabled={infoSaving || Boolean(sourceIssue)}
+ >
{infoSaving ? 'Saving…' : 'Save'}
</button>
</div>
@@ -1131,6 +1177,16 @@
font-size: var(--fs-xs);
line-height: 1.5;
}
+ .field-help {
+ margin: 5px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .save-problem {
+ align-self: center;
+ color: var(--warn);
+ font-size: var(--fs-xs);
+ }
.twin-open {
padding: 0;
border: 0;
diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.js
index c0c40e9..7773219 100644
--- a/frontend/src/components/EntityDetails.test.js
+++ b/frontend/src/components/EntityDetails.test.js
@@ -25,7 +25,7 @@ describe('import enrichment details', () => {
expect(source).toContain('<details class="metadata-details">');
expect(source).toContain('<summary>EXIF metadata');
expect(source).toContain('{infoData.taken_at}');
- expect(source).toContain('formatCoords(infoData.gps)');
+ expect(source).toContain('gpsText(infoData.gps)');
expect(source).toContain('{#each Object.entries(infoData.exif ?? {}) as [key, value] (key)}');
});
diff --git a/frontend/src/components/EntityImages.svelte b/frontend/src/components/EntityImages.svelte
index 1815d6b..0a98e7f 100644
--- a/frontend/src/components/EntityImages.svelte
+++ b/frontend/src/components/EntityImages.svelte
@@ -7,6 +7,7 @@
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
+ import ConfirmDialog from './ConfirmDialog.svelte';
import Icon from './Icon.svelte';
import Modal from './Modal.svelte';
import SearchInput from './SearchInput.svelte';
@@ -24,6 +25,7 @@
let media = $state([]);
let picked = $state([]);
let query = $state('');
+ let dropping = $state(null);
let loadSeq = 0;
const selected = $derived(
@@ -185,14 +187,31 @@
}
}
- async function removeSelected() {
+ /** One button, two acts, and only one of them is a delete.
+ *
+ * A photo chosen from the Media Library is a reference: taking it off leaves the media
+ * in the case, so it goes on the click. A photo imported from the computer exists
+ * nowhere else — this gallery is the only copy the case ever had, and it is not an
+ * artifact, so there is no Trash behind it and no Undo on the toast. That one is asked
+ * for, and the two are not called the same thing: `Remove` said nothing about which of
+ * them the click was about. */
+ function askRemove() {
if (!selected || busy) return;
+ if (selected.direct) dropping = selected;
+ else drop(selected);
+ }
+
+ async function drop(image) {
busy = true;
try {
const result = await api.del(
- `/api/cases/${caseState.current.id}/entities/${entity.id}/images/${selected.id}`
+ `/api/cases/${caseState.current.id}/entities/${entity.id}/images/${image.id}`
+ );
+ dropping = null;
+ await changed(
+ result.images,
+ image.direct ? 'Photo deleted.' : 'Photo removed from this entity.'
);
- await changed(result.images, 'Photo removed from this entity.');
} catch (error) {
toast(error.message, 'danger');
} finally {
@@ -243,10 +262,12 @@
{/if}
<button
class="btn btn-ghost btn-sm remove"
- title="Remove from this entity"
- onclick={removeSelected}
+ title={selected.direct
+ ? 'This copy exists nowhere else'
+ : 'Take it off this entity; the media stays in the case'}
+ onclick={askRemove}
disabled={busy}
- >Remove</button>
+ >{selected.direct ? 'Delete this copy' : 'Remove'}</button>
</div>
{#if images.length > 1}
<div class="thumbs" aria-label="Attached photos">
@@ -271,6 +292,19 @@
{/if}
</section>
+{#if dropping}
+ <ConfirmDialog
+ title="Delete this photo?"
+ message="It was imported into this entity, so the case holds no other copy."
+ detail="The Trash keeps deleted artifacts. A presentation photo is not one, so this cannot be brought back."
+ confirmLabel="Delete"
+ tone="danger"
+ busy={busy}
+ onconfirm={() => drop(dropping)}
+ oncancel={() => (dropping = null)}
+ />
+{/if}
+
{#if pickerOpen}
<Modal title="Choose photos" width="620px" onclose={() => (pickerOpen = false)}>
<div class="picker-head">
diff --git a/frontend/src/components/EntityImages.test.js b/frontend/src/components/EntityImages.test.js
index fffe350..5b56173 100644
--- a/frontend/src/components/EntityImages.test.js
+++ b/frontend/src/components/EntityImages.test.js
@@ -26,11 +26,28 @@ describe('entity photo gallery', () => {
});
it('detaches without deleting the underlying media', () => {
- expect(source).toContain('title="Remove from this entity"');
- expect(source).toContain('/entities/${entity.id}/images/${selected.id}`');
+ expect(source).toContain('/entities/${entity.id}/images/${image.id}`');
expect(source).not.toContain('/media?path=');
});
+ it('names the two acts apart, since only one of them is a delete', () => {
+ // "Remove" covered both: a reference the media survives, and the only copy the case
+ // ever had of an imported photo. One word for two outcomes is one of them unannounced.
+ expect(source).toContain("{selected.direct ? 'Delete this copy' : 'Remove'}");
+ expect(source).toContain('Take it off this entity; the media stays in the case');
+ expect(source).not.toContain('title="Remove from this entity"');
+ });
+
+ it('asks before deleting a photo no Trash will hold', () => {
+ // A presentation photo is not an artifact, so `engine/trash.py` never sees it and the
+ // toast carries no Undo: the click has to be the confirmation.
+ expect(source).toContain('if (selected.direct) dropping = selected;');
+ expect(source).toContain('else drop(selected);');
+ expect(source).toContain('<ConfirmDialog');
+ expect(source).toContain('tone="danger"');
+ expect(source).toContain('this cannot be brought back');
+ });
+
it('shows no empty frame and keeps an added main image bounded', () => {
expect(source).not.toContain('No photos yet.');
expect(source).toContain('height: 220px;');
diff --git a/frontend/src/components/FilterBar.svelte b/frontend/src/components/FilterBar.svelte
index 5401e9d..7d3ec44 100644
--- a/frontend/src/components/FilterBar.svelte
+++ b/frontend/src/components/FilterBar.svelte
@@ -348,7 +348,7 @@
class="chip-open"
aria-expanded={open === chip.axis}
{disabled}
- title="{axis?.hint ?? ''} — click to change it"
+ title={axis?.hint ?? 'Change this term'}
onclick={() => chose(chip.axis)}
>
{chip.text}
diff --git a/frontend/src/components/FilterBar.test.js b/frontend/src/components/FilterBar.test.js
index ed409d2..5863cc9 100644
--- a/frontend/src/components/FilterBar.test.js
+++ b/frontend/src/components/FilterBar.test.js
@@ -32,7 +32,7 @@ describe('a bar that never changes shape', () => {
// "I do not know what to click" is the fault a name and a count leave behind
expect(markup).toContain('<span class="why">{axis.hint}</span>');
expect(markup).toContain('<span class="why">{question.hint}</span>');
- expect(markup).toContain('title="{axis?.hint ?? \'\'} — click to change it"');
+ expect(markup).toContain("title={axis?.hint ?? 'Change this term'}");
expect(markup).toContain('class="heading titled"');
});
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index c05bc38..b6afa62 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -45,7 +45,14 @@
crosshair: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0-1v4m0 12v4M2 12h4m12 0h4',
user: 'M12 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Zm-8 17c0-4 3.6-6.5 8-6.5s8 2.5 8 6.5',
layers: 'm12 3 9 5-9 5-9-5 9-5Zm-9 9.5 9 5 9-5M3 17l9 5 9-5',
+ // A funnel: what a filter is drawn as everywhere, and deliberately not a
+ // magnifier — that one already means the search over the rows, and two
+ // magnifiers on one screen doing two different things is a third thing to learn.
+ filter: 'M4 5h16l-6.2 7.4V20l-3.6-2.2v-5.4L4 5Z',
grid: 'M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm9 0h7v7h-7v-7Z',
+ // A table: the frame, its header row, one column divider. Distinct from `grid`
+ // above, which is four equal cells and means an AOI sweep.
+ table: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm-1 4.5h18M10 9.5V19',
video: 'M4 6h11a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm12 4 5-3v10l-5-3',
image: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm2 12 4-4a1 1 0 0 1 1.4 0l4.6 4M9 9.5h.01',
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',
@@ -62,6 +69,10 @@
edit: 'M14 5.5 18.5 10M4 20l1-4.5L16.5 4a2.1 2.1 0 0 1 3 3L8 18.5 4 20Z',
external: 'M14 4h6v6m0-6L10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3',
grip: 'M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01',
+ // One column of `grip`'s dots: the settings of the thing beside it, rather than
+ // a handle to drag it. A chevron here read as "sort", which is the button next to
+ // this one.
+ more: 'M12 6h.01M12 12h.01M12 18h.01',
// the three assets, each drawn as itself: one shared handle icon made a lorry,
// a freighter and an airframe read as the same row in a list of twenty
car: 'M5 17h14M4 17v-4.5l2-5A1.5 1.5 0 0 1 7.4 6h9.2a1.5 1.5 0 0 1 1.4 1.5l2 5V17M4 12.5h16M7.5 17v2M16.5 17v2M8 14.5h.01M16 14.5h.01',
@@ -98,7 +109,7 @@
freehand: 'M3 17c3-9 5 5 8-2s4-8 6-2 3-2 4-5',
arrow: 'M5 19 19 5m0 0h-8m8 0v8',
text: 'M5 6V4h14v2M12 4v16m-3 0h6',
- hand: 'M8 12V6a1.5 1.5 0 0 1 3 0v5m0-6.5a1.5 1.5 0 0 1 3 0V11m0-5a1.5 1.5 0 0 1 3 0v9a6 6 0 0 1-6 6h-1a6 6 0 0 1-5-2.7L3.5 15A1.6 1.6 0 0 1 6 13.2l2 1.8',
+ cursor: 'm4 3 6.2 15.5 2.2-6.5 6.5-2.2L4 3Z',
inspect: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14Zm9 16-4.35-4.35M8 11h6m-3-3v6',
crop: 'M6 2v14a2 2 0 0 0 2 2h14M2 6h14a2 2 0 0 1 2 2v14',
screen: 'M4 5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm5 15h6m-3-4v4',
diff --git a/frontend/src/components/Modal.svelte b/frontend/src/components/Modal.svelte
index 70d8097..353d9eb 100644
--- a/frontend/src/components/Modal.svelte
+++ b/frontend/src/components/Modal.svelte
@@ -1,11 +1,15 @@
<script>
import Icon from './Icon.svelte';
import { portal } from '../lib/fullscreen.js';
+ import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';
let { title, onclose, width = '440px', children } = $props();
+ const self = {};
+ $effect(() => joinOverlays(self));
+
function onkeydown(e) {
- if (e.key === 'Escape') onclose?.();
+ if (e.key === 'Escape' && isTopOverlay(self)) onclose?.();
}
</script>
@@ -31,6 +35,8 @@
</div>
<style>
+ /* One z-index for every modal: the second one opened is later in the portal, so it
+ paints over the first without a ladder of numbers nobody can keep straight. */
.overlay {
position: fixed;
inset: 0;
diff --git a/frontend/src/components/PlateExport.render.test.js b/frontend/src/components/PlateExport.render.test.js
new file mode 100644
index 0000000..f13260d
--- /dev/null
+++ b/frontend/src/components/PlateExport.render.test.js
@@ -0,0 +1,155 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const PAGE = {
+ svg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
+ width: 900,
+ height: 600,
+ filename: 'graph-rooftop-202608132010',
+};
+
+const writePlate = vi.fn(() => Promise.resolve({ file: 'graph.svg', path: '/home/a/reports' }));
+const copyPlateImage = vi.fn(() => Promise.resolve());
+const revealPlates = vi.fn(() => Promise.resolve());
+/** The rule itself is `plateExport.test.js`'s; here it only has to be the same one. */
+const plateScale = ({ width, height }) => Math.min(2, 4000 / Math.max(width, height, 1));
+vi.mock('../lib/plateExport.js', () => ({ writePlate, copyPlateImage, revealPlates, plateScale }));
+
+const readDestinations = vi.fn(() => Promise.resolve({ views: '/home/a/reports' }));
+vi.mock('../lib/exportDest.js', () => ({
+ readDestinations,
+ destinationLabel: (path) => String(path).split('/').pop(),
+ CASE_FOLDER_LABEL: "the case's exports folder",
+}));
+
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('./views.fixture.svelte.js');
+ return { caseState, toast };
+});
+vi.mock('./ExportFolderPicker.svelte', async () => await import('./Modal.svelte'));
+
+const { caseState } = await import('./views.fixture.svelte.js');
+const { default: PlateExport } = await import('./PlateExport.svelte');
+
+let live = null;
+
+async function settle() {
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(PlateExport, { target, props: { surface: 'graph', plate: () => PAGE, ...props } });
+ flushSync();
+ target.querySelector('button').click();
+ await settle();
+ return target;
+}
+
+/** Scoped to the dialog: the toolbar button that opens it also reads "Export". */
+const pressed = (label) =>
+ [...document.querySelectorAll('.plate-form button')]
+ .find((button) => button.textContent.trim().startsWith(label));
+
+beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Bakhmut convoy' };
+ writePlate.mockClear();
+ copyPlateImage.mockClear();
+ toast.mockClear();
+ readDestinations.mockClear();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('exporting a reading', () => {
+ it('offers the vector page first, and names where the file will land', async () => {
+ await open();
+
+ expect(document.body.textContent).toContain('SVG');
+ expect(document.body.textContent).toContain('PNG');
+ expect(document.body.textContent).toContain('/home/a/reports');
+ expect(document.querySelector('input[value="svg"]').checked).toBe(true);
+ });
+
+ it('writes the plate the surface handed over, and offers the folder afterwards', async () => {
+ await open();
+ pressed('Export').click();
+ await settle();
+
+ expect(writePlate).toHaveBeenCalledWith('case-a', PAGE, { format: 'svg' });
+ expect(toast.mock.calls[0][0]).toBe('graph.svg written to reports');
+ // The toast carries the way back to the file, like every other export.
+ expect(toast.mock.calls[0][3].label).toBe('Show');
+ toast.mock.calls[0][3].onClick();
+ expect(revealPlates).toHaveBeenCalledWith('case-a');
+ });
+
+ it('sends an image when the analyst asks for one', async () => {
+ await open();
+ const png = document.querySelector('input[value="png"]');
+ png.checked = true;
+ png.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ pressed('Export').click();
+ await settle();
+
+ expect(writePlate).toHaveBeenCalledWith('case-a', PAGE, { format: 'png' });
+ });
+
+ it('copies the same page as pixels', async () => {
+ await open();
+ pressed('Copy image').click();
+ await settle();
+
+ expect(copyPlateImage).toHaveBeenCalledWith(PAGE);
+ expect(toast).toHaveBeenCalledWith('Copied as an image', 'ok');
+ });
+
+ it('says there is nothing to export rather than writing an empty page', async () => {
+ await open({ plate: () => null });
+ pressed('Export').click();
+ await settle();
+
+ expect(writePlate).not.toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith('There is nothing on the graph to export yet.', 'warn');
+ });
+
+ it('promises the scale the image will really have', async () => {
+ await open();
+ expect(document.body.textContent).toContain('twice the page size');
+
+ unmount(live);
+ live = null;
+ // A page wider than half the canvas cap cannot be rasterised at 2×, and a dialog
+ // that says otherwise sends the analyst off with a softer image than it promised.
+ await open({ plate: () => ({ ...PAGE, width: 3000, height: 2200 }) });
+ expect(document.body.textContent).toContain('at 1.3× the page size');
+ expect(document.body.textContent).not.toContain('twice the page size');
+ });
+
+ it('does not name the default folder when the saved one could not be read', async () => {
+ readDestinations.mockRejectedValueOnce(new Error('settings unreadable'));
+ await open();
+
+ expect(document.body.textContent).toContain('the folder saved for views');
+ expect(document.body.textContent).not.toContain("the case's exports folder");
+ });
+
+ it('reports a failed write instead of closing on it', async () => {
+ writePlate.mockRejectedValueOnce(new Error('folder is read-only'));
+ await open();
+ pressed('Export').click();
+ await settle();
+
+ expect(toast).toHaveBeenCalledWith('Export failed: folder is read-only', 'danger');
+ expect(document.body.textContent).toContain('Destination');
+ });
+});
diff --git a/frontend/src/components/PlateExport.svelte b/frontend/src/components/PlateExport.svelte
new file mode 100644
index 0000000..127bf3f
--- /dev/null
+++ b/frontend/src/components/PlateExport.svelte
@@ -0,0 +1,156 @@
+<script>
+ /** Exporting the reading on screen as a plate — one dialog for Graph and Timeline.
+ *
+ * The surface hands over a callback that serialises what it is drawing; nothing here
+ * knows how a graph or an axis is drawn. See `lib/plate.js` for what a plate is. */
+ import { copyPlateImage, plateScale, revealPlates, writePlate } from '../lib/plateExport.js';
+ import { CASE_FOLDER_LABEL, destinationLabel, readDestinations } from '../lib/exportDest.js';
+ import { caseState, toast } from '../lib/state.svelte.js';
+ import ExportFolderPicker from './ExportFolderPicker.svelte';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+
+ let {
+ /** Serialise what is on screen: `{ svg, width, height, filename }`, or null. */
+ plate = () => null,
+ /** What the reading is called in the toast: "graph" or "timeline". */
+ surface = 'graph',
+ disabled = false,
+ } = $props();
+
+ let open = $state(false);
+ let format = $state('svg');
+ /** The saved destination: `null` until the settings answer, `''` for the case folder. */
+ let destination = $state(null);
+ let destRead = $state(true);
+ let chosen = $state(false);
+ let picker = $state(false);
+ let busy = $state(false);
+ /** The reading, serialised when the dialog opened: the surface behind a modal cannot
+ * change, and the size of the page decides what the PNG can honestly promise. */
+ let page = $state(null);
+
+ const scale = $derived(page ? plateScale(page) : null);
+ const pngNote = $derived(
+ scale === null || scale > 1.95
+ ? 'An image, at twice the page size.'
+ : scale >= 1
+ ? `An image, at ${scale.toFixed(1)}× the page size.`
+ : 'An image, smaller than the page this reading needs.'
+ );
+ /** Never the default's wording while the saved folder is unknown: a plate would land
+ * somewhere else and the dialog would have said the case folder. */
+ const destLabel = $derived(
+ destination !== null
+ ? destination || CASE_FOLDER_LABEL
+ : destRead ? 'Reading the saved folder…' : 'the folder saved for views'
+ );
+
+ function start() {
+ open = true;
+ chosen = false;
+ destRead = true;
+ page = plate();
+ readDestinations()
+ // Not over a folder the analyst has since picked: they are faster than a fetch.
+ .then((dirs) => { if (!chosen) destination = dirs.views; })
+ .catch(() => { destRead = false; });
+ }
+
+ /** Say plainly when there was nothing to serialise. */
+ function drawn() {
+ if (!page?.svg) {
+ toast(`There is nothing on the ${surface} to export yet.`, 'warn');
+ return null;
+ }
+ return page;
+ }
+
+ async function run() {
+ const caseId = caseState.current?.id;
+ const page = drawn();
+ if (!caseId || !page || busy) return;
+ busy = true;
+ try {
+ const result = await writePlate(caseId, page, { format });
+ open = false;
+ toast(`${result.file} written to ${destinationLabel(result.path)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () => revealPlates(caseId).catch((error) => toast(error.message, 'warn')),
+ });
+ } catch (error) {
+ toast(`Export failed: ${error.message}`, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function copy() {
+ const page = drawn();
+ if (!page || busy) return;
+ busy = true;
+ try {
+ await copyPlateImage(page);
+ open = false;
+ toast('Copied as an image', 'ok');
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+</script>
+
+<button class="btn btn-sm" {disabled} onclick={start} title="Export this reading">
+ <Icon name="download" size={13} /> Export
+</button>
+
+{#if open}
+ <Modal title="Export this reading" onclose={() => (open = false)} width="480px">
+ <div class="plate-form">
+ <label class="choice">
+ <input type="radio" bind:group={format} value="svg" />
+ <span><strong>SVG</strong><small>Vector: zooms without softening, and the text stays text.</small></span>
+ </label>
+ <label class="choice">
+ <input type="radio" bind:group={format} value="png" />
+ <span><strong>PNG</strong><small>{pngNote}</small></span>
+ </label>
+ <div class="dest">
+ <span>Destination</span>
+ <span class="path mono" title={destLabel}>{destLabel}</span>
+ <button class="btn btn-ghost btn-sm" onclick={() => (picker = true)}>Change</button>
+ </div>
+ <p class="note">The plate carries the lens, the question, the window and the legend.</p>
+ <div class="actions">
+ <button class="btn" onclick={() => (open = false)}>Cancel</button>
+ <button class="btn" disabled={busy} onclick={copy}>
+ <Icon name="copy" size={12} /> Copy image
+ </button>
+ <button class="btn btn-primary" disabled={busy} onclick={run}>
+ {busy ? 'Exporting…' : 'Export'}
+ </button>
+ </div>
+ </div>
+ </Modal>
+{/if}
+
+{#if picker}
+ <ExportFolderPicker
+ kind="views"
+ current={destination ?? ''}
+ onclose={() => (picker = false)}
+ onchosen={(path) => { chosen = true; destination = path; }}
+ />
+{/if}
+
+<style>
+ .plate-form { display: grid; gap: 12px; }
+ .choice { display: flex; align-items: flex-start; gap: 9px; padding: 9px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .choice span, .choice small { display: block; }
+ .choice small { margin-top: 3px; color: var(--text-3); }
+ .dest { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: var(--fs-sm); }
+ .path { min-width: 0; flex: 1 1 auto; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-3); }
+ .note { margin: 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
+</style>
diff --git a/frontend/src/components/ProofGlyph.svelte b/frontend/src/components/ProofGlyph.svelte
new file mode 100644
index 0000000..f81e2f8
--- /dev/null
+++ b/frontend/src/components/ProofGlyph.svelte
@@ -0,0 +1,31 @@
+<script>
+ /** One proof symbol, drawn for the interface — the toolbar picker and the
+ * layer list. The canvas draws the same paths through Konva; this is the
+ * DOM half so a button can show what it stamps. */
+ import { ICON_BOX, iconByName, isSolidIcon } from '../lib/proofIcons.js';
+
+ let { name, size = 20, color = 'currentColor' } = $props();
+
+ const entry = $derived(iconByName(name));
+ const solid = $derived(isSolidIcon(name));
+</script>
+
+{#if entry}
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 {ICON_BOX} {ICON_BOX}"
+ aria-hidden="true"
+ focusable="false"
+ >
+ <path
+ d={entry.path}
+ fill={solid ? color : 'none'}
+ fill-rule={solid ? 'evenodd' : null}
+ stroke={solid ? 'none' : color}
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ />
+ </svg>
+{/if}
diff --git a/frontend/src/components/ProofPreview.svelte b/frontend/src/components/ProofPreview.svelte
index f266b79..cf7efdc 100644
--- a/frontend/src/components/ProofPreview.svelte
+++ b/frontend/src/components/ProofPreview.svelte
@@ -19,6 +19,7 @@
normalizeProofStyle, textColors, attributionLine, loadImage,
BG, CAPTION_SIZE, FOOTER_SIZE, SIG_SCALE, SIG_TEXT_SIZE,
} from '../lib/composer.js';
+ import { closeStrandedGesture } from '../lib/konvaGesture.js';
import { prefs } from '../lib/state.svelte.js';
let { style = $bindable(), logoMissing = $bindable(false) } = $props();
@@ -61,10 +62,14 @@
const space = safeStyle.space;
const bg = safeStyle.bg ?? BG;
const tc = textColors(bg);
+ // The preview has no proof behind it, so the band shows the credit line the
+ // style asks for and nothing else: coordinates are content, and a house style
+ // holds none.
+ const footerOn = safeStyle.footerEnabled && safeStyle.footerText !== false;
const text = {
captionSize: safeStyle.captionSize ?? CAPTION_SIZE,
footerSize: safeStyle.footerSize ?? FOOTER_SIZE,
- footerEnabled: safeStyle.footerEnabled,
+ footerEnabled: footerOn,
};
const pnls = panels(safeStyle);
const { width, height } = docSize(pnls, [], {}, text, [], 'grid', space);
@@ -100,7 +105,7 @@
});
// footer
- if (text.footerEnabled) {
+ if (footerOn) {
const fs = text.footerSize;
layer.add(new Konva.Text({
x: space.pad, y: height - space.pad - footerBand(fs) + Math.round((footerBand(fs) - fs) / 2),
@@ -217,6 +222,22 @@
cw = host.clientWidth || cw;
ro.observe(host);
}
+ // A release the page never sees leaves Konva resizing the signature under a
+ // bare pointer, and the size it settles on never reaches the template. Each
+ // render builds a new transformer, so the live one is read at close time
+ // rather than held. A frame's delay lets a healthy gesture close itself.
+ const closeStranded = () => {
+ if (!stage) return;
+ closeStrandedGesture({
+ transformer: layer.findOne('Transformer'),
+ stage,
+ isDragging: () => Konva.isDragging(),
+ });
+ };
+ const settlePointer = () => requestAnimationFrame(closeStranded);
+ window.addEventListener('pointerup', settlePointer, true);
+ window.addEventListener('pointercancel', settlePointer, true);
+ window.addEventListener('blur', settlePointer);
// load the real signature once; a missing file flips logoMissing for the editor
loadImage('/api/settings/signature.png')
.then((img) => { sigImg = img; logoMissing = false; render(); })
@@ -224,7 +245,11 @@
render();
return () => {
ro.disconnect();
+ window.removeEventListener('pointerup', settlePointer, true);
+ window.removeEventListener('pointercancel', settlePointer, true);
+ window.removeEventListener('blur', settlePointer);
stage?.destroy();
+ stage = null;
};
});
@@ -232,7 +257,8 @@
$effect(() => {
JSON.stringify([
style.bg, style.space, style.captionSize, style.footerSize,
- style.footer, style.footerEnabled, style.footerColor, style.footerAlign, style.captionsEnabled,
+ style.footer, style.footerEnabled, style.footerText, style.footerColor, style.footerAlign,
+ style.captionsEnabled,
style.panelDirection,
style.signature, style.signatureText,
]);
diff --git a/frontend/src/components/ProofTemplateEditor.svelte b/frontend/src/components/ProofTemplateEditor.svelte
index 421a625..469b8b0 100644
--- a/frontend/src/components/ProofTemplateEditor.svelte
+++ b/frontend/src/components/ProofTemplateEditor.svelte
@@ -168,8 +168,16 @@
onchange={(e) => (data.footerEnabled = e.target.checked)} /> Show footer</label>
</span>
{#if footerOn}
- <input type="text" placeholder="Composed with Azimut" maxlength="200"
- bind:value={data.footer} />
+ <!-- What the band prints. A style saved before these existed says
+ nothing about them and leaves a proof's own answer alone. -->
+ <label class="chk"><input type="checkbox" checked={data.footerCoords === true}
+ onchange={(e) => (data.footerCoords = e.target.checked)} /> Show coordinates</label>
+ <label class="chk"><input type="checkbox" checked={data.footerText !== false}
+ onchange={(e) => (data.footerText = e.target.checked)} /> Show text</label>
+ {#if data.footerText !== false}
+ <input type="text" placeholder="Composed with Azimut" maxlength="200"
+ bind:value={data.footer} />
+ {/if}
<div class="color-row">
<span>Colour</span>
<input type="color" value={data.footerColor ?? autoFooterColor}
diff --git a/frontend/src/components/RelationList.svelte b/frontend/src/components/RelationList.svelte
index 59d6148..399a94f 100644
--- a/frontend/src/components/RelationList.svelte
+++ b/frontend/src/components/RelationList.svelte
@@ -27,10 +27,12 @@
relationOptions,
relationQualifier,
relationReading,
+ retractionWarning,
} from '../lib/relations.svelte.js';
import { loadEntityTypes, reliabilityOf } from '../lib/entityTypes.svelte.js';
import { entityIcon } from '../lib/entityIcon.js';
import { openEntity } from '../lib/navigate.js';
+ import ConfirmDialog from './ConfirmDialog.svelte';
import Icon from './Icon.svelte';
let {
@@ -56,6 +58,8 @@
let expanded = $state(false);
let busyId = $state(null);
+ //: The retraction waiting on an answer: `{ link, suggested, action, words }`.
+ let retracting = $state(null);
/**
* A row control acts on its own relation, and nothing above it should treat the
@@ -223,10 +227,21 @@
/** Drop the edge. The same gesture whichever status it had, because a relation
* is a statement and taking it back is the only way to correct one — the
* wording differs so it reads as "not that" on a proposal and "no longer
- * true" on something the analyst had already accepted. */
+ * true" on something the analyst had already accepted.
+ *
+ * A proposal goes on the click; a statement the analyst made is asked about first
+ * (`retractionWarning`), since nothing holds it afterwards. */
+ function askRemove(link, suggested, action) {
+ if (busyId) return;
+ const words = retractionWarning(link, action);
+ if (words) retracting = { link, suggested, action, words };
+ else remove(link, suggested, action);
+ }
+
async function remove(link, suggested, action) {
if (busyId) return;
busyId = link.id;
+ retracting = null;
try {
await api.del(`/api/cases/${caseId}/links/${link.id}`);
const noun = action === 'mention' ? 'Mention' : 'Relation';
@@ -298,7 +313,7 @@
class="btn btn-ghost btn-sm act no"
title={suggested ? `Dismiss this ${action}` : `Remove this ${action}`}
disabled={busyId === relation.link.id}
- onclick={own(() => remove(relation.link, suggested, action))}
+ onclick={own(() => askRemove(relation.link, suggested, action))}
>
<Icon name="x" size={12} />
</button>
@@ -388,6 +403,19 @@
</div>
{/if}
+{#if retracting}
+ <ConfirmDialog
+ title={retracting.words.title}
+ message={retracting.words.message}
+ detail={retracting.words.detail}
+ confirmLabel={retracting.words.confirmLabel}
+ tone="danger"
+ busy={busyId === retracting.link.id}
+ onconfirm={() => remove(retracting.link, retracting.suggested, retracting.action)}
+ oncancel={() => (retracting = null)}
+ />
+{/if}
+
<style>
.relations {
display: flex;
diff --git a/frontend/src/components/RelationList.test.js b/frontend/src/components/RelationList.test.js
index 568b007..38aca35 100644
--- a/frontend/src/components/RelationList.test.js
+++ b/frontend/src/components/RelationList.test.js
@@ -36,11 +36,24 @@ describe('RelationList', () => {
expect(source).toContain("const noun = action === 'mention' ? 'Mention' : 'Relation';");
expect(source).toContain('title={suggested ? `Dismiss this ${action}` : `Remove this ${action}`}');
// the remove button sits outside the suggested-only branch
- const removeAt = source.indexOf('onclick={own(() => remove(relation.link, suggested, action))}');
+ const removeAt = source.indexOf(
+ 'onclick={own(() => askRemove(relation.link, suggested, action))}'
+ );
const branchEnd = source.indexOf('{/if}', source.indexOf('{#if suggested}'));
expect(removeAt).toBeGreaterThan(branchEnd);
});
+ it('asks before a stated relation goes, and not before a proposal', () => {
+ // A proposal is a tool's guess and dismissing it is the review gesture this panel is
+ // for. A relation the analyst stated is the case's own claim, and `remove_relation`
+ // holds it nowhere — so that one is the click that has to be meant.
+ expect(source).toContain('const words = retractionWarning(link, action);');
+ expect(source).toContain('if (words) retracting = { link, suggested, action, words };');
+ expect(source).toContain('else remove(link, suggested, action);');
+ expect(source).toContain('<ConfirmDialog');
+ expect(source).toContain('tone="danger"');
+ });
+
it('corrects a wrong reading on the same edge, without deleting it', () => {
// a relation stays editable: same id, same provenance, right verb
expect(source).toContain("api.patch(`/api/cases/${caseId}/links/${link.id}`, { type })");
@@ -76,7 +89,7 @@ describe('RelationList', () => {
for (const wired of [
'onclick={own(() => walk(relation.entity))}',
'onclick={own(() => confirm(relation.link))}',
- 'onclick={own(() => remove(relation.link, suggested, action))}',
+ 'onclick={own(() => askRemove(relation.link, suggested, action))}',
'onclick={own(() => (expanded = true))}',
]) {
expect(source).toContain(wired);
diff --git a/frontend/src/components/SheetAnchors.svelte b/frontend/src/components/SheetAnchors.svelte
new file mode 100644
index 0000000..b69b1a4
--- /dev/null
+++ b/frontend/src/components/SheetAnchors.svelte
@@ -0,0 +1,158 @@
+<script>
+ /**
+ * The **sync points** several rows are lined up on, and the time each one happened.
+ *
+ * The method no consumer tool has. Ten videos of one event each carry an offset against
+ * a shot that is visible and audible in all of them — `-00:01:50`, `00:04:04` — and the
+ * binders wrote exactly that, in a column called `start synchro`. Their **relative
+ * order is usable straight away**, before anybody knows what time anything happened.
+ * The moment the shot itself is dated, every one of those rows has an absolute time to
+ * the second.
+ *
+ * Named here rather than on the columns, because one moment serves several of them and a
+ * time restated per column is a time that will disagree with itself. A sheet holds
+ * several: the binders had `start synchro` *and* `end synchro`, and a real event has
+ * more than one moment that several videos happen to catch.
+ *
+ * Dating one is optional and staying undated is the normal state. What it costs is only
+ * the absolute times; the ordering is already there.
+ */
+ import Icon from './Icon.svelte';
+ import { MAX_ANCHORS, MAX_ANCHOR_NAME, formatOffset, offsetMoment, parseOffset } from '../lib/sheetRoles.js';
+
+ let { table, meta, onchange, onclose } = $props();
+
+ const anchors = $derived(Object.entries(meta?.anchors ?? {}));
+ /** Which columns count from each anchor, so renaming or dropping one is not done blind. */
+ const columns = $derived(
+ Object.entries(meta?.roles ?? {}).filter(([, role]) => role?.kind === 'offset'),
+ );
+
+ let adding = $state('');
+
+ function counting(name) {
+ return columns.filter(([, role]) => role.anchor === name).map(([column]) => column);
+ }
+
+ /** What one anchor's column would read once it is dated: the first row that carries an
+ * offset, shown as the time it lands on. A worked example beats a rule — nobody can
+ * check `-00:01:50` against `01:57:00Z` in their head. */
+ function example(name, at) {
+ const [column] = counting(name);
+ if (!column || !at) return null;
+ const index = (table?.columns ?? []).indexOf(column);
+ for (const row of table?.rows ?? []) {
+ const seconds = parseOffset(row[index]);
+ if (seconds !== null) {
+ return { offset: formatOffset(seconds), moment: offsetMoment(at, seconds) };
+ }
+ }
+ return null;
+ }
+
+ function set(name, at) {
+ onchange({ ...(meta.anchors ?? {}), [name]: { at } });
+ }
+
+ function drop(name) {
+ const next = { ...(meta.anchors ?? {}) };
+ delete next[name];
+ onchange(next);
+ }
+
+ function add() {
+ const name = adding.trim().slice(0, MAX_ANCHOR_NAME);
+ if (!name || meta?.anchors?.[name]) return;
+ adding = '';
+ set(name, '');
+ }
+</script>
+
+<div class="anchors">
+ <p class="lead">
+ A <strong>sync point</strong> is one moment visible in several rows: a launch, an impact, a
+ shot heard in every video. Name it now and date it later; the order the rows run in does
+ not wait for that.
+ </p>
+
+ <div class="list">
+ {#each anchors as [name, entry] (name)}
+ {@const used = counting(name)}
+ {@const shown = example(name, entry.at)}
+ <div class="entry">
+ <div class="head">
+ <Icon name="clock" size={12} />
+ <span class="name">{name}</span>
+ <div class="spacer"></div>
+ <button class="drop" title="Remove this sync point" aria-label="Remove {name}"
+ onclick={() => drop(name)}>
+ <Icon name="x" size={12} />
+ </button>
+ </div>
+ <label class="field">
+ <span>When it happened</span>
+ <input class="input" type="datetime-local" step="1"
+ aria-label="When {name} happened"
+ value={(entry.at ?? '').replace('Z', '').slice(0, 19)}
+ onchange={(event) =>
+ set(name, event.currentTarget.value ? `${event.currentTarget.value}Z` : '')} />
+ </label>
+ <p class="why">
+ {#if used.length}
+ {used.join(', ')} {used.length === 1 ? 'is' : 'are'} synced on it.
+ {:else}
+ No column is synced on it yet. Set a column's type to <em>Offset</em>.
+ {/if}
+ {#if shown?.moment}
+ <br />{shown.offset} lands on {shown.moment.replace('T', ' ').slice(0, 19)}.
+ {:else if !entry.at}
+ <br />Undated, so the rows have an order and no times.
+ {/if}
+ </p>
+ </div>
+ {:else}
+ <p class="hint">No sync point named yet.</p>
+ {/each}
+ </div>
+
+ {#if anchors.length < MAX_ANCHORS}
+ <div class="add">
+ <input class="input" placeholder="what happens at it"
+ aria-label="Name a sync point" bind:value={adding}
+ onkeydown={(event) => event.key === 'Enter' && add()} />
+ <button class="btn btn-sm" disabled={!adding.trim()} onclick={add}>Name it</button>
+ </div>
+ {/if}
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Done</button>
+ </div>
+</div>
+
+<style>
+ .anchors { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .list { max-height: 340px; overflow: auto; margin-top: 12px; }
+ .entry {
+ padding: 7px 9px; margin-bottom: 6px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .head { display: flex; align-items: center; gap: 6px; color: var(--text-3); }
+ .name {
+ min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-1); font-size: var(--fs-sm);
+ }
+ .drop { flex: none; color: var(--text-3); }
+ .drop:hover { color: var(--danger); }
+ .field { display: block; padding: 5px 0 2px; }
+ .field span { display: block; color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 3px; }
+ .field .input { width: 100%; }
+ .why { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+ .why em { font-style: normal; color: var(--text-2); }
+ .hint { padding: 14px 10px; color: var(--text-3); font-size: var(--fs-sm); line-height: 1.5; }
+ .add { display: flex; gap: 6px; margin-top: 8px; }
+ .add .input { flex: 1; }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetAppend.svelte b/frontend/src/components/SheetAppend.svelte
new file mode 100644
index 0000000..c9e03b5
--- /dev/null
+++ b/frontend/src/components/SheetAppend.svelte
@@ -0,0 +1,147 @@
+<script>
+ /**
+ * Adding a batch of rows to the sheet that is already open.
+ *
+ * Import filed a **new sheet**, always — right the first time and wrong every time after
+ * it. The daily batch of links, the second export out of the same tool, the forty rows a
+ * colleague sent: all of them belong in the worklist that already carries the statuses,
+ * the roles and the colours, and the only ways in were to paste into a selection whose
+ * columns happened to line up, or to keep twelve sheets nobody compares.
+ *
+ * Two answers here and nothing else. **Which columns land where**, proposed by name and
+ * then the analyst's; and **what would be dropped**, said before the press, because "40
+ * rows added" over three silently discarded columns is the kind of import somebody finds
+ * out about a week later.
+ *
+ * The CSV is parsed by the server (`POST /sheets/parse`) like every other CSV in this app.
+ * The append itself is an ordinary structural edit, so it undoes like anything else.
+ */
+ import Icon from './Icon.svelte';
+ import { api } from '../lib/api.js';
+ import { ID_COLUMN } from '../lib/sheet.js';
+ import { guessMapping, mappingSummary } from '../lib/sheetAppend.js';
+
+ let { caseId, table, onappend, onclose } = $props();
+
+ let text = $state('');
+ let incoming = $state(null); // { columns, rows }
+ let mapping = $state({});
+ let reading = $state(false);
+ let failed = $state('');
+
+ const columns = $derived(
+ (table?.columns ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+ const summary = $derived(incoming ? mappingSummary(incoming.columns, mapping) : null);
+ const ready = $derived(Boolean(incoming?.rows?.length && summary?.taken));
+
+ async function read() {
+ if (!text.trim() || reading) return;
+ reading = true;
+ failed = '';
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/parse`, { text });
+ incoming = answer;
+ mapping = guessMapping(answer.columns, table?.columns ?? []);
+ } catch (error) {
+ failed = error?.message || 'That table could not be read.';
+ incoming = null;
+ } finally {
+ reading = false;
+ }
+ }
+
+ function pick(name, onto) {
+ mapping = { ...mapping, [name]: onto };
+ }
+
+ function pickFile(files) {
+ const file = files?.[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = () => {
+ text = String(reader.result ?? '');
+ read();
+ };
+ reader.readAsText(file);
+ }
+</script>
+
+<div class="append">
+ {#if !incoming}
+ <p class="lead">
+ Paste the rows, or pick a file. The delimiter is guessed, and every row is keyed here.
+ </p>
+ <textarea class="input paste-box" rows="8" bind:value={text} aria-label="The rows to add"
+ placeholder="id,url,city&#10;…"></textarea>
+ {#if failed}<p class="failed" role="alert">{failed}</p>{/if}
+ <div class="modal-row">
+ <label class="btn btn-sm">
+ <Icon name="upload" size={13} /> Pick a file
+ <input type="file" accept=".csv,.tsv,text/csv,text/plain" hidden
+ onchange={(event) => { pickFile(event.currentTarget.files); event.currentTarget.value = ''; }} />
+ </label>
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={!text.trim() || reading} onclick={read}>
+ {reading ? 'Reading' : 'Read it'}
+ </button>
+ </div>
+ {:else}
+ <p class="lead">
+ <strong>{incoming.rows.length}</strong> {incoming.rows.length === 1 ? 'row' : 'rows'},
+ {incoming.columns.length} {incoming.columns.length === 1 ? 'column' : 'columns'}. Say
+ where each one lands.
+ </p>
+ <div class="pairs">
+ {#each incoming.columns as name (name)}
+ {#if String(name).toLowerCase() !== ID_COLUMN}
+ <label class="pair">
+ <span class="from" title={name}>{name}</span>
+ <Icon name="arrowRight" size={11} />
+ <select class="input" value={mapping[name] ?? ''} aria-label="Where {name} lands"
+ onchange={(event) => pick(name, event.currentTarget.value)}>
+ <option value="">— leave it out</option>
+ {#each columns as onto (onto)}<option value={onto}>{onto}</option>{/each}
+ </select>
+ </label>
+ {/if}
+ {/each}
+ </div>
+ {#if summary.dropped.length}
+ <p class="note">
+ Left out: {summary.dropped.join(', ')}. Add a column to this sheet first to keep them.
+ </p>
+ {/if}
+ {#if failed}<p class="failed" role="alert">{failed}</p>{/if}
+ <div class="modal-row">
+ <button class="btn btn-sm" onclick={() => { incoming = null; failed = ''; }}>Back</button>
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={!ready}
+ onclick={() => onappend(incoming, mapping)}>
+ Add {incoming.rows.length} {incoming.rows.length === 1 ? 'row' : 'rows'}
+ </button>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .append { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .lead strong { color: var(--text-1); }
+ .paste-box { width: 100%; margin-top: 10px; font-family: var(--font-mono); resize: vertical; }
+ .pairs { max-height: 320px; overflow: auto; margin-top: 12px; }
+ .pair {
+ display: grid; grid-template-columns: minmax(0, 1fr) auto 190px; align-items: center;
+ gap: 8px; padding: 3px 0;
+ }
+ .from {
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-1); font-size: var(--fs-sm);
+ }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 4px 0; }
+ .failed { color: var(--danger); font-size: var(--fs-sm); margin-top: 10px; }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetBridge.render.test.js b/frontend/src/components/SheetBridge.render.test.js
new file mode 100644
index 0000000..89671e1
--- /dev/null
+++ b/frontend/src/components/SheetBridge.render.test.js
@@ -0,0 +1,549 @@
+// @vitest-environment happy-dom
+/**
+ * The screens the bridge to the case is made of, actually mounted.
+ *
+ * Each is a **plan read before it is pressed**, which is the promise the road is safe
+ * under: forty rows becoming forty entities is not a thing to find out about afterwards.
+ * So what these drive is the half a lib suite cannot — that the screen asks the server
+ * what would happen, shows that answer, and only then offers a button that writes.
+ *
+ * And the two answers the hours form exists to ask for, because guessing either would move
+ * evidence in time: which day a column of bare clocks belongs to, and which zone it is
+ * written in. It answers them by **showing one row read back**, which is checkable by eye.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+const post = vi.fn();
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+
+const { default: SheetToCase } = await import('./SheetToCase.svelte');
+const { default: SheetDate } = await import('./SheetDate.svelte');
+const { default: SheetAnchors } = await import('./SheetAnchors.svelte');
+
+const TABLE = {
+ columns: ['id', 'Subject', 'Local time', 'Est. time', 'start synchro'],
+ rows: [
+ ['r1', 'First impact', '01:57', '', '-00:01:50'],
+ ['r2', 'Second impact', '', '02:05', '00:04:04'],
+ ],
+};
+const META = {
+ roles: { 'start synchro': { kind: 'offset', anchor: 'IGLA launch' } },
+ anchors: { 'IGLA launch': { at: '2026-01-03T01:57:00Z' } },
+};
+
+let live = null;
+
+function open(component, props) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(component, { target, props });
+ flushSync();
+ return target;
+}
+
+async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+}
+
+/** The DOM keeps the source's line breaks, so a sentence written across two lines in the
+ * markup arrives with them. Asserting on prose means asserting on the words. */
+const flat = (target) => target.textContent.replace(/\s+/g, ' ');
+
+const labels = (target) =>
+ [...target.querySelectorAll('button')].map((node) => node.textContent.trim());
+
+const press = (target, text) => {
+ const found = [...target.querySelectorAll('button')].find((node) =>
+ node.textContent.trim().startsWith(text),
+ );
+ found.click();
+ flushSync();
+};
+
+/** The registry the promotion screens read their types out of. Two is enough: what is
+ * under test is the plan, not the vocabulary. */
+const TYPES = [
+ { type: 'person', label: 'Person', promotable: true, attrs: [] },
+ { type: 'organization', label: 'Organization', promotable: true, attrs: [] },
+ { type: 'structure', label: 'Structure', promotable: true, attrs: [] },
+ { type: 'place', label: 'Place', promotable: true, attrs: [] },
+];
+
+/** The relation registry, cut to the three verbs these tests turn on: one pair with a
+ * single reading, one with two, and one pair the vocabulary joins by nothing. */
+const RELATIONS = [
+ {
+ type: 'member-of', label: 'is a member of', inverse_label: 'has member',
+ manual: true, action: 'relation', group: '',
+ from_types: ['person', 'organization'], to_types: ['organization'],
+ from_media_kinds: [], to_media_kinds: [],
+ },
+ {
+ type: 'owns', label: 'owns', inverse_label: 'is owned by',
+ manual: true, action: 'relation', group: '',
+ from_types: ['person', 'organization'], to_types: ['organization'],
+ from_media_kinds: [], to_media_kinds: [],
+ },
+ {
+ type: 'sited-at', label: 'is sited at', inverse_label: 'is the site of',
+ manual: true, action: 'relation', group: '',
+ from_types: ['structure'], to_types: ['place'],
+ from_media_kinds: [], to_media_kinds: [],
+ },
+];
+
+beforeEach(() => {
+ get.mockReset();
+ post.mockReset();
+ get.mockImplementation((url) => {
+ if (url.endsWith('/relation-types')) return Promise.resolve(RELATIONS);
+ if (url.endsWith('/confidence-levels')) return Promise.resolve([]);
+ return Promise.resolve(TYPES);
+ });
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('the hours form, as one mode of the pass', () => {
+ const onchoices = vi.fn();
+
+ beforeEach(() => onchoices.mockReset());
+
+ function screen(props = {}) {
+ return open(SheetDate, {
+ table: TABLE,
+ meta: { ...META, roles: { ...META.roles, 'Local time': { kind: 'when' } } },
+ subject: 'Subject',
+ onchoices,
+ ...props,
+ });
+ }
+
+ it('picks the column the sheet already says holds a time', async () => {
+ const target = screen();
+ await settle();
+ expect(target.querySelector('[aria-label="The established hour"]').value).toBe('Local time');
+ expect(onchoices).toHaveBeenCalledWith(
+ expect.objectContaining({ when_column: 'Local time' }),
+ );
+ });
+
+ it('asks for the day only where the cells hold clocks, and says why', async () => {
+ const target = screen();
+ await settle();
+ expect(target.querySelector('[aria-label="The day these hours belong to"]')).toBeTruthy();
+ expect(flat(target)).toContain('These cells hold clocks with no day');
+ });
+
+ it('reads one row back, which is how the day and the zone are checked', async () => {
+ const target = screen();
+ await settle();
+ // Before a day: the moment cannot be spelled, and it says so rather than guessing today.
+ expect(flat(target)).toContain('waiting for the day');
+
+ const day = target.querySelector('[aria-label="The day these hours belong to"]');
+ day.value = '2026-01-03';
+ day.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ expect(flat(target)).toContain('2026-01-03 01:57 local');
+ expect(onchoices).toHaveBeenCalledWith(expect.objectContaining({ day: '2026-01-03' }));
+ });
+
+ it('folds away the answers that have a right default', async () => {
+ const target = screen();
+ await settle();
+ expect(target.querySelector('[aria-label="What the time says"]')).toBeFalsy();
+ press(target, 'More answers');
+ await settle();
+ expect(target.querySelector('[aria-label="What the time says"]')).toBeTruthy();
+ expect(target.querySelector('[aria-label="The time zone this column is in"]')).toBeTruthy();
+ });
+
+ it('offers the other road when the sheet has an offset column', async () => {
+ const target = screen();
+ await settle();
+ expect(labels(target)).toContain('From a sync point');
+
+ press(target, 'From a sync point');
+ await settle();
+ // The anchor and its time are said, because "-00:01:50 from what, exactly" is the
+ // question this road has to answer.
+ expect(target.textContent).toContain('IGLA launch');
+ expect(flat(target)).toContain('is dated 2026-01-03 01:57:00');
+ });
+
+ it('says an undated sync point dates nothing rather than failing quietly', async () => {
+ const target = screen({
+ meta: { ...META, anchors: { 'IGLA launch': { at: '' } } },
+ });
+ await settle();
+ press(target, 'From a sync point');
+ await settle();
+ expect(flat(target)).toContain('has no time yet, so nothing can be dated from it');
+ });
+
+ it('offers to date an undated sync point instead of ending on the sentence', async () => {
+ const onanchors = vi.fn();
+ const target = screen({
+ meta: { ...META, anchors: { 'IGLA launch': { at: '' } } },
+ onanchors,
+ });
+ await settle();
+ press(target, 'From a sync point');
+ await settle();
+
+ // The rows already carry their order; the shot's own time is the only thing between
+ // that and real hours, so it is a press away rather than three screens back.
+ press(target, 'Date it');
+ expect(onanchors).toHaveBeenCalled();
+ });
+
+ it('does not offer to date a sync point that is already dated', async () => {
+ const target = screen({ onanchors: vi.fn() });
+ await settle();
+ press(target, 'From a sync point');
+ await settle();
+ expect(labels(target)).not.toContain('Date it');
+ });
+
+ it('reports nothing at all until it has a column to read', async () => {
+ const target = screen({ meta: { ...META } });
+ await settle();
+ const when = target.querySelector('[aria-label="The established hour"]');
+ expect(when.value).toBe('');
+ expect(onchoices).toHaveBeenCalledWith(null);
+ });
+});
+
+describe('the sync points rows are lined up on', () => {
+ const onchange = vi.fn();
+
+ beforeEach(() => onchange.mockReset());
+
+ it('says which columns are synced on it, and what one offset lands on', () => {
+ const target = open(SheetAnchors, {
+ table: TABLE,
+ meta: META,
+ onchange,
+ onclose: vi.fn(),
+ });
+ expect(target.textContent).toContain('IGLA launch');
+ expect(flat(target)).toContain('start synchro is synced on it');
+ // A worked example, because nobody checks `-00:01:50` against `01:57:00Z` in their head.
+ expect(target.textContent).toContain('-00:01:50 lands on 2026-01-03 01:55:10');
+ });
+
+ it('says an undated sync point leaves the rows their order and no times', () => {
+ const target = open(SheetAnchors, {
+ table: TABLE,
+ meta: { ...META, anchors: { 'IGLA launch': { at: '' } } },
+ onchange,
+ onclose: vi.fn(),
+ });
+ expect(target.textContent).toContain('Undated, so the rows have an order and no times');
+ });
+
+ it('names a new one without dating it, because that is the normal state', () => {
+ const target = open(SheetAnchors, {
+ table: TABLE,
+ meta: { ...META, anchors: {} },
+ onchange,
+ onclose: vi.fn(),
+ });
+ const box = target.querySelector('[aria-label="Name a sync point"]');
+ box.value = 'second impact';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ press(target, 'Name it');
+ expect(onchange).toHaveBeenCalledWith({ 'second impact': { at: '' } });
+ });
+});
+
+
+describe('a whole sheet into the case, in one declaration', () => {
+ const onpreview = vi.fn();
+ const onpass = vi.fn();
+
+ const ROSTER = {
+ columns: ['id', 'Name', 'Unit', 'Coordinates', 'Source'],
+ rows: [['r1', 'Ivanov', '3rd Brigade', '48.5, 35.1', 'https://example.org/a']],
+ };
+ const ROLES = {
+ roles: { Coordinates: { kind: 'latlon' }, Source: { kind: 'url' } },
+ };
+
+ beforeEach(() => {
+ onpreview.mockReset();
+ onpass.mockReset();
+ });
+
+ function screen(props = {}) {
+ return open(SheetToCase, {
+ table: ROSTER,
+ meta: ROLES,
+ count: 1,
+ onpreview,
+ onpass,
+ onclose: vi.fn(),
+ ...props,
+ });
+ }
+
+ const modeSelect = (target, column) =>
+ target.querySelector(`[aria-label="What ${column} is"]`);
+
+ function setMode(target, column, mode) {
+ const select = modeSelect(target, column);
+ select.value = mode;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ }
+
+ function setType(target, column, type) {
+ const select = target.querySelector(`[aria-label="What ${column} becomes"]`);
+ select.value = type;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ }
+
+ /** Whether the press that reads a plan is on offer. */
+ const press_ready = (target) =>
+ !([...target.querySelectorAll('button')].find((node) =>
+ node.textContent.trim().startsWith('Preview'),
+ ).disabled);
+
+ const options = (node) =>
+ [...node.querySelectorAll('option')].map((o) => o.textContent.replace(/\s+/g, ' ').trim());
+
+ it('offers a mode only where the column role carries it', async () => {
+ const target = screen();
+ await settle();
+ // Any column of words can name something; the four that need a role are gated on it.
+ expect(options(modeSelect(target, 'Name'))).toEqual([
+ 'Ignore', 'One entity per row', 'One entity per value',
+ ]);
+ // Named after the one type they mint, in the vocabulary's own word.
+ expect(options(modeSelect(target, 'Coordinates'))).toContain('Place (coordinates)');
+ expect(options(modeSelect(target, 'Source'))).toContain('Bookmark (links)');
+ expect(options(modeSelect(target, 'Source'))).not.toContain('Place (coordinates)');
+ });
+
+ it('sends an analyst after the points themselves to the mode that makes them', async () => {
+ const target = screen();
+ await settle();
+ // The right column under the wrong mode, which is the shape of the mistake: this one
+ // puts a subject on its ground, and a geolocation index wants the ground itself.
+ setMode(target, 'Coordinates', 'point');
+ await settle();
+ expect(flat(target)).toContain('set Coordinates to “One entity per row” and pick Place');
+
+ setMode(target, 'Coordinates', 'row');
+ setType(target, 'Coordinates', 'place');
+ await settle();
+ // And then it is its own point, said rather than asked for a second time.
+ expect(target.querySelector('.short')).toBeFalsy();
+ expect(flat(target)).toContain('Each place is read from Coordinates');
+ expect(press_ready(target)).toBe(true);
+ });
+
+ it('asks for the coordinates of a place named by a column of words', async () => {
+ const target = screen();
+ await settle();
+ setMode(target, 'Name', 'row');
+ setType(target, 'Name', 'place');
+ await settle();
+ // A column of names is not a column of coordinates, and the door says so rather than
+ // letting 468 rows each say it.
+ expect(flat(target)).toContain('set the column holding them to “Place (coordinates)”');
+ expect(press_ready(target)).toBe(false);
+
+ setMode(target, 'Coordinates', 'point');
+ await settle();
+ expect(press_ready(target)).toBe(true);
+ });
+
+ it('says what a declaration is short of rather than greying the press out', async () => {
+ const target = screen();
+ await settle();
+ setMode(target, 'Source', 'addresses');
+ await settle();
+
+ // The server refuses those three at the door; a disabled button is the same refusal
+ // with the reason taken off it.
+ expect(target.querySelector('.note').textContent).toContain(
+ 'one column has to be the subject',
+ );
+ setMode(target, 'Name', 'row');
+ await settle();
+ expect(target.querySelector('.note')).toBeFalsy();
+ });
+
+ it('offers the pairs the vocabulary allows, and not the ones it does not', async () => {
+ const target = screen();
+ await settle();
+ setMode(target, 'Name', 'row');
+ setType(target, 'Name', 'person');
+ setMode(target, 'Unit', 'value');
+ setType(target, 'Unit', 'organization');
+ setMode(target, 'Coordinates', 'point');
+ await settle();
+
+ const pair = target.querySelector('[aria-label="How Name and Unit are joined"]');
+ expect(pair).toBeTruthy();
+ // The registry's own readings, in the words it wrote them in.
+ expect(options(pair)).toEqual([
+ 'Not joined', 'Name is a member of Unit', 'Name owns Unit',
+ ]);
+ // A person and a point have no verb between them, so that pair is absent entirely.
+ expect(target.querySelector('[aria-label="How Name and Coordinates are joined"]')).toBeFalsy();
+ });
+
+ it('fills in a pair the vocabulary leaves no choice about', async () => {
+ onpreview.mockResolvedValue({ entities: [], joins: [] });
+ const target = screen();
+ await settle();
+ // A structure is sited at its ground and nothing else, so asking the analyst to confirm
+ // the only possible answer is asking nothing. One click on "Not joined" takes it off.
+ setMode(target, 'Name', 'row');
+ setType(target, 'Name', 'structure');
+ setMode(target, 'Coordinates', 'point');
+ await settle();
+
+ const pair = target.querySelector('[aria-label="How Name and Coordinates are joined"]');
+ expect(options(pair)).toEqual(['Not joined', 'Name is sited at Coordinates']);
+ expect(pair.value).toBe('sited-at:out');
+
+ press(target, 'Preview');
+ await settle();
+ expect(onpreview).toHaveBeenCalledWith(
+ expect.objectContaining({
+ joins: [{ from: 'Name', to: 'Coordinates', verb: 'sited-at' }],
+ }),
+ );
+
+ pair.value = '';
+ pair.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ press(target, 'Preview');
+ await settle();
+ expect(onpreview).toHaveBeenLastCalledWith(expect.objectContaining({ joins: [] }));
+ });
+
+ it('reads the inverse from the same side, and flips the edge instead', async () => {
+ onpreview.mockResolvedValue({ entities: [], joins: [] });
+ const target = screen();
+ await settle();
+ // The unit is the subject this time, so the only legal verb runs the other way: a
+ // person is a member of an organization, never the reverse.
+ setMode(target, 'Unit', 'row');
+ setType(target, 'Unit', 'organization');
+ setMode(target, 'Name', 'value');
+ setType(target, 'Name', 'person');
+ await settle();
+
+ const pair = target.querySelector('[aria-label="How Unit and Name are joined"]');
+ expect(options(pair)).toEqual([
+ 'Not joined', 'Unit has member Name', 'Unit is owned by Name',
+ ]);
+
+ pair.value = 'member-of:in';
+ pair.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ press(target, 'Preview');
+ await settle();
+ // Read on the unit's side, drawn from the person: the reading settles the direction and
+ // the analyst is never asked which way an arrow points.
+ expect(onpreview).toHaveBeenCalledWith(
+ expect.objectContaining({ joins: [{ from: 'Name', to: 'Unit', verb: 'member-of' }] }),
+ );
+ });
+
+ it('carries the picked reading as an ordered join', async () => {
+ onpreview.mockResolvedValue({ entities: [], joins: [] });
+ const target = screen();
+ await settle();
+ setMode(target, 'Name', 'row');
+ setType(target, 'Name', 'person');
+ setMode(target, 'Unit', 'value');
+ setType(target, 'Unit', 'organization');
+ await settle();
+
+ const pair = target.querySelector('[aria-label="How Name and Unit are joined"]');
+ pair.value = 'member-of:out';
+ pair.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ press(target, 'Preview');
+ await settle();
+
+ expect(onpreview).toHaveBeenCalledWith(
+ expect.objectContaining({
+ joins: [{ from: 'Name', to: 'Unit', verb: 'member-of' }],
+ }),
+ );
+ });
+
+ it('offers no press that writes until the plan has been read', async () => {
+ const target = screen();
+ await settle();
+ setMode(target, 'Name', 'row');
+ await settle();
+ expect(labels(target)).toContain('Preview');
+ expect(labels(target).some((label) => label.startsWith('Send '))).toBe(false);
+ });
+
+ it('counts both layers on the button, so the press is not a leap', async () => {
+ onpreview.mockResolvedValue({
+ entities: [
+ { mode: 'row', column: 'Name', counts: { make: 2, join: 1, update: 0, skip: 1, error: 0 }, rows: [] },
+ ],
+ joins: [{ from: 'Name', to: 'Unit', verb: 'member-of', label: 'is a member of', rows: 3, blocked: [] }],
+ });
+ const target = screen();
+ await settle();
+ setMode(target, 'Name', 'row');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+ expect(labels(target)).toContain('Send 6');
+ });
+
+ it('shows a row whose end is missing with its reason', async () => {
+ onpreview.mockResolvedValue({
+ entities: [
+ {
+ mode: 'value', column: 'Unit',
+ counts: { make: 0, join: 0, update: 0, skip: 1, error: 0 },
+ rows: [{
+ key: '3rd Brigade', value: '3rd Brigade', action: 'skip',
+ reason: 'the case holds 2 of this name',
+ candidates: [{ id: 'e1', label: '3rd Brigade' }, { id: 'e2', label: '3rd Brigade' }],
+ }],
+ },
+ ],
+ joins: [{
+ from: 'Name', to: 'Unit', verb: 'member-of', label: 'is a member of',
+ rows: 0, blocked: [{ key: 'r1', reason: 'the case holds 2 of this name' }],
+ }],
+ });
+ const target = screen();
+ await settle();
+ setMode(target, 'Unit', 'value');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+
+ expect(flat(target)).toContain('the case holds 2 of this name');
+ expect(flat(target)).toContain('1 without an end');
+ // And the ambiguity is answerable here rather than only reportable.
+ expect(target.querySelector('[aria-label="Attach 3rd Brigade to something the case holds"]'))
+ .toBeTruthy();
+ });
+});
diff --git a/frontend/src/components/SheetBuildProofs.svelte b/frontend/src/components/SheetBuildProofs.svelte
new file mode 100644
index 0000000..f887761
--- /dev/null
+++ b/frontend/src/components/SheetBuildProofs.svelte
@@ -0,0 +1,343 @@
+<script>
+ /**
+ * A geolocation index into proofs, a row at a time.
+ *
+ * The one road out of a sheet that goes and fetches files, which is why it is a button
+ * of its own and not a mode of *To the case*: that press is one transaction because
+ * nothing in it touches the network, and this one is a hundred downloads.
+ *
+ * Three columns and a note say what a row is — the footage, the published picture, the
+ * point, and what to call the result — and how much of that a row holds decides what it
+ * becomes: a place on its own, the footage posed on that place, or the whole
+ * constellation a hand-made import writes.
+ *
+ * **The plan downloads nothing.** The refusals come out of the cells and the "already
+ * there" answers out of the case, so an analyst reads what a hundred downloads would do
+ * before one of them starts. And a build is safe to press twice without this screen
+ * remembering anything: a proof is found by the name it was saved under.
+ */
+ import { untrack } from 'svelte';
+ import Icon from './Icon.svelte';
+ import { proposal } from '../lib/sheetBuild.js';
+ import { ID_COLUMN } from '../lib/sheet.js';
+
+ let {
+ table, meta, count, scope = 'ticked', busy = false, progress = null, report = null,
+ onpreview, onbuild, oncancel, onclose,
+ } = $props();
+
+ /** What each column is. Named for what the row becomes rather than for what the cell
+ * looks like: two columns of addresses are not interchangeable here, and which is the
+ * footage is the whole difference between a proof and a picture. */
+ const PARTS = [
+ { id: 'title', label: 'Name of the proof' },
+ { id: 'source', label: 'Address of the footage' },
+ { id: 'proof', label: 'Address of the published picture' },
+ { id: 'point', label: 'Coordinates' },
+ { id: 'note', label: 'Note carried onto the proof' },
+ { id: 'status', label: 'Status' },
+ ];
+
+ const WORDS = {
+ make: 'Build',
+ join: 'Already there',
+ update: 'Refresh',
+ skip: 'Left out',
+ error: 'Cannot build',
+ };
+ /** What a row turned out to be. The plan's word is an intention, and a row that has
+ * been built for ten seconds should not still be saying it is about to be. */
+ const DONE = { built: 'Built', restated: 'Refreshed', failed: 'Failed' };
+
+ const columns = $derived(
+ (table?.columns ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+
+ // Read once, on purpose: this is a proposal the analyst then edits, and a derived one
+ // would undo their choice every time a cell changed under them.
+ let picked = $state(untrack(() => proposal(table, meta)));
+ /** Whether the camera was at the point. One answer for the whole press: a column of its
+ * own waits for a binder that actually holds one. */
+ let pov = $state(false);
+ /** Ruled-out rows are dropped by default and handed back with one click, because a
+ * filter nobody can see is the app deciding which lines of a binder count. */
+ let keepRuledOut = $state(false);
+ /** Rows read in the plan and put aside. */
+ let left = $state(new Set());
+
+ let plan = $state(null);
+ let planning = $state(false);
+ let failed = $state('');
+ /** Whether this plan has already been pressed. The case moved under it, so the plan on
+ * screen is now a description of what *was* true, and offering the button again would
+ * offer to build rows that are already built. Reading it again is one press. */
+ let pressed = $state(false);
+
+ const ready = $derived(Boolean(picked.point && (picked.source || picked.proof) && count));
+ const doing = $derived(
+ (plan?.rows ?? []).filter(
+ (row) => ['make', 'join', 'update'].includes(row.action) && !left.has(row.key),
+ ),
+ );
+ /** What a row came back with, by row key, once a press is over. */
+ const outcomes = $derived(
+ new Map((report?.rows ?? []).map((row) => [row.key, row])),
+ );
+
+ function declaration() {
+ return {
+ ...picked,
+ pov,
+ skip_states: keepRuledOut ? [] : ['ruled out'],
+ skip: [...left],
+ };
+ }
+
+ function set(part, name) {
+ picked = { ...picked, [part]: name };
+ plan = null;
+ }
+
+ async function look() {
+ planning = true;
+ failed = '';
+ try {
+ plan = await onpreview(declaration());
+ left = new Set();
+ pressed = false;
+ } catch (error) {
+ failed = error?.message || 'That declaration could not be read.';
+ plan = null;
+ } finally {
+ planning = false;
+ }
+ }
+
+ function leaveOut(key) {
+ const next = new Set(left);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ left = next;
+ }
+</script>
+
+<div class="build">
+ <p class="lead">
+ <strong>{count}</strong> {scope} {count === 1 ? 'row' : 'rows'}. This one goes to the
+ network: each row downloads what it points at, and a row that fails costs that row.
+ </p>
+
+ <p class="label">What each column is</p>
+ <div class="parts">
+ {#each PARTS as part (part.id)}
+ <label class="row">
+ <span>{part.label}</span>
+ <select class="input" aria-label={part.label} value={picked[part.id] ?? ''}
+ onchange={(event) => set(part.id, event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ {/each}
+ </div>
+
+ <label class="check">
+ <input type="checkbox" checked={pov}
+ onchange={(event) => (pov = event.currentTarget.checked)} />
+ <span>The camera was at this point, not looking at it</span>
+ </label>
+ {#if picked.status}
+ <label class="check">
+ <input type="checkbox" checked={keepRuledOut}
+ onchange={(event) => { keepRuledOut = event.currentTarget.checked; plan = null; }} />
+ <span>Build the rows ruled out too</span>
+ </label>
+ {/if}
+
+ {#if failed}
+ <p class="failed" role="alert">{failed}</p>
+ {/if}
+
+ {#if plan}
+ <p class="label">
+ {report ? 'What it wrote' : 'What this would write'}
+ {#each ['make', 'join', 'update', 'skip', 'error'] as action (action)}
+ {#if plan.counts?.[action]}
+ <span class="tally-part {action}">
+ <strong>{plan.counts[action]}</strong> {WORDS[action].toLowerCase()}
+ </span>
+ {/if}
+ {/each}
+ </p>
+ <div class="plan">
+ {#each plan.rows as row (row.key)}
+ {@const done = outcomes.get(row.key)}
+ {@const said = done
+ ? (done.outcome === 'failed' ? done.reason : done.outcome)
+ : row.reason || row.writes}
+ <div class="plan-row {done ? done.outcome : row.action}" class:aside={left.has(row.key)}>
+ <span class="mark">{done ? DONE[done.outcome] : WORDS[row.action]}</span>
+ <!-- A binder's title is a sentence, and it used to take the whole line and leave
+ four characters for the reason — which on a failed row is the only part worth
+ reading. So the reason gets the room and both carry what they say in full. -->
+ <span class="who" title={row.title || row.coords || row.key}>
+ {row.title || row.coords || row.key}
+ </span>
+ <small class="why" title={said}
+ class:warn={done ? done.outcome === 'failed' : row.action === 'error'}>
+ {said}
+ </small>
+ {#if ['make', 'join', 'update'].includes(row.action)}
+ <button class="undo" onclick={() => leaveOut(row.key)}>
+ {left.has(row.key) ? 'Put back' : 'Leave out'}
+ </button>
+ {/if}
+ </div>
+ {/each}
+ </div>
+ {/if}
+
+ {#if progress}
+ <!-- Counted in rows, not in bytes: what an analyst watches for two minutes is how far
+ down the binder it has got, and a row is the unit this road is atomic in. The
+ same bar the Media Library draws, so a download reads the same wherever it is. -->
+ {@const of = progress.total ?? 0}
+ {@const at = progress.done ?? 0}
+ <div class="progress" aria-live="polite">
+ <div class="bar" role="progressbar" aria-valuenow={at} aria-valuemin="0"
+ aria-valuemax={of} aria-label="Rows built">
+ <div class="fill" class:indeterminate={!of}
+ style:width={of ? `${Math.round((at / of) * 100)}%` : '40%'}></div>
+ </div>
+ <span class="progress-meta" title={progress.label ?? ''}>
+ {at} of {of}{#if progress.label} · <em>{progress.label}</em>{/if}
+ </span>
+ </div>
+ {:else if report}
+ <p class="progress done" aria-live="polite">
+ <Icon name="check" size={13} />
+ {[
+ report.counts?.built && `${report.counts.built} built`,
+ report.counts?.restated && `${report.counts.restated} refreshed`,
+ report.counts?.failed && `${report.counts.failed} failed`,
+ report.stopped && 'stopped',
+ ]
+ .filter(Boolean)
+ .join(' · ') || 'Nothing to build in those rows'}
+ </p>
+ <!-- Where the result is, and the one loose end this road leaves: a proof of several
+ panels has no render until somebody opens it. -->
+ <p class="note">
+ Each row now points at what it produced. A proof composed of several pictures has no
+ export until it is opened in the composer once.
+ </p>
+ {/if}
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ {#if busy}
+ <button class="btn" onclick={oncancel}>Stop</button>
+ {:else if report}
+ <button class="btn" disabled={planning} onclick={look}>Preview again</button>
+ <button class="btn btn-primary" onclick={onclose}>Done</button>
+ {:else}
+ <button class="btn" onclick={onclose}>Close</button>
+ <button class="btn" disabled={!ready || planning} onclick={look}>
+ {planning ? 'Reading…' : plan ? 'Preview again' : 'Preview'}
+ </button>
+ {#if plan && !pressed}
+ <button class="btn btn-primary" disabled={!doing.length}
+ onclick={() => { pressed = true; onbuild(declaration()); }}>
+ Build {doing.length} {doing.length === 1 ? 'row' : 'rows'}
+ </button>
+ {/if}
+ {/if}
+ </div>
+</div>
+
+<style>
+ /* Nothing in here widens the dialog: a modal that scrolls sideways is a modal whose
+ buttons walk off the screen. */
+ .build { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .lead strong { color: var(--text-1); }
+ .label {
+ display: flex; align-items: center; flex-wrap: wrap; gap: 10px;
+ color: var(--text-3); font-size: var(--fs-xs); margin: 12px 0 5px; line-height: 1.5;
+ }
+ .parts { display: flex; flex-direction: column; }
+ .row {
+ display: grid; grid-template-columns: minmax(0, 1fr) 210px; align-items: center;
+ gap: 8px; padding: 3px 0;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .check { display: flex; align-items: center; gap: 7px; padding: 6px 0 2px; }
+ .check span { color: var(--text-2); font-size: var(--fs-sm); }
+ .failed { color: var(--danger); font-size: var(--fs-sm); margin-top: 10px; }
+
+ .tally-part { color: var(--text-3); }
+ .tally-part strong { color: var(--text-1); font-weight: 600; }
+ .tally-part.error, .tally-part.error strong { color: var(--danger); }
+ .plan {
+ max-height: 260px; overflow: auto;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .plan-row {
+ display: flex; align-items: center; gap: 8px; padding: 4px 7px;
+ border-bottom: 1px solid var(--border); font-size: var(--fs-xs);
+ }
+ .plan-row:last-child { border-bottom: 0; }
+ .plan-row.aside { opacity: 0.5; }
+ .mark {
+ flex: none; width: 84px; color: var(--text-3);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .plan-row.make .mark, .plan-row.built .mark { color: var(--ok); }
+ .plan-row.join .mark, .plan-row.update .mark, .plan-row.restated .mark {
+ color: var(--accent);
+ }
+ .plan-row.error .mark, .plan-row.failed .mark { color: var(--danger); }
+ /* The title yields, the reason grows: a row that could not be built says why, and a
+ sentence of a title is not what the analyst is reading at that moment. */
+ .who {
+ flex: 0 1 auto; min-width: 0; max-width: 44%; color: var(--text-1);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .why {
+ flex: 1 1 0; min-width: 0; color: var(--text-3);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .why.warn { color: var(--anno-6); }
+ .progress {
+ display: flex; align-items: center; gap: 9px; margin-top: 12px; min-width: 0;
+ color: var(--text-2); font-size: var(--fs-sm);
+ }
+ .progress em { color: var(--text-1); font-style: normal; }
+ .progress.done { color: var(--ok); }
+ .bar {
+ flex: 1 1 auto; min-width: 90px; height: 6px; border-radius: 3px;
+ background: var(--bg-3); overflow: hidden;
+ }
+ .fill {
+ height: 100%; background: var(--accent); border-radius: 3px;
+ transition: width 0.4s var(--ease);
+ }
+ /* Before the first row lands there is nothing to be a fraction of, so it moves rather
+ than sitting at zero looking stuck. */
+ .fill.indeterminate { animation: creep 1.4s var(--ease) infinite; }
+ @keyframes creep {
+ 0% { margin-left: -40%; }
+ 100% { margin-left: 100%; }
+ }
+ /* A binder's title is a sentence. Unbounded and `nowrap`, one of them pushed the line
+ past the modal, squeezed the bar to nothing and set the whole dialog scrolling
+ sideways — so the name yields and the bar keeps its floor. */
+ .progress-meta {
+ flex: 0 1 auto; min-width: 0; max-width: 55%;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .spacer { flex: 1; }
+ .undo { flex: none; margin-left: auto; color: var(--text-3); font-size: var(--fs-xs); }
+ .undo:hover { color: var(--accent); text-decoration: underline; }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+</style>
diff --git a/frontend/src/components/SheetCellEditor.svelte b/frontend/src/components/SheetCellEditor.svelte
new file mode 100644
index 0000000..cb370c0
--- /dev/null
+++ b/frontend/src/components/SheetCellEditor.svelte
@@ -0,0 +1,315 @@
+<script>
+ /**
+ * The box a cell is edited in, and what its column can offer while you type.
+ *
+ * A role is a lens and never a validator, so this **always** keeps the free text box.
+ * The binders write `OK en cours` in a status column, `AFTER` in a date column and
+ * `To be found` where a coordinate goes, on every page; an editor that offered only a
+ * closed list or only a calendar would refuse exactly the cells that carry the
+ * reasoning.
+ *
+ * What a role adds is a shortcut beside the box:
+ *
+ * - a **state** or a **set of values** offers its vocabulary, **narrowed to what has
+ * been typed**. On a column of thirty values, a list that showed all thirty while the
+ * analyst typed `s-1` was a list nobody read. On a multi-value column the narrowing
+ * works on the value after the last separator, because that is the one being written.
+ * - the keyboard drives that list: ↑ and ↓ move, Enter and Tab take what is
+ * highlighted, and a value the vocabulary has never heard of can be **added to it**
+ * from here rather than from the column panel.
+ * - a **date** offers a calendar, and what it writes is the form the column already
+ * uses — picking a date in a `dd/MM/yyyy` column leaves it a `dd/MM/yyyy` column.
+ *
+ * Clicking an offer stays a **toggle** on a multi-value column: that is how a list is
+ * built and unbuilt with the mouse. The keyboard *completes* instead, which is what
+ * typing means.
+ */
+ import Icon from './Icon.svelte';
+ import { closeOnOutsidePointer } from '../lib/dismiss.js';
+ import {
+ DEFAULT_SEPARATOR,
+ dateSpelling,
+ parseWhen,
+ pickerType,
+ spellWhen,
+ valueColour,
+ } from '../lib/sheetRoles.js';
+
+ let {
+ value = '',
+ role = null,
+ column = null,
+ table = null,
+ oninput,
+ oncommit,
+ onaddvalue = null,
+ } = $props();
+
+ const kind = $derived(role?.kind ?? null);
+ const vocabulary = $derived(kind === 'state' || kind === 'choice' ? (role.values ?? []) : []);
+ const multi = $derived(kind === 'choice' ? role.multi : null);
+
+ /** Where the value being written starts. On a list column that is after the last
+ * separator; everywhere else it is the whole cell. */
+ const cut = $derived(multi ? String(value).lastIndexOf(multi) : -1);
+ const head = $derived(cut === -1 ? '' : String(value).slice(0, cut + multi.length));
+ const term = $derived((cut === -1 ? String(value) : String(value).slice(cut + multi.length)).trim());
+
+ /** Whether the word being written is already, exactly, one the column knows. */
+ const known = $derived(
+ Boolean(term) && vocabulary.some((entry) => entry.toLowerCase() === term.toLowerCase()),
+ );
+ /**
+ * The vocabulary narrowed to what is being typed.
+ *
+ * Narrowed only while the word is **unfinished**. A term that is already exactly one of
+ * the column's values is not a prefix being completed, it is an answer that has landed
+ * — and filtering on it collapsed the list to the value just chosen, which on a
+ * multi-value column left nothing to click for the second one.
+ */
+ const offers = $derived(
+ term && !known
+ ? vocabulary.filter((entry) => entry.toLowerCase().includes(term.toLowerCase()))
+ : vocabulary,
+ );
+
+ let highlight = $state(0);
+ // Back to the top whenever the list changes under it: a highlight left on row seven of
+ // a list that is now two long points at nothing.
+ $effect(() => {
+ void offers.length;
+ highlight = 0;
+ });
+
+ /** The cells of this column, which is where both answers below come from. */
+ const cells = $derived(
+ kind === 'when' && table && column ? table.rows.map((row) => row[column.index]) : [],
+ );
+ /** How this column writes its dates, read from the column and not declared: a picker
+ * that restyled the file from a click would break the promise the file keeps the
+ * words. */
+ const spelling = $derived(dateSpelling(cells));
+ /** The column says which of the three it holds; the picker follows it. */
+ const shape = $derived(role?.shape ?? 'date');
+
+ /** What the picker should open on: whatever the cell already holds, in its own shape. */
+ const picked = $derived.by(() => {
+ if (kind !== 'when') return '';
+ const read = parseWhen(value, role);
+ if (!read) return '';
+ if (shape === 'time') {
+ return read.shape === 'time'
+ ? read.text
+ : new Date(read.key).toISOString().slice(11, 16);
+ }
+ if (read.shape !== 'moment') return '';
+ const iso = new Date(read.key).toISOString();
+ return shape === 'datetime' ? iso.slice(0, 16) : iso.slice(0, 10);
+ });
+
+ const held = $derived(
+ multi
+ ? String(value).split(multi).map((part) => part.trim()).filter(Boolean)
+ : [String(value).trim()],
+ );
+ const taken = $derived(new Set(held));
+
+ const colourOf = (entry) => valueColour(role, entry);
+
+ /**
+ * A pointer landing anywhere outside commits and closes.
+ *
+ * `blur` on the box is not enough on its own, and the reason is this component's own
+ * shape: the offers hang *below* the cell in an absolute panel, so a click just under
+ * the cell — which reads as "outside" to the analyst — lands on the panel, where the
+ * press is deliberately swallowed to keep a chip clickable. Without this the editor
+ * stayed open and nothing appeared to happen.
+ */
+ let box = $state(null);
+ $effect(() => (box ? closeOnOutsidePointer(box, commit) : undefined));
+
+ /**
+ * Which way the offers open.
+ *
+ * They hang inside the grid's own scroller, so on the last rows on screen a list that
+ * always dropped downwards was cut off by the edge of the table — on a status column,
+ * exactly the rows an analyst works through last. Measured once as the editor opens,
+ * against the scroller rather than the window: below the table is not room.
+ */
+ /** What the list asks for before it is worth turning it over. Its own `max-height`, so
+ * the two answers cannot drift apart. */
+ const OFFERS_H = 260;
+ let field = $state(null);
+ let above = $state(false);
+ $effect(() => {
+ if (!field) return;
+ const cell = field.getBoundingClientRect();
+ const room = field.closest('#sheet-grid')?.getBoundingClientRect() ?? {
+ top: 0,
+ bottom: window.innerHeight,
+ };
+ above = room.bottom - cell.bottom < OFFERS_H && cell.top - room.top > OFFERS_H;
+ });
+
+ /** Leave the cell holding one clean list rather than what the keystrokes left behind.
+ * Only on a column that declares a separator, where re-joining is what the column
+ * *means*: `Buk-M2E, , ZU23-2, ` is not two answers and a third empty one. */
+ function commit() {
+ if (multi) {
+ const tidy = held.join(multi);
+ if (tidy !== String(value)) oninput(tidy);
+ }
+ oncommit();
+ }
+
+ /** Click an offer: put the value in, or take it back out. The mouse gesture, and the
+ * reason it is a toggle is that a list is unbuilt as often as it is built. */
+ function toggle(entry) {
+ if (!multi) {
+ oninput(entry);
+ oncommit();
+ return;
+ }
+ const values = [...held];
+ const at = values.indexOf(entry);
+ if (at === -1) values.push(entry);
+ else values.splice(at, 1);
+ oninput(values.join(multi || DEFAULT_SEPARATOR));
+ }
+
+ /** Take the highlighted offer as the completion of what is being typed. The keyboard
+ * gesture: it finishes the word, and on a list column it leaves the separator behind
+ * so the next value can be typed straight away. */
+ function complete(entry) {
+ if (!multi) {
+ oninput(entry);
+ return;
+ }
+ oninput(`${head}${entry}${multi}`);
+ }
+
+ /**
+ * The keys the offer list owns, taken before the grid's own handler sees them.
+ *
+ * The grid listens on the window and gives Enter and Tab their meaning there, which is
+ * right while nothing is open under the cursor. With a list open they mean "take this
+ * one", so the press is stopped here rather than reaching two handlers with two ideas.
+ */
+ function onkeydown(event) {
+ if (!offers.length) return;
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ event.stopPropagation();
+ const step = event.key === 'ArrowDown' ? 1 : -1;
+ highlight = (highlight + step + offers.length) % offers.length;
+ return;
+ }
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ event.stopPropagation();
+ complete(offers[highlight]);
+ // A single-value column has nothing left to say once its answer is in.
+ if (!multi) commit();
+ return;
+ }
+ if (event.key === 'Tab') {
+ event.preventDefault();
+ event.stopPropagation();
+ complete(offers[highlight]);
+ commit();
+ }
+ }
+</script>
+
+<!-- `display: contents`, so the wrapper is only there to be asked whether a pointer
+ landed inside it. -->
+<div class="editing" bind:this={box}>
+ <!-- svelte-ignore a11y_autofocus -->
+ <textarea class="editor" autofocus {value} bind:this={field}
+ oninput={(event) => oninput(event.currentTarget.value)}
+ {onkeydown}
+ onblur={commit}></textarea>
+
+ {#if vocabulary.length || kind === 'when'}
+ <!-- Held open by the pointer going down on it rather than by focus: the box loses
+ focus the moment a chip is pressed, and a blur that committed first would close
+ this before the click landed. -->
+ <div class="offers" class:above role="presentation"
+ onpointerdown={(event) => event.preventDefault()}>
+ {#each offers as entry, at (entry)}
+ <button class="offer c-{colourOf(entry) ?? 'none'}" class:tinted={colourOf(entry)}
+ class:on={taken.has(entry)} class:lit={at === highlight}
+ onclick={() => toggle(entry)}>
+ <i class="tick">{#if taken.has(entry)}<Icon name="check" size={11} />{/if}</i>
+ <span>{entry}</span>
+ </button>
+ {/each}
+ {#if vocabulary.length && !offers.length}
+ <p class="none">No value of this column matches.</p>
+ {/if}
+ {#if term && !known && onaddvalue}
+ <button class="offer add" onclick={() => onaddvalue(term)}>
+ <i class="tick"><Icon name="plus" size={11} /></i>
+ <span>Add “{term}” to this column's words</span>
+ </button>
+ {/if}
+ {#if kind === 'when'}
+ <label class="calendar">
+ <Icon name="clock" size={12} />
+ <input type={pickerType(shape)} value={picked}
+ aria-label={shape === 'time' ? 'Pick a time' : 'Pick a date'}
+ onchange={(event) =>
+ oninput(spellWhen(event.currentTarget.value, { shape, spelling, keep: value }))} />
+ </label>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .editing { display: contents; }
+ .editor {
+ position: absolute; z-index: 4; left: 0; top: 0; width: 100%; min-height: 30px;
+ max-height: 180px; padding: 5px 8px; resize: none;
+ border: 2px solid var(--accent); border-radius: 2px;
+ background: var(--bg-2); color: var(--text-1);
+ font-size: var(--fs-sm); font-family: inherit; line-height: 1.4;
+ }
+ .editor:focus { outline: none; }
+ /* A list down the page, not words side by side: these are the answers a column takes,
+ and a row per answer is how a list is read. */
+ .offers {
+ position: absolute; z-index: 5; left: 0; top: calc(100% + 2px);
+ display: flex; flex-direction: column; gap: 1px;
+ min-width: 100%; width: max-content; max-width: 320px; max-height: 260px; overflow: auto;
+ padding: 4px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 10px 24px #0005;
+ }
+ /* Turned over on the last rows on screen, where downwards is off the table. */
+ .offers.above { top: auto; bottom: calc(100% + 2px); box-shadow: 0 -10px 24px #0005; }
+ .offer {
+ display: flex; align-items: center; gap: 6px; width: 100%; padding: 4px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left;
+ font-size: var(--fs-sm); white-space: nowrap;
+ }
+ .offer .tick { display: flex; width: 11px; flex: none; color: var(--accent); }
+ .offer span { overflow: hidden; text-overflow: ellipsis; }
+ .offer:hover { background: var(--bg-2); color: var(--text-1); }
+ .offer.on { color: var(--text-1); }
+ /* Where Enter would land. Marked with the selection colour, which is what it is. */
+ .offer.lit { background: var(--accent-soft); color: var(--text-1); }
+ .offer.add { color: var(--text-3); }
+ .offer.add:hover { color: var(--accent); }
+ /* A value with a colour of its own wears it here too, so the list reads the same as the
+ cells it fills. The `.c-*` classes are global (`app.css`) and set `--mark`. */
+ .offer.tinted span { color: var(--mark); }
+ .none { padding: 4px 7px; color: var(--text-3); font-size: var(--fs-xs); }
+ .calendar {
+ display: flex; align-items: center; gap: 4px; margin-top: 3px; padding: 1px 5px;
+ border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text-3);
+ }
+ .calendar input {
+ border: 0; background: none; color: var(--text-1); font-size: var(--fs-xs);
+ font-family: inherit;
+ }
+</style>
diff --git a/frontend/src/components/SheetClean.svelte b/frontend/src/components/SheetClean.svelte
new file mode 100644
index 0000000..b45b4ea
--- /dev/null
+++ b/frontend/src/components/SheetClean.svelte
@@ -0,0 +1,351 @@
+<script>
+ /**
+ * The passes that fix a column that came from somewhere else.
+ *
+ * Six of them, in one screen, because they are one job: the import arrived with the city
+ * and the country in one cell, a trailing space that makes two values out of one, four
+ * hundred rows saying a word the analyst has stopped using, and the sources buried in
+ * prose. Doing that by hand is where an afternoon goes; doing it in six separate dialogs
+ * is where the analyst goes.
+ *
+ * Every pass **says what it would do before it does it** — how many cells, and the first
+ * few as they would come out. That is the whole safety of the screen: a separator chosen
+ * wrong turns a column into confetti, and a replace with the case wrong rewrites nothing
+ * or everything. There is no regular expression box, deliberately: a pattern with no
+ * preview is how a sheet loses a column, and the passes here cover what the binders
+ * actually need.
+ *
+ * It reads the rows **on screen**, filter and all. An analyst who filtered to the twelve
+ * rows left to check and then pressed a pass over four hundred would not call that a
+ * feature, so the count says which twelve, every time.
+ *
+ * No rules here: `lib/sheetClean.js` builds every edit and this screen shows them.
+ */
+ import { untrack } from 'svelte';
+ import Icon from './Icon.svelte';
+ import {
+ CASINGS,
+ caseEdits,
+ extractTable,
+ mergeTable,
+ replaceEdits,
+ splitPreview,
+ splitTable,
+ tidyEdits,
+ } from '../lib/sheetClean.js';
+ import { DEFAULT_SEPARATOR } from '../lib/sheetRoles.js';
+
+ let {
+ table,
+ meta,
+ column,
+ /** The columns a pass may write, as `{ name, index }` — the caller has already left
+ * out the handle and the two the app fills. */
+ writable = [],
+ /** The rows on screen, as table indices. Every cell pass is bounded by this. */
+ rows = [],
+ mode: opened = 'replace',
+ onedits,
+ ontable,
+ onclose,
+ } = $props();
+
+ const PASSES = [
+ { id: 'replace', label: 'Find and replace', icon: 'search' },
+ { id: 'tidy', label: 'Take the spacing out', icon: 'wand' },
+ { id: 'case', label: 'Change the casing', icon: 'text' },
+ { id: 'split', label: 'Split into columns', icon: 'layers' },
+ { id: 'merge', label: 'Merge with another', icon: 'stack' },
+ { id: 'extract', label: 'Lift the links out', icon: 'link' },
+ ];
+
+ /** Which pass is on screen. Seeded from the caller and the analyst's from then on: the
+ * heading menu opens this on the pass it named, and the tabs are here to change it.
+ * Read once on purpose — the dialog is built afresh every time it opens. */
+ let mode = $state(untrack(() => opened));
+ let find = $state('');
+ let replace = $state('');
+ let matchCase = $state(false);
+ let wholeCell = $state(false);
+ let everyColumn = $state(false);
+ let casing = $state('title');
+ let separator = $state(',');
+ let keepOriginal = $state(true);
+ let mergeWith = $state([]);
+ let joiner = $state(' ');
+ let what = $state('url');
+
+ const CASE_WORDS = { upper: 'UPPER CASE', lower: 'lower case', title: 'Title Case' };
+
+ /** Which columns a cell pass writes. One column unless the analyst says the sheet, which
+ * is what a replace wants when a word to drop is spread across five of them. */
+ const columns = $derived(
+ everyColumn && mode === 'replace' ? writable.map((entry) => entry.index) : [column.index],
+ );
+
+ const edits = $derived.by(() => {
+ if (mode === 'replace') {
+ return replaceEdits(table, { columns, rows, find, replace, matchCase, wholeCell });
+ }
+ if (mode === 'tidy') return tidyEdits(table, columns, rows);
+ if (mode === 'case') return caseEdits(table, columns, rows, casing);
+ return [];
+ });
+
+ const split = $derived(mode === 'split' ? splitPreview(table, column.index, separator) : null);
+ const extract = $derived(
+ mode === 'extract' ? extractTable(table, meta, column.index, { what }) : null,
+ );
+ const merged = $derived(
+ mode === 'merge' && mergeWith.length
+ ? mergeTable(table, meta, [column.index, ...mergeWith], { joiner, keep: keepOriginal })
+ : null,
+ );
+
+ /** What the press would change, as one line. Said as cells for a pass that rewrites
+ * them and as columns for a pass that grows the table, because those are two different
+ * kinds of consequence. */
+ const says = $derived.by(() => {
+ if (mode === 'split') {
+ if (!(split?.parts >= 2)) return 'Nothing in this column splits on that.';
+ const rest = split.over
+ ? `, and ${split.over === 1 ? 'one cell keeps' : `${split.over} cells keep`} the rest in the last one`
+ : '';
+ return `${split.parts} new columns, out of ${split.rows} ${split.rows === 1 ? 'row' : 'rows'}${rest}`;
+ }
+ if (mode === 'merge') {
+ return mergeWith.length ? `One new column: ${merged?.name}` : 'Pick a column to merge with.';
+ }
+ if (mode === 'extract') {
+ return extract?.filled
+ ? `One new column, filled on ${extract.filled} ${extract.filled === 1 ? 'row' : 'rows'}`
+ : 'No link in this column.';
+ }
+ return edits.length
+ ? `${edits.length} ${edits.length === 1 ? 'cell' : 'cells'} would change`
+ : 'Nothing would change.';
+ });
+
+ /** Three of them, as they would come out. A count is what to expect; a sample is what
+ * it actually did to the words. */
+ const samples = $derived.by(() => {
+ if (mode === 'split') return (split?.samples ?? []).map((parts) => parts.join(' · '));
+ // Read by name rather than by arithmetic: a merge lands after the *last* column it
+ // was given, and dropping the originals moves it again.
+ if (mode === 'merge') {
+ const at = merged?.table.columns.indexOf(merged?.name) ?? -1;
+ if (at === -1) return [];
+ return (merged?.table.rows ?? []).slice(0, 3).map((row) => row[at]).filter(Boolean);
+ }
+ if (mode === 'extract') {
+ const at = extract?.table.columns.indexOf(extract?.name) ?? -1;
+ if (at === -1) return [];
+ return (extract?.table.rows ?? []).slice(0, 3).map((row) => row[at]).filter(Boolean);
+ }
+ return edits.slice(0, 3).map((edit) => `${edit.before || '—'} → ${edit.after || '—'}`);
+ });
+
+ const ready = $derived.by(() => {
+ if (mode === 'split') return (split?.parts ?? 0) >= 2;
+ if (mode === 'merge') return Boolean(mergeWith.length);
+ if (mode === 'extract') return Boolean(extract?.filled);
+ return edits.length > 0;
+ });
+
+ const others = $derived(writable.filter((entry) => entry.index !== column.index));
+
+ function toggleMerge(index) {
+ mergeWith = mergeWith.includes(index)
+ ? mergeWith.filter((entry) => entry !== index)
+ : [...mergeWith, index];
+ }
+
+ function apply() {
+ if (!ready) return;
+ if (mode === 'split') {
+ const done = splitTable(table, meta, column.index, { separator, keep: keepOriginal });
+ ontable(done, `${done.names.length} columns out of “${column.name}”`);
+ } else if (mode === 'merge') {
+ ontable(merged, `“${merged.name}” written`);
+ } else if (mode === 'extract') {
+ ontable(extract, `“${extract.name}” written`);
+ } else {
+ onedits(edits, `${edits.length} ${edits.length === 1 ? 'cell' : 'cells'} rewritten`);
+ }
+ onclose();
+ }
+</script>
+
+<div class="clean">
+ <div class="passes">
+ {#each PASSES as pass (pass.id)}
+ <button class="pass" class:on={mode === pass.id} onclick={() => (mode = pass.id)}>
+ <Icon name={pass.icon} size={12} />
+ <span>{pass.label}</span>
+ </button>
+ {/each}
+ </div>
+
+ <div class="body">
+ <p class="subject">
+ <strong>{column.name}</strong>
+ <span>· {rows.length} {rows.length === 1 ? 'row' : 'rows'} on screen</span>
+ </p>
+
+ {#if mode === 'replace'}
+ <label class="field">
+ <span>Find</span>
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input" autofocus bind:value={find} placeholder="OK en cours" />
+ </label>
+ <label class="field">
+ <span>Write instead</span>
+ <input class="input" bind:value={replace} placeholder="in progress" />
+ </label>
+ <label class="check">
+ <input type="checkbox" bind:checked={wholeCell} />
+ <span>Only where it is the whole cell</span>
+ </label>
+ <label class="check">
+ <input type="checkbox" bind:checked={matchCase} />
+ <span>Match the case</span>
+ </label>
+ <label class="check">
+ <input type="checkbox" bind:checked={everyColumn} />
+ <span>In every column, not just this one</span>
+ </label>
+ {:else if mode === 'tidy'}
+ <p class="note">
+ Trims the ends and collapses the runs inside to one space, so <code>Kherson&nbsp;</code>
+ and <code>Kherson</code> stop being two values. Line breaks stay.
+ </p>
+ {:else if mode === 'case'}
+ <div class="chips">
+ {#each CASINGS as entry (entry)}
+ <button class="chip" class:on={casing === entry} onclick={() => (casing = entry)}>
+ {CASE_WORDS[entry]}
+ </button>
+ {/each}
+ </div>
+ {:else if mode === 'split'}
+ <label class="field inline">
+ <span>Split on</span>
+ <input class="input narrow" bind:value={separator} placeholder="," />
+ </label>
+ <div class="chips">
+ {#each [',', ';', '|', DEFAULT_SEPARATOR, ' - ', '/'] as entry (entry)}
+ <button class="chip" class:on={separator === entry} onclick={() => (separator = entry)}>
+ {entry === ' ' ? 'space' : entry}
+ </button>
+ {/each}
+ </div>
+ <label class="check">
+ <input type="checkbox" bind:checked={keepOriginal} />
+ <span>Keep this column too</span>
+ </label>
+ {:else if mode === 'merge'}
+ <p class="what">And which others</p>
+ <div class="chips">
+ {#each others as entry (entry.index)}
+ <button class="chip" class:on={mergeWith.includes(entry.index)}
+ onclick={() => toggleMerge(entry.index)}>{entry.name}</button>
+ {/each}
+ </div>
+ <label class="field inline">
+ <span>Written between them</span>
+ <input class="input narrow" bind:value={joiner} placeholder=" " />
+ </label>
+ <label class="check">
+ <input type="checkbox" bind:checked={keepOriginal} />
+ <span>Keep the columns it was made from</span>
+ </label>
+ {:else}
+ <div class="chips">
+ <button class="chip" class:on={what === 'url'} onclick={() => (what = 'url')}>
+ The addresses
+ </button>
+ <button class="chip" class:on={what === 'host'} onclick={() => (what = 'host')}>
+ Just the hosts
+ </button>
+ </div>
+ <p class="note">
+ A column of hosts shows how many rows come from the same channel.
+ </p>
+ {/if}
+
+ <p class="says" class:none={!ready}>{says}</p>
+ {#if samples.length}
+ <div class="samples">
+ {#each samples as sample, index (index)}
+ <p class="sample">{sample}</p>
+ {/each}
+ </div>
+ {/if}
+ </div>
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={!ready} onclick={apply}>
+ {mode === 'replace' ? 'Replace' : mode === 'split' ? 'Split' : mode === 'merge' ? 'Merge' : 'Apply'}
+ </button>
+ </div>
+</div>
+
+<style>
+ .clean { display: grid; grid-template-columns: 190px minmax(0, 1fr); gap: 14px; }
+ .passes {
+ display: flex; flex-direction: column; gap: 2px;
+ border-right: 1px solid var(--border); padding-right: 10px;
+ }
+ .pass {
+ display: flex; align-items: center; gap: 7px; width: 100%; padding: 6px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .pass:hover { background: var(--bg-2); color: var(--text-1); }
+ .pass.on { background: var(--accent-soft); color: var(--accent); }
+ .pass span { flex: 1; min-width: 0; }
+ .body { min-width: 0; }
+ .subject { color: var(--text-1); font-size: var(--fs-sm); margin-bottom: 8px; }
+ .subject span { color: var(--text-3); }
+ .field { display: block; padding: 4px 0; }
+ .field span { display: block; color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 3px; }
+ .field .input { width: 100%; }
+ .field.inline { display: flex; align-items: center; gap: 8px; }
+ .field.inline span { margin: 0; }
+ .narrow { width: 80px; text-align: center; font-family: var(--font-mono); }
+ .check {
+ display: flex; align-items: center; gap: 7px; padding: 4px 1px;
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .chips { display: flex; flex-wrap: wrap; gap: 4px; padding: 6px 0; }
+ .chip {
+ padding: 3px 8px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ font-family: var(--font-mono);
+ }
+ .chip:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .chip.on { border-color: var(--accent); color: var(--accent); }
+ .what { color: var(--text-3); font-size: var(--fs-xs); padding-top: 4px; }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 4px 0; }
+ .note code { font-family: var(--font-mono); }
+
+ /* What the press would do, in the accent when it would do something. */
+ .says {
+ margin-top: 12px; padding: 6px 8px; border-radius: var(--r-sm);
+ background: var(--accent-soft); color: var(--accent); font-size: var(--fs-xs);
+ }
+ .says.none { background: var(--bg-2); color: var(--text-3); }
+ .samples {
+ margin-top: 6px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ overflow: hidden;
+ }
+ .sample {
+ padding: 4px 8px; border-bottom: 1px solid var(--border);
+ color: var(--text-2); font-size: var(--fs-xs); font-family: var(--font-mono);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .sample:last-child { border-bottom: 0; }
+ .modal-row { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetColumnPanel.svelte b/frontend/src/components/SheetColumnPanel.svelte
new file mode 100644
index 0000000..c8e46e8
--- /dev/null
+++ b/frontend/src/components/SheetColumnPanel.svelte
@@ -0,0 +1,289 @@
+<script>
+ /**
+ * How one column is set up, with room.
+ *
+ * A heading has three doors and this is the one used least: what the column *is* — its
+ * name, its type and vocabulary, the line of instruction, what it can be read for. Nearly
+ * all of it decided once and then left alone.
+ *
+ * The other two are next door because they are wanted constantly: the **funnel** asks
+ * something of the rows (`SheetFilterMenu`), and a **right-click on the heading** is the
+ * short list of gestures — insert, duplicate, rename, sort, split, hide, delete
+ * (`SheetHeadingMenu`). Those are not restated here; one screen offering a thing twice is
+ * how two of them come to disagree.
+ *
+ * It is a **side panel** and shares its slot with the row panel, which opening either one
+ * puts away. That is what a dialog could not do: the panel stays open as the next heading
+ * is clicked, so setting up a fresh import is one click per column rather than a dialog
+ * opened and closed for each. It also keeps the column's own cells on screen beside the
+ * words being written about them.
+ *
+ * It owns no rules. Every answer is a call back up, and `lib/sheet.js` and
+ * `lib/sheetRoles.js` are where a filter or a role means something.
+ */
+ import Icon from './Icon.svelte';
+ import SheetRoleEditor from './SheetRoleEditor.svelte';
+ import { ID_COLUMN, columnValues, filterSummary, urlsIn } from '../lib/sheet.js';
+ import { countedOf, isChipped } from '../lib/sheetRoles.js';
+ import { rowTargets, unresolved } from '../lib/sheetRows.js';
+
+ let {
+ table,
+ meta,
+ column,
+ filter = null,
+ onrename,
+ onfreeze,
+ onclearfilter,
+ onrole,
+ onnote,
+ onprogress,
+ onmap,
+ ontimeline,
+ onnormalise,
+ onduplicates,
+ onnearby,
+ onvalue,
+ ongeocode,
+ oncheck,
+ onanchors,
+ onclose,
+ } = $props();
+
+ const role = $derived(meta?.roles?.[column.name] ?? null);
+ /** A column of values counts its own values in the funnel, one by one, so "what is said
+ * twice here" is a reading it already gives. */
+ const chipped = $derived(isChipped(role));
+ const asked = $derived(filterSummary(filter));
+ const isKey = $derived(String(column.name).toLowerCase() === ID_COLUMN);
+ const frozen = $derived(meta?.frozen === column.name);
+ const isProgress = $derived(meta?.progress === column.name);
+ const counted = $derived(countedOf(role));
+ /** How many of a `row` column's names reach no single row. The binders' own version of
+ * this column had already decayed to `#REF!`; re-read from the words every time, the
+ * same decay is a number that goes up the moment somebody renames a row. */
+ const adrift = $derived(
+ role?.kind === 'row' ? unresolved(rowTargets(table, column.index, role)) : 0,
+ );
+
+ /** What this column actually says, commonest first. The funnel counts the same values and
+ * makes you open it column by column; a worklist's real question — *which cities does
+ * this hold, and how many rows each* — is a reading, so it is read here. */
+ const spread = $derived(columnValues(table, column.name, role, { limit: 8 }));
+
+ /** Whether the column holds addresses, over a sample rather than the whole sheet: this is
+ * only deciding whether to offer a button, and reading twenty thousand rows to draw one
+ * is a cost nobody asked for. */
+ const holdsLinks = $derived(
+ (table?.rows ?? []).slice(0, 200).some((row) => urlsIn(row[column.index]).length),
+ );
+
+ let note = $state('');
+ let name = $state('');
+ // Re-seeded when the dialog opens on another heading, so the boxes hold that column's
+ // answers rather than the previous one's.
+ $effect(() => {
+ note = meta?.notes?.[column.name] ?? '';
+ });
+ $effect(() => {
+ name = column.name;
+ });
+</script>
+
+<aside class="panel column-panel" aria-label="How this column is set up">
+ <header>
+ <Icon name="sliders" size={13} />
+ <span class="which">{column.name}</span>
+ <div class="spacer"></div>
+ <button class="btn btn-ghost btn-sm" title="Close" aria-label="Close this column"
+ onclick={onclose}>
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+
+ <div class="body">
+ {#if isKey}
+ <p class="note">The row's handle. It is never renamed, moved or rewritten.</p>
+ {:else}
+ <label class="field">
+ <span>Name</span>
+ <input class="input name" bind:value={name} aria-label="Column name"
+ onkeydown={(event) => event.key === 'Enter' && onrename(name)}
+ onblur={() => onrename(name)} />
+ </label>
+
+ {#if asked}
+ <!-- Said, not offered: the funnel on the heading is where a filter is set, and this
+ is the dialog telling you the rows you are looking at are not all of them. -->
+ <section class="asked">
+ <Icon name="filter" size={12} />
+ <span>{asked}</span>
+ <button class="clear" onclick={onclearfilter}>Clear</button>
+ </section>
+ {/if}
+
+ <SheetRoleEditor {table} {meta} {column} {role} onchange={onrole} {onanchors} />
+
+ <section>
+ <label class="field">
+ <span>Note</span>
+ <input class="input" placeholder="what belongs here" bind:value={note}
+ onkeydown={(event) => event.key === 'Enter' && onnote(note)}
+ onblur={() => onnote(note)} />
+ </label>
+ </section>
+
+ <!-- What this column can be *read* for, which is not the same as what can be done to
+ it: the frequent gestures — insert, duplicate, rename, split, hide, delete — are one
+ right-click on the heading, so they are not restated here. -->
+ <section>
+ <p class="what">Read this column</p>
+ {#if spread?.values?.length}
+ <!-- The count per value, which is the pivot a worklist asks for constantly: how
+ many rows say Kherson. Clicking one is the filter, so the reading and the
+ question are one gesture apart. -->
+ <div class="spread">
+ {#each spread.values as entry (entry.value)}
+ <button class="value-row" onclick={() => onvalue(entry.value)}
+ title="Keep only rows with “{entry.value}”">
+ <span>{entry.value || '(blank)'}</span>
+ <small>{entry.rows}</small>
+ </button>
+ {/each}
+ </div>
+ {#if spread.total > spread.values.length}
+ <p class="menu-note">The 8 commonest of {spread.total}. The filter lists the rest.</p>
+ {/if}
+ {/if}
+ {#if role?.kind === 'latlon'}
+ <button class="row-btn" onclick={() => onmap(column.name)}>
+ <Icon name="satellite" size={12} /><span>Show on the map</span>
+ </button>
+ <button class="row-btn" onclick={() => onnearby(column.name)}>
+ <Icon name="crosshair" size={12} /><span>Find points too close</span>
+ </button>
+ <button class="row-btn" onclick={() => onnormalise(column.name)}>
+ <Icon name="wand" size={12} /><span>Rewrite as <code>lat, lon</code></span>
+ </button>
+ <!-- The other direction of the geocoder, and the one a geolocation index wants at
+ the end: the points are established, and now the rows need a place name. -->
+ <button class="row-btn" onclick={() => ongeocode('reverse')}>
+ <Icon name="globe" size={12} /><span>Name these points…</span>
+ </button>
+ {/if}
+ {#if role?.kind === 'when'}
+ <!-- What it does, said as what it does. "Send to the Timeline" read as filing the
+ dates there; it opens the Timeline on the period they cover. -->
+ <button class="row-btn" onclick={() => ontimeline(column.name)}>
+ <Icon name="clock" size={12} /><span>Open the Timeline on this period</span>
+ </button>
+ {/if}
+ {#if !role || role.kind === 'choice' || role.kind === 'state'}
+ <!-- A column of place names is what a binder actually holds, and typing four
+ hundred coordinates by hand is what it costs. Proposed, never applied. -->
+ <button class="row-btn" onclick={() => ongeocode('forward')}>
+ <Icon name="pin" size={12} /><span>Read these places into coordinates…</span>
+ </button>
+ {/if}
+ {#if holdsLinks}
+ <!-- The only reading that reaches the network, and only on this press. -->
+ <button class="row-btn" onclick={() => oncheck(column.name)}>
+ <Icon name="external" size={12} /><span>Check these links…</span>
+ </button>
+ {/if}
+ {#if !chipped}
+ <!-- Not on a column of values: there, every value said twice is every value, and
+ the spread above already counts them one by one. -->
+ <button class="row-btn" onclick={() => onduplicates(column.name)}>
+ <Icon name="copy" size={12} /><span>Show duplicates</span>
+ </button>
+ {/if}
+ </section>
+
+ <!-- Into the case is one road now, and it is a whole-sheet answer: every column takes
+ a mode in one screen, so a per-column button here would be the second way in. What
+ stays is the reading this panel is for — how many names reach no row. -->
+ {#if role?.kind === 'row' && adrift}
+ <section>
+ <p class="what">Into the case</p>
+ <p class="menu-note">
+ {adrift} {adrift === 1 ? 'name reaches' : 'names reach'} no single row, and are
+ marked in the cells.
+ </p>
+ </section>
+ {/if}
+
+ <!-- A sheet-wide answer, set from the column that carries it: one column per sheet says
+ how far along the work is, and this is where it is chosen or given up. -->
+ <section>
+ <p class="what">This sheet</p>
+ <button class="row-btn" class:on={isProgress} onclick={() => onprogress(column.name)}>
+ <Icon name="chart" size={12} />
+ <span>{isProgress ? 'Stop counting progress here' : 'Count the sheet progress here'}</span>
+ </button>
+ <button class="row-btn" class:on={frozen} onclick={() => onfreeze(column.name)}>
+ <Icon name="pushpin" size={12} />
+ <span>{frozen ? 'Let it scroll' : 'Keep it in view'}</span>
+ </button>
+ {#if counted}
+ <p class="menu-note">
+ This column counts {counted} {counted === 1 ? 'column' : 'columns'}, so the cells
+ read <code>0</code> to <code>{counted}</code>.
+ </p>
+ {/if}
+ </section>
+ {/if}
+ </div>
+</aside>
+
+<style>
+ /* The same 340px slot the row panel takes, and the two take turns in it: you are either
+ reading a row across its fields or working on a column down the rows. Opening one puts
+ the other away, so there is never a question about which the panel is showing. */
+ .panel {
+ width: 340px; flex: none; display: flex; flex-direction: column; min-height: 0;
+ border-left: 1px solid var(--border); background: var(--bg-1);
+ }
+ header {
+ display: flex; align-items: center; gap: 6px; padding: 5px 8px;
+ border-bottom: 1px solid var(--border); color: var(--text-3);
+ }
+ .which {
+ min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-1); font-size: var(--fs-sm); font-weight: 500;
+ }
+ .body { flex: 1; min-height: 0; overflow: auto; padding: 6px 10px 14px; }
+ .spacer { flex: 1; }
+ section { padding-top: 6px; margin-top: 5px; border-top: 1px solid var(--border); }
+ .what { padding: 2px 3px 5px; color: var(--text-3); font-size: var(--fs-xs); }
+ .asked {
+ display: flex; align-items: center; gap: 6px; padding: 6px 7px; margin-top: 8px;
+ border-radius: var(--r-sm); background: var(--accent-soft); color: var(--accent);
+ font-size: var(--fs-xs);
+ }
+ .asked span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .asked .clear { flex: none; color: inherit; text-decoration: underline; }
+ .field { display: block; padding: 2px 0; }
+ .field span { display: block; color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 3px; }
+ .field .input { width: 100%; }
+ .row-btn {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 6px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .row-btn:hover { background: var(--bg-2); color: var(--text-1); }
+ .row-btn.on { color: var(--accent); }
+ .row-btn span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ /* The count per value: the word, then how many rows hold it. A row per value, because
+ that is how a tally is read. */
+ .spread { max-height: 190px; overflow: auto; margin-bottom: 4px; }
+ .value-row {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 4px 6px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .value-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .value-row span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .value-row small { flex: none; color: var(--text-3); font-size: var(--fs-xs); }
+ .note { padding: 6px 4px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+ .menu-note { padding: 6px 7px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetDate.svelte b/frontend/src/components/SheetDate.svelte
new file mode 100644
index 0000000..264f1cb
--- /dev/null
+++ b/frontend/src/components/SheetDate.svelte
@@ -0,0 +1,281 @@
+<script>
+ /**
+ * A column of hours as **statements** the case holds — one mode of the press that sends a
+ * sheet to the case.
+ *
+ * The binders do not hold dates. They hold a reasoning *about* a date across three
+ * columns: the hour that was established, the hour that was estimated, and how it was
+ * worked out. Copied into one date field that is one number and two lost columns.
+ *
+ * So this asks for four things and shows what they produce. **The worked example is the
+ * point**: `01:57` on a chosen day reads back as the moment that will be stored, so the
+ * two answers a file cannot hold — which day a bare clock belongs to, which zone it is
+ * written in — are checked by eye instead of by a paragraph explaining them. Everything
+ * else folds away, because it has a right default.
+ *
+ * The subject comes from the pass, and so does the plan and the press: this reports its
+ * answers upward and owns none of that.
+ */
+ import { ID_COLUMN } from '../lib/sheet.js';
+ import { parseWhen, whenShape } from '../lib/sheetRoles.js';
+
+ let { table, meta, subject = '', onchoices, onanchors } = $props();
+
+ const CONFIDENCE = [
+ { id: 'certain', label: 'Certain' },
+ { id: 'probable', label: 'Probable' },
+ { id: 'possible', label: 'Possible' },
+ ];
+ const ROLES = [
+ { id: 'occurred', label: 'It happened then' },
+ { id: 'observed', label: 'It was seen then' },
+ { id: 'valid', label: 'It held then' },
+ ];
+ const ZONES = [
+ { id: '', label: 'Local' },
+ { id: 'Z', label: 'UTC' },
+ ];
+
+ const columns = $derived(
+ (table?.columns ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+ /** Offset columns, the other road in: rows lined up on one shot, dated the moment it is. */
+ const offsets = $derived(columns.filter((name) => meta?.roles?.[name]?.kind === 'offset'));
+ /** Columns the sheet already says hold a time, which is what gets picked by default. */
+ const timed = $derived(columns.filter((name) => meta?.roles?.[name]?.kind === 'when'));
+
+ let from = $state('columns'); // 'columns' | 'anchor'
+ let whenColumn = $state('');
+ let estimateColumn = $state('');
+ let methodColumn = $state('');
+ let placeColumn = $state('');
+ let linkColumn = $state('');
+ let offsetColumn = $state('');
+ let day = $state('');
+ let zone = $state('');
+ let confidence = $state('probable');
+ let timeRole = $state('occurred');
+ let more = $state(false);
+
+ // Seeded from what the sheet already declares, so the ordinary case is answered before it
+ // is asked: a column with the `when` role is the column of hours.
+ $effect(() => {
+ if (!whenColumn && timed.length) whenColumn = timed[0];
+ });
+ $effect(() => {
+ if (!offsetColumn && offsets.length) offsetColumn = offsets[0];
+ });
+
+ const byAnchor = $derived(from === 'anchor');
+ const anchor = $derived(meta?.roles?.[offsetColumn]?.anchor ?? '');
+ const anchorAt = $derived(meta?.anchors?.[anchor]?.at ?? '');
+ const ready = $derived(
+ Boolean(subject && (byAnchor ? offsetColumn : whenColumn || estimateColumn)),
+ );
+
+ /** The cells of the chosen column, which is what says whether the file holds a day. */
+ const cells = $derived.by(() => {
+ const at = (table?.columns ?? []).indexOf(whenColumn || estimateColumn);
+ if (at === -1) return [];
+ return (table?.rows ?? []).map((row) => row[at] ?? '');
+ });
+ /** Bare clocks have no date in them, so that is the one answer the sheet has to give. */
+ const needsDay = $derived(!byAnchor && cells.length > 0 && whenShape(cells) === 'time');
+
+ /** One row read back as the moment that will be stored. Read with the same parser the
+ * cell editor uses, so what is shown is what the column already means. */
+ const example = $derived.by(() => {
+ for (const cell of cells) {
+ const read = parseWhen(String(cell), meta?.roles?.[whenColumn] ?? {});
+ if (!read) continue;
+ if (read.shape === 'time') {
+ return day ? { cell, moment: `${day} ${read.text}` } : { cell, moment: '' };
+ }
+ return { cell, moment: read.text.replace('T', ' ') };
+ }
+ return null;
+ });
+
+ function choices() {
+ return {
+ when_column: byAnchor ? '' : whenColumn,
+ estimate_column: byAnchor ? '' : estimateColumn,
+ method_column: byAnchor ? '' : methodColumn,
+ offset_column: byAnchor ? offsetColumn : '',
+ place_column: placeColumn,
+ link_column: linkColumn,
+ day,
+ zone,
+ confidence,
+ time_role: timeRole,
+ };
+ }
+
+ $effect(() => onchoices(ready ? choices() : null));
+</script>
+
+<div class="date">
+ {#if offsets.length}
+ <div class="kinds">
+ <button class="kind" class:on={!byAnchor} onclick={() => (from = 'columns')}>
+ From hours
+ </button>
+ <button class="kind" class:on={byAnchor} onclick={() => (from = 'anchor')}>
+ From a sync point
+ </button>
+ </div>
+ {/if}
+
+ {#if byAnchor}
+ <label class="row">
+ <span>Synced on</span>
+ <select class="input" value={offsetColumn} aria-label="The offset column"
+ onchange={(event) => (offsetColumn = event.currentTarget.value)}>
+ {#each offsets as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ <p class="note">
+ {#if !anchor}
+ No sync point on this column.
+ {:else if anchorAt}
+ <em>{anchor}</em> is dated {anchorAt.replace('T', ' ').slice(0, 19)}.
+ {:else}
+ <em>{anchor}</em> has no time yet, so nothing can be dated from it.
+ <!-- The one thing these rows are missing, one press away instead of three screens
+ back: they already carry their order, and the shot's own time is what turns
+ that into hours. -->
+ {#if onanchors}
+ <button class="link" onclick={onanchors}>Date it</button>
+ {/if}
+ {/if}
+ </p>
+ {:else}
+ <label class="row">
+ <span>The hour</span>
+ <select class="input" value={whenColumn} aria-label="The established hour"
+ onchange={(event) => (whenColumn = event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+
+ {#if needsDay}
+ <label class="row">
+ <span>The day it belongs to</span>
+ <input class="input" type="date" aria-label="The day these hours belong to"
+ bind:value={day} />
+ </label>
+ <p class="note">These cells hold clocks with no day.</p>
+ {/if}
+
+ <label class="row">
+ <span>How sure that hour is</span>
+ <select class="input" value={confidence} aria-label="How sure the hour is"
+ onchange={(event) => (confidence = event.currentTarget.value)}>
+ {#each CONFIDENCE as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}
+ </select>
+ </label>
+
+ {#if example}
+ <p class="example">
+ <code>{example.cell}</code>
+ {#if example.moment}
+ → <strong>{example.moment}</strong> {zone === 'Z' ? 'UTC' : 'local'}
+ {:else}
+ → <em>waiting for the day</em>
+ {/if}
+ </p>
+ {/if}
+ {/if}
+
+ <button class="disclose" onclick={() => (more = !more)}>
+ {more ? 'Fewer answers' : 'More answers'}
+ </button>
+
+ {#if more}
+ <div class="folded">
+ {#if !byAnchor}
+ <label class="row">
+ <span>If the hour is an estimate</span>
+ <select class="input" value={estimateColumn} aria-label="The estimated hour"
+ onchange={(event) => (estimateColumn = event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ <label class="row">
+ <span>How it was worked out</span>
+ <select class="input" value={methodColumn} aria-label="How it was worked out"
+ onchange={(event) => (methodColumn = event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ <label class="row">
+ <span>Written in</span>
+ <select class="input" value={zone} aria-label="The time zone this column is in"
+ onchange={(event) => (zone = event.currentTarget.value)}>
+ {#each ZONES as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}
+ </select>
+ </label>
+ {/if}
+ <label class="row">
+ <span>What the time says</span>
+ <select class="input" value={timeRole} aria-label="What the time says"
+ onchange={(event) => (timeRole = event.currentTarget.value)}>
+ {#each ROLES as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}
+ </select>
+ </label>
+ <label class="row">
+ <span>Where it places them</span>
+ <select class="input" value={placeColumn} aria-label="The column holding the place"
+ onchange={(event) => (placeColumn = event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ <label class="row">
+ <span>What they rest on</span>
+ <select class="input" value={linkColumn} aria-label="The column holding the sources"
+ onchange={(event) => (linkColumn = event.currentTarget.value)}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .date { display: flex; flex-direction: column; }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 2px 0; }
+ .link { color: var(--accent); font-size: inherit; text-decoration: underline; }
+ .row {
+ display: grid; grid-template-columns: minmax(0, 1fr) 190px; align-items: center;
+ gap: 8px; padding: 3px 0;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .kinds { display: flex; flex-wrap: wrap; gap: 4px; padding-bottom: 4px; }
+ .kind {
+ padding: 3px 8px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .kind:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .kind.on { border-color: var(--accent); color: var(--accent); }
+
+ /* One row read back as what will be stored. A worked example beats a rule: nobody can
+ check `01:57` against a stored timestamp in their head. */
+ .example {
+ display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
+ padding: 5px 0 2px; color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .example code { color: var(--text-2); }
+ .example strong { color: var(--text-1); font-weight: 600; }
+
+ .disclose {
+ align-self: flex-start; padding: 5px 0 2px;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .disclose:hover { color: var(--accent); text-decoration: underline; }
+ .folded { padding-bottom: 2px; }
+</style>
diff --git a/frontend/src/components/SheetEntityPicker.svelte b/frontend/src/components/SheetEntityPicker.svelte
new file mode 100644
index 0000000..78d2ca2
--- /dev/null
+++ b/frontend/src/components/SheetEntityPicker.svelte
@@ -0,0 +1,271 @@
+<script>
+ /**
+ * Point a sheet cell at an entity the case already holds.
+ *
+ * A single search bar is not enough here and the reason is worth stating: the
+ * analyst pointing a cell at an entity usually does **not** know the label. The
+ * cell says `3rd Bde` and the case holds `3rd Separate Brigade`; it says `AB-123`
+ * and the case holds a vehicle filed under a folder. Typing into a bar only works
+ * when you already know the answer.
+ *
+ * So the picker leads with what the case *has*: a count per type, taken from the
+ * catalog summary, and a list that is populated before a key is pressed. Narrowing
+ * by type is one click and it says how big each answer is first — the same rule the
+ * catalog's own filter menu follows, so nobody picks a term and lands on nothing.
+ */
+ import { untrack } from 'svelte';
+ import Icon from './Icon.svelte';
+ import { api } from '../lib/api.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+
+ let { caseId, cellText = '', current = null, onpick, onclear, onclose } = $props();
+
+ /** One page. Not a ceiling: `next_cursor` carries the rest, and the count above the
+ * list says how much rest there is — a case of a thousand entities is walkable
+ * rather than silently cut at the first forty. */
+ const PAGE = 40;
+
+ /** How the **whole filtered set** is ordered, server-side. That is the point: sorting
+ * the forty rows already loaded answers a different question from sorting the
+ * thousand that match. A→Z leads because a picker is used to find a name.
+ * Mirrors `store/cursors._PAGE_ORDERS`. */
+ const ORDERS = [
+ { id: 'label', label: 'A→Z' },
+ { id: '-label', label: 'Z→A' },
+ { id: '-created', label: 'Newest' },
+ { id: 'created', label: 'Oldest' },
+ ];
+
+ /** Seeded from the cell once, then the analyst's to change. Untracked on purpose:
+ * a picker that reset the box every time the cell behind it changed would fight
+ * whoever is typing in it. */
+ let query = $state(untrack(() => String(cellText ?? '').trim()));
+ let type = $state(null);
+ let order = $state('label');
+ let items = $state([]);
+ let cursor = $state(null);
+ /** How many match what is being asked — not how many are on screen. */
+ let matching = $state(0);
+ let counts = $state([]);
+ let total = $state(0);
+ let loading = $state(true);
+ let loadingMore = $state(false);
+ let highlighted = $state(0);
+ let listElement = $state(null);
+
+ $effect(() => {
+ if (!caseId) return;
+ let live = true;
+ api
+ .get(`/api/cases/${caseId}/catalog/summary`)
+ .then((answer) => {
+ if (!live) return;
+ total = answer.total ?? 0;
+ counts = Object.entries(answer.by_type ?? {})
+ .map(([id, count]) => ({ id, count }))
+ .sort((a, b) => b.count - a.count || a.id.localeCompare(b.id));
+ })
+ .catch(() => {});
+ return () => (live = false);
+ });
+
+ function page(term, wanted, chosen, from) {
+ const params = new URLSearchParams({ limit: String(PAGE), order: chosen });
+ if (term) params.set('q', term);
+ if (wanted) params.set('type', wanted);
+ if (from) params.set('cursor', from);
+ return api.get(`/api/cases/${caseId}/catalog/entities?${params}`);
+ }
+
+ // One effect for the first page, keyed on all three questions asked of it, so a type
+ // chosen while a word is typed narrows rather than replacing. Changing any of them
+ // starts the list over: a cursor belongs to the query it was issued for.
+ $effect(() => {
+ const term = query.trim();
+ const wanted = type;
+ const chosen = order;
+ if (!caseId) return;
+ let live = true;
+ loading = true;
+ page(term, wanted, chosen, null)
+ .then((answer) => {
+ if (!live) return;
+ items = answer.items ?? [];
+ cursor = answer.next_cursor ?? null;
+ matching = answer.total ?? items.length;
+ highlighted = 0;
+ loading = false;
+ })
+ .catch(() => {
+ if (!live) return;
+ items = [];
+ cursor = null;
+ matching = 0;
+ loading = false;
+ });
+ return () => (live = false);
+ });
+
+ /** The next page, appended. Deliberately a press rather than an infinite scroll: a
+ * list that grows while it is being read moves the row under the pointer. */
+ async function more() {
+ if (!cursor || loadingMore) return;
+ loadingMore = true;
+ try {
+ const answer = await page(query.trim(), type, order, cursor);
+ items = [...items, ...(answer.items ?? [])];
+ cursor = answer.next_cursor ?? null;
+ } catch {
+ cursor = null;
+ } finally {
+ loadingMore = false;
+ }
+ }
+
+ function onKey(event) {
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ const step = event.key === 'ArrowDown' ? 1 : -1;
+ highlighted = Math.min(Math.max(highlighted + step, 0), Math.max(0, items.length - 1));
+ // Walking onto the last row loads the next page: the keyboard should not stop
+ // at a boundary the list only has because it pages.
+ if (highlighted === items.length - 1) more();
+ listElement?.children[highlighted]?.scrollIntoView({ block: 'nearest' });
+ return;
+ }
+ if (event.key === 'Enter' && items[highlighted]) {
+ event.preventDefault();
+ onpick(items[highlighted]);
+ }
+ }
+</script>
+
+<div class="picker">
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input" autofocus placeholder="Find an entity by name" bind:value={query}
+ aria-label="Find an entity" onkeydown={onKey} />
+
+ {#if counts.length}
+ <div class="types">
+ <button class="chip" class:on={!type} onclick={() => (type = null)}>
+ Everything <small>{total}</small>
+ </button>
+ {#each counts as entry (entry.id)}
+ <button class="chip" class:on={type === entry.id}
+ onclick={() => (type = type === entry.id ? null : entry.id)}>
+ <Icon name={entityIcon({ type: entry.id })} size={11} />
+ {entry.id} <small>{entry.count}</small>
+ </button>
+ {/each}
+ </div>
+ {/if}
+
+ <div class="bar">
+ <span class="shown">
+ {#if items.length}
+ <strong>{items.length}</strong> of {matching} shown
+ {/if}
+ </span>
+ <div class="orders">
+ {#each ORDERS as entry (entry.id)}
+ <button class="order" class:on={order === entry.id}
+ onclick={() => (order = entry.id)}>{entry.label}</button>
+ {/each}
+ </div>
+ </div>
+
+ <div class="results" bind:this={listElement}>
+ {#each items as entity, index (entity.id)}
+ <button class="result" class:on={index === highlighted} class:linked={entity.id === current}
+ onclick={() => onpick(entity)} onpointerenter={() => (highlighted = index)}>
+ <Icon name={entityIcon(entity)} size={14} />
+ <span class="label">{entity.label}</span>
+ {#if entity.folder}<small class="folder">{entity.folder}</small>{/if}
+ <small class="type">{entity.type}</small>
+ {#if entity.id === current}<Icon name="check" size={12} />{/if}
+ </button>
+ {:else}
+ <p class="hint">
+ {#if loading}
+ Looking.
+ {:else if query.trim() || type}
+ Nothing in this case matches. {total} {total === 1 ? 'entity' : 'entities'} filed in
+ all; clear the box to see them.
+ {:else}
+ This case holds no entities yet.
+ {/if}
+ </p>
+ {/each}
+
+ {#if cursor}
+ <button class="more" onclick={more} disabled={loadingMore}>
+ {loadingMore ? 'Loading' : `Load ${Math.min(PAGE, matching - items.length)} more`}
+ </button>
+ {/if}
+ </div>
+
+ <div class="foot">
+ {#if current}
+ <button class="btn btn-danger btn-sm" onclick={onclear}>Clear the link</button>
+ {/if}
+ <div class="spacer"></div>
+ <small class="keys">↑↓ to move · Enter to pick</small>
+ <button class="btn btn-sm" onclick={onclose}>Cancel</button>
+ </div>
+</div>
+
+<style>
+ .picker { display: flex; flex-direction: column; min-height: 0; }
+ .types { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 8px; }
+ .chip {
+ display: inline-flex; align-items: center; gap: 5px; padding: 3px 8px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .chip:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .chip.on { border-color: var(--accent); color: var(--accent); }
+ .chip small { color: var(--text-3); }
+
+ .bar { display: flex; align-items: center; gap: 8px; margin-top: 10px; }
+ .shown { flex: 1; color: var(--text-3); font-size: var(--fs-xs); }
+ .shown strong { color: var(--text-1); font-weight: 600; }
+ .orders { display: flex; }
+ .order {
+ padding: 2px 7px; color: var(--text-3); font-size: var(--fs-xs);
+ border: 1px solid var(--border); border-left-width: 0;
+ }
+ .order:first-child { border-left-width: 1px; border-radius: var(--r-sm) 0 0 var(--r-sm); }
+ .order:last-child { border-radius: 0 var(--r-sm) var(--r-sm) 0; }
+ .order:hover { color: var(--text-1); background: var(--bg-2); }
+ .order.on { color: var(--accent); background: var(--bg-2); }
+
+ .results {
+ max-height: 340px; min-height: 120px; overflow: auto; margin-top: 6px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .more {
+ width: 100%; padding: 8px; color: var(--text-2); font-size: var(--fs-sm);
+ border-top: 1px solid var(--border);
+ }
+ .more:hover { background: var(--bg-2); color: var(--text-1); }
+ .more:disabled { color: var(--text-3); }
+ .result {
+ display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto auto;
+ align-items: center; gap: 8px; width: 100%; padding: 7px 9px;
+ color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .result:hover, .result.on { background: var(--bg-2); color: var(--text-1); }
+ .result.on { box-shadow: inset 2px 0 0 var(--accent); }
+ .result.linked { color: var(--accent); }
+ .result .label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .result small { color: var(--text-3); font-size: var(--fs-xs); }
+ .result .folder { font-family: var(--font-mono); }
+ .result .type {
+ padding: 1px 5px; border-radius: var(--r-sm); background: var(--bg-3);
+ }
+ .hint { padding: 14px 10px; color: var(--text-3); font-size: var(--fs-sm); line-height: 1.5; }
+
+ .foot { display: flex; align-items: center; gap: 8px; margin-top: 12px; }
+ .spacer { flex: 1; }
+ .keys { color: var(--text-3); font-size: var(--fs-xs); }
+</style>
diff --git a/frontend/src/components/SheetFilterMenu.svelte b/frontend/src/components/SheetFilterMenu.svelte
new file mode 100644
index 0000000..24dc302
--- /dev/null
+++ b/frontend/src/components/SheetFilterMenu.svelte
@@ -0,0 +1,235 @@
+<script>
+ /**
+ * What is asked of one column, in a menu that hangs off its heading.
+ *
+ * The second of the two doors a heading has, and the one that gets used all day. It
+ * was behind the same `...` as the role editor, the note, the seven actions and the
+ * delete — so filtering, the gesture an analyst makes a hundred times an hour, cost
+ * the same as declaring a vocabulary, which is done once per column ever.
+ *
+ * So the two are split by **how often they are wanted**: the funnel asks, the `...`
+ * sets up. Everything here is a question about the rows; nothing here changes what
+ * the column *is*.
+ *
+ * A menu rather than the panel, on purpose, and it does not contradict the panel's
+ * own reason for existing: what did not fit in two hundred pixels was a name, three
+ * filters, a list of values, a role with its vocabulary, a note and seven actions —
+ * the filter *alone* fits, and it is what every spreadsheet puts here. The panel
+ * also costs 340px of grid at the moment the analyst wants to watch rows disappear.
+ *
+ * Drawn outside the scroller and placed from the heading's own rectangle: inside it,
+ * the grid's `overflow: auto` would clip it and its own scrollbars would grow to
+ * account for it.
+ */
+ import Icon from './Icon.svelte';
+ import { columnValues, isFilterActive, normalizeFilter } from '../lib/sheet.js';
+ import { readable } from '../lib/sheetRoles.js';
+
+ let {
+ table,
+ column,
+ role = null,
+ filter = null,
+ at = { x: 0, y: 0 },
+ onvalue,
+ onfill,
+ oncontains,
+ onwithout,
+ onrange,
+ onclear,
+ onclose,
+ } = $props();
+
+ const NOTHING_ASKED = { values: null, fill: null, contains: '', without: '', from: '', to: '' };
+
+ let contains = $state('');
+ let without = $state('');
+ let from = $state('');
+ let to = $state('');
+ /** What is typed into the value search. Narrows against the whole column, which is what
+ * makes a hundred and twenty cities reachable from a list forty long. */
+ let among = $state('');
+
+ /** The values on offer, counted the way the column reads them: a list column is
+ * counted value by value, so `Buk-M2E, ZU23-2` offers two answers rather than one
+ * entry no second row will ever match. Narrowed by the box above it and cut to a
+ * page, so a column of a hundred and twenty cities is walkable rather than refused. */
+ const read = $derived(columnValues(table, column.name, role, { term: among }));
+ const current = $derived(normalizeFilter(filter) ?? NOTHING_ASKED);
+ const active = $derived(isFilterActive(filter));
+ /** How many filled cells the column's own lens cannot read. Offered as a filter rather
+ * than a warning: a role never refuses a cell, so the analyst needs the list. */
+ const unread = $derived(role ? readable(table, column.index, role).unreadable : 0);
+ /** Whether a bound is a question this column can answer. Only where the column says it
+ * holds quantities: two bounds on a column of names would be two boxes doing nothing. */
+ const ordered = $derived(role?.kind === 'number' || role?.kind === 'when');
+ const dated = $derived(role?.kind === 'when');
+
+ // Re-seeded when the menu opens on another column, so the boxes hold that column's
+ // answers rather than the previous one's.
+ $effect(() => {
+ contains = normalizeFilter(filter)?.contains ?? '';
+ });
+ $effect(() => {
+ without = normalizeFilter(filter)?.without ?? '';
+ });
+ $effect(() => {
+ from = normalizeFilter(filter)?.from ?? '';
+ });
+ $effect(() => {
+ to = normalizeFilter(filter)?.to ?? '';
+ });
+ $effect(() => {
+ void column.name;
+ among = '';
+ });
+
+ /** Kept on screen where a column near the right edge would put it off. Read once as
+ * the menu opens: it does not follow the heading, because a grid scrolled under an
+ * open menu closes it. */
+ const WIDTH = 260;
+ const left = $derived(
+ typeof window === 'undefined' ? at.x : Math.max(8, Math.min(at.x, window.innerWidth - WIDTH - 8)),
+ );
+</script>
+
+<div class="filter-menu" style="left: {left}px; top: {at.y}px; width: {WIDTH}px"
+ role="dialog" aria-label="Filter {column.name}">
+ <header>
+ <span class="name">{column.name}</span>
+ {#if active}
+ <button class="clear" onclick={onclear}>Clear</button>
+ {/if}
+ <button class="shut" title="Close" aria-label="Close this filter" onclick={onclose}>
+ <Icon name="x" size={13} />
+ </button>
+ </header>
+
+ <div class="asks">
+ <button class="ask" class:on={current.fill === 'filled'} onclick={() => onfill('filled')}>
+ <Icon name="check" size={12} /> Filled
+ </button>
+ <button class="ask" class:on={current.fill === 'blank'} onclick={() => onfill('blank')}>
+ <Icon name="x" size={12} /> Empty
+ </button>
+ </div>
+ {#if unread}
+ <button class="ask wide" class:on={current.fill === 'unreadable'}
+ title="Cells the type cannot read"
+ onclick={() => onfill('unreadable')}>
+ <Icon name="alert" size={12} /> {unread} to check
+ </button>
+ {/if}
+
+ <!-- The two halves of the same question. `Without` was here on its own, which meant
+ a column of prose — past the bound there is no list of values to tick — could be
+ ruled out by a word and never kept by one. -->
+ <label class="field">
+ <span>Holding</span>
+ <input class="input" placeholder="a word it must hold"
+ bind:value={contains}
+ onkeydown={(event) => event.key === 'Enter' && oncontains(contains)}
+ onblur={() => oncontains(contains)} />
+ </label>
+ <label class="field">
+ <span>Without</span>
+ <input class="input" placeholder="a word it must not hold"
+ bind:value={without}
+ onkeydown={(event) => event.key === 'Enter' && onwithout(without)}
+ onblur={() => onwithout(without)} />
+ </label>
+
+ {#if ordered}
+ <!-- The question a list of values cannot ask: *before this date*, *under five
+ kilometres*. Only on a column that says it holds quantities, and either bound
+ alone is a question. -->
+ <div class="bounds">
+ <label class="field">
+ <span>From</span>
+ <input class="input" type={dated ? 'date' : 'text'} placeholder={dated ? '' : 'lowest'}
+ bind:value={from}
+ onkeydown={(event) => event.key === 'Enter' && onrange({ from })}
+ onblur={() => onrange({ from })} />
+ </label>
+ <label class="field">
+ <span>To</span>
+ <input class="input" type={dated ? 'date' : 'text'} placeholder={dated ? '' : 'highest'}
+ bind:value={to}
+ onkeydown={(event) => event.key === 'Enter' && onrange({ to })}
+ onblur={() => onrange({ to })} />
+ </label>
+ </div>
+ {/if}
+
+ {#if read}
+ <!-- A column of a hundred and twenty cities used to answer nothing at all here: past
+ forty distinct values the menu said "too many to list". Now it pages, and the box
+ narrows against the whole column rather than against the page. -->
+ {#if read.total > read.values.length || among}
+ <label class="field">
+ <span>Among {read.total} values</span>
+ <input class="input" placeholder="narrow the list" bind:value={among} />
+ </label>
+ {/if}
+ <div class="values">
+ {#each read.values as entry (entry.value)}
+ <button class="row-btn" onclick={() => onvalue(entry.value)}>
+ <input type="checkbox" checked={current.values?.has(entry.value) ?? false}
+ tabindex="-1" />
+ <span>{entry.value || '(blank)'}</span>
+ <!-- How many rows hold it, which is what the filter will hand back. -->
+ <small>{entry.rows}</small>
+ </button>
+ {:else}
+ <p class="note">No match.</p>
+ {/each}
+ </div>
+ {#if read.capped}
+ <p class="note">
+ The {read.values.length} commonest of {read.matching}. Narrow the list above.
+ </p>
+ {/if}
+ {/if}
+</div>
+
+<style>
+ .filter-menu {
+ position: fixed; z-index: 20;
+ display: flex; flex-direction: column; gap: 2px;
+ max-height: min(440px, calc(100vh - 120px)); overflow: auto;
+ padding: 6px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ header { display: flex; align-items: center; gap: 6px; padding: 1px 2px 5px; }
+ .name {
+ flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-1); font-size: var(--fs-sm); font-weight: 500;
+ }
+ .clear { flex: none; color: var(--text-3); font-size: var(--fs-xs); }
+ .clear:hover { color: var(--accent); }
+ .shut { flex: none; display: flex; color: var(--text-3); }
+ .shut:hover { color: var(--text-1); }
+ .asks { display: flex; gap: 4px; }
+ .ask {
+ flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 5px;
+ padding: 5px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .ask.wide { width: 100%; margin-top: 4px; }
+ .ask:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .ask.on { border-color: var(--accent); color: var(--accent); }
+ .field { display: block; padding: 6px 0 0; }
+ .field span { display: block; color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 3px; }
+ .field .input { width: 100%; }
+ .bounds { display: flex; gap: 6px; }
+ .bounds .field { flex: 1; min-width: 0; }
+ .values { max-height: 240px; overflow: auto; margin-top: 8px; }
+ .row-btn {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 6px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .row-btn:hover { background: var(--bg-2); color: var(--text-1); }
+ .row-btn span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .row-btn small { color: var(--text-3); font-size: var(--fs-xs); }
+ .note { padding: 8px 4px 2px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+</style>
diff --git a/frontend/src/components/SheetFromCase.svelte b/frontend/src/components/SheetFromCase.svelte
new file mode 100644
index 0000000..a46a83f
--- /dev/null
+++ b/frontend/src/components/SheetFromCase.svelte
@@ -0,0 +1,215 @@
+<script>
+ /**
+ * A worklist made out of what the case already believes.
+ *
+ * The missing half of the promotion road. Rows have always been able to become entities;
+ * an analyst holding forty places in the graph and wanting to work through them had to
+ * retype the forty, because the Board has nowhere to write a verdict and the sheet had no
+ * way to hear about the graph.
+ *
+ * Two shapes, and the choice is the first thing asked because it decides everything
+ * after it.
+ *
+ * **One row per entity** takes a type and the fields that deserve a column. Nothing else
+ * travels — a sheet holding every attribute of every entity would be a second copy of the
+ * graph, and the second copy is the one that goes stale. The rows come back pointing at
+ * what they came from, so editing them and promoting them again updates those entities
+ * rather than minting twins.
+ *
+ * **My geolocations** takes neither: its shape is fixed, one row per proof with
+ * the media it rests on and the place it puts on the map. That fixed shape is what lets it
+ * be kept level with the case afterwards, which the other one cannot be.
+ */
+ import Icon from './Icon.svelte';
+ import { api } from '../lib/api.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { entityFields, entityLabel, loadEntityTypes } from '../lib/entityTypes.svelte.js';
+
+ let { caseId, busy = false, onmake, onclose } = $props();
+
+ /** What the route takes at most. Mirrors `engine/sheetfromcase.MAX_FROM_CASE`: past two
+ * thousand rows nobody works through it, and the honest answer is a filtered Board. */
+ const MAX_ROWS = 2000;
+
+ let shape = $state('generic');
+ let counts = $state([]);
+ let type = $state('');
+ let fields = $state([]);
+ let title = $state('');
+ let touched = $state(false);
+
+ loadEntityTypes();
+
+ $effect(() => {
+ if (!caseId) return;
+ let live = true;
+ api
+ .get(`/api/cases/${caseId}/catalog/summary`)
+ .then((answer) => {
+ if (!live) return;
+ counts = Object.entries(answer.by_type ?? {})
+ .map(([id, count]) => ({ id, count }))
+ .sort((a, b) => b.count - a.count || a.id.localeCompare(b.id));
+ if (!type && counts.length) type = counts[0].id;
+ })
+ .catch(() => {});
+ return () => (live = false);
+ });
+
+ // The fields belong to the type, so a choice made for a person means nothing for a place.
+ $effect(() => {
+ void type;
+ fields = [];
+ });
+
+ // Named after what it holds until the analyst says otherwise, which is what they would
+ // have typed anyway.
+ $effect(() => {
+ if (touched) return;
+ if (proofs) title = 'My geolocations';
+ else if (type) title = `${entityLabel(type)} to check`;
+ });
+
+ const proofs = $derived(shape === 'proofs');
+ const available = $derived(entityFields(type).filter((field) => field.kind !== 'geojson'));
+ // The proofs shape counts proofs, whatever type the other branch is sitting on.
+ const held = $derived(
+ counts.find((entry) => entry.id === (proofs ? 'proof' : type))?.count ?? 0,
+ );
+ const taken = $derived(Math.min(held, MAX_ROWS));
+ const ready = $derived(Boolean((proofs || type) && title.trim() && held));
+
+ function toggle(key) {
+ fields = fields.includes(key) ? fields.filter((entry) => entry !== key) : [...fields, key];
+ }
+</script>
+
+<div class="from-case">
+ <p class="label">What the sheet is</p>
+ <div class="shapes">
+ <button class="shape" class:on={!proofs} onclick={() => (shape = 'generic')}>
+ <strong>One row per entity</strong>
+ <small>a worklist over a type you choose</small>
+ </button>
+ <button class="shape" class:on={proofs} onclick={() => (shape = 'proofs')}>
+ <strong>My geolocations</strong>
+ <small>one row per proof, kept level with the case</small>
+ </button>
+ </div>
+
+ {#if !proofs}
+ <p class="label">What is in it</p>
+ {#if counts.length}
+ <div class="types">
+ {#each counts as entry (entry.id)}
+ <button class="chip" class:on={type === entry.id} onclick={() => (type = entry.id)}>
+ <Icon name={entityIcon({ type: entry.id })} size={11} />
+ {entityLabel(entry.id)} <small>{entry.count}</small>
+ </button>
+ {/each}
+ </div>
+ {:else}
+ <p class="note">This case holds no entities yet.</p>
+ {/if}
+ {/if}
+
+ <label class="row">
+ <span>Name</span>
+ <input class="input" bind:value={title} placeholder="Places to check"
+ oninput={() => (touched = true)} />
+ </label>
+
+ {#if !proofs && available.length}
+ <p class="label">
+ And which fields get a column. None is fine if the sheet only carries your own.
+ </p>
+ <div class="fields">
+ {#each available as field (field.key)}
+ <label class="check">
+ <input type="checkbox" checked={fields.includes(field.key)}
+ onchange={() => toggle(field.key)} />
+ <span title={field.hint ?? ''}>{field.label}</span>
+ </label>
+ {/each}
+ </div>
+ {/if}
+
+ <p class="says" class:none={!ready}>
+ {#if !held}
+ {proofs ? 'This case holds no proofs yet.' : 'This case holds nothing of that type.'}
+ {:else if proofs}
+ <strong>{taken}</strong> {taken === 1 ? 'row' : 'rows'}, one per proof, with its source
+ media, its place and its coordinates.
+ {#if held > MAX_ROWS}<span>Only the first {MAX_ROWS} by name.</span>{/if}
+ {:else}
+ <strong>{taken}</strong> {taken === 1 ? 'row' : 'rows'}, one per
+ {entityLabel(type).toLowerCase()}, plus a status and a note to work in.
+ {#if held > MAX_ROWS}<span>Only the first {MAX_ROWS} by name.</span>{/if}
+ {/if}
+ </p>
+ <p class="note">
+ {#if proofs}
+ The case writes those columns and Refresh keeps them level with it. Status, Notes and any
+ column you add are yours.
+ {:else}
+ Each row points back at what it came from, so promoting it later updates that entity
+ instead of making a second one.
+ {/if}
+ </p>
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={busy || !ready}
+ onclick={() => onmake({ title: title.trim(), shape, type, fields, limit: MAX_ROWS })}>
+ {busy ? 'Building' : 'Build the sheet'}
+ </button>
+ </div>
+</div>
+
+<style>
+ .from-case { display: flex; flex-direction: column; min-height: 0; }
+ .label { color: var(--text-3); font-size: var(--fs-xs); margin: 12px 0 5px; line-height: 1.5; }
+ .label:first-child { margin-top: 0; }
+ .shapes { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
+ .shape {
+ display: flex; flex-direction: column; gap: 2px; padding: 8px 10px; text-align: left;
+ border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2);
+ }
+ .shape:hover { border-color: var(--border-strong); }
+ .shape.on { border-color: var(--accent); background: var(--accent-soft); }
+ .shape strong { color: var(--text-1); font-size: var(--fs-sm); font-weight: 600; }
+ .shape.on strong { color: var(--accent); }
+ .shape small { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.4; }
+ .types { display: flex; flex-wrap: wrap; gap: 4px; }
+ .chip {
+ display: inline-flex; align-items: center; gap: 5px; padding: 3px 8px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .chip:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .chip.on { border-color: var(--accent); color: var(--accent); }
+ .chip small { color: var(--text-3); }
+ .row {
+ display: grid; grid-template-columns: 90px minmax(0, 1fr); align-items: center;
+ gap: 8px; margin-top: 12px;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .fields {
+ display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 2px 10px;
+ max-height: 180px; overflow: auto;
+ }
+ .check { display: flex; align-items: center; gap: 7px; color: var(--text-2); font-size: var(--fs-xs); }
+ .check span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .says {
+ margin-top: 12px; padding: 6px 8px; border-radius: var(--r-sm);
+ background: var(--accent-soft); color: var(--accent); font-size: var(--fs-xs);
+ line-height: 1.5;
+ }
+ .says.none { background: var(--bg-2); color: var(--text-3); }
+ .says strong { font-weight: 600; }
+ .says span { color: var(--text-3); }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 4px 0; }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetFromProofs.render.test.js b/frontend/src/components/SheetFromProofs.render.test.js
new file mode 100644
index 0000000..a18eb9a
--- /dev/null
+++ b/frontend/src/components/SheetFromProofs.render.test.js
@@ -0,0 +1,145 @@
+// @vitest-environment happy-dom
+/**
+ * The two shapes a sheet can be built in, and the one screen that asks which.
+ *
+ * The `geoloc` template and the proofs shape carry almost the same columns and run in
+ * opposite directions: one takes addresses in and downloads them, the other lays out
+ * proofs the case already established. Choosing between them is the first thing this
+ * modal asks, because it decides everything after it — and the outgoing branch takes
+ * neither a type nor a field list, which is what these tests are here to hold.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+const post = vi.fn();
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+
+const { default: SheetFromCase } = await import('./SheetFromCase.svelte');
+
+const TYPES = [
+ { type: 'person', label: 'Person', promotable: true, attrs: [{ key: 'role', label: 'Role' }] },
+ { type: 'proof', label: 'Proof', promotable: true, attrs: [] },
+];
+
+let live = null;
+
+function open(props) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SheetFromCase, { target, props });
+ flushSync();
+ return target;
+}
+
+async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+}
+
+const flat = (target) => target.textContent.replace(/\s+/g, ' ');
+
+const press = (target, text) => {
+ const found = [...target.querySelectorAll('button')].find((node) =>
+ node.textContent.replace(/\s+/g, ' ').trim().startsWith(text),
+ );
+ found.click();
+ flushSync();
+};
+
+beforeEach(() => {
+ get.mockReset();
+ post.mockReset();
+ get.mockImplementation((url) => {
+ if (url.endsWith('/catalog/summary')) {
+ return Promise.resolve({ by_type: { person: 4, proof: 12 } });
+ }
+ return Promise.resolve(TYPES);
+ });
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('choosing what the sheet is', () => {
+ const onmake = vi.fn();
+
+ beforeEach(() => onmake.mockReset());
+
+ it('offers both shapes and starts on the one that was here first', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ expect(flat(target)).toContain('One row per entity');
+ expect(flat(target)).toContain('My geolocations');
+ expect(target.querySelector('.shape.on strong').textContent).toBe('One row per entity');
+ });
+
+ it('drops the type and the fields on the outgoing branch', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ // The incoming branch asks both questions: the type, and — on a type that declares
+ // any — which of its fields deserve a column.
+ expect(target.querySelector('.types')).not.toBeNull();
+ press(target, 'Person');
+ expect(target.querySelector('.fields')).not.toBeNull();
+
+ press(target, 'My geolocations');
+ // The outgoing one asks neither: its shape is fixed, which is what lets it be kept
+ // level with the case afterwards.
+ expect(target.querySelector('.types')).toBeNull();
+ expect(target.querySelector('.fields')).toBeNull();
+ });
+
+ it('counts the proofs, not whatever type the other branch was sitting on', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ press(target, 'My geolocations');
+ expect(flat(target)).toContain('12 rows, one per proof');
+ expect(flat(target)).toContain('its source media, its place and its coordinates');
+ });
+
+ it('names the sheet after the shape until the analyst says otherwise', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ press(target, 'My geolocations');
+ expect(target.querySelector('input.input').value).toBe('My geolocations');
+ });
+
+ it('says the case holds no proofs rather than offering an empty build', async () => {
+ get.mockImplementation((url) =>
+ url.endsWith('/catalog/summary')
+ ? Promise.resolve({ by_type: { person: 4 } })
+ : Promise.resolve(TYPES),
+ );
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ press(target, 'My geolocations');
+ expect(flat(target)).toContain('This case holds no proofs yet');
+ const build = [...target.querySelectorAll('button')].find((node) =>
+ node.textContent.includes('Build the sheet'),
+ );
+ expect(build.disabled).toBe(true);
+ });
+
+ it('carries the shape to the route that builds it', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ press(target, 'My geolocations');
+ press(target, 'Build the sheet');
+ expect(onmake).toHaveBeenCalledWith(
+ expect.objectContaining({ shape: 'proofs', title: 'My geolocations' }),
+ );
+ });
+
+ it('still sends the generic shape with its type and fields', async () => {
+ const target = open({ caseId: 'c1', onmake, onclose: vi.fn() });
+ await settle();
+ press(target, 'Build the sheet');
+ expect(onmake).toHaveBeenCalledWith(
+ expect.objectContaining({ shape: 'generic', type: 'proof' }),
+ );
+ });
+});
diff --git a/frontend/src/components/SheetGeocode.render.test.js b/frontend/src/components/SheetGeocode.render.test.js
new file mode 100644
index 0000000..21bbc13
--- /dev/null
+++ b/frontend/src/components/SheetGeocode.render.test.js
@@ -0,0 +1,138 @@
+// @vitest-environment happy-dom
+/**
+ * The two halves of a place column, actually mounted.
+ *
+ * The bug this exists to keep fixed was reported as "it is so slow it is useless": a column
+ * whose cells already point at placed entities sent every one of them to Nominatim, one a
+ * second, and came back with nothing — `3rd Bde` is not a toponym. What the case answers is
+ * exact, offline and instant, so it has to be asked first, and the geocoder has to be left
+ * out of it entirely for those rows.
+ *
+ * The lib suite next door reads the rules; this one drives the dialog, because "the pass
+ * proposed a write without any lookup" is a claim about the screen.
+ */
+import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+const post = vi.fn();
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+
+const { default: SheetGeocode } = await import('./SheetGeocode.svelte');
+
+const TABLE = {
+ columns: ['id', 'Subject', 'Coordinates'],
+ rows: [
+ ['r1', '3rd Bde', ''],
+ ['r2', 'Kherson, Ukraine', ''],
+ ],
+};
+const META = { links: { r1: { Subject: 'e_brigade' } } };
+const WRITABLE = [
+ { name: 'Subject', index: 1 },
+ { name: 'Coordinates', index: 2 },
+];
+
+let live = null;
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SheetGeocode, {
+ target,
+ props: {
+ caseId: 'c1',
+ sheetId: 's1',
+ table: TABLE,
+ meta: META,
+ column: { name: 'Subject', index: 1 },
+ mode: 'forward',
+ rows: [0, 1],
+ writable: WRITABLE,
+ onedits: vi.fn(),
+ onclose: vi.fn(),
+ ...props,
+ },
+ });
+ flushSync();
+ return target;
+}
+
+/** The dialog asks the case as it opens, so a test has to let that answer land: a macrotask
+ * drains the request's own microtasks, and the flush draws what it changed. */
+async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+}
+
+function buttons(target) {
+ return [...target.querySelectorAll('button')].map((node) => node.textContent.trim());
+}
+
+beforeEach(() => {
+ get.mockReset();
+ post.mockReset();
+ post.mockResolvedValue({ points: { e_brigade: { lat: 48.85, lon: 2.35 } } });
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('a forward pass over a column the case partly answers', () => {
+ it('asks the case as it opens, and only about the entities the cells point at', async () => {
+ open();
+ await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/c1/sheets/s1/points', { ids: ['e_brigade'] });
+ });
+
+ it('offers the linked row as a write with no lookup run at all', async () => {
+ const target = open();
+ await settle();
+ // The point the case holds, in the app's own spelling, proposed and not applied.
+ expect(target.textContent).toContain('1 row is answered by the case itself');
+ expect(buttons(target)).toContain('Write 1 cell');
+ expect(get).not.toHaveBeenCalled();
+ });
+
+ it('leaves the unlinked row to the geocoder, and says how many that is', async () => {
+ const target = open();
+ await settle();
+ expect(target.textContent).toContain('1 distinct name left to look up');
+ expect(buttons(target)).toContain('Look up 1');
+ });
+
+ it('writes the case answer into the target column when the write is pressed', async () => {
+ const onedits = vi.fn();
+ const target = open({ onedits });
+ await settle();
+ target.querySelectorAll('button').forEach((node) => {
+ if (node.textContent.trim() === 'Write 1 cell') node.click();
+ });
+ flushSync();
+ expect(onedits).toHaveBeenCalledWith(
+ [{ row: 0, column: 2, before: '', after: '48.85000, 2.35000' }],
+ '1 cell written.',
+ );
+ });
+
+ it('offers no lookup at all when the case covers the whole column', async () => {
+ const target = open({
+ table: { columns: TABLE.columns, rows: [TABLE.rows[0]] },
+ rows: [0],
+ });
+ await settle();
+ expect(buttons(target)).toContain('Write 1 cell');
+ expect(buttons(target).some((label) => label.startsWith('Look up'))).toBe(false);
+ });
+
+ it('falls back to the geocoder for every row when the case cannot answer', async () => {
+ post.mockResolvedValue({ points: {} });
+ const target = open();
+ await settle();
+ expect(target.textContent).not.toContain('answered by the case');
+ expect(buttons(target)).toContain('Look up 2');
+ });
+});
diff --git a/frontend/src/components/SheetGeocode.svelte b/frontend/src/components/SheetGeocode.svelte
new file mode 100644
index 0000000..4be1cd6
--- /dev/null
+++ b/frontend/src/components/SheetGeocode.svelte
@@ -0,0 +1,310 @@
+<script>
+ /**
+ * A column of place names read into coordinates, or a column of coordinates read into
+ * place names.
+ *
+ * Both directions were already in this app — the map searches, the media library backfills
+ * countries — and the sheet, which is where a geolocation index is actually worked, could
+ * reach neither. So four hundred rows of `Kherson, Ukraine` were typed in by hand.
+ *
+ * The screen is built around the two rules this has to keep:
+ *
+ * - **Nothing is applied on its own.** The pass looks the values up, shows what it found,
+ * and writes only on the second press. A geocoder's first hit is a guess, and a guess
+ * written unattended into a column of evidence is indistinguishable from a coordinate
+ * somebody read off a photograph.
+ * - **Only the empty cells.** A row that already holds an answer is never asked about,
+ * which is stated on screen rather than assumed.
+ *
+ * It reads the rows **on screen**, filter and all, like the cleaning passes. Nominatim is
+ * paced at about one request a second on the server, so the lookups run one at a time with
+ * a count and a Stop — a progress bar here is not decoration, it is the honest shape of
+ * the thing.
+ *
+ * A forward pass has **two halves**, and the first one is free: the rows whose cell already
+ * points at an entity the case has placed are answered off the graph, exactly and at once.
+ * Only the words left over are worth a stranger's server. Before that split, a column of
+ * linked subjects spent forty seconds being told nothing, because `3rd Bde` is not a
+ * toponym and Nominatim was the wrong thing to ask.
+ */
+ import { untrack } from 'svelte';
+ import Icon from './Icon.svelte';
+ import { ID_COLUMN } from '../lib/sheet.js';
+ import {
+ MAX_CASE_POINTS,
+ MAX_LOOKUPS,
+ casePoints,
+ geocodeValue,
+ linkedRows,
+ namesToRead,
+ placeCell,
+ pointCell,
+ pointsToRead,
+ reverseValue,
+ } from '../lib/sheetGeo.js';
+
+ let {
+ caseId,
+ sheetId,
+ table,
+ meta,
+ column,
+ mode = 'forward',
+ rows = [],
+ writable = [],
+ onedits,
+ onclose,
+ } = $props();
+
+ const forward = $derived(mode === 'forward');
+ /** Where the answers go. Never the column being read, and never the row's handle. */
+ const targets = $derived(
+ (writable ?? []).filter(
+ (entry) => entry.index !== column.index && String(entry.name).toLowerCase() !== ID_COLUMN,
+ ),
+ );
+
+ let targetName = $state('');
+ let looking = $state(false);
+ let stopped = $state(false);
+ let done = $state(0);
+ /** What was found, as `{ label, cell, rows }` — one entry per lookup, so the analyst reads
+ * the answers rather than a number claiming there were some. */
+ let found = $state([]);
+ let missed = $state([]);
+
+ const targetIndex = $derived((table?.columns ?? []).indexOf(targetName));
+
+ /** The rows the case may answer, read without regard to the target column so the graph is
+ * asked once for the dialog rather than once per column considered. */
+ const linkable = $derived(forward ? linkedRows(table, meta, column.index, -1, rows) : []);
+ /** What the graph answered, `{ id: { lat, lon } }`. Empty until it has, and empty for good
+ * if it could not: the geocoder then covers the column exactly as it used to. */
+ let points = $state({});
+
+ // Asked once as the screen opens, and untracked: the links are what they are for as long
+ // as this dialog is up, so re-asking would be the same question put again on every colour
+ // or filter the grid behind it writes into the sidecar.
+ $effect(() => {
+ untrack(() => ask());
+ });
+
+ async function ask() {
+ const ids = linkable.map((entry) => entry.id);
+ if (ids.length) points = await casePoints(caseId, sheetId, ids);
+ }
+
+ /** The rows written straight from the case: a link, a point behind it, and an empty cell
+ * to put it in. An entity the case places two ways answers nothing and stays here. */
+ const fromCase = $derived(
+ linkable
+ .filter(
+ (entry) =>
+ targetIndex !== -1 && !String(table.rows[entry.row]?.[targetIndex] ?? '').trim(),
+ )
+ .map((entry) => ({ ...entry, cell: pointCell(points[entry.id]) }))
+ .filter((entry) => entry.cell),
+ );
+ const answered = $derived(new Set(fromCase.map((entry) => entry.row)));
+ const work = $derived(
+ forward
+ ? namesToRead(
+ table,
+ column.index,
+ targetIndex,
+ (rows ?? []).filter((index) => !answered.has(index)),
+ )
+ : pointsToRead(table, column.index, targetIndex, rows),
+ );
+ const capped = $derived(work.length > MAX_LOOKUPS);
+ const batch = $derived(work.slice(0, MAX_LOOKUPS));
+ /** Whether a lookup has run, so the buttons say "look" once and "look again" after. */
+ const lookedUp = $derived(done > 0 || found.length > 0 || missed.length > 0);
+ const writes = $derived([
+ ...fromCase.map((entry) => ({
+ row: entry.row,
+ column: targetIndex,
+ before: table.rows[entry.row]?.[targetIndex] ?? '',
+ after: entry.cell,
+ })),
+ ...found.flatMap((entry) =>
+ entry.rows.map((row) => ({
+ row,
+ column: targetIndex,
+ before: table.rows[row]?.[targetIndex] ?? '',
+ after: entry.cell,
+ })),
+ ),
+ ]);
+
+ // Seeded once there is something to choose, and only then: a column picked before the
+ // dialog knows the sheet's headings would be a blank select.
+ $effect(() => {
+ if (!targetName && targets.length) targetName = targets[0].name;
+ });
+
+ async function look() {
+ if (!batch.length || looking || targetIndex === -1) return;
+ looking = true;
+ stopped = false;
+ done = 0;
+ found = [];
+ missed = [];
+ for (const entry of batch) {
+ if (stopped) break;
+ const answer = forward
+ ? await geocodeValue(entry.value)
+ : await reverseValue(entry.point.lat, entry.point.lon);
+ const cell = forward ? pointCell(answer) : placeCell(answer);
+ if (cell) {
+ found = [
+ ...found,
+ {
+ label: forward ? entry.value : `${entry.point.lat}, ${entry.point.lon}`,
+ says: forward ? (answer?.display_name ?? '') : cell,
+ cell,
+ rows: forward ? entry.rows : [entry.row],
+ },
+ ];
+ } else {
+ missed = [...missed, forward ? entry.value : `${entry.point.lat}, ${entry.point.lon}`];
+ }
+ done += 1;
+ }
+ looking = false;
+ }
+</script>
+
+<div class="geo">
+ <p class="lead">
+ {#if forward}
+ Every place name in <em>{column.name}</em> is read into the column you choose: from the
+ case where the cell points at something it has placed, from the geocoder for the rest.
+ Rows that already hold coordinates are left alone.
+ {:else}
+ Every point in <em>{column.name}</em> is looked up, and the place name lands in the
+ column you choose. Rows that already hold one are left alone.
+ {/if}
+ </p>
+
+ {#if !targets.length}
+ <p class="note">This sheet has no other column to write into. Add one first.</p>
+ {:else}
+ <label class="row">
+ <span>Write the {forward ? 'coordinates' : 'place name'} into</span>
+ <select class="input" value={targetName} aria-label="Where the answers go"
+ onchange={(event) => (targetName = event.currentTarget.value)}>
+ {#each targets as entry (entry.name)}<option value={entry.name}>{entry.name}</option>{/each}
+ </select>
+ </label>
+
+ {#if forward && fromCase.length}
+ <p class="note">
+ <Icon name="pin" size={11} />
+ <strong>{fromCase.length}</strong>
+ {fromCase.length === 1 ? 'row is' : 'rows are'} answered by the case itself, from the
+ entity the cell points at. No lookup for those.
+ {#if linkable.length === MAX_CASE_POINTS}
+ Only the first {MAX_CASE_POINTS} linked rows are read; run it again for the rest.
+ {/if}
+ </p>
+ {/if}
+ <p class="note">
+ <strong>{work.length}</strong>
+ {#if forward}
+ distinct {work.length === 1 ? 'name' : 'names'} left to look up, over
+ {work.reduce((count, entry) => count + entry.rows.length, 0)} rows on screen.
+ {:else}
+ {work.length === 1 ? 'point' : 'points'} to look up, out of the rows on screen.
+ {/if}
+ {#if capped}Only the first {MAX_LOOKUPS} are asked for; run it again for the rest.{/if}
+ </p>
+ {#if work.length}
+ <p class="note">
+ <Icon name="globe" size={11} />
+ Uses OpenStreetMap's geocoder, about one lookup a second, so its servers see what is
+ looked for. Nothing is written until you press again.
+ </p>
+ {/if}
+
+ {#if looking || found.length || missed.length}
+ <div class="progress">
+ <span>{done} of {batch.length} looked up</span>
+ {#if looking}
+ <button class="btn btn-sm" onclick={() => (stopped = true)}>Stop</button>
+ {/if}
+ </div>
+ <div class="found">
+ {#each found as entry (entry.label)}
+ <p class="hit">
+ <span class="from" title={entry.label}>{entry.label}</span>
+ <Icon name="arrowRight" size={10} />
+ <b>{entry.cell}</b>
+ <small title={entry.says}>{entry.says}</small>
+ <em>{entry.rows.length} {entry.rows.length === 1 ? 'row' : 'rows'}</em>
+ </p>
+ {/each}
+ {#each missed as value (value)}
+ <p class="hit bad">
+ <span class="from" title={value}>{value}</span>
+ <small>nothing came back</small>
+ </p>
+ {/each}
+ </div>
+ {/if}
+ {/if}
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <!-- The two halves are two presses, because they cost different things: the case answers
+ for nothing, the geocoder for a second a name. A column the case covers entirely
+ never offers a lookup at all. -->
+ {#if batch.length && targetIndex !== -1}
+ <button class="btn" class:btn-primary={!writes.length} disabled={looking} onclick={look}>
+ {looking ? 'Looking up' : lookedUp ? 'Look again' : `Look up ${batch.length}`}
+ </button>
+ {/if}
+ {#if writes.length}
+ <button class="btn btn-primary" disabled={looking}
+ onclick={() => onedits(writes, `${writes.length} ${writes.length === 1 ? 'cell' : 'cells'} written.`)}>
+ Write {writes.length} {writes.length === 1 ? 'cell' : 'cells'}
+ </button>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .geo { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .row {
+ display: grid; grid-template-columns: minmax(0, 1fr) 190px; align-items: center;
+ gap: 8px; padding: 10px 0 4px;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .note {
+ display: flex; align-items: center; gap: 5px; flex-wrap: wrap;
+ color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 4px 0;
+ }
+ .note strong { color: var(--text-1); }
+ .progress {
+ display: flex; align-items: center; gap: 8px; margin-top: 10px;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .found {
+ max-height: 240px; overflow: auto; margin-top: 6px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .hit {
+ display: flex; align-items: center; gap: 7px; padding: 4px 7px;
+ border-bottom: 1px solid var(--border); font-size: var(--fs-xs);
+ }
+ .hit:last-child { border-bottom: 0; }
+ .hit .from { flex: none; width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-2); }
+ .hit b { flex: none; color: var(--text-1); font-family: var(--font-mono); }
+ .hit small { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-3); }
+ .hit em { flex: none; color: var(--text-3); font-style: normal; }
+ .hit.bad small { color: var(--anno-6); }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetHeadingMenu.svelte b/frontend/src/components/SheetHeadingMenu.svelte
new file mode 100644
index 0000000..819c40d
--- /dev/null
+++ b/frontend/src/components/SheetHeadingMenu.svelte
@@ -0,0 +1,175 @@
+<script>
+ /**
+ * What a heading can do, in one press.
+ *
+ * A heading used to have two doors: the funnel, which asks something of the column, and
+ * a `...` that opened the **setup panel** — a name, a role with its vocabulary, a note
+ * and seven actions, 340 pixels of grid gone. That was right for declaring what a column
+ * *is* and wrong for everything an analyst does to a column all day: insert one beside
+ * it, copy it, sort it, split it, rename it. Those had either no door at all or the wrong
+ * one, and nothing on the heading said so.
+ *
+ * So this is the third door and it is the one that opens first. A short list of the
+ * frequent gestures, reachable two ways — the `...`, and a **right-click anywhere on the
+ * heading**, which is what anyone who has used a spreadsheet tries before reading any
+ * label. The rare half is still in the panel and this menu's last row is how you get
+ * there, so nothing was taken away.
+ *
+ * It owns no rules: every row is a call back up, and the grid decides what a split or a
+ * duplicate means to the table.
+ */
+ import Icon from './Icon.svelte';
+ import { ID_COLUMN } from '../lib/sheet.js';
+
+ let {
+ column,
+ meta = null,
+ at = { x: 0, y: 0 },
+ onsort,
+ onsecondsort,
+ onfilter,
+ oninsert,
+ onduplicate,
+ onrename,
+ onclean,
+ onsplit,
+ onfreeze,
+ onhide,
+ ondrop,
+ onsetup,
+ onclose,
+ } = $props();
+
+ const isKey = $derived(String(column?.name ?? '').toLowerCase() === ID_COLUMN);
+ const sort = $derived(meta?.sort?.column === column?.name ? meta.sort : null);
+ const frozen = $derived(meta?.frozen === column?.name);
+ /** The column the sheet is sorted on, when it is another one: only then is "break its
+ * ties with this" a question, since a column cannot break its own. */
+ const first = $derived(
+ meta?.sort?.column && meta.sort.column !== column?.name ? meta.sort.column : null,
+ );
+ const second = $derived(meta?.sort?.then?.column === column?.name ? meta.sort.then : null);
+
+ /** Kept on screen where a column near an edge would put it off. Read once as the menu
+ * opens, like the filter menu's: the grid scrolling under it closes it. */
+ const WIDTH = 250;
+ const HEIGHT = 420;
+ const left = $derived(
+ typeof window === 'undefined' ? at.x : Math.max(8, Math.min(at.x, window.innerWidth - WIDTH - 8)),
+ );
+ const top = $derived(
+ typeof window === 'undefined' ? at.y : Math.max(8, Math.min(at.y, window.innerHeight - HEIGHT)),
+ );
+
+ /**
+ * Every row acts, then closes.
+ *
+ * That order matters and it cost a bug: closing first clears the state the menu was
+ * opened *about*, and the handlers read the column out of it — so an action fired after
+ * the close was an action on nothing. The menu still never stays open over the change it
+ * made, which is the point of closing at all.
+ */
+ function run(action, ...args) {
+ action?.(...args);
+ onclose();
+ }
+</script>
+
+<div class="heading-menu" style="left: {left}px; top: {top}px; width: {WIDTH}px"
+ role="menu" aria-label="What to do with {column.name}">
+ <p class="head">{column.name}</p>
+
+ {#if isKey}
+ <p class="note">The row's handle. It is never renamed, moved or rewritten.</p>
+ <button class="row" role="menuitem" onclick={() => run(onsetup)}>
+ <Icon name="sliders" size={12} /><span>Set up this column…</span>
+ </button>
+ {:else}
+ <button class="row" class:on={sort && !sort.desc} role="menuitem"
+ onclick={() => run(onsort, false)}>
+ <Icon name="chevronUp" size={12} /><span>Sort A → Z</span>
+ </button>
+ <button class="row" class:on={sort?.desc} role="menuitem" onclick={() => run(onsort, true)}>
+ <Icon name="chevronDown" size={12} /><span>Sort Z → A</span>
+ </button>
+ {#if first}
+ <!-- "By status, then by date" is how a worklist is read, and one key meant
+ re-sorting by hand every time the first one tied. Not a fourth state on the
+ heading's own click: "sort by this" and "sort by this too" one gesture apart
+ would be a trap. -->
+ <button class="row" class:on={Boolean(second)} role="menuitem"
+ onclick={() => run(onsecondsort)}>
+ <Icon name="layers" size={12} />
+ <span>
+ {second
+ ? `Then by this, ${second.desc ? 'Z → A' : 'A → Z'}`
+ : `Sort by “${first}”, then by this`}
+ </span>
+ </button>
+ {/if}
+ <button class="row" role="menuitem" onclick={() => run(onfilter)}>
+ <Icon name="filter" size={12} /><span>Filter…</span>
+ </button>
+
+ <div class="rule"></div>
+ <button class="row" role="menuitem" onclick={() => run(oninsert, 'left')}>
+ <Icon name="chevronLeft" size={12} /><span>Insert a column left</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(oninsert, 'right')}>
+ <Icon name="chevronRight" size={12} /><span>Insert a column right</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onduplicate)}>
+ <Icon name="copy" size={12} /><span>Duplicate this column</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onrename)}>
+ <Icon name="edit" size={12} /><span>Rename</span>
+ </button>
+
+ <div class="rule"></div>
+ <button class="row" role="menuitem" onclick={() => run(onclean)}>
+ <Icon name="wand" size={12} /><span>Find and replace…</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onsplit)}>
+ <Icon name="layers" size={12} /><span>Split, merge or tidy…</span>
+ </button>
+
+ <div class="rule"></div>
+ <button class="row" class:on={frozen} role="menuitem" onclick={() => run(onfreeze)}>
+ <Icon name="pushpin" size={12} />
+ <span>{frozen ? 'Let it scroll' : 'Keep it in view'}</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onhide)}>
+ <Icon name="eyeOff" size={12} /><span>Hide</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onsetup)}>
+ <Icon name="sliders" size={12} /><span>Set up this column…</span>
+ </button>
+ <button class="row danger" role="menuitem" onclick={() => run(ondrop)}>
+ <Icon name="trash" size={12} /><span>Delete this column</span>
+ </button>
+ {/if}
+</div>
+
+<style>
+ .heading-menu {
+ position: fixed; z-index: 21;
+ display: flex; flex-direction: column; gap: 1px;
+ max-height: min(420px, calc(100vh - 24px)); overflow: auto;
+ padding: 5px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ .head {
+ padding: 3px 7px 5px; color: var(--text-3); font-size: var(--fs-xs);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .row {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .row:hover { background: var(--bg-2); color: var(--text-1); }
+ .row.on { color: var(--accent); }
+ .row.danger:hover { background: var(--danger-soft); color: var(--danger); }
+ .row span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .rule { height: 1px; margin: 4px 2px; background: var(--border); }
+ .note { padding: 4px 7px 6px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+</style>
diff --git a/frontend/src/components/SheetHelp.svelte b/frontend/src/components/SheetHelp.svelte
new file mode 100644
index 0000000..e9dbd90
--- /dev/null
+++ b/frontend/src/components/SheetHelp.svelte
@@ -0,0 +1,104 @@
+<script>
+ /**
+ * What the grid can do, said once, where it can be found.
+ *
+ * The tool grew three doors on a heading, a menu in the gutter, a menu on a cell, a
+ * dozen keys and six cleaning passes, and **announced none of them**. Every one of those
+ * was the right call on its own — a spreadsheet keeps its power under a right-click too —
+ * but a right-click nobody tries is a feature nobody has. The measured outcome of that
+ * silence is an analyst concluding the grid cannot filter.
+ *
+ * So: one list, opened with `?`, that names the gestures rather than describing the
+ * screen. It is deliberately not a tour and it blocks nothing; there is no "next".
+ *
+ * It holds no logic and no state — if a row here goes out of date, the row is wrong,
+ * which is the honest failure mode for a legend.
+ */
+ import Icon from './Icon.svelte';
+
+ let { onclose } = $props();
+
+ const KEYS = [
+ ['Enter', 'Edit the cell, and commit and step down'],
+ ['Tab / Shift+Tab', 'Commit and step across; on the last cell, a new row'],
+ ['Any character', 'Start editing on that character'],
+ ['Arrows', 'Walk the cursor, Shift to pull a selection'],
+ ['Home / End', 'The first and last column of the row'],
+ ['PageUp / PageDown', 'A screenful of rows'],
+ ['Ctrl+A', 'Select every row on screen'],
+ ['Escape', 'Close what is open, then let go of the cell'],
+ ['Ctrl+C / Ctrl+V', 'Copy the rectangle, paste a block from the cursor'],
+ ['Ctrl+D', 'Copy the top of the selection down'],
+ ['Delete', 'Empty the selected cells'],
+ ['Ctrl+Z / Ctrl+Shift+Z', 'Undo, redo'],
+ ['Ctrl+Enter', 'Add a row'],
+ ['Ctrl+F', 'Reach the search'],
+ ['Ctrl+S', 'Save now instead of waiting for the autosave'],
+ ['?', 'This list'],
+ ];
+
+ const GESTURES = [
+ ['Right-click a heading', 'Sort, filter, insert, duplicate, rename, split, hide, delete'],
+ ['Right-click a cell', 'Keep only this value'],
+ ['Right-click the gutter', 'Insert, duplicate, paint, merge, pin, delete a row'],
+ ['Double-click a heading', 'Rename it in place'],
+ ['Drag a heading', 'Move the column, in the file'],
+ ['Drag its right edge', 'Resize it'],
+ ['Press and pull over cells', 'Select a rectangle; Shift-click a far corner does the same'],
+ ['Shift-click in the gutter', 'Tick every row between'],
+ ['Click a chip in a cell', 'Filter on that value; on a yes/no column, flip it'],
+ ['Drop a CSV on the grid', 'File it as a new sheet'],
+ ['Drop an image on a row', 'Bring it into the case and cite it in that cell'],
+ ['The last, empty row', 'Type in it and the row exists'],
+ ['The bar above the headings', 'The cell under the cursor, written full width'],
+ ];
+</script>
+
+<div class="help">
+ <p class="lead">
+ The grid keeps its gestures where a spreadsheet keeps them.
+ </p>
+ <div class="two">
+ <section>
+ <p class="what">Keys</p>
+ {#each KEYS as [key, what] (key)}
+ <p class="line"><kbd>{key}</kbd><span>{what}</span></p>
+ {/each}
+ </section>
+ <section>
+ <p class="what">Pointer</p>
+ {#each GESTURES as [gesture, what] (gesture)}
+ <p class="line"><b>{gesture}</b><span>{what}</span></p>
+ {/each}
+ </section>
+ </div>
+ <p class="foot">
+ <Icon name="info" size={12} />
+ The sheet is the CSV in the case folder, and it autosaves. A save that would overwrite a
+ change made outside the app is refused.
+ </p>
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn btn-primary" onclick={onclose}>Got it</button>
+ </div>
+</div>
+
+<style>
+ .help { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .two { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin-top: 12px; }
+ @media (max-width: 700px) { .two { grid-template-columns: 1fr; } }
+ .what { color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 6px; }
+ .line { display: flex; align-items: baseline; gap: 8px; padding: 2px 0; font-size: var(--fs-xs); }
+ .line kbd {
+ flex: none; min-width: 132px; color: var(--text-1); font-family: var(--font-mono);
+ }
+ .line b { flex: none; min-width: 132px; color: var(--text-1); font-weight: 500; }
+ .line span { color: var(--text-3); line-height: 1.5; }
+ .foot {
+ display: flex; align-items: center; gap: 6px; margin-top: 14px; padding-top: 10px;
+ border-top: 1px solid var(--border); color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetLegend.svelte b/frontend/src/components/SheetLegend.svelte
new file mode 100644
index 0000000..d1eaa08
--- /dev/null
+++ b/frontend/src/components/SheetLegend.svelte
@@ -0,0 +1,56 @@
+<script>
+ /**
+ * What each row colour means in this sheet.
+ *
+ * Six colours and no legend is six colours whose meaning lives in one analyst's head:
+ * yellow was "check the timestamp again" on Monday and "asked the source" by Thursday, and
+ * a case is handed over. The colours were the one annotation in the grid that said nothing
+ * about itself.
+ *
+ * Only the colours actually used are worth naming, so the ones in the sheet come first and
+ * carry their count; the rest are there to be started. Kept in the sidecar beside the
+ * colours themselves — losing both together costs presentation and never a finding, which
+ * is the deal the sidecar is under.
+ */
+ import { ROW_COLOURS } from '../lib/sheet.js';
+
+ let { meta, counts = {}, onlabel } = $props();
+
+ const rows = $derived(
+ [...ROW_COLOURS].sort((a, b) => (counts[b] ?? 0) - (counts[a] ?? 0)),
+ );
+</script>
+
+<div class="legend-menu">
+ <p class="head">What the colours mean</p>
+ {#each rows as colour (colour)}
+ <div class="line">
+ <span class="swatch c-{colour}"></span>
+ <input class="input" value={meta?.legend?.[colour] ?? ''}
+ placeholder={counts[colour] ? 'what it marks' : 'unused'}
+ aria-label="What {colour} means"
+ onkeydown={(event) => event.key === 'Enter' && event.currentTarget.blur()}
+ onblur={(event) => onlabel(colour, event.currentTarget.value)} />
+ <small>{counts[colour] ?? 0}</small>
+ </div>
+ {/each}
+ <p class="note">Saved next to the sheet, not in the CSV.</p>
+</div>
+
+<style>
+ .legend-menu {
+ position: absolute; z-index: 8; top: calc(100% + 4px); right: 0; width: 300px;
+ padding: 7px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0004;
+ }
+ .head { padding: 1px 3px 6px; color: var(--text-3); font-size: var(--fs-xs); }
+ .line { display: flex; align-items: center; gap: 7px; padding: 2px 0; }
+ /* The same swatch the bar and the gutter menu draw. `.c-*` is global and sets `--mark`. */
+ .swatch {
+ flex: none; width: 14px; height: 14px; border-radius: var(--r-sm);
+ border: 1px solid var(--border-strong); background: var(--mark, var(--bg-3));
+ }
+ .line .input { flex: 1; min-width: 0; font-size: var(--fs-xs); padding: 2px 6px; }
+ .line small { flex: none; width: 26px; text-align: right; color: var(--text-3); font-size: var(--fs-xs); }
+ .note { padding: 7px 3px 1px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+</style>
diff --git a/frontend/src/components/SheetMove.render.test.js b/frontend/src/components/SheetMove.render.test.js
new file mode 100644
index 0000000..36cd167
--- /dev/null
+++ b/frontend/src/components/SheetMove.render.test.js
@@ -0,0 +1,172 @@
+// @vitest-environment happy-dom
+/**
+ * The two screens a row crosses on its way to another sheet, actually mounted.
+ *
+ * Both exist because the one-press version was a trap. The lot is whatever the grid was
+ * holding — and a drag down a column is forty rows nobody counted — so the first screen
+ * **lists them and lets them be taken back out**. The columns were matched on their names
+ * alone, so a heading spelled differently at the other end was a loss the analyst read
+ * about in the toast, after the rows had left; so the second screen **lines them up** and
+ * says what stays behind before there is a button to press.
+ *
+ * What these drive is the half a lib suite cannot: that the press is only reachable
+ * through the screen that said what it would do.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: SheetMove } = await import('./SheetMove.svelte');
+
+const SHEETS = [
+ { id: 's1', title: 'Inbox', rows: 40, columns: 4, headings: ['id', 'Adresse', 'Statut', 'Note'] },
+ { id: 's2', title: 'Worklist', rows: 3, columns: 3, headings: ['id', 'Adresse', 'note'] },
+];
+const ROWS = [
+ { key: 'r1', label: 'Quai sud', colour: 'green' },
+ { key: 'r2', label: 'Pont nord', colour: null },
+];
+
+let live = null;
+const onmove = vi.fn();
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SheetMove, {
+ target,
+ props: {
+ sheets: SHEETS,
+ sheetId: 's1',
+ columns: ['id', 'Adresse', 'Statut', 'Note'],
+ rows: ROWS,
+ scope: 'selected',
+ onmove,
+ onclose: vi.fn(),
+ ...props,
+ },
+ });
+ flushSync();
+ return target;
+}
+
+const press = (target, text) => {
+ const found = [...target.querySelectorAll('button')].find((node) =>
+ node.textContent.trim().startsWith(text),
+ );
+ found.click();
+ flushSync();
+};
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ onmove.mockReset();
+ document.body.innerHTML = '';
+});
+
+describe('the rows a move is about to take', () => {
+ it('says which of the two selections it is holding', () => {
+ // "40 rows" that turn out to be the wrong forty is the one thing this must not do.
+ expect(open().textContent).toContain('2 selected rows');
+ unmount(live);
+ live = null;
+ expect(open({ scope: 'ticked' }).textContent).toContain('2 ticked rows');
+ });
+
+ it('lists them, and a row taken back out stops counting', () => {
+ const target = open();
+ press(target, 'Review');
+
+ const boxes = [...target.querySelectorAll('input[type="checkbox"]')];
+ expect(target.textContent).toContain('Quai sud');
+ expect(boxes).toHaveLength(2);
+
+ boxes[1].click();
+ flushSync();
+ expect(target.textContent).toContain('1 selected row');
+ expect(target.textContent).toContain('1 kept back');
+ });
+
+ it('offers no press until the second screen has been read', () => {
+ const target = open();
+ const labels = [...target.querySelectorAll('button')].map((node) => node.textContent.trim());
+
+ expect(labels).toContain('Next');
+ expect(labels.some((label) => label.startsWith('Move'))).toBe(false);
+ });
+
+ it('has nothing to offer when the case holds one sheet', () => {
+ const target = open({ sheets: [SHEETS[0]] });
+
+ expect(target.textContent).toContain('no other sheet');
+ expect([...target.querySelectorAll('select')]).toHaveLength(0);
+ });
+});
+
+describe('lining the columns up', () => {
+ function second(props = {}) {
+ const target = open(props);
+ press(target, 'Next');
+ return target;
+ }
+
+ it('proposes the exact name, guesses the one spelled differently, and says which', () => {
+ const target = second();
+ const [adresse, statut, note] = [...target.querySelectorAll('select')];
+
+ expect(adresse.value).toBe('Adresse');
+ expect(statut.value).toBe(''); // that sheet has nothing for it
+ expect(note.value).toBe('note');
+ expect(target.textContent).toContain('guessed');
+ expect(target.textContent).toContain('2 columns move, 1 stays behind');
+ });
+
+ it('hands back what was pointed where, and only the rows still in the lot', () => {
+ const target = second();
+ press(target, 'Move 2 rows');
+
+ expect(onmove).toHaveBeenCalledWith('s2', ['r1', 'r2'], { Adresse: 'Adresse', Note: 'note' });
+ });
+
+ it('lets a column be pointed somewhere else, and frees the one it left', () => {
+ const target = second();
+ const [adresse, statut] = [...target.querySelectorAll('select')];
+
+ // Two columns cannot both land in `Adresse`: the first one lets go of it.
+ statut.value = 'Adresse';
+ statut.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ expect(adresse.value).toBe('');
+
+ press(target, 'Move 2 rows');
+ expect(onmove).toHaveBeenCalledWith('s2', ['r1', 'r2'], { Statut: 'Adresse', Note: 'note' });
+ });
+
+ it('sends nothing for a column set back to “Don’t move”', () => {
+ const target = second();
+ const note = [...target.querySelectorAll('select')].at(-1);
+
+ note.value = '';
+ note.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ expect(target.textContent).toContain('1 column moves, 2 stay behind');
+ expect(target.textContent).toContain('Left empty over there: note');
+
+ press(target, 'Move 2 rows');
+ expect(onmove).toHaveBeenCalledWith('s2', ['r1', 'r2'], { Adresse: 'Adresse' });
+ });
+
+ it('goes back to the rows with the lot as it was left', () => {
+ const target = open();
+ press(target, 'Review');
+ target.querySelectorAll('input[type="checkbox"]')[0].click();
+ flushSync();
+ press(target, 'Next');
+ press(target, 'Back');
+
+ expect(target.textContent).toContain('1 selected row');
+ press(target, 'Next');
+ press(target, 'Move 1 row');
+ expect(onmove).toHaveBeenCalledWith('s2', ['r2'], { Adresse: 'Adresse', Note: 'note' });
+ });
+});
diff --git a/frontend/src/components/SheetMove.svelte b/frontend/src/components/SheetMove.svelte
new file mode 100644
index 0000000..c25cde9
--- /dev/null
+++ b/frontend/src/components/SheetMove.svelte
@@ -0,0 +1,241 @@
+<script>
+ /**
+ * Move the ticked rows into another sheet, in two screens.
+ *
+ * The gesture the binders' tabs were built out of. An inbox, a worklist and a reference
+ * table at **one schema**, and a row moves up a floor once it has been worked out: the
+ * link to sort, then the lead being checked, then the thing the case is sure of. Copying
+ * it by hand is what everybody does instead, and it loses the colour, the entity the
+ * cell points at and the record that the row was already promoted — which is exactly the
+ * state worth keeping.
+ *
+ * It used to be one press: pick a sheet, move, and read afterwards which columns had
+ * been dropped. Two things were wrong with that. The lot is whatever the grid was
+ * holding, and a drag down a column is a lot of rows nobody counted — so the rows are
+ * **listed and un-tickable here**. And the columns were matched on their names alone, so
+ * `Adresse` arriving at a sheet that calls it `Address` was a silent loss — so the
+ * second screen **lines them up** and says what stays behind before the press.
+ */
+ import Icon from './Icon.svelte';
+ import { ID_COLUMN, suggestMapping } from '../lib/sheet.js';
+
+ let {
+ sheets,
+ sheetId,
+ columns,
+ rows = [],
+ scope = 'ticked',
+ busy = false,
+ onmove,
+ onclose,
+ } = $props();
+
+ const others = $derived((sheets ?? []).filter((sheet) => sheet.id !== sheetId));
+ let to = $state('');
+ /** Which screen: the rows and where they go, then which column lands in which. */
+ let step = $state('where');
+ let reviewing = $state(false);
+ /** Rows the analyst took back out of the lot. Kept by key, so a re-sort cannot move it. */
+ let dropped = $state(new Set());
+ /** One line per column of this sheet, each pointed at one of theirs or at nothing. */
+ let pairs = $state([]);
+
+ $effect(() => {
+ if (!to && others.length) to = others[0].id;
+ });
+
+ const target = $derived(others.find((sheet) => sheet.id === to) ?? null);
+ const going = $derived(rows.filter((row) => !dropped.has(row.key)));
+ const mine = $derived(
+ (columns ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+ const theirs = $derived(
+ (target?.headings ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+ const moving = $derived(pairs.filter((pair) => pair.to));
+ /** Columns of theirs nothing is pointed at: the rows land with those cells empty. */
+ const empty = $derived(theirs.filter((name) => !moving.some((pair) => pair.to === name)));
+
+ function toggle(key) {
+ const next = new Set(dropped);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ dropped = next;
+ }
+
+ /** Onto the second screen, with the names lined up as far as they line up themselves. */
+ function next() {
+ if (!target || !going.length) return;
+ pairs = suggestMapping(mine, target.headings ?? []);
+ step = 'columns';
+ }
+
+ function point(name, at) {
+ pairs = pairs.map((pair) =>
+ pair.name === name
+ ? { ...pair, to: at, guessed: false }
+ : // One column of theirs holds one of ours: the second would overwrite the first,
+ // and the server refuses it anyway.
+ pair.to === at && at
+ ? { ...pair, to: '', guessed: false }
+ : pair,
+ );
+ }
+
+ function press() {
+ onmove(
+ to,
+ going.map((row) => row.key),
+ Object.fromEntries(moving.map((pair) => [pair.name, pair.to])),
+ );
+ }
+</script>
+
+<div class="move">
+ {#if !others.length}
+ <p class="hint">
+ <Icon name="table" size={12} />
+ This case holds no other sheet. Make one from this one's columns first.
+ </p>
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ </div>
+ {:else if step === 'where'}
+ <p class="lead">
+ <strong>{going.length}</strong> {scope} {going.length === 1 ? 'row' : 'rows'}, out of
+ this sheet and into another. Their colour, their links and what they had already
+ promoted travel with them.
+ </p>
+
+ <label class="row">
+ <span>Into</span>
+ <select class="input" value={to} aria-label="The sheet to move them into"
+ onchange={(event) => (to = event.currentTarget.value)}>
+ {#each others as sheet (sheet.id)}
+ <option value={sheet.id}>{sheet.title} · {sheet.rows} rows</option>
+ {/each}
+ </select>
+ </label>
+
+ <!-- The lot, said row by row. "Forty rows" that turn out to be the wrong forty is the
+ one thing this must not do, and the grid's selection is a drag away from being
+ every row on screen. -->
+ <button class="review" onclick={() => (reviewing = !reviewing)}>
+ <Icon name={reviewing ? 'chevronDown' : 'chevronRight'} size={12} />
+ {reviewing ? 'Hide the rows' : `Review the ${rows.length} ${rows.length === 1 ? 'row' : 'rows'}`}
+ {#if dropped.size}<span class="held">{dropped.size} kept back</span>{/if}
+ </button>
+ {#if reviewing}
+ <ul class="rows">
+ {#each rows as row (row.key)}
+ <li class:out={dropped.has(row.key)}>
+ <label>
+ <input type="checkbox" checked={!dropped.has(row.key)}
+ onchange={() => toggle(row.key)} />
+ <span class="dot c-{row.colour ?? 'none'}"></span>
+ <span class="what">{row.label || row.key}</span>
+ </label>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={!to || !going.length} onclick={next}>
+ Next
+ </button>
+ </div>
+ {:else}
+ <p class="lead">
+ <strong>{going.length}</strong> {going.length === 1 ? 'row' : 'rows'} into
+ <strong>{target?.title}</strong>. A column with nothing in front of it stays behind.
+ </p>
+
+ <ul class="pairs">
+ {#each pairs as pair (pair.name)}
+ <li>
+ <span class="mine">{pair.name}</span>
+ <Icon name="arrowRight" size={12} />
+ <select class="input" value={pair.to} aria-label="Where {pair.name} lands"
+ onchange={(event) => point(pair.name, event.currentTarget.value)}>
+ <option value="">Don't move</option>
+ {#each theirs as name (name)}
+ <option value={name}>{name}</option>
+ {/each}
+ </select>
+ <!-- Said out loud, because `Time` onto `Local time` is right about as often as
+ it is wrong and a guess that looks like a match is worse than none. -->
+ <span class="guess">{pair.guessed ? 'guessed' : ''}</span>
+ </li>
+ {/each}
+ </ul>
+
+ <p class="note">
+ {moving.length} {moving.length === 1 ? 'column moves' : 'columns move'}, {mine.length -
+ moving.length} {mine.length - moving.length === 1 ? 'stays' : 'stay'} behind.
+ {#if empty.length}Left empty over there: {empty.join(', ')}.{/if}
+ </p>
+
+ <div class="modal-row">
+ <button class="btn" onclick={() => (step = 'where')}>Back</button>
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button class="btn btn-primary" disabled={busy || !to || !going.length} onclick={press}>
+ {busy ? 'Moving' : `Move ${going.length} ${going.length === 1 ? 'row' : 'rows'}`}
+ </button>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .move { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .lead strong { color: var(--text-1); }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 8px 0 0; }
+ .hint {
+ display: flex; align-items: center; gap: 7px; padding: 14px 4px;
+ color: var(--text-3); font-size: var(--fs-sm); line-height: 1.5;
+ }
+ .row {
+ display: grid; grid-template-columns: minmax(0, 1fr) 190px; align-items: center;
+ gap: 8px; padding: 10px 0 3px;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .review {
+ display: flex; align-items: center; gap: 6px; margin-top: 10px; padding: 4px 0;
+ border: 0; background: transparent; color: var(--text-3);
+ font: inherit; font-size: var(--fs-xs); cursor: pointer;
+ }
+ .review:hover { color: var(--text-1); }
+ .held { color: var(--warn); }
+ .rows {
+ max-height: 210px; overflow-y: auto; margin: 4px 0 0; padding: 0; list-style: none;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .rows li { border-bottom: 1px solid var(--border); }
+ .rows li:last-child { border-bottom: 0; }
+ .rows label {
+ display: flex; align-items: center; gap: 8px; padding: 6px 10px;
+ font-size: var(--fs-sm); cursor: pointer;
+ }
+ .rows li.out .what { color: var(--text-3); text-decoration: line-through; }
+ .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--mark, transparent); }
+ .what { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .pairs {
+ max-height: 300px; overflow-y: auto; margin: 12px 0 0; padding: 0; list-style: none;
+ }
+ .pairs li {
+ display: grid; grid-template-columns: minmax(0, 1fr) 12px 190px 58px;
+ align-items: center; gap: 8px; padding: 4px 0;
+ }
+ .mine {
+ color: var(--text-1); font-size: var(--fs-sm);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .guess { color: var(--text-3); font-size: var(--fs-xs); }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+ .spacer { flex: 1; }
+</style>
diff --git a/frontend/src/components/SheetRoleEditor.svelte b/frontend/src/components/SheetRoleEditor.svelte
new file mode 100644
index 0000000..d9e8384
--- /dev/null
+++ b/frontend/src/components/SheetRoleEditor.svelte
@@ -0,0 +1,644 @@
+<script>
+ /**
+ * What one column of a sheet is, said in the analyst's words.
+ *
+ * A role is a **lens, never a validator**. Everything here reads cells and nothing
+ * rewrites them, because the file keeps the words and the sidecar keeps what the app
+ * knows about them. So a value outside a vocabulary is shown, a coordinate that says
+ * `To be found` stays as it is, and this panel reports how much of the column its lens
+ * can read rather than refusing the column that does not fit.
+ *
+ * The vocabulary is a **list of rows**, not a textarea. The textarea was smaller and it
+ * hid three things the analyst has to see: which colour a value carries (typed as
+ * `done #green`, which nothing on screen taught), how many rows actually hold it, and
+ * which words the cells use that the list has never heard of. What the textarea had
+ * going for it was that dragging a line reorders the column — the order *is* the
+ * ranking the sort reads — so that survives as two buttons per row.
+ *
+ * Its own component because the column panel is already the busiest control in the app.
+ */
+ import Icon from './Icon.svelte';
+ import { ID_COLUMN } from '../lib/sheet.js';
+ import {
+ BOOLEAN_DEFAULTS,
+ COUNTING_NATURES,
+ DEFAULT_SEPARATOR,
+ LINKED_NATURES,
+ MAX_COUNTED_COLUMNS,
+ NUMBER_SUMMARIES,
+ ROW_COLOURS,
+ STATE_COLOURS,
+ STATE_DEFAULTS,
+ WHEN_SHAPES,
+ detectRole,
+ editVocabulary,
+ normalizeRole,
+ parseLatLon,
+ readable,
+ sortVocabulary,
+ valueColour,
+ vocabularyUse,
+ whenShape,
+ } from '../lib/sheetRoles.js';
+
+ let { table, meta = null, column, role = null, onchange, onanchors = null } = $props();
+
+ /**
+ * The kinds, in **two families**, because they are two different promises.
+ *
+ * A lens changes how the grid reads a column the analyst writes: the file keeps the
+ * words either way, and clearing the lens loses nothing. The other two are columns the
+ * **app writes into the CSV** — a cell typed there is overwritten on the next save — and
+ * offering them in one flat row of ten chips said nothing about which half you were in.
+ */
+ const READINGS = [
+ { id: null, label: 'Text', hint: 'read as written' },
+ { id: 'state', label: 'State', hint: 'where the row got to' },
+ { id: 'choice', label: 'Values', hint: 'one chip per value' },
+ { id: 'boolean', label: 'Yes / no', hint: 'two words, one click to flip' },
+ { id: 'number', label: 'Number', hint: 'counted over the rows on screen' },
+ { id: 'latlon', label: 'Point', hint: 'lat, lon' },
+ { id: 'when', label: 'Date or time', hint: 'a date, a time, or both' },
+ { id: 'picture', label: 'Picture', hint: 'a case file or an address, drawn in the cell' },
+ { id: 'url', label: 'Source', hint: 'the pages the rows rest on' },
+ { id: 'row', label: 'Another row', hint: 'names other rows of this sheet' },
+ { id: 'offset', label: 'Offset', hint: 'a time either side of a shared sync point' },
+ ];
+ const WRITTEN = [
+ { id: 'stamped', label: 'Added on', hint: 'the app dates every empty cell here' },
+ { id: 'computed', label: 'Answered by the app', hint: 'on the map, or a count over other columns' },
+ { id: 'locked', label: 'Held by the case', hint: 'the app writes it and keeps it level with the case' },
+ ];
+ const KINDS = [...READINGS, ...WRITTEN];
+
+ /** What a computed column can answer. The first needs the graph; the other two are
+ * arithmetic over the row's own cells, which is the one number a comparison grid needs
+ * and the only kind of formula this tool has. */
+ const NATURES = [
+ { id: 'has_point', label: 'On the map', hint: 'YES when what the row points at has a place' },
+ { id: 'filled_of', label: 'How complete', hint: 'how many of the chosen columns are answered' },
+ { id: 'yes_of', label: 'Score', hint: 'how many of the chosen columns say yes' },
+ { id: 'point', label: 'Its point', hint: 'where the case puts what a column points at' },
+ { id: 'relations', label: 'What it is joined to', hint: 'the far end of that entity\'s edges' },
+ { id: 'in_case', label: 'Still in the case', hint: 'NO once what the row was built from is deleted' },
+ ];
+
+ const SUMMARY_WORDS = {
+ none: 'Nothing',
+ count: 'How many',
+ sum: 'Total',
+ mean: 'Average',
+ range: 'Lowest to highest',
+ };
+
+ const cells = $derived(
+ (table?.rows ?? []).map((row) => String(row[column.index] ?? '').trim()).filter(Boolean),
+ );
+ const suggestion = $derived(detectRole(cells));
+ const kind = $derived(role?.kind ?? null);
+ const chipped = $derived(kind === 'state' || kind === 'choice' || kind === 'boolean');
+
+ /** How much of the column the chosen lens can actually read. The same rule the filter
+ * menus follow — say how big an answer is before it is acted on — applied to a role:
+ * sending a date column to the Timeline when it can read a third of it is worth
+ * knowing before, not after. */
+ const reads = $derived(
+ role && !['stamped', 'computed', 'locked'].includes(kind)
+ ? readable(table, column.index, role)
+ : null,
+ );
+
+ /** What the vocabulary is worth against the cells: a count per value, the values
+ * nothing uses, and the words the column holds that the list has never heard of. */
+ const use = $derived(chipped ? vocabularyUse(table, column.index, role) : null);
+
+ const dubious = $derived.by(() => {
+ if (kind !== 'latlon') return null;
+ let coarse = 0;
+ for (const value of cells) {
+ const point = parseLatLon(value);
+ if (point && !point.outOfBounds && point.decimals <= 2) coarse += 1;
+ }
+ return coarse ? { coarse } : null;
+ });
+
+ /** The columns a counting nature may read: every other column the analyst writes. Not
+ * this one — a score counting itself is a number that answers about itself — and not
+ * the row's handle, which is always filled and would add one to every row. */
+ const countable = $derived(
+ (table?.columns ?? []).filter(
+ (name) => name !== column.name && String(name).toLowerCase() !== ID_COLUMN,
+ ),
+ );
+ const counted = $derived(new Set(role?.columns ?? []));
+ const counting = $derived(kind === 'computed' && COUNTING_NATURES.includes(role?.of));
+ /** A linked nature follows one named column's link, so it needs to be told which — and
+ * "whichever the row points at" would answer about a place column when the analyst
+ * meant the subject one. */
+ const linked = $derived(kind === 'computed' && LINKED_NATURES.includes(role?.of));
+ /** The anchors this sheet has named, for an offset column to count from. Named here
+ * rather than typed, because an anchor misspelt is an anchor that dates nothing. */
+ const anchors = $derived(Object.keys(meta?.anchors ?? {}));
+
+ /** Which value's palette is open, by index. One at a time: seven swatches on forty
+ * rows is a wall, and the colour is looked at far less often than the word. */
+ let painting = $state(-1);
+ /** The value being typed into the box at the bottom. */
+ let adding = $state('');
+
+ function pick(next) {
+ if (next === kind) return;
+ if (!next) return onchange(null);
+ const seed = { kind: next };
+ // The four words and the four colours together: a state column is worth having
+ // because the grid reads at a glance, and that starts painted rather than paintable.
+ if (next === 'state') {
+ seed.values = [...STATE_DEFAULTS];
+ seed.colours = { ...STATE_COLOURS };
+ }
+ if (next === 'boolean') seed.values = [...BOOLEAN_DEFAULTS];
+ if (next === 'choice') seed.multi = null;
+ // The shape is seeded from what the column already holds and then it is the
+ // analyst's: a column of bare clocks should not have to be told twice, and an empty
+ // one has to be tellable at all.
+ if (next === 'when') seed.shape = whenShape(cells);
+ // The nature the column had before there were three of them, so an existing sheet
+ // reads the same and a new one starts on the answer that needs no setting up.
+ if (next === 'computed') seed.of = 'has_point';
+ // A cell holding several unit names is what an order of battle looks like, so the
+ // separator is on rather than off: the other way round, the first cell read as one
+ // name nobody could match.
+ if (next === 'row') seed.multi = DEFAULT_SEPARATOR;
+ // The sheet's only anchor when there is one, because a column declared against no
+ // anchor counts from nothing.
+ if (next === 'offset') seed.anchor = anchors.length === 1 ? anchors[0] : '';
+ onchange(normalizeRole(seed));
+ }
+
+ function patch(fields) {
+ onchange(normalizeRole({ ...role, ...fields }));
+ }
+
+ /** Every vocabulary edit goes through one call, because they are all the same edit:
+ * a list and a colour map out the other side. */
+ function edit(change) {
+ patch(editVocabulary(role, change));
+ }
+
+ function add() {
+ const value = adding.trim();
+ if (!value) return;
+ adding = '';
+ edit({ value });
+ }
+
+ /** Take the words the column already uses. The bridge that makes a state column light
+ * up on an imported binder: the file's own eight words — `To be found`, `pass`,
+ * `OK en cours` — become the vocabulary instead of sitting outside a list of four
+ * that were never in this file. */
+ function seedFromColumn() {
+ const seen = [];
+ for (const value of cells) if (!seen.includes(value)) seen.push(value);
+ patch({ values: seen.slice(0, 40), colours: role?.colours ?? {} });
+ }
+
+ /** Keep what is declared and add what the cells say beside it, so an order already
+ * arranged by hand is not thrown away to catch one stray word. */
+ function adoptOutside() {
+ patch({
+ values: [...(role?.values ?? []), ...use.outside.map((entry) => entry.value)].slice(0, 40),
+ colours: role?.colours ?? {},
+ });
+ }
+</script>
+
+<div class="role">
+ <p class="what">Type</p>
+ {#if suggestion && suggestion !== kind}
+ <button class="suggest" onclick={() => pick(suggestion)}>
+ <Icon name="wand" size={11} />
+ Looks like {KINDS.find((entry) => entry.id === suggestion)?.label.toLowerCase()}
+ </button>
+ {/if}
+
+ <!-- How to read what the analyst writes. The file keeps the words, so nothing here is
+ ever lost by changing the lens or clearing it. -->
+ <div class="kinds">
+ {#each READINGS as entry (entry.label)}
+ <button class="kind" class:on={kind === entry.id} title={entry.hint}
+ onclick={() => pick(entry.id)}>{entry.label}</button>
+ {/each}
+ </div>
+ <!-- And the other family: columns the app writes into the CSV. Apart, because a cell
+ typed into one of these is overwritten by the next save. -->
+ <p class="what">Or let the app write it</p>
+ <div class="kinds">
+ {#each WRITTEN as entry (entry.label)}
+ <button class="kind" class:on={kind === entry.id} title={entry.hint}
+ onclick={() => pick(entry.id)}>{entry.label}</button>
+ {/each}
+ </div>
+
+ {#if reads && reads.unreadable}
+ <p class="reads">
+ <strong>{reads.unreadable}</strong> of {reads.total} filled
+ {reads.unreadable === 1 ? 'cell is' : 'cells are'} not read as
+ {KINDS.find((entry) => entry.id === kind)?.label.toLowerCase()}.
+ </p>
+ {/if}
+ {#if dubious}
+ <p class="reads">{dubious.coarse} written to 2 decimals, which is about a kilometre.</p>
+ {/if}
+
+ {#if chipped}
+ <p class="what">
+ {kind === 'state' ? 'Values, least done first' : kind === 'boolean' ? 'Yes, then no' : 'Values'}
+ </p>
+ <div class="vocab">
+ {#each role.values ?? [] as value, at (value)}
+ <div class="entry">
+ <button class="dot c-{valueColour(role, value) ?? 'none'}"
+ class:painted={valueColour(role, value)}
+ title="Paint {value}" aria-label="Paint {value}"
+ onclick={() => (painting = painting === at ? -1 : at)}></button>
+ <input class="input word" value={value} aria-label="Value {at + 1}"
+ onkeydown={(event) => event.key === 'Enter' && event.currentTarget.blur()}
+ onblur={(event) => edit({ value: event.currentTarget.value, at })} />
+ <small class="held" title="rows holding it">{use?.counts?.[value] ?? 0}</small>
+ {#if kind !== 'boolean'}
+ <button class="move" title="Move up" aria-label="Move {value} up"
+ disabled={at === 0} onclick={() => edit({ value, at, to: at - 1 })}>
+ <Icon name="chevronUp" size={11} />
+ </button>
+ <button class="move" title="Move down" aria-label="Move {value} down"
+ disabled={at === (role.values?.length ?? 0) - 1}
+ onclick={() => edit({ value, at, to: at + 1 })}>
+ <Icon name="chevronDown" size={11} />
+ </button>
+ <button class="move drop" title="Remove" aria-label="Remove {value}"
+ onclick={() => edit({ value, at, to: -1 })}>
+ <Icon name="x" size={11} />
+ </button>
+ {/if}
+ </div>
+ {#if painting === at}
+ <div class="palette">
+ {#each ROW_COLOURS as colour (colour)}
+ <button class="dot c-{colour} painted" title={colour} aria-label="Paint {value} {colour}"
+ onclick={() => { edit({ value, at, colour }); painting = -1; }}></button>
+ {/each}
+ <button class="dot c-none" title="No colour" aria-label="Clear the colour on {value}"
+ onclick={() => { edit({ value, at, colour: null }); painting = -1; }}></button>
+ </div>
+ {/if}
+ {/each}
+ </div>
+
+ {#if kind !== 'boolean'}
+ <div class="add">
+ <input class="input" placeholder="add a value" bind:value={adding} aria-label="Add a value"
+ onkeydown={(event) => event.key === 'Enter' && add()} />
+ <button class="btn btn-sm" disabled={!adding.trim()} onclick={add}>Add</button>
+ </div>
+ <div class="vocab-actions">
+ <button class="menu-row" onclick={() => patch(sortVocabulary(role))}>
+ <Icon name="chevronDown" size={11} /> A → Z
+ </button>
+ <button class="menu-row" onclick={() => patch(sortVocabulary(role, { desc: true }))}>
+ <Icon name="chevronUp" size={11} /> Z → A
+ </button>
+ </div>
+ <button class="menu-row" onclick={seedFromColumn}>
+ <Icon name="download" size={12} /> Use the column's own words
+ </button>
+ {#if use?.outside?.length}
+ <button class="menu-row" onclick={adoptOutside}>
+ <Icon name="plus" size={12} />
+ Add the {use.outside.length}
+ {use.outside.length === 1 ? 'word' : 'words'} the cells use and this list does not
+ </button>
+ {/if}
+ {#if use?.unused?.length}
+ <p class="menu-note">
+ {use.unused.length} declared {use.unused.length === 1 ? 'value is' : 'values are'}
+ in no row: {use.unused.join(', ')}.
+ </p>
+ {/if}
+ {/if}
+ {/if}
+
+ {#if kind === 'boolean'}
+ <!-- A drawing choice, offered where the two words are: the column is the same
+ yes/no column either way, and the file holds the same pair. -->
+ <label class="check">
+ <input type="checkbox" checked={role.tick}
+ onchange={(event) => patch({ tick: event.currentTarget.checked })} />
+ <span>Draw the cells as a tick box</span>
+ </label>
+ {#if role.tick}
+ <p class="menu-note">
+ Ticking writes <code>{role.values?.[0]}</code>, unticking writes
+ <code>{role.values?.[1]}</code>, a third click empties the cell.
+ </p>
+ {/if}
+ {/if}
+
+ {#if kind === 'choice'}
+ <!-- A yes/no question, then the answer it needs. It used to be one box whose
+ placeholder was the word "no", which said neither what a separator was for nor
+ that leaving it empty meant one value per cell. -->
+ <label class="check">
+ <input type="checkbox" checked={Boolean(role.multi)}
+ onchange={(event) =>
+ patch({ multi: event.currentTarget.checked ? DEFAULT_SEPARATOR : null })} />
+ <span>One cell can hold several values</span>
+ </label>
+ {#if role.multi}
+ <label class="field inline">
+ <span>Written between them</span>
+ <input class="input narrow" aria-label="What separates them" value={role.multi}
+ onchange={(event) => patch({ multi: event.currentTarget.value || DEFAULT_SEPARATOR })} />
+ </label>
+ {/if}
+ {/if}
+
+ {#if kind === 'number'}
+ <label class="field inline">
+ <span>Unit</span>
+ <input class="input narrow" aria-label="Unit" value={role.unit ?? ''}
+ placeholder="%, €, km"
+ onchange={(event) => patch({ unit: event.currentTarget.value })} />
+ </label>
+ <!-- Where it is written. The heading carries it either way; this says whether every
+ cell repeats it, which a column of shares wants and a column of distances
+ mostly does not. Offered only once there is a unit to place. -->
+ {#if role.unit}
+ <label class="check">
+ <input type="checkbox" checked={role.unitInCells}
+ onchange={(event) => patch({ unitInCells: event.currentTarget.checked })} />
+ <span>Write <code>{role.unit}</code> after every cell too</span>
+ </label>
+ {/if}
+ <p class="what">What the footer says about the rows on screen</p>
+ <div class="kinds">
+ {#each NUMBER_SUMMARIES as entry (entry)}
+ <button class="kind" class:on={(role.summary ?? 'sum') === entry}
+ onclick={() => patch({ summary: entry })}>{SUMMARY_WORDS[entry]}</button>
+ {/each}
+ </div>
+ {/if}
+
+ {#if kind === 'when'}
+ <p class="what">What it holds</p>
+ <div class="kinds">
+ {#each WHEN_SHAPES as entry (entry)}
+ <button class="kind" class:on={role.shape === entry} onclick={() => patch({ shape: entry })}>
+ {entry === 'date' ? 'A date' : entry === 'time' ? 'A time' : 'Both'}
+ </button>
+ {/each}
+ </div>
+ {#if role.shape !== 'time'}
+ <div class="kinds">
+ <button class="kind" class:on={role.dayFirst} onclick={() => patch({ dayFirst: true })}>
+ 03/01 = 3 Jan
+ </button>
+ <button class="kind" class:on={!role.dayFirst} onclick={() => patch({ dayFirst: false })}>
+ 03/01 = 1 Mar
+ </button>
+ </div>
+ {/if}
+ {/if}
+
+ {#if kind === 'picture'}
+ <!-- The one role that reaches the network, so it says so. Nothing is fetched until a
+ column is declared one of these, which is the analyst's own action — the rule the
+ whole app runs on. -->
+ <p class="menu-note">
+ Each cell is drawn as its picture. A web address is fetched from its host, which then
+ knows this case looked; a case file stays local.
+ </p>
+ {/if}
+
+ {#if kind === 'url'}
+ <!-- Links are already live in any cell without a role. What declaring one buys is a
+ promotion that knows which column the sources are in. -->
+ <p class="menu-note">
+ Promoting files each address as a bookmark that mentions the row's entity.
+ </p>
+ {/if}
+
+ {#if kind === 'row'}
+ <!-- Names and not keys. A file whose links read `r7f3a` is a file the collaborator
+ opening it cannot follow, and names are what the binders wrote. -->
+ <label class="field inline">
+ <span>Which column names them</span>
+ <select class="input narrow" aria-label="The column that names the other rows"
+ value={role.of ?? ''}
+ onchange={(event) => patch({ of: event.currentTarget.value || null })}>
+ <option value="">The first column</option>
+ {#each countable as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ <label class="check">
+ <input type="checkbox" checked={Boolean(role.multi)}
+ onchange={(event) =>
+ patch({ multi: event.currentTarget.checked ? DEFAULT_SEPARATOR : null })} />
+ <span>One cell can name several rows</span>
+ </label>
+ {#if role.multi}
+ <label class="field inline">
+ <span>Written between them</span>
+ <input class="input narrow" aria-label="What separates them" value={role.multi}
+ onchange={(event) => patch({ multi: event.currentTarget.value || DEFAULT_SEPARATOR })} />
+ </label>
+ {/if}
+ <p class="menu-note">
+ A name that reaches no single row is left as written. Sending the rows to the case
+ draws real <code>part-of</code> edges from this column.
+ </p>
+ {/if}
+
+ {#if kind === 'offset'}
+ <label class="field inline">
+ <span>Synced on</span>
+ <select class="input narrow" aria-label="The sync point this column is synced on"
+ value={role.anchor ?? ''}
+ onchange={(event) => patch({ anchor: event.currentTarget.value })}>
+ <option value="">—</option>
+ {#each anchors as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ {#if onanchors}
+ <button class="menu-row" onclick={onanchors}>
+ <Icon name="clock" size={12} /> Sync points…
+ </button>
+ {/if}
+ <p class="menu-note">
+ A moment visible in several rows, used to line them up. <code>-00:01:50</code> is before
+ it, <code>00:04:04</code> after. Dating the sync point dates every row.
+ </p>
+ {/if}
+
+ {#if kind === 'stamped'}
+ <p class="menu-note">
+ Every empty cell is dated on the next save, including rows already in the sheet, and never
+ rewritten after that. It goes into the file.
+ </p>
+ {/if}
+ {#if kind === 'locked'}
+ <p class="menu-note">
+ The case holds this column. Refresh rewrites it, so typing here would be overwritten. The
+ cell still opens what it points at.
+ </p>
+ {/if}
+ {#if kind === 'computed'}
+ <p class="what">What it answers</p>
+ <div class="kinds">
+ {#each NATURES as entry (entry.id)}
+ <button class="kind" class:on={(role.of ?? 'has_point') === entry.id} title={entry.hint}
+ onclick={() => patch({ of: entry.id })}>{entry.label}</button>
+ {/each}
+ </div>
+ {#if counting}
+ <!-- The comparison grid's own question: eleven candidates down, six criteria across,
+ and the number that says which rows are done or which ones pass. Chosen column by
+ column rather than "all of them", because a worklist's private notes column is
+ not a criterion. -->
+ <p class="what">
+ Counted over {counted.size}
+ {counted.size === 1 ? 'column' : 'columns'}
+ </p>
+ <div class="counted">
+ {#each countable as name (name)}
+ <label class="check tight">
+ <input type="checkbox" checked={counted.has(name)}
+ disabled={!counted.has(name) && counted.size >= MAX_COUNTED_COLUMNS}
+ onchange={() =>
+ patch({
+ columns: counted.has(name)
+ ? [...counted].filter((held) => held !== name)
+ : [...counted, name],
+ })} />
+ <span>{name}</span>
+ </label>
+ {/each}
+ </div>
+ <p class="menu-note">
+ {#if !counted.size}
+ Nothing is written until a column is ticked.
+ {:else if role.of === 'yes_of'}
+ A yes/no column answers with its own first word; anywhere else
+ <code>yes</code>, <code>x</code>, <code>ok</code> and <code>1</code> count.
+ {:else}
+ Every ticked column that holds something counts, whatever it holds.
+ {/if}
+ The bare number goes in the file, so a spreadsheet can sort and total it.
+ </p>
+ {:else if linked}
+ <!-- Where `On the map` answers *whether* the case knows, these answer **what** it
+ knows — which is the number that was being copied by hand into the column
+ along. The column is named because a sheet can point at the case from more
+ than one. -->
+ <label class="field inline">
+ <span>Following the link in</span>
+ <select class="input narrow" aria-label="The column whose link it follows"
+ value={role.from ?? ''}
+ onchange={(event) => patch({ from: event.currentTarget.value || null })}>
+ <option value="">—</option>
+ {#each countable as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ {#if role.of === 'relations'}
+ <label class="field inline">
+ <span>Written between them</span>
+ <input class="input narrow" aria-label="What separates them" value={role.multi ?? DEFAULT_SEPARATOR}
+ onchange={(event) => patch({ multi: event.currentTarget.value || DEFAULT_SEPARATOR })} />
+ </label>
+ {/if}
+ <p class="menu-note">
+ {#if !role.from}
+ Nothing is written until a column is chosen.
+ {:else if role.of === 'point'}
+ The point the case holds for what <code>{role.from}</code> points at. Blank when
+ it has none, or when two different points reach it.
+ {:else}
+ What the case has joined <code>{role.from}</code>'s entity to, one hop out.
+ {/if}
+ </p>
+ {:else if role.of === 'in_case'}
+ <p class="menu-note">
+ NO once the case stops holding what the row was built from. Rows you typed yourself
+ stay blank: they were never built from anything.
+ </p>
+ {:else}
+ <p class="menu-note">YES when the row points at something with a place.</p>
+ {/if}
+ <p class="menu-note">Read-only in the grid, and written into the file on every save.</p>
+ {/if}
+</div>
+
+<style>
+ .role { border-top: 1px solid var(--border); padding-top: 5px; margin-top: 4px; }
+ .what { padding: 6px 7px 4px; color: var(--text-3); font-size: var(--fs-xs); }
+ .suggest {
+ display: flex; align-items: center; gap: 6px; width: 100%; padding: 5px 7px;
+ margin-bottom: 4px; border-radius: var(--r-sm);
+ background: var(--accent-soft); color: var(--accent); font-size: var(--fs-xs);
+ }
+ .kinds { display: flex; flex-wrap: wrap; gap: 3px; padding: 0 3px; }
+ .kind {
+ padding: 3px 7px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .kind:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .kind.on { border-color: var(--accent); color: var(--accent); }
+ .reads {
+ padding: 5px 7px 0; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5;
+ }
+ .reads strong { color: var(--text-1); font-weight: 600; }
+
+ /* One row per value: the word, what it is painted, how many rows hold it, and where it
+ sits in the order — which is the ranking the sort reads. */
+ .vocab { max-height: 260px; overflow: auto; padding: 0 3px; }
+ .entry { display: flex; align-items: center; gap: 4px; padding: 1px 0; }
+ .word { flex: 1; min-width: 0; font-size: var(--fs-xs); padding: 2px 5px; }
+ .held { flex: none; width: 22px; text-align: right; color: var(--text-3); font-size: var(--fs-xs); }
+ .dot {
+ flex: none; width: 13px; height: 13px; border-radius: 50%;
+ border: 1px solid var(--border-strong); background: var(--bg-2);
+ }
+ .dot.painted { border-color: var(--mark); background: var(--mark); }
+ .move { flex: none; display: flex; color: var(--text-3); padding: 1px; }
+ .move:hover:not(:disabled) { color: var(--text-1); }
+ .move:disabled { opacity: 0.3; }
+ .move.drop:hover { color: var(--danger); }
+ .palette {
+ display: flex; gap: 4px; padding: 3px 0 5px 17px;
+ }
+ .add { display: flex; gap: 4px; padding: 6px 3px 2px; }
+ .add .input { flex: 1; min-width: 0; font-size: var(--fs-xs); }
+ .vocab-actions { display: flex; gap: 4px; }
+ .vocab-actions .menu-row { width: auto; flex: 1; }
+
+ .field { display: block; padding: 6px 4px 2px; }
+ .field span { display: block; color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 3px; }
+ .field.inline { display: flex; align-items: center; gap: 6px; }
+ .field.inline span { margin: 0; }
+ .narrow { width: 62px; text-align: center; font-family: var(--font-mono); }
+ .check {
+ display: flex; align-items: center; gap: 7px; padding: 5px 5px 2px;
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .check code { font-family: var(--font-mono); }
+ .check.tight { padding: 2px 5px; }
+ .check.tight span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ /* A column per line, scrolled: a sheet may hold sixty and a wrapping row of sixty
+ checkboxes is not a list anybody reads. */
+ .counted { max-height: 170px; overflow: auto; padding: 0 2px; }
+ .menu-row {
+ display: flex; align-items: center; gap: 7px; width: 100%; padding: 5px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-xs);
+ }
+ .menu-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .menu-note { padding: 6px 7px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; }
+</style>
diff --git a/frontend/src/components/SheetRowMenu.svelte b/frontend/src/components/SheetRowMenu.svelte
new file mode 100644
index 0000000..73f2d53
--- /dev/null
+++ b/frontend/src/components/SheetRowMenu.svelte
@@ -0,0 +1,136 @@
+<script>
+ /**
+ * What a row can do, from the row.
+ *
+ * The gutter held one tick box and nothing else, so inserting a line where the analyst
+ * was reading meant appending one four hundred rows below and dragging it back, and
+ * forking a candidate into two hypotheses — the same address checked two ways — could
+ * not be done at all.
+ *
+ * Right-click, because that is where a spreadsheet keeps this and because the gutter has
+ * no room for anything more. It acts on **the batch when the row is in it**: forty ticked
+ * rows and a right-click on one of them means the forty, and the heading says which it
+ * is, since "delete" that turns out to mean the wrong forty is the one thing this must
+ * not do.
+ */
+ import Icon from './Icon.svelte';
+ import { ROW_COLOURS } from '../lib/sheet.js';
+
+ let {
+ at = { x: 0, y: 0 },
+ count = 1,
+ pinned = false,
+ onread,
+ oninsert,
+ onduplicate,
+ onpaint,
+ onpin,
+ onmerge,
+ ondelete,
+ onclose,
+ } = $props();
+
+ const many = $derived(count > 1);
+ const rows = $derived(`${count} ${count === 1 ? 'row' : 'rows'}`);
+
+ const WIDTH = 230;
+ const HEIGHT = 320;
+ const left = $derived(
+ typeof window === 'undefined' ? at.x : Math.max(8, Math.min(at.x, window.innerWidth - WIDTH - 8)),
+ );
+ const top = $derived(
+ typeof window === 'undefined' ? at.y : Math.max(8, Math.min(at.y, window.innerHeight - HEIGHT)),
+ );
+
+ /**
+ * Every row acts, then closes.
+ *
+ * That order matters and it cost a bug: closing first clears the state the menu was
+ * opened *about*, and the handlers read the column out of it — so an action fired after
+ * the close was an action on nothing. The menu still never stays open over the change it
+ * made, which is the point of closing at all.
+ */
+ function run(action, ...args) {
+ action?.(...args);
+ onclose();
+ }
+</script>
+
+<div class="row-menu" style="left: {left}px; top: {top}px; width: {WIDTH}px"
+ role="menu" aria-label="What to do with {rows}">
+ <p class="head">{rows}</p>
+
+ {#if !many}
+ <button class="row" role="menuitem" onclick={() => run(onread)}>
+ <Icon name="panelRight" size={12} /><span>Open it field by field</span>
+ </button>
+ {/if}
+ <button class="row" role="menuitem" onclick={() => run(oninsert, 'above')}>
+ <Icon name="chevronUp" size={12} /><span>Insert a row above</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(oninsert, 'below')}>
+ <Icon name="chevronDown" size={12} /><span>Insert a row below</span>
+ </button>
+ <button class="row" role="menuitem" onclick={() => run(onduplicate)}>
+ <Icon name="copy" size={12} /><span>Duplicate {many ? rows : 'it'}</span>
+ </button>
+ {#if many}
+ <!-- The other half of "this value is said twice": the grid could find the rows and
+ paint them, and then left the retyping of one row out of three by hand. -->
+ <button class="row" role="menuitem" onclick={() => run(onmerge)}>
+ <Icon name="layers" size={12} /><span>Merge {rows} into one</span>
+ </button>
+ {:else}
+ <!-- The reference candidate a comparison grid is read against, which otherwise
+ scrolls away at row twelve and takes the point of the grid with it. -->
+ <button class="row" class:on={pinned} role="menuitem" onclick={() => run(onpin)}>
+ <Icon name="pushpin" size={12} />
+ <span>{pinned ? 'Let it scroll' : 'Keep it in view'}</span>
+ </button>
+ {/if}
+
+ <div class="rule"></div>
+ <div class="paint">
+ <span class="what">Paint</span>
+ {#each ROW_COLOURS as colour (colour)}
+ <button class="swatch c-{colour}" title="Paint {rows} {colour}"
+ aria-label="Paint {rows} {colour}" onclick={() => run(onpaint, colour)}></button>
+ {/each}
+ <button class="swatch none" title="Clear the colour" aria-label="Clear the colour"
+ onclick={() => run(onpaint, null)}></button>
+ </div>
+
+ <div class="rule"></div>
+ <button class="row danger" role="menuitem" onclick={() => run(ondelete)}>
+ <Icon name="trash" size={12} /><span>Delete {many ? rows : 'it'}</span>
+ </button>
+</div>
+
+<style>
+ .row-menu {
+ position: fixed; z-index: 21;
+ display: flex; flex-direction: column; gap: 1px;
+ padding: 5px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ .head { padding: 3px 7px 5px; color: var(--text-3); font-size: var(--fs-xs); }
+ .row {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .row:hover { background: var(--bg-2); color: var(--text-1); }
+ .row.on { color: var(--accent); }
+ .row.danger:hover { background: var(--danger-soft); color: var(--danger); }
+ .row span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .rule { height: 1px; margin: 4px 2px; background: var(--border); }
+ .paint { display: flex; align-items: center; gap: 5px; padding: 3px 7px; }
+ .what { flex: none; color: var(--text-3); font-size: var(--fs-xs); }
+ /* The same swatch the bar above the grid draws, so a colour is picked the same way
+ wherever it is offered. The `.c-*` classes are global (`app.css`) and set `--mark`. */
+ .swatch {
+ width: 16px; height: 16px; border-radius: var(--r-sm);
+ border: 1px solid var(--border-strong); background: var(--mark, var(--bg-3));
+ }
+ .swatch.none { background: repeating-linear-gradient(45deg, var(--bg-2) 0 3px, var(--bg-3) 3px 6px); }
+ .swatch:hover { outline: 2px solid var(--accent); outline-offset: 1px; }
+</style>
diff --git a/frontend/src/components/SheetRowPanel.svelte b/frontend/src/components/SheetRowPanel.svelte
new file mode 100644
index 0000000..415025d
--- /dev/null
+++ b/frontend/src/components/SheetRowPanel.svelte
@@ -0,0 +1,380 @@
+<script>
+ /**
+ * One row of a sheet, read down instead of across.
+ *
+ * The field binders this tool replaces run to fourteen columns and more — a type, a
+ * local time, an estimated local time, an upload time, an hour note, a code, a
+ * city, coordinates, two links, two synchro offsets — and a grid thirty pixels tall
+ * cannot show one row of that. Scrolling sideways to read one case loses the case.
+ *
+ * So the same row, one field per line, every cell editable, and the links live. It
+ * is a second view of the table and not a second store: every change goes back
+ * through the same cell edit the grid uses.
+ *
+ * Two things live here and nowhere else, because both belong to the **row** rather than
+ * to any of its cells. The **pieces it carries**: the screenshot of the message giving
+ * the hour, the emailed reply — which the binders kept in two whole tabs of pasted
+ * images, floating beside the work they were the proof of. They are *referenced*, never
+ * copied, because the file is already the case's. And **who points at this row**, when a
+ * column names other rows: the other half of an order of battle, derived from the words
+ * rather than kept by hand in a second column that drifts.
+ */
+ import Icon from './Icon.svelte';
+ import { ID_COLUMN, linkLabel, urlsIn } from '../lib/sheet.js';
+ import {
+ DEFAULT_SEPARATOR,
+ cycleTick,
+ dateSpelling,
+ flipBoolean,
+ pickerType,
+ spellWhen,
+ valueColour,
+ } from '../lib/sheetRoles.js';
+
+ let {
+ table,
+ rowIndex,
+ rowKey,
+ linkOf,
+ roles = {},
+ attached = [],
+ pointedBy = [],
+ changes = [],
+ onedit,
+ onlink,
+ onattach,
+ ondetach,
+ onfindmedia,
+ onopenentity,
+ onstep,
+ onclose,
+ } = $props();
+
+ /** Whether the row holds an address at all, since "find what was downloaded from these"
+ * is a question about pages and reads as noise on a row that names none. */
+ const holdsLinks = $derived(
+ (table.rows[rowIndex] ?? []).some((cell) => urlsIn(cell).length),
+ );
+
+ const row = $derived(table.rows[rowIndex] ?? []);
+ const fields = $derived(
+ (table.columns ?? []).map((name, index) => ({
+ name,
+ index,
+ value: row[index] ?? '',
+ isKey: String(name).toLowerCase() === ID_COLUMN,
+ })),
+ );
+ const filled = $derived(fields.filter((field) => !field.isKey && String(field.value).trim()).length);
+ const total = $derived(fields.length - 1);
+
+ /**
+ * What a column knows, offered here too.
+ *
+ * The grid gives a status column its four words, a yes/no column a box and a date column
+ * a calendar; read down a panel, the same fourteen columns were fourteen bare boxes. So
+ * the panel is a worse place to work than the row it is showing, on exactly the columns
+ * that were set up carefully. Same helpers as the cell editor, so a word written here and
+ * a word written in the grid are the same word.
+ */
+ const vocabulary = (name) => {
+ const role = roles[name];
+ return role?.kind === 'state' || role?.kind === 'choice' ? (role.values ?? []) : [];
+ };
+ /** Whether the app writes this column rather than the analyst. Typing into one of those
+ * is typing into a value the next save overwrites, which the grid already refuses. */
+ const appFilled = (name) => ['stamped', 'computed', 'locked'].includes(roles[name]?.kind);
+ const held = (field) => {
+ const separator = roles[field.name]?.multi;
+ return new Set(
+ separator
+ ? String(field.value).split(separator).map((part) => part.trim()).filter(Boolean)
+ : [String(field.value).trim()],
+ );
+ };
+
+ /** Click a word: put it in, or take it back out. A toggle, because a list is unbuilt as
+ * often as it is built — the same gesture the cell editor's own list answers to. */
+ function takeValue(field, word) {
+ const separator = roles[field.name]?.multi;
+ if (!separator) {
+ onedit(rowIndex, field.index, String(field.value).trim() === word ? '' : word);
+ return;
+ }
+ const values = String(field.value)
+ .split(separator)
+ .map((part) => part.trim())
+ .filter(Boolean);
+ const at = values.indexOf(word);
+ if (at === -1) values.push(word);
+ else values.splice(at, 1);
+ onedit(rowIndex, field.index, values.join(separator || DEFAULT_SEPARATOR));
+ }
+
+ function flip(field) {
+ const role = roles[field.name];
+ const next = role?.tick ? cycleTick(role, field.value) : flipBoolean(role, field.value);
+ onedit(rowIndex, field.index, next);
+ }
+
+ /** What the calendar should open on, in the spelling the column already uses. */
+ function pickWhen(field, picked) {
+ const role = roles[field.name];
+ const cells = table.rows.map((line) => line[field.index]);
+ onedit(
+ rowIndex,
+ field.index,
+ spellWhen(picked, {
+ shape: role?.shape ?? 'date',
+ spelling: dateSpelling(cells),
+ keep: field.value,
+ }),
+ );
+ }
+</script>
+
+<aside class="panel" aria-label="This row, field by field">
+ <header>
+ <button class="btn btn-ghost btn-sm" title="The row above" onclick={() => onstep(-1)}>
+ <Icon name="chevronUp" size={13} />
+ </button>
+ <button class="btn btn-ghost btn-sm" title="The row below" onclick={() => onstep(1)}>
+ <Icon name="chevronDown" size={13} />
+ </button>
+ <span class="progress">{filled} of {total} filled</span>
+ <div class="spacer"></div>
+ <button class="btn btn-ghost btn-sm" title="Close" aria-label="Close this row" onclick={onclose}>
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+
+ <div class="fields">
+ {#each fields as field (field.name)}
+ {@const linked = linkOf(rowIndex, field.name)}
+ {@const links = urlsIn(field.value)}
+ <div class="field" class:key={field.isKey}>
+ <div class="label">
+ <span>{field.name}</span>
+ {#if linked}
+ <button class="mark" title="Open this entity" onclick={() => onopenentity(linked)}>
+ <Icon name="link" size={11} />
+ </button>
+ {/if}
+ {#if !field.isKey}
+ <button class="mark at" title="Link to an entity" aria-label="Link {field.name} to an entity"
+ onclick={() => onlink(rowIndex, field.index)}>@</button>
+ {/if}
+ </div>
+ {#if field.isKey}
+ <p class="handle">{field.value}</p>
+ {:else if appFilled(field.name)}
+ <!-- Written by the app on every save, so a box here would be a box whose value
+ is gone by the next one. The grid refuses the same keystroke. -->
+ <p class="written">{field.value || '—'}<small>written by the app</small></p>
+ {:else}
+ {@const role = roles[field.name]}
+ {@const words = vocabulary(field.name)}
+ {@const taken = held(field)}
+ {#if role?.kind === 'boolean'}
+ <!-- Two words is a toggle, in the panel as in the grid. -->
+ <button class="answer" class:on={taken.has(role.values?.[0])} onclick={() => flip(field)}>
+ <Icon name={taken.has(role.values?.[0]) ? 'check' : 'x'} size={12} />
+ <span>{field.value || 'not answered'}</span>
+ </button>
+ {:else}
+ <textarea class="input" rows={String(field.value).includes('\n') ? 3 : 1}
+ aria-label={field.name} value={field.value}
+ onchange={(event) => onedit(rowIndex, field.index, event.currentTarget.value)}
+ ></textarea>
+ {/if}
+ {#if words.length}
+ <!-- The column's own words, under the box rather than instead of it: the
+ binders write outside their vocabulary on every page. -->
+ <div class="words">
+ {#each words as word (word)}
+ <button class="word c-{valueColour(role, word) ?? 'none'}"
+ class:tinted={valueColour(role, word)} class:on={taken.has(word)}
+ onclick={() => takeValue(field, word)}>{word}</button>
+ {/each}
+ </div>
+ {/if}
+ {#if role?.kind === 'when'}
+ <label class="calendar">
+ <Icon name="clock" size={12} />
+ <input type={pickerType(role.shape ?? 'date')}
+ aria-label="Pick a value for {field.name}"
+ onchange={(event) => pickWhen(field, event.currentTarget.value)} />
+ </label>
+ {/if}
+ {#if links.length}
+ <p class="links">
+ {#each links as url (url)}
+ <a href={url} target="_blank" rel="noreferrer noopener">
+ <Icon name="external" size={11} /> {linkLabel(url)}
+ </a>
+ {/each}
+ </p>
+ {/if}
+ {/if}
+ </div>
+ {/each}
+
+ <!-- The pieces the row carries, which is the tab of pasted screenshots the binders
+ could not attach to anything. A reference and not a copy: the case already holds
+ the file, so nothing new is filed and the bundle does not drift. -->
+ <div class="carried">
+ <p class="carried-head">
+ <Icon name="file" size={11} />
+ <span>What this row carries</span>
+ </p>
+ {#each attached as piece (piece.id)}
+ <div class="piece">
+ <button class="piece-name" title="Open it" onclick={() => onopenentity(piece.id)}>
+ {piece.label || piece.id}
+ </button>
+ <small>{piece.type}</small>
+ <button class="drop" title="Take it off this row"
+ aria-label="Take {piece.label} off this row" onclick={() => ondetach(piece.id)}>
+ <Icon name="x" size={11} />
+ </button>
+ </div>
+ {/each}
+ <div class="carry-actions">
+ <button class="menu-row" onclick={() => onattach(rowKey)}>
+ <Icon name="plus" size={11} /> Attach a case file
+ </button>
+ {#if holdsLinks}
+ <!-- The library's imports and this row's links are the same pages twice, and
+ nothing joined them: the analyst had the video and the row could not say so. -->
+ <button class="menu-row" onclick={() => onfindmedia(rowKey)}>
+ <Icon name="download" size={11} /> Find library files from these links
+ </button>
+ {/if}
+ </div>
+ </div>
+
+ {#if pointedBy.length}
+ <!-- Derived from the words every time rather than kept in a second column: that is
+ the column the binders kept by hand, and it had already decayed to `#REF!`. -->
+ <div class="carried">
+ <p class="carried-head">
+ <Icon name="link" size={11} />
+ <span>Pointed at by</span>
+ </p>
+ <p class="pointed">{pointedBy.join(', ')}</p>
+ </div>
+ {/if}
+
+ {#if changes.length}
+ <!-- This session only. A durable log would be a new file beside the CSV, which
+ means deciding what the Trash and the bundle do with it — so this says what
+ it is rather than pretending to be a history. -->
+ <div class="log">
+ <p class="log-head">Changed here, this session</p>
+ {#each changes.slice().reverse() as change, index (index)}
+ <p class="change">
+ <span class="log-column">{change.column}</span>
+ <s>{change.before || '—'}</s>
+ <Icon name="arrowRight" size={10} />
+ <b>{change.after || '—'}</b>
+ </p>
+ {/each}
+ </div>
+ {/if}
+ </div>
+</aside>
+
+<style>
+ .panel {
+ width: 340px; flex: none; display: flex; flex-direction: column; min-height: 0;
+ border-left: 1px solid var(--border); background: var(--bg-1);
+ }
+ header {
+ display: flex; align-items: center; gap: 4px; padding: 5px 8px;
+ border-bottom: 1px solid var(--border);
+ }
+ .spacer { flex: 1; }
+ .progress { color: var(--text-3); font-size: var(--fs-xs); }
+ .fields { flex: 1; min-height: 0; overflow: auto; padding: 4px 10px 14px; }
+ .field { padding: 7px 0; border-bottom: 1px solid var(--border); }
+ .field:last-child { border-bottom: 0; }
+ .label { display: flex; align-items: center; gap: 6px; margin-bottom: 3px; }
+ .label span {
+ flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .mark { display: flex; color: var(--accent); }
+ .mark.at { color: var(--text-3); font-family: var(--font-mono); font-weight: 600; }
+ .mark.at:hover { color: var(--accent); }
+ .field.key .handle {
+ color: var(--text-3); font-family: var(--font-mono); font-size: var(--fs-xs);
+ }
+ .field textarea { width: 100%; resize: vertical; line-height: 1.45; }
+ /* A column the app writes. Shown, never editable: the next save would take the typing
+ back without a word. */
+ .written {
+ display: flex; align-items: baseline; gap: 8px;
+ color: var(--text-2); font-size: var(--fs-sm);
+ }
+ .written small { color: var(--text-3); font-size: var(--fs-xs); }
+ /* A yes/no column, answered the way the grid answers it. */
+ .answer {
+ display: flex; align-items: center; gap: 6px; padding: 4px 8px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-sm);
+ }
+ .answer:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .answer.on { border-color: var(--ok); color: var(--ok); }
+ /* The column's own words. The `.c-*` classes are global and set `--mark`, so a word
+ wears here the colour it wears in the cells. */
+ .words { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 5px; }
+ .word {
+ padding: 2px 7px; border-radius: 9px; border: 1px solid var(--border);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .word:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .word.tinted { color: var(--mark); }
+ .word.on {
+ border-color: var(--mark, var(--accent)); color: var(--mark, var(--accent));
+ background: color-mix(in srgb, var(--mark, var(--accent)) 14%, transparent);
+ }
+ .calendar {
+ display: inline-flex; align-items: center; gap: 5px; margin-top: 5px; padding: 1px 6px;
+ border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text-3);
+ }
+ .calendar input {
+ border: 0; background: none; color: var(--text-1); font-size: var(--fs-xs);
+ font-family: inherit;
+ }
+ .links { display: flex; flex-wrap: wrap; gap: 4px 10px; margin-top: 4px; }
+ .links a {
+ display: inline-flex; align-items: center; gap: 4px;
+ color: var(--accent); font-size: var(--fs-xs);
+ }
+ .log { margin-top: 14px; padding-top: 8px; border-top: 1px solid var(--border-strong); }
+ .log-head { color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 5px; }
+ .change {
+ display: flex; align-items: center; gap: 5px; padding: 2px 0;
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .change s { color: var(--text-3); }
+ .log-column { color: var(--text-3); min-width: 70px; }
+ .carried { margin-top: 12px; padding-top: 8px; border-top: 1px solid var(--border-strong); }
+ .carried-head {
+ display: flex; align-items: center; gap: 5px; margin-bottom: 5px;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .piece { display: flex; align-items: center; gap: 6px; padding: 2px 0; font-size: var(--fs-xs); }
+ .piece-name {
+ flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--accent); text-align: left;
+ }
+ .piece small { flex: none; color: var(--text-3); }
+ .piece .drop { flex: none; color: var(--text-3); }
+ .piece .drop:hover { color: var(--danger); }
+ .carry-actions { padding-top: 3px; }
+ .menu-row { display: flex; align-items: center; gap: 6px; width: 100%; padding: 4px 2px;
+ color: var(--text-2); text-align: left; font-size: var(--fs-xs); border-radius: var(--r-sm); }
+ .menu-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .pointed { color: var(--text-2); font-size: var(--fs-xs); line-height: 1.5; }
+</style>
diff --git a/frontend/src/components/SheetToCase.svelte b/frontend/src/components/SheetToCase.svelte
new file mode 100644
index 0000000..85ffa96
--- /dev/null
+++ b/frontend/src/components/SheetToCase.svelte
@@ -0,0 +1,666 @@
+<script>
+ /**
+ * A whole sheet into the case, in one declaration and one press.
+ *
+ * This replaces four screens that each promoted one thing and none of which could draw
+ * an edge — because an edge needs *two* columns and each of them only ever saw one. A
+ * binder's line says *this person, in that unit, seen at that point, at this hour*; the
+ * case used to get the nodes and lose the sentence.
+ *
+ * So: **a mode per column**, and then the joins. The modes are the four old roads plus
+ * the two halves of the fifth: what a row *is*, what a column's words *are*, the point,
+ * the addresses, the hour, and a column naming other rows.
+ *
+ * **The joins are not drawn by hand.** For every ordered pair of columns that designates
+ * something, the vocabulary is asked what it allows between their two types, and only
+ * the pairs with an answer are offered. The select shows the *readings* — "is a member
+ * of", "has member" — which is what settles the direction without a question about
+ * direction. A person and a point have no verb between them, so that pair never appears.
+ *
+ * Nothing is decided here. The plan comes from the same code the press runs, and the one
+ * decision this screen adds is the old one: **a name is not an identity**, so a word the
+ * case already holds twice is offered and never merged on its own.
+ */
+ import Icon from './Icon.svelte';
+ import SheetDate from './SheetDate.svelte';
+ import { ID_COLUMN } from '../lib/sheet.js';
+ import { columnKinds } from '../lib/sheetBuild.js';
+ import {
+ entityFields,
+ entityLabel,
+ loadEntityTypes,
+ promotableTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { loadRelationTypes, relationOptions } from '../lib/relations.svelte.js';
+
+ let {
+ table, meta, count, scope = 'ticked', busy = false,
+ onpreview, onpass, onanchors, onclose,
+ } = $props();
+
+ loadEntityTypes();
+ loadRelationTypes();
+
+ /** The modes a column may take, and when the sheet says a column can take one. A mode
+ * offered on a column whose role cannot carry it is a refusal waiting to happen, so the
+ * role decides what is in the select.
+ *
+ * Three of them mint one type and only that type, so they are named after it — the
+ * vocabulary's own word, with what the column has to hold beside it. The other two make
+ * whatever type is picked next to them, so they are named after the grain instead. */
+ const MODES = [
+ { id: 'ignore', label: 'Ignore' },
+ { id: 'row', label: 'One entity per row' },
+ { id: 'value', label: 'One entity per value' },
+ { id: 'point', label: 'Place (coordinates)', role: 'latlon' },
+ { id: 'addresses', label: 'Bookmark (links)', role: 'url' },
+ { id: 'statement', label: 'Claim (hours)', role: ['when', 'offset'] },
+ { id: 'row-edges', label: 'Edges to other rows', role: 'row' },
+ ];
+
+ /** The two verbs a column of row names may become. Kept to two rather than the whole
+ * vocabulary: those are what an order of battle is made of. */
+ const ROW_VERBS = [
+ { id: 'part-of', label: 'is part of' },
+ { id: 'member-of', label: 'is a member of' },
+ ];
+
+ const CONFIDENCE = [
+ { id: '', label: 'Not stated' },
+ { id: '3', label: 'Certain' },
+ { id: '2', label: 'Probable' },
+ { id: '1', label: 'Possible' },
+ ];
+
+ const columns = $derived(
+ (table?.columns ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN),
+ );
+ const types = $derived(promotableTypes());
+
+ /** Column name -> mode. Everything starts ignored: only what was asked for travels. */
+ let modes = $state({});
+ /** Column name -> the entity type its mode makes. */
+ let picked = $state({});
+ /** Attr key -> the column filling it, for the subject's own type. */
+ let mapping = $state({});
+ let group = $state(false);
+ let groupLabel = $state('');
+ /** Column name -> the verb a row-names column draws. */
+ let rowVerbs = $state({});
+ /** `"from›to"` -> `"verb:direction"`, which is what the analyst picked in a pair select. */
+ let verbs = $state({});
+ let confidence = $state('');
+ /** What the embedded hours form reports, or null while it is not ready. */
+ let statement = $state(null);
+ /** Column -> key -> the entity the analyst attached that row or word to. */
+ let attach = $state({});
+ /** Column -> Set of keys read in the plan and left alone. */
+ let skipped = $state({});
+
+ let plan = $state(null);
+ let planning = $state(false);
+ let failed = $state('');
+
+ /**
+ * What a column holds, declared or read off its cells.
+ *
+ * Declared wins. Read second, because a sheet imported five minutes ago has no roles on
+ * it yet and a column of `48.5, 35.1` is a column of coordinates whether or not anybody
+ * has said so — and offering *Place (coordinates)* only once the role is set means the
+ * mode is missing exactly when the analyst first wants it.
+ *
+ * Shared with the build screen (`lib/sheetBuild.js`), because the two would otherwise
+ * disagree about the same column the first time either reading was touched.
+ */
+ const holds = $derived(columnKinds(table, meta));
+
+ /** Which modes this column may take. A role gates the four that need one; `row` and
+ * `value` are always available, because any column of words can name something. */
+ function modesFor(name) {
+ const kind = holds[name] ?? '';
+ return MODES.filter((mode) => {
+ if (!mode.role) return true;
+ return Array.isArray(mode.role) ? mode.role.includes(kind) : mode.role === kind;
+ });
+ }
+
+ /** Which types a mode may make. A `place` is the one type a column of words cannot
+ * become: a point is the only identity in this app that is a number, so it is read off
+ * coordinates and never off a name. The server refuses it; this is why it is not there
+ * to be picked in the first place. */
+ function typesFor(mode) {
+ return mode === 'value' ? types.filter((entry) => entry.type !== 'place') : types;
+ }
+
+ const subjectColumn = $derived(
+ columns.find((name) => modes[name] === 'row') ?? '',
+ );
+ const subjectType = $derived(subjectColumn ? picked[subjectColumn] ?? '' : '');
+ const valueColumns = $derived(columns.filter((name) => modes[name] === 'value'));
+ const pointColumn = $derived(columns.find((name) => modes[name] === 'point') ?? '');
+ const addressColumn = $derived(columns.find((name) => modes[name] === 'addresses') ?? '');
+ const statementColumn = $derived(columns.find((name) => modes[name] === 'statement') ?? '');
+ const edgeColumns = $derived(columns.filter((name) => modes[name] === 'row-edges'));
+
+ /** Every column that ends up designating something, with the type it designates. The
+ * point is a `place` whichever type the subject is, which is what lets a second column
+ * be joined to the ground a row was located on. */
+ const pointing = $derived([
+ ...(subjectColumn && subjectType ? [{ column: subjectColumn, type: subjectType }] : []),
+ ...valueColumns.filter((name) => picked[name]).map((name) => ({ column: name, type: picked[name] })),
+ ...(pointColumn && subjectType ? [{ column: pointColumn, type: 'place' }] : []),
+ ]);
+
+ /** The ordered pairs the vocabulary has a verb for, each with its readings. A pair with
+ * none is absent rather than shown empty: an empty select is a question with no answer. */
+ const pairs = $derived(
+ pointing.flatMap((start, at) =>
+ pointing.slice(at + 1).map((end) => {
+ const options = relationOptions(start.type, end.type);
+ return { start, end, options };
+ }),
+ ).filter((pair) => pair.options.length),
+ );
+
+ /** What a pair is joined by, which is the analyst's answer or the vocabulary's when it
+ * leaves no choice. A pair with one legal reading arrives filled in and takes one click
+ * to undo; asking for a confirmation of the only possible answer is asking nothing. */
+ function chosen(pair) {
+ const key = `${pair.start.column}\u203a${pair.end.column}`;
+ if (key in verbs) return verbs[key];
+ return pair.options.length === 1
+ ? `${pair.options[0].type}:${pair.options[0].direction}`
+ : '';
+ }
+
+ const fields = $derived(
+ subjectType ? entityFields(subjectType).filter((field) => field.kind !== 'geojson') : [],
+ );
+
+ function setMode(name, mode) {
+ // One subject and one of each row-scoped mode: the second declaration wins and the
+ // first goes back to being ignored, rather than a refusal the analyst has to read.
+ const single = ['row', 'point', 'addresses', 'statement'];
+ const next = { ...modes, [name]: mode };
+ if (single.includes(mode)) {
+ for (const other of columns) {
+ if (other !== name && next[other] === mode) next[other] = 'ignore';
+ }
+ }
+ modes = next;
+ if ((mode === 'row' || mode === 'value') && !picked[name]) {
+ picked = { ...picked, [name]: types[0]?.type ?? '' };
+ }
+ if (mode === 'row-edges' && !rowVerbs[name]) {
+ rowVerbs = { ...rowVerbs, [name]: ROW_VERBS[0].id };
+ }
+ }
+
+ // A stale plan is worse than none: one that describes the previous declaration reads as
+ // an answer about this one. Attachments go with it, since they are answers to *its*
+ // questions.
+ $effect(() => {
+ void [modes, picked, mapping, group, groupLabel, rowVerbs, verbs, confidence, statement];
+ plan = null;
+ attach = {};
+ skipped = {};
+ });
+
+ /**
+ * What the declaration is still short of, in one line, or nothing when it is whole.
+ *
+ * The modes that are *about* something are refused at the door by the server, and a press
+ * greyed out with no reason on it is that refusal with the reason taken off. The point is
+ * the one worth spelling out: *Place (coordinates)* puts a subject on its ground, so an
+ * analyst who wants the points themselves has declared the right column under the wrong
+ * mode and nothing on screen says which one is right.
+ */
+ const missing = $derived.by(() => {
+ if (!subjectColumn) {
+ if (pointColumn && !addressColumn && !statementColumn) {
+ return `Place (coordinates) puts a subject on its ground. For the points themselves, set ${pointColumn} to “One entity per row” and pick Place.`;
+ }
+ if (pointColumn || addressColumn || statementColumn) {
+ return 'A place, a bookmark and a claim are each about something, so one column has to be the subject.';
+ }
+ return '';
+ }
+ if (subjectType === 'place' && !pointColumn && holds[subjectColumn] !== 'latlon') {
+ return `A place is its coordinates: set the column holding them to “Place (coordinates)”.`;
+ }
+ return '';
+ });
+
+ /** Where a subject that is a place gets its point, when it is its own column. Said rather
+ * than asked for — and it is also where the answer to "how do I name these" belongs,
+ * because the name of a place is whatever column is the subject. */
+ const pointFromItself = $derived(
+ subjectType === 'place' && !pointColumn && holds[subjectColumn] === 'latlon'
+ ? subjectColumn
+ : '',
+ );
+
+ const ready = $derived(
+ Boolean(
+ count &&
+ !missing &&
+ (subjectColumn ? subjectType : true) &&
+ (subjectColumn || valueColumns.length) &&
+ valueColumns.every((name) => picked[name]),
+ ),
+ );
+
+ function declaration() {
+ return {
+ subject: subjectColumn
+ ? {
+ column: subjectColumn,
+ type: subjectType,
+ fields: Object.fromEntries(
+ Object.entries(mapping)
+ .filter(([, column]) => column)
+ .map(([attr, column]) => [column, attr]),
+ ),
+ attach: attach[subjectColumn] ?? {},
+ skip: [...(skipped[subjectColumn] ?? [])],
+ group,
+ group_label: groupLabel.trim() || null,
+ }
+ : null,
+ point: pointColumn,
+ addresses: addressColumn,
+ values: valueColumns.map((name) => ({
+ column: name,
+ type: picked[name],
+ attach: attach[name] ?? {},
+ skip: [...(skipped[name] ?? [])],
+ })),
+ statement: statementColumn && statement
+ ? { ...statement, skip: [...(skipped[statementColumn] ?? [])] }
+ : null,
+ row_edges: edgeColumns.map((name) => ({ column: name, verb: rowVerbs[name] })),
+ joins: pairs.flatMap((pair) => {
+ const answer = chosen(pair);
+ if (!answer) return [];
+ const [verb, direction] = answer.split(':');
+ return [
+ direction === 'in'
+ ? { from: pair.end.column, to: pair.start.column, verb }
+ : { from: pair.start.column, to: pair.end.column, verb },
+ ];
+ }),
+ confidence: confidence ? Number(confidence) : null,
+ };
+ }
+
+ async function look() {
+ if (!ready || planning) return;
+ planning = true;
+ failed = '';
+ try {
+ plan = await onpreview(declaration());
+ } catch (error) {
+ failed = error?.message || 'This pass could not be read.';
+ plan = null;
+ } finally {
+ planning = false;
+ }
+ }
+
+ /** Attach one row or word to something the case already holds, or take that back. Read
+ * again afterwards: attaching changes what the plan says about it. */
+ async function attachTo(column, key, entityId) {
+ const held = { ...(attach[column] ?? {}) };
+ if (entityId) held[key] = entityId;
+ else delete held[key];
+ attach = { ...attach, [column]: held };
+ await lookAgain();
+ }
+
+ async function leaveOut(column, key) {
+ const held = new Set(skipped[column] ?? []);
+ if (!held.delete(key)) held.add(key);
+ skipped = { ...skipped, [column]: held };
+ await lookAgain();
+ }
+
+ /** The plan again, without the effect above wiping it first — an attachment is an answer
+ * to the plan on screen, not a new declaration. */
+ async function lookAgain() {
+ planning = true;
+ try {
+ plan = await onpreview(declaration());
+ } catch (error) {
+ failed = error?.message || 'This pass could not be read.';
+ } finally {
+ planning = false;
+ }
+ }
+
+ const WORDS = {
+ make: 'New',
+ join: 'Attach',
+ update: 'Update',
+ skip: 'Left out',
+ error: 'Cannot read',
+ };
+ const LAYERS = {
+ row: 'Rows',
+ value: 'Words',
+ statement: 'Statements',
+ 'row-edges': 'Row edges',
+ };
+
+ /** How much the press would write, counted over both layers so the button is not a leap. */
+ const willWrite = $derived(
+ plan
+ ? (plan.entities ?? []).reduce(
+ (total, layer) =>
+ total + (layer.counts?.make ?? 0) + (layer.counts?.join ?? 0) + (layer.counts?.update ?? 0),
+ 0,
+ ) + (plan.joins ?? []).reduce((total, join) => total + (join.rows ?? 0), 0)
+ : 0,
+ );
+</script>
+
+<div class="to-case">
+ <p class="lead">
+ <strong>{count}</strong> {scope} {count === 1 ? 'row' : 'rows'}. A row already sent is
+ updated; a name the case holds twice is offered, never merged.
+ </p>
+
+ <p class="label">What each column is</p>
+ <div class="columns">
+ {#each columns as name (name)}
+ <div class="column">
+ <span class="name" title={name}>{name}</span>
+ <select class="input" value={modes[name] ?? 'ignore'} aria-label="What {name} is"
+ onchange={(event) => setMode(name, event.currentTarget.value)}>
+ {#each modesFor(name) as mode (mode.id)}
+ <option value={mode.id}>{mode.label}</option>
+ {/each}
+ </select>
+ {#if modes[name] === 'row' || modes[name] === 'value'}
+ <select class="input" value={picked[name] ?? ''} aria-label="What {name} becomes"
+ onchange={(event) => (picked = { ...picked, [name]: event.currentTarget.value })}>
+ {#each typesFor(modes[name]) as entry (entry.type)}
+ <option value={entry.type}>{entry.label}</option>
+ {/each}
+ </select>
+ {:else if modes[name] === 'row-edges'}
+ <select class="input" value={rowVerbs[name] ?? ''} aria-label="What {name} draws"
+ onchange={(event) => (rowVerbs = { ...rowVerbs, [name]: event.currentTarget.value })}>
+ {#each ROW_VERBS as verb (verb.id)}
+ <option value={verb.id}>{verb.label}</option>
+ {/each}
+ </select>
+ {:else}
+ <span class="filler"></span>
+ {/if}
+ </div>
+ {/each}
+ </div>
+
+ {#if subjectColumn && count > 1}
+ <label class="check">
+ <input type="checkbox" checked={group}
+ onchange={(event) => (group = event.currentTarget.checked)} />
+ <span>These rows are one thing, not {count}</span>
+ </label>
+ {#if group}
+ <label class="row">
+ <span>Call it</span>
+ <input class="input" placeholder="the first row's name" bind:value={groupLabel}
+ aria-label="What to call the one entity" />
+ </label>
+ {/if}
+ {/if}
+
+ {#if pointFromItself}
+ <p class="note">
+ Each place is read from <em>{pointFromItself}</em> and named by what its cell says. To
+ name them from another column, make that one the subject and set this one to
+ “Place (coordinates)”.
+ </p>
+ {/if}
+
+ {#if fields.length}
+ <p class="label">Which columns fill {entityLabel(subjectType).toLowerCase()} fields</p>
+ <div class="fields">
+ {#each fields as field (field.key)}
+ <label class="row">
+ <span title={field.hint ?? ''}>{field.label}</span>
+ <select class="input" aria-label={field.label} value={mapping[field.key] ?? ''}
+ onchange={(event) => (mapping = { ...mapping, [field.key]: event.currentTarget.value })}>
+ <option value="">—</option>
+ {#each columns as name (name)}<option value={name}>{name}</option>{/each}
+ </select>
+ </label>
+ {/each}
+ </div>
+ {/if}
+
+ {#if statementColumn}
+ <p class="label">What <em>{statementColumn}</em> states</p>
+ <div class="nested">
+ <SheetDate {table} {meta} {count} subject={subjectColumn} {onanchors}
+ onchoices={(answer) => (statement = answer)} />
+ </div>
+ {/if}
+
+ {#if pairs.length}
+ <p class="label">And what joins what. Only the pairs the vocabulary allows.</p>
+ <div class="joins">
+ {#each pairs as pair (pair.start.column + '›' + pair.end.column)}
+ <div class="join">
+ <span class="ends">
+ <Icon name={entityIcon({ type: pair.start.type })} size={11} />
+ {pair.start.column}
+ <span class="dash">·</span>
+ <Icon name={entityIcon({ type: pair.end.type })} size={11} />
+ {pair.end.column}
+ </span>
+ <select class="input" aria-label="How {pair.start.column} and {pair.end.column} are joined"
+ value={chosen(pair)}
+ onchange={(event) =>
+ (verbs = { ...verbs, [`${pair.start.column}›${pair.end.column}`]: event.currentTarget.value })}>
+ <option value="">Not joined</option>
+ <!-- Always read from the first column's side, because that is how the registry
+ writes both halves: `member-of` reads "is a member of" and its inverse
+ reads "has member", so one sentence per option and the arrow follows. -->
+ {#each pair.options as option (option.type + option.direction)}
+ <option value="{option.type}:{option.direction}"
+ >{pair.start.column} {option.label} {pair.end.column}</option>
+ {/each}
+ </select>
+ </div>
+ {/each}
+ </div>
+
+ <label class="row">
+ <span>How sure these joins are</span>
+ <select class="input" value={confidence} aria-label="How sure these joins are"
+ onchange={(event) => (confidence = event.currentTarget.value)}>
+ {#each CONFIDENCE as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}
+ </select>
+ </label>
+ {/if}
+
+ {#if missing}
+ <p class="note short">{missing}</p>
+ {/if}
+
+ {#if failed}
+ <p class="failed" role="alert">{failed}</p>
+ {/if}
+
+ {#if plan}
+ {#each plan.entities ?? [] as layer (layer.mode + layer.column)}
+ <div class="layer">
+ <p class="layer-head">
+ {LAYERS[layer.mode] ?? layer.mode}
+ {#if layer.column}<em>{layer.column}</em>{/if}
+ {#each ['make', 'join', 'update', 'skip', 'error'] as action (action)}
+ {#if layer.counts?.[action]}
+ <span class="tally-part {action}">
+ <strong>{layer.counts[action]}</strong> {WORDS[action].toLowerCase()}
+ </span>
+ {/if}
+ {/each}
+ </p>
+ {#if layer.mode === 'row' || layer.mode === 'value' || layer.mode === 'statement'}
+ <div class="plan">
+ {#each layer.rows as row (row.key)}
+ <div class="plan-row {row.action}">
+ <span class="mark">{WORDS[row.action]}</span>
+ <span class="who">{row.label || row.value || row.subject_label || row.key}</span>
+ {#if row.when}
+ <small class="when">{row.when}</small>
+ <small class="why">{row.confidence}</small>
+ {:else if row.action === 'update' || row.action === 'join'}
+ <small class="why">{row.entity_label}</small>
+ {:else if row.reason}
+ <small class="why">{row.reason}</small>
+ {/if}
+ <div class="spacer"></div>
+ {#if row.candidates?.length}
+ <select class="input tiny" aria-label="Attach {row.label || row.value} to something the case holds"
+ value={attach[layer.column]?.[row.key] ?? ''}
+ onchange={(event) => attachTo(layer.column, row.key, event.currentTarget.value)}>
+ <option value="">Create it</option>
+ {#each row.candidates as candidate (candidate.id)}
+ <option value={candidate.id}>Attach to {candidate.label}</option>
+ {/each}
+ </select>
+ {/if}
+ <button class="undo" onclick={() => leaveOut(layer.column, row.key)}>
+ {skipped[layer.column]?.has(row.key) ? 'Put back' : 'Leave out'}
+ </button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ {/each}
+
+ {#each plan.joins ?? [] as join (join.from + join.verb + join.to)}
+ <p class="join-plan">
+ <span class="who">{join.from} {join.label} {join.to}</span>
+ <strong>{join.rows}</strong> {join.rows === 1 ? 'row' : 'rows'}
+ {#if join.blocked?.length}
+ <small class="why warn">
+ {join.blocked.length} without an end: {join.blocked[0].reason}
+ </small>
+ {/if}
+ </p>
+ {/each}
+ {/if}
+
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ {#if !plan}
+ <button class="btn btn-primary" disabled={!ready || planning} onclick={look}>
+ {planning ? 'Reading…' : 'Preview'}
+ </button>
+ {:else}
+ <button class="btn" disabled={planning} onclick={look}>Preview again</button>
+ <button class="btn btn-primary" disabled={busy || !willWrite}
+ onclick={() => onpass(declaration())}>
+ {busy ? 'Sending' : `Send ${willWrite}`}
+ </button>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .to-case { display: flex; flex-direction: column; min-height: 0; }
+ .lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .lead strong { color: var(--text-1); }
+ .label { color: var(--text-3); font-size: var(--fs-xs); margin: 12px 0 5px; line-height: 1.5; }
+ .note { color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5; padding: 4px 0; }
+ /* What is still missing, apart from what merely happens: one of the two stands between
+ the analyst and the button. */
+ .short { color: var(--anno-6); }
+
+ .columns { max-height: 210px; overflow: auto; }
+ .column {
+ display: grid; grid-template-columns: minmax(0, 1fr) 165px 150px;
+ align-items: center; gap: 8px; padding: 2px 0;
+ }
+ .column .name {
+ color: var(--text-1); font-size: var(--fs-sm);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .filler { display: block; }
+
+ .row {
+ display: grid; grid-template-columns: minmax(0, 1fr) 190px; align-items: center;
+ gap: 8px; padding: 3px 0;
+ }
+ .row span { color: var(--text-2); font-size: var(--fs-sm); }
+ .fields { max-height: 170px; overflow: auto; }
+ .check { display: flex; align-items: center; gap: 7px; padding: 8px 0 2px; }
+ .check span { color: var(--text-2); font-size: var(--fs-sm); }
+
+ /* The hours form, kept whole rather than copied: it is one mode of this press. */
+ .nested {
+ border-left: 2px solid var(--border); padding-left: 10px; margin: 2px 0 6px;
+ }
+
+ .joins { display: flex; flex-direction: column; gap: 3px; }
+ .join {
+ display: grid; grid-template-columns: minmax(0, 1fr) 250px; align-items: center; gap: 8px;
+ }
+ .ends {
+ display: inline-flex; align-items: center; gap: 4px;
+ color: var(--text-2); font-size: var(--fs-sm);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .dash { color: var(--text-3); }
+
+ .failed { color: var(--danger); font-size: var(--fs-sm); margin-top: 10px; }
+
+ /* What the press would do, layer by layer: the counts are read first and the list when
+ one of them is surprising. */
+ .layer { margin-top: 12px; }
+ .layer-head {
+ display: flex; align-items: center; flex-wrap: wrap; gap: 10px;
+ color: var(--text-3); font-size: var(--fs-xs); margin-bottom: 4px;
+ }
+ .layer-head em { color: var(--text-2); font-style: normal; }
+ .tally-part { color: var(--text-3); }
+ .tally-part strong { color: var(--text-1); font-weight: 600; }
+ .tally-part.error, .tally-part.error strong { color: var(--danger); }
+ .plan {
+ max-height: 200px; overflow: auto;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .plan-row {
+ display: flex; align-items: center; gap: 8px; padding: 4px 7px;
+ border-bottom: 1px solid var(--border); font-size: var(--fs-xs);
+ }
+ .plan-row:last-child { border-bottom: 0; }
+ .mark {
+ flex: none; width: 74px; color: var(--text-3);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .plan-row.make .mark { color: var(--ok); }
+ .plan-row.join .mark, .plan-row.update .mark { color: var(--accent); }
+ .plan-row.error .mark { color: var(--danger); }
+ .who { color: var(--text-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .why { color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .why.warn { color: var(--anno-6); }
+ .when { color: var(--text-2); white-space: nowrap; }
+ .join-plan {
+ display: flex; align-items: center; gap: 8px; padding: 3px 0;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .join-plan strong { color: var(--text-1); }
+ .spacer { flex: 1; }
+ .tiny { max-width: 190px; font-size: var(--fs-xs); padding: 1px 4px; }
+ .undo { flex: none; color: var(--text-3); font-size: var(--fs-xs); }
+ .undo:hover { color: var(--accent); text-decoration: underline; }
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 16px; }
+</style>
diff --git a/frontend/src/components/SourceDialog.render.test.js b/frontend/src/components/SourceDialog.render.test.js
new file mode 100644
index 0000000..3f92e54
--- /dev/null
+++ b/frontend/src/components/SourceDialog.render.test.js
@@ -0,0 +1,88 @@
+// @vitest-environment happy-dom
+/**
+ * The dialog that asks where a batch came from, actually mounted.
+ *
+ * What matters here is what it will and will not let through: an import may state
+ * nothing (most drops are the analyst's own working files), a correction must
+ * state something, and neither takes an address that is not one.
+ */
+import { describe, expect, it, afterEach, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: SourceDialog } = await import('./SourceDialog.svelte');
+
+let live = null;
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(SourceDialog, { target, props });
+ flushSync();
+ return document.body;
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+const field = (root) => root.querySelector('#import-source');
+const confirm = (root) => [...root.querySelectorAll('button')].at(-1);
+
+function type(root, value) {
+ const input = field(root);
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+describe('on the way in', () => {
+ it('counts the files it is about to file', () => {
+ const root = open({ count: 3 });
+ expect(root.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe('Import 3 files');
+ });
+
+ it('lets a batch through with no origin stated, and says so on the button', () => {
+ const onconfirm = vi.fn();
+ const root = open({ count: 2, onconfirm });
+ expect(confirm(root).disabled).toBe(false);
+ expect(confirm(root).textContent.trim()).toBe('Import without a source');
+ confirm(root).click();
+ expect(onconfirm).toHaveBeenCalledWith('');
+ });
+
+ it('hands back the trimmed address', () => {
+ const onconfirm = vi.fn();
+ const root = open({ count: 1, onconfirm });
+ type(root, ' https://t.me/channel/42 ');
+ expect(confirm(root).textContent.trim()).toBe('Import');
+ confirm(root).click();
+ expect(onconfirm).toHaveBeenCalledWith('https://t.me/channel/42');
+ });
+
+ it('refuses what is not an address, before the server has to', () => {
+ const root = open({ count: 1 });
+ type(root, 'a friend sent it');
+ expect(root.textContent).toContain('The source must be an http(s) address.');
+ expect(confirm(root).disabled).toBe(true);
+ });
+});
+
+describe('afterwards', () => {
+ it('is titled for the batch it corrects and needs an answer', () => {
+ const root = open({ mode: 'state', count: 4 });
+ expect(root.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
+ 'Source of 4 files'
+ );
+ // nothing to save: this dialog was opened to state one
+ expect(confirm(root).disabled).toBe(true);
+ type(root, 'https://example.org/post/7');
+ expect(confirm(root).disabled).toBe(false);
+ });
+
+ it('opens on the last source stated this session', () => {
+ const root = open({ mode: 'state', count: 1, value: 'https://example.org/thread' });
+ expect(field(root).value).toBe('https://example.org/thread');
+ });
+});
diff --git a/frontend/src/components/SourceDialog.svelte b/frontend/src/components/SourceDialog.svelte
new file mode 100644
index 0000000..615abd4
--- /dev/null
+++ b/frontend/src/components/SourceDialog.svelte
@@ -0,0 +1,85 @@
+<script>
+ /**
+ * Where a batch of imported files came from.
+ *
+ * One dialog for the two moments it can be said: on the way in, and after the
+ * files have landed and the analyst remembers. Same field, same words, same
+ * rule — a second dialog for the second moment would be a second vocabulary.
+ *
+ * Stating nothing is a real answer on the way in: most imports are the
+ * analyst's own working files, and a dialog that refused to close without an
+ * address would be a tax on every drop.
+ */
+ import { sourceProblem } from '../lib/statedSource.js';
+ import Modal from './Modal.svelte';
+
+ let {
+ /** How many files the answer covers. */
+ count = 1,
+ /** `import` on the way in, `state` for files already in the case. */
+ mode = 'import',
+ /** Prefill: the last source stated this session, or what the file carries. */
+ value = '',
+ busy = false,
+ onconfirm = () => {},
+ onclose = () => {},
+ } = $props();
+
+ // svelte-ignore state_referenced_locally
+ let url = $state(value);
+ const problem = $derived(sourceProblem(url));
+ const files = $derived(`${count} file${count > 1 ? 's' : ''}`);
+</script>
+
+<Modal
+ title={mode === 'import' ? `Import ${files}` : `Source of ${files}`}
+ {onclose}
+ width="520px"
+>
+ <label class="modal-label" for="import-source">Source URL</label>
+ <!-- svelte-ignore a11y_autofocus -->
+ <input
+ id="import-source"
+ class="input"
+ placeholder="https://…"
+ autofocus
+ bind:value={url}
+ onkeydown={(e) => e.key === 'Enter' && !problem && !busy && onconfirm(url.trim())}
+ />
+ <p class="field-help">
+ Optional. Where the {count > 1 ? 'files' : 'file'} came from, when you fetched
+ {count > 1 ? 'them' : 'it'} yourself. Recorded as stated, not as fetched.
+ </p>
+
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ {#if problem}<span class="problem">{problem}</span>{/if}
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button
+ class="btn btn-primary"
+ onclick={() => onconfirm(url.trim())}
+ disabled={busy || Boolean(problem) || (mode === 'state' && !url.trim())}
+ >
+ {#if busy}
+ {mode === 'import' ? 'Importing…' : 'Saving…'}
+ {:else if mode === 'import'}
+ {url.trim() ? 'Import' : 'Import without a source'}
+ {:else}
+ Save
+ {/if}
+ </button>
+ </div>
+</Modal>
+
+<style>
+ .field-help {
+ margin: 5px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .problem {
+ align-self: center;
+ color: var(--warn);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/components/details.fixture.svelte.js b/frontend/src/components/details.fixture.svelte.js
index faf2c97..8bfe189 100644
--- a/frontend/src/components/details.fixture.svelte.js
+++ b/frontend/src/components/details.fixture.svelte.js
@@ -7,6 +7,8 @@
* factory runs inside the `.test.js`, so the reactive fixtures live here and the
* test hands this module back as the mock.
*/
+import { formatCoords } from '../lib/coords.js';
+
export const entity = $state({
id: 'e1',
type: 'place',
@@ -20,5 +22,23 @@ export const caseState = $state({
rev: 0,
});
+/** What `/media/item` answers with, for the tests that make `entity` a media.
+ * Reactive too: the Source field is gated on how the file entered the case, and
+ * a test flips that between an import and a download. */
+export const mediaItem = $state({
+ path: 'media/shot.png',
+ filename: 'shot.png',
+ title: 'shot',
+ kind: 'image',
+ size: 1024,
+ sha256: 'a'.repeat(64),
+ source: { type: 'upload', original_name: 'shot.png' },
+});
+
export const reloadCase = () => Promise.resolve();
export const toast = () => {};
+
+/** The panel's one entry point for writing a pair. The real one renders in the
+ * format the analyst chose; this fixture carries no settings, so it renders the
+ * decimal degrees an unset preference gives. */
+export const fmtCoords = (lat, lon) => formatCoords(lat, lon);
diff --git a/frontend/src/components/views.fixture.svelte.js b/frontend/src/components/views.fixture.svelte.js
new file mode 100644
index 0000000..4c4d031
--- /dev/null
+++ b/frontend/src/components/views.fixture.svelte.js
@@ -0,0 +1,11 @@
+/**
+ * Reactive stand-in for `AnalysisViews.render.test.js`.
+ *
+ * The menu reads its case out of an effect, so a plain object would never make it
+ * re-run. 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 caseState = $state({
+ current: { id: 'case-a', name: 'Renaming' },
+ rev: 0,
+});
diff --git a/frontend/src/lib/analysisSearch.svelte.js b/frontend/src/lib/analysisSearch.svelte.js
index f4ecf42..befe63c 100644
--- a/frontend/src/lib/analysisSearch.svelte.js
+++ b/frontend/src/lib/analysisSearch.svelte.js
@@ -117,6 +117,20 @@ export function adoptSavedAnalysisView(caseId, view) {
return true;
}
+/** Carry a rename onto the reading a surface is holding.
+ *
+ * The label has to land here as well as in the menu: an autosave sends the name it
+ * is holding, so a live view left on the old one would write it straight back. */
+export function renameAnalysisView(caseId, viewId, name) {
+ if (analysisSearch.caseId !== caseId) return false;
+ const slot = [analysisSearch.catalog, analysisSearch.timeline].find(
+ (candidate) => candidate.activeView?.id === viewId
+ );
+ if (!slot) return false;
+ slot.activeView = { ...slot.activeView, name };
+ return true;
+}
+
/** Leave the named reading of one family. The catalog question can stay on screen
* or be dropped with it. */
export function leaveAnalysisView(caseId, surface, { clear = false } = {}) {
diff --git a/frontend/src/lib/analysisSearch.test.js b/frontend/src/lib/analysisSearch.test.js
index 6e18b19..a05ce76 100644
--- a/frontend/src/lib/analysisSearch.test.js
+++ b/frontend/src/lib/analysisSearch.test.js
@@ -6,6 +6,7 @@ import {
catalogViews,
leaveAnalysisView,
openAnalysisCase,
+ renameAnalysisView,
setAnalysisFilter,
setAnalysisPeriod,
timelineViews,
@@ -157,6 +158,24 @@ describe('the two families of saved views', () => {
expect(catalogViews.activeView).toBeNull();
});
+ it('carries a rename onto the open reading, spec and family untouched', () => {
+ const spec = { timeline: { tracks: [] } };
+ activateAnalysisView('case-a', {
+ id: 'v_time', name: 'Tracks', mode: 'live', surface: 'timeline', spec,
+ });
+
+ expect(renameAnalysisView('case-a', 'v_time', 'Convoy tracks')).toBe(true);
+ expect(timelineViews.activeView.name).toBe('Convoy tracks');
+ // The autosave sends the name it is holding, so an unrenamed spec would be
+ // written back with the old label — the recipe itself stays the same object.
+ expect(timelineViews.activeView.spec).toBe(spec);
+ expect(catalogViews.activeView).toBeNull();
+
+ expect(renameAnalysisView('case-a', 'v_other', 'Nowhere')).toBe(false);
+ expect(renameAnalysisView('case-b', 'v_time', 'Wrong case')).toBe(false);
+ expect(timelineViews.activeView.name).toBe('Convoy tracks');
+ });
+
it('empties both families at the case boundary', () => {
activateAnalysisView('case-a', { id: 'v_board', mode: 'live', surface: 'board', spec: {} });
activateAnalysisView('case-a', { id: 'v_time', mode: 'live', surface: 'timeline', spec: {} });
diff --git a/frontend/src/lib/analysisViews.js b/frontend/src/lib/analysisViews.js
index 6ab0d39..ffbbde9 100644
--- a/frontend/src/lib/analysisViews.js
+++ b/frontend/src/lib/analysisViews.js
@@ -1,3 +1,7 @@
+/** Naming, ordering and dating the saved readings a Views menu lists. */
+
+const ORDER_KEY = 'azimut:view-order';
+
export function copyName(name, existing = []) {
const used = new Set(existing.map((value) => String(value).trim().toLocaleLowerCase()));
const base = `${String(name).trim()} copy`;
@@ -6,3 +10,94 @@ export function copyName(name, existing = []) {
while (used.has(`${base} ${index}`.toLocaleLowerCase())) index += 1;
return `${base} ${index}`;
}
+
+/**
+ * The orderings a menu offers. `recent` leads because it is the order the case
+ * itself wrote, and the reading being worked on is the one just saved.
+ *
+ * `surface` is offered to the catalog family only: the Timeline's own list holds
+ * one surface, so sorting it by surface would move nothing.
+ */
+export const VIEW_ORDERS = [
+ { id: 'recent', label: 'Recently updated', families: ['catalog', 'timeline'] },
+ { id: 'name', label: 'Name A→Z', families: ['catalog', 'timeline'] },
+ { id: 'surface', label: 'Surface', families: ['catalog'] },
+];
+
+export function viewOrders(family) {
+ return VIEW_ORDERS.filter((order) => order.families.includes(family));
+}
+
+export function normalizeViewOrder(value, family = 'catalog') {
+ return viewOrders(family).some((order) => order.id === value) ? value : 'recent';
+}
+
+const byName = (a, b) =>
+ String(a.name ?? '').localeCompare(String(b.name ?? ''), undefined, { sensitivity: 'base' });
+
+/** Order a list of view summaries. Pure: the caller keeps its own array. */
+export function sortViews(views, order = 'recent') {
+ const rows = [...(views ?? [])];
+ if (order === 'name') return rows.sort(byName);
+ if (order === 'surface') {
+ return rows.sort(
+ (a, b) => String(a.surface ?? '').localeCompare(String(b.surface ?? '')) || byName(a, b)
+ );
+ }
+ // Newest edit first, and a name breaks the tie so two views saved in the same
+ // second do not swap places between reads.
+ return rows.sort(
+ (a, b) => String(b.updated_at ?? '').localeCompare(String(a.updated_at ?? '')) || byName(a, b)
+ );
+}
+
+/** The chosen ordering, per family. A missing or unavailable store is not fatal. */
+export function readViewOrder(family) {
+ try {
+ return normalizeViewOrder(localStorage.getItem(`${ORDER_KEY}:${family}`), family);
+ } catch {
+ return 'recent'; // localStorage unavailable (private mode) — non-fatal
+ }
+}
+
+export function writeViewOrder(family, order) {
+ try {
+ localStorage.setItem(`${ORDER_KEY}:${family}`, normalizeViewOrder(order, family));
+ } catch {
+ /* localStorage unavailable (private mode) — non-fatal */
+ }
+}
+
+const MONTHS = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
+];
+
+const pad = (value) => String(value).padStart(2, '0');
+
+/** The exact UTC minute a row was last written, for the row's tooltip. */
+export function exactStamp(iso) {
+ const at = new Date(String(iso ?? ''));
+ if (Number.isNaN(at.getTime())) return String(iso ?? '');
+ return (
+ `${at.getUTCFullYear()}-${pad(at.getUTCMonth() + 1)}-${pad(at.getUTCDate())}` +
+ ` ${pad(at.getUTCHours())}:${pad(at.getUTCMinutes())} UTC`
+ );
+}
+
+/**
+ * How long ago, in the terse register the rest of the app reads in. Past a week the
+ * distance stops meaning anything to an analyst, so the date itself is shown.
+ */
+export function timeAgo(iso, now = Date.now()) {
+ const at = new Date(String(iso ?? ''));
+ if (Number.isNaN(at.getTime())) return '';
+ const seconds = Math.round((now - at.getTime()) / 1000);
+ if (seconds < 60) return 'just now';
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes} min ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours} h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 7) return `${days} d ago`;
+ return `${at.getUTCDate()} ${MONTHS[at.getUTCMonth()]} ${at.getUTCFullYear()}`;
+}
diff --git a/frontend/src/lib/analysisViews.test.js b/frontend/src/lib/analysisViews.test.js
index c329c6a..0237bd9 100644
--- a/frontend/src/lib/analysisViews.test.js
+++ b/frontend/src/lib/analysisViews.test.js
@@ -1,8 +1,121 @@
-import { describe, expect, it } from 'vitest';
-import { copyName } from './analysisViews.js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ copyName,
+ exactStamp,
+ normalizeViewOrder,
+ readViewOrder,
+ sortViews,
+ timeAgo,
+ viewOrders,
+ writeViewOrder,
+} from './analysisViews.js';
+
+function storage() {
+ const values = new Map();
+ return {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ };
+}
+
+const rows = [
+ { id: 'v1', name: 'ports', surface: 'graph', updated_at: '2026-08-02T09:00:00Z' },
+ { id: 'v2', name: 'Ammunition', surface: 'board', updated_at: '2026-08-11T18:30:00Z' },
+ { id: 'v3', name: 'Bridges', surface: 'board', updated_at: '2026-08-11T18:30:00Z' },
+];
describe('analysis view names', () => {
it('finds an unused duplicate name without a failing save first', () => {
expect(copyName('Ports', ['Ports', 'Ports copy', 'Ports copy 2'])).toBe('Ports copy 3');
});
});
+
+describe('ordering a views menu', () => {
+ it('leaves the caller its own array', () => {
+ const order = rows.map((row) => row.id);
+ sortViews(rows, 'name');
+ expect(rows.map((row) => row.id)).toEqual(order);
+ });
+
+ it('reads newest edit first, with the name breaking a tied second', () => {
+ expect(sortViews(rows, 'recent').map((row) => row.id)).toEqual(['v2', 'v3', 'v1']);
+ });
+
+ it('sorts by name without letting case decide the order', () => {
+ expect(sortViews(rows, 'name').map((row) => row.id)).toEqual(['v2', 'v3', 'v1']);
+ expect(sortViews([{ name: 'b' }, { name: 'A' }], 'name').map((row) => row.name))
+ .toEqual(['A', 'b']);
+ });
+
+ it('groups by surface, then by name inside it', () => {
+ expect(sortViews(rows, 'surface').map((row) => row.id)).toEqual(['v2', 'v3', 'v1']);
+ expect(sortViews([
+ { name: 'Zulu', surface: 'board' },
+ { name: 'Alpha', surface: 'graph' },
+ ], 'surface').map((row) => row.name)).toEqual(['Zulu', 'Alpha']);
+ });
+
+ it('falls back to the order the case wrote when asked for nonsense', () => {
+ expect(sortViews(rows, 'whatever').map((row) => row.id)).toEqual(['v2', 'v3', 'v1']);
+ expect(sortViews(null)).toEqual([]);
+ });
+
+ it('offers Surface only where a family holds more than one', () => {
+ expect(viewOrders('catalog').map((order) => order.id)).toEqual(['recent', 'name', 'surface']);
+ expect(viewOrders('timeline').map((order) => order.id)).toEqual(['recent', 'name']);
+ expect(normalizeViewOrder('surface', 'timeline')).toBe('recent');
+ expect(normalizeViewOrder('surface', 'catalog')).toBe('surface');
+ });
+});
+
+describe('remembering the chosen ordering', () => {
+ beforeEach(() => vi.stubGlobal('localStorage', storage()));
+
+ it('keeps one choice per family', () => {
+ writeViewOrder('catalog', 'name');
+ writeViewOrder('timeline', 'recent');
+ expect(readViewOrder('catalog')).toBe('name');
+ expect(readViewOrder('timeline')).toBe('recent');
+ });
+
+ it('refuses to remember an ordering its family cannot offer', () => {
+ writeViewOrder('timeline', 'surface');
+ expect(readViewOrder('timeline')).toBe('recent');
+ });
+
+ it('survives a store that is not there', () => {
+ vi.stubGlobal('localStorage', {
+ getItem: () => { throw new Error('denied'); },
+ setItem: () => { throw new Error('denied'); },
+ });
+ expect(readViewOrder('catalog')).toBe('recent');
+ expect(() => writeViewOrder('catalog', 'name')).not.toThrow();
+ });
+});
+
+describe('dating a saved reading', () => {
+ const now = Date.parse('2026-08-13T12:00:00Z');
+
+ it('reads the distance in the register the rest of the app uses', () => {
+ expect(timeAgo('2026-08-13T11:59:30Z', now)).toBe('just now');
+ expect(timeAgo('2026-08-13T11:20:00Z', now)).toBe('40 min ago');
+ expect(timeAgo('2026-08-13T04:00:00Z', now)).toBe('8 h ago');
+ expect(timeAgo('2026-08-11T12:00:00Z', now)).toBe('2 d ago');
+ });
+
+ it('states the date once the distance stops meaning anything', () => {
+ expect(timeAgo('2026-08-01T12:00:00Z', now)).toBe('1 Aug 2026');
+ expect(timeAgo('2025-12-24T23:00:00Z', now)).toBe('24 Dec 2025');
+ });
+
+ it('says nothing about a stamp it cannot read', () => {
+ expect(timeAgo('', now)).toBe('');
+ expect(timeAgo('not a date', now)).toBe('');
+ expect(exactStamp('not a date')).toBe('not a date');
+ });
+
+ it('spells the exact minute in UTC, whatever the machine reads in', () => {
+ expect(exactStamp('2026-08-11T18:30:12Z')).toBe('2026-08-11 18:30 UTC');
+ });
+});
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index 04a832c..b44d9f8 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -1,8 +1,29 @@
/** Thin fetch wrapper for the local Azimut API. */
+/**
+ * Read a FastAPI error body into one line.
+ *
+ * A refused request answers with a string; a body the schema rejected answers
+ * with the validator's list of objects, and handing that straight to `Error`
+ * stringified every validation failure in the app as "[object Object]".
+ */
+function detailLine(detail) {
+ if (typeof detail === 'string') return detail;
+ if (!Array.isArray(detail)) return '';
+ return detail
+ .map((item) => {
+ if (typeof item === 'string') return item;
+ const field = Array.isArray(item?.loc) ? item.loc.filter((p) => p !== 'body').join('.') : '';
+ const message = item?.msg ?? '';
+ return field && message ? `${field}: ${message}` : message || field;
+ })
+ .filter(Boolean)
+ .join('; ');
+}
+
class ApiError extends Error {
constructor(status, detail) {
- super(detail || `HTTP ${status}`);
+ super(detailLine(detail) || `HTTP ${status}`);
this.status = status;
}
}
diff --git a/frontend/src/lib/api.test.js b/frontend/src/lib/api.test.js
new file mode 100644
index 0000000..60d80cf
--- /dev/null
+++ b/frontend/src/lib/api.test.js
@@ -0,0 +1,60 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { ApiError, api } from './api.js';
+
+function answers(status, body) {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue({
+ ok: status < 400,
+ status,
+ json: async () => body,
+ })
+ );
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('API errors', () => {
+ it('reads a refusal the backend wrote as a sentence', async () => {
+ answers(409, { detail: 'a case named “Rooftop” already exists' });
+ await expect(api.get('/api/cases')).rejects.toThrow('a case named “Rooftop” already exists');
+ });
+
+ it('reads a schema rejection, which arrives as the validator’s list of objects', async () => {
+ // FastAPI answers 422 with `detail` as an array. Handed straight to Error,
+ // every validation failure in the app surfaced as "[object Object]".
+ answers(422, {
+ detail: [
+ { loc: ['body', 'lon'], msg: 'Input should be less than or equal to 180', type: 'less_than_equal' },
+ ],
+ });
+ await expect(api.post('/api/satellite/capture', {})).rejects.toThrow(
+ 'lon: Input should be less than or equal to 180'
+ );
+ });
+
+ it('joins several rejected fields into one line', async () => {
+ answers(422, {
+ detail: [
+ { loc: ['body', 'lat'], msg: 'field required' },
+ { loc: ['body', 'zoom'], msg: 'must be an integer' },
+ ],
+ });
+ await expect(api.post('/api/x', {})).rejects.toThrow('lat: field required; zoom: must be an integer');
+ });
+
+ it('falls back to the status when the body says nothing usable', async () => {
+ answers(500, { detail: [] });
+ await expect(api.get('/api/x')).rejects.toThrow('HTTP 500');
+ });
+
+ it('carries the status for callers that branch on it', async () => {
+ answers(404, { detail: 'case not found' });
+ await expect(api.get('/api/cases/nope')).rejects.toMatchObject({
+ status: 404,
+ constructor: ApiError,
+ });
+ });
+});
diff --git a/frontend/src/lib/clipboardPaste.js b/frontend/src/lib/clipboardPaste.js
index 2620715..dd97002 100644
--- a/frontend/src/lib/clipboardPaste.js
+++ b/frontend/src/lib/clipboardPaste.js
@@ -13,9 +13,9 @@
* four tools, because scattered copy becomes four vocabularies inside a week.
*/
import { api } from './api.js';
+import { isSourceUrl, sourceProblem } from './statedSource.js';
const IMAGE_TYPE = /^image\//i;
-const HTTP_URL = /^https?:\/\/\S+$/i;
/** The API's own cap on a swallowed image (api/limits.py), said here so the
* refusal names the limit instead of waiting for a 413. */
@@ -31,7 +31,7 @@ export const MAX_PASTE_IMAGE_BYTES = 25 * 1024 * 1024;
export function sourceFromHtml(html) {
const match = /<img\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(html ?? '');
const url = (match?.[1] ?? match?.[2] ?? '').trim();
- return HTTP_URL.test(url) ? url : '';
+ return isSourceUrl(url) ? url : '';
}
function imageFrom(clipboardData) {
@@ -58,9 +58,9 @@ export function readPaste(clipboardData) {
const file = imageFrom(clipboardData);
if (file) {
const fromMarkup = sourceFromHtml(clipboardData.getData?.('text/html') ?? '');
- return { kind: 'image', file, sourceUrl: fromMarkup || (HTTP_URL.test(text) ? text : '') };
+ return { kind: 'image', file, sourceUrl: fromMarkup || (isSourceUrl(text) ? text : '') };
}
- if (HTTP_URL.test(text)) return { kind: 'url', url: text };
+ if (isSourceUrl(text)) return { kind: 'url', url: text };
if (text) return { kind: 'text', text };
return null;
}
@@ -147,9 +147,7 @@ export function resolvePaste(tool, payload, { folder = '' } = {}) {
export function pasteProblem(resolved) {
const values = resolved?.values ?? {};
if (resolved?.kind === 'url' && !(values.title ?? '').trim()) return 'A bookmark needs a title.';
- const source = (values.source ?? '').trim();
- if (source && !HTTP_URL.test(source)) return 'The source must be an http(s) address.';
- return '';
+ return sourceProblem(values.source);
}
/**
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index b44ac45..e9aff7d 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -184,9 +184,11 @@ export function legendLineHeight(legendSize = LEGEND_SIZE) {
return Math.round(legendSize + 13);
}
-/** Height of the footer band for a given footer font size. */
-export function footerBand(footerSize = FOOTER_SIZE) {
- return Math.round(footerSize + 13);
+/** Height of the footer band for a given footer font size and line count.
+ * One line is the attribution; the coordinates, when the proof prints them,
+ * add their own above it. */
+export function footerBand(footerSize = FOOTER_SIZE, lines = 1) {
+ return Math.round(footerSize + 13) * Math.max(1, lines);
}
// Default band heights, derived from the size defaults so they can't drift out
@@ -475,22 +477,223 @@ export function autoSourceUrls(panels) {
return [...set];
}
+//: What joins several addresses into the block a post and a report read. A line each:
+//: they are addresses, and a reader scanning four of them down a column reads them where
+//: four strung along one line with a dot between is a wall to pick apart.
+export const SOURCE_SEPARATOR = '\n';
+
+//: One http(s) address and nothing else.
+const ADDRESS = /^https?:\/\/\S+$/i;
+
+/**
+ * The addresses a proof states for itself, as a list.
+ *
+ * An array is the shape a proof carries now. A string is what one saved before this
+ * carried, and it splits back into its parts only when every part is an address —
+ * the line the composer wrote itself. Anything else is one thing the analyst typed,
+ * and it stays one entry rather than being cut at its spaces.
+ */
+export function normalizeSources(value) {
+ let list;
+ if (Array.isArray(value)) {
+ list = value;
+ } else {
+ const text = String(value ?? '').trim();
+ const parts = text ? text.split(/\s*·\s*|\s+/) : [];
+ list = parts.every((part) => ADDRESS.test(part)) ? parts : [text];
+ }
+ return [...new Set(list.map((one) => String(one ?? '').trim()).filter(Boolean))];
+}
+
+/**
+ * The addresses a proof states, or `null` when it states none of its own.
+ *
+ * The distinction is the whole point: **an empty list is an answer**. A proof whose
+ * source boxes have all been emptied says it has no public source — the footage was
+ * handed over privately, and saying so is not the same as never having said anything.
+ * Falling back to the panels there put addresses back on a proof somebody had just
+ * taken them off, and carried them into the post behind their back.
+ *
+ * `null`/absent, or the empty string a proof saved before this carried, is "nothing
+ * stated" and the panels answer for it.
+ */
+export function statedSources(value) {
+ if (value === null || value === undefined) return null;
+ if (typeof value === 'string') return value.trim() ? normalizeSources(value) : null;
+ return Array.isArray(value) ? normalizeSources(value) : null;
+}
+
+/**
+ * Case files a proof rests on, each with the address that brought it in.
+ *
+ * The address is what makes the list reconcilable: taking a source off the proof has to
+ * take what that source brought with it, and a bare path cannot say which row it came
+ * from. A proof saved before this carried bare paths, and they read as material nothing
+ * named — kept, since the list cannot disown what it cannot name.
+ */
+export function normalizeMaterial(value) {
+ const seen = new Set();
+ const held = [];
+ for (const one of Array.isArray(value) ? value : []) {
+ const path = String((typeof one === 'string' ? one : one?.path) ?? '').trim();
+ if (!path || seen.has(path)) continue;
+ seen.add(path);
+ held.push({ path, url: String(one?.url ?? '').trim() });
+ }
+ return held;
+}
+
+/** The material still answered for by one of the addresses the proof states. */
+export function statedMaterial(material, sources) {
+ const stated = new Set(sources);
+ return normalizeMaterial(material).filter((one) => !one.url || stated.has(one.url));
+}
+
/** Auto source line: distinct panel source links joined, or '' when none. */
export function autoSource(panels) {
- return autoSourceUrls(panels).join(' · ');
+ return autoSourceUrls(panels).join(SOURCE_SEPARATOR);
+}
+
+/** How many points one proof may state. Mirrors `satellite.MAX_PROOF_POINTS`:
+ * past fifteen a proof is a case, and the panel is a wall rather than a reading. */
+export const MAX_POINTS = 15;
+
+/** True when the single-point field says something the list does not.
+ *
+ * The two are written together and never drift (`statePoints`), so a disagreement
+ * means the field was set by something that does not know the list — an older
+ * build, a route stating one point. What it says is the newer answer.
+ * Mirrors `engine/satellite._mirror_broken`. */
+function mirrorBroken(p, entries) {
+ if (!('coordsText' in (p ?? {}))) return false;
+ const first = entries[0] && typeof entries[0] === 'object' ? entries[0] : {};
+ return String(p.coordsText ?? '').trim() !== String(first.coords ?? '').trim();
}
-/** Effective coordinates text for a proof/spec: manual override else auto. */
+/**
+ * The points a proof states, its conclusion first — `{coords, label, pov}` each,
+ * with `coords` still the text the analyst typed.
+ *
+ * A proof shows more than one place more often than it shows one: three impacts,
+ * a building, the camera that filmed it. The first is the conclusion — the map
+ * mark, the coordinate a post cites — and `pov` rides on the point that carries
+ * it, at most one, because a camera stood in one place.
+ *
+ * A spec written before the list reads as the one point it holds, so nothing
+ * migrates. Mirrors `engine/satellite.spec_points`, minus the parsing: the
+ * server reads the text, this side only carries it.
+ */
+export function specPoints(p) {
+ const entries = Array.isArray(p?.points) ? p.points : null;
+ const stated = entries && !mirrorBroken(p, entries)
+ ? entries
+ .filter((one) => one && typeof one === 'object')
+ .map((one) => ({
+ coords: String(one.coords ?? '').trim(),
+ label: String(one.label ?? '').trim(),
+ pov: one.pov === true,
+ }))
+ .filter((one) => one.coords)
+ : [];
+ const points = stated.length
+ ? stated
+ : (String(p?.coordsText ?? '').trim()
+ ? [{ coords: String(p.coordsText).trim(), label: '', pov: p?.pov === true }]
+ : []);
+ let taken = false;
+ return points.map((one) => {
+ const pov = one.pov && !taken;
+ taken = taken || pov;
+ return { ...one, pov };
+ });
+}
+
+/**
+ * Write what a proof states onto a spec: the list, and the mirror of it.
+ *
+ * The mirror is not a leftover. A case bundle travels between installations and
+ * the binaries are versioned, so a build older than the list has to find the
+ * conclusion where it has always been rather than open a proof with no point.
+ * Mirrors `engine/satellite.state_points`.
+ */
+export function statePoints(spec, points) {
+ const stated = (points ?? [])
+ .map((one) => ({
+ coords: String(one?.coords ?? '').trim(),
+ label: String(one?.label ?? '').trim(),
+ pov: one?.pov === true,
+ }))
+ .filter((one) => one.coords)
+ .map((one) => ({
+ coords: one.coords,
+ ...(one.label ? { label: one.label } : {}),
+ ...(one.pov ? { pov: true } : {}),
+ }));
+ spec.points = stated;
+ spec.coordsText = stated[0]?.coords ?? '';
+ spec.pov = stated[0]?.pov === true;
+ return spec;
+}
+
+/** Effective coordinates text for a proof/spec: what it concludes on, else auto. */
export function proofCoordsText(p, format = 'dd') {
- const manual = p.coordsText?.trim();
- if (manual) return manual;
+ const stated = specPoints(p)[0]?.coords;
+ if (stated) return stated;
return formatCoords(autoCoords(p.panels ?? []), format);
}
-/** Effective source line for a proof/spec: manual override else auto. */
+/** Every point a proof states, ready to print: `{coords, label}` per line.
+ * Falls back to the one the panels give it, which is what the field shows. */
+export function proofCoordsLines(p, format = 'dd') {
+ const stated = specPoints(p);
+ if (stated.length) return stated.map(({ coords, label }) => ({ coords, label }));
+ const auto = formatCoords(autoCoords(p.panels ?? []), format);
+ return auto ? [{ coords: auto, label: '' }] : [];
+}
+
+/** The coordinates as the plate prints them, one string per line.
+ *
+ * Unnamed points share a line: three impacts nobody named are three numbers, and
+ * giving each its own line grows the picture for nothing. A point the analyst
+ * named earns its line, because the name is what they wanted read. */
+export function coordsPlateLines(lines) {
+ const bare = (lines ?? []).filter((one) => !one.label).map((one) => one.coords);
+ const named = (lines ?? [])
+ .filter((one) => one.label)
+ .map((one) => `${one.label} — ${one.coords}`);
+ return [...(bare.length ? [bare.join(' · ')] : []), ...named];
+}
+
+/** The coordinates as a post carries them: one per line, named when named.
+ * A tweet has no height to save, so nothing is joined. */
+export function coordsPostLines(lines) {
+ return (lines ?? []).map((one) => (one.label ? `${one.label} — ${one.coords}` : one.coords));
+}
+
+/** Every line the plate's footer prints: the coordinates when asked, then the
+ * credit line unless it was turned off. One source for the height and for the
+ * drawing, so a proof that grew a line cannot be measured as if it had not.
+ *
+ * Empty is a valid answer — a footer switched on with nothing to print takes no
+ * band at all, rather than an empty strip under the panels. */
+export function footerLines(proof, format = 'dd') {
+ const printed = proof?.footerCoords === true
+ ? coordsPlateLines(proofCoordsLines(proof, format))
+ : [];
+ const credit = proof?.footerText === false
+ ? []
+ : [proof?.footer?.trim() || attributionLine(proof?.panels ?? [])];
+ return [...printed, ...credit];
+}
+
+/** 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
+ * source as text. Only editing it is a list.
+ */
export function proofSource(p) {
- const manual = p.source?.trim();
- if (manual) return manual;
+ const stated = statedSources(p.sources ?? p.source ?? null);
+ if (stated) return stated.join(SOURCE_SEPARATOR);
return autoSource(p.panels ?? []);
}
@@ -515,7 +718,7 @@ export function legendRowCount(count, columns) {
export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [], layout = 'grid', space) {
const {
captionSize = CAPTION_SIZE, legendSize = LEGEND_SIZE, footerSize = FOOTER_SIZE,
- footerEnabled = true,
+ footerEnabled = true, footerLines = 1,
} = text;
const { pad } = normSpace(space);
const boxes = layoutPanels(panels, captionSize, layout, space);
@@ -529,7 +732,7 @@ export function docSize(panels, shapes, notes = {}, text = {}, legendOrder = [],
const height =
panelsBottom(panels, captionSize, layout, space) +
(legend.length ? 10 + legendRows * legendLineHeight(legendSize) : 0) +
- (footerEnabled ? footerBand(footerSize) : 0) + pad;
+ (footerEnabled && footerLines > 0 ? footerBand(footerSize, footerLines) : 0) + pad;
return { width: contentW, height, legend, cols };
}
@@ -836,13 +1039,36 @@ export function toSpec(proof) {
// style values, so reopening it can restore the template picker.
templateId: typeof proof.templateId === 'string' ? proof.templateId : null,
coords: autoCoords(proof.panels), // auto geo (first geo panel), for reference
- coordsText: proof.coordsText?.trim() ? proof.coordsText.trim() : null, // null → auto
- // Whether the point is where the camera stood rather than what it filmed.
- // The proof cannot deduce it — a rooftop shot is recorded somewhere it never
- // shows — so the analyst says, and the place filed on save takes the verb
- // from it (engine/satellite.place_for_proof).
- pov: proof.pov === true,
- source: proof.source?.trim() ? proof.source.trim() : null, // null → auto (link only)
+ // The points the proof concludes on, and the mirror of the first for a build
+ // that predates the list. Whether a point is where the camera stood rather
+ // than what it filmed rides on the point itself: the proof cannot deduce it —
+ // a rooftop shot is recorded somewhere it never shows — so the analyst says,
+ // per line, and the place filed on save takes its verb from that line
+ // (engine/satellite.restate_proof_point).
+ ...statePoints({}, proof.points),
+ // What the plate's footer prints. `footer` is the credit line itself;
+ // `footerText` is whether it prints at all, and `footerCoords` whether the
+ // proof's points print above it. Coordinates are off unless asked: they are
+ // the footer lines that change the picture's height.
+ footerCoords: proof.footerCoords === true,
+ footerText: proof.footerText !== false,
+ // The addresses the proof states, empty → traced from the panels instead. Named
+ // for the plural like the multi-parent key of a media's own origin (`sources`,
+ // beside `from`), because it draws the same distinction: one of them, or several.
+ // null → traced from the panels; a list, empty included, → what the analyst states.
+ sources: statedSources(proof.sources ?? proof.source ?? null),
+ // Case files the proof rests on without composing them: the clip a panel was cut
+ // from, the second angle nobody cropped. The save states `derived-from` over these
+ // as well as over the panels, which is what puts them in the chain and, through it,
+ // on the point (`api/proofs.save_proof`).
+ //
+ // Only what a stated address still answers for. A source taken off the proof takes
+ // its files out of the chain with it — otherwise removing a row left the line
+ // shorter and the graph exactly as it was, which is a proof saying two things.
+ material: statedMaterial(
+ proof.material,
+ statedSources(proof.sources ?? proof.source ?? null) ?? autoSourceUrls(proof.panels ?? []),
+ ),
captionSize: proof.captionSize ?? CAPTION_SIZE,
legendSize: proof.legendSize ?? LEGEND_SIZE,
footerSize: proof.footerSize ?? FOOTER_SIZE,
@@ -911,6 +1137,8 @@ export function templateFromProof(proof) {
footerSize: proof.footerSize ?? FOOTER_SIZE,
footer: proof.footer ?? '',
footerEnabled: proof.footerEnabled !== false,
+ footerText: proof.footerText !== false,
+ footerCoords: proof.footerCoords === true,
footerColor: proof.footerColor ?? null,
footerAlign: proof.footerAlign === 'right' ? 'right' : 'left',
captionsEnabled: proof.captionsEnabled !== false,
@@ -949,6 +1177,11 @@ export function normalizeProofStyle(style = {}) {
footerSize: boundedNumber(source.footerSize, FOOTER_SIZE, 8, 80),
footer: typeof source.footer === 'string' ? source.footer.slice(0, 200) : '',
footerEnabled: typeof source.footerEnabled === 'boolean' ? source.footerEnabled : true,
+ // A template saved before these existed says nothing about them, and a style
+ // that says nothing must not change what a proof does: the credit line goes on
+ // printing, the coordinates go on not printing.
+ footerText: typeof source.footerText === 'boolean' ? source.footerText : true,
+ footerCoords: source.footerCoords === true,
footerColor: source.footerColor == null ? null : normalizedColor(source.footerColor, null),
footerAlign: source.footerAlign === 'right' ? 'right' : 'left',
captionsEnabled: typeof source.captionsEnabled === 'boolean' ? source.captionsEnabled : true,
@@ -977,6 +1210,10 @@ export function applyProofStyle(proof, style, available = {}) {
if ('footerSize' in source) proof.footerSize = normalized.footerSize;
if ('footer' in source) proof.footer = normalized.footer;
if ('footerEnabled' in source) proof.footerEnabled = normalized.footerEnabled;
+ // Absent from an older template, so an old house style leaves both alone rather
+ // than quietly taking a proof's coordinates off its plate.
+ if ('footerText' in source) proof.footerText = normalized.footerText;
+ if ('footerCoords' in source) proof.footerCoords = normalized.footerCoords;
if ('footerColor' in source) proof.footerColor = normalized.footerColor;
if ('footerAlign' in source) proof.footerAlign = normalized.footerAlign;
if ('captionsEnabled' in source) proof.captionsEnabled = normalized.captionsEnabled;
diff --git a/frontend/src/lib/composer.test.js b/frontend/src/lib/composer.test.js
index 3fedea4..dad14b0 100644
--- a/frontend/src/lib/composer.test.js
+++ b/frontend/src/lib/composer.test.js
@@ -5,6 +5,7 @@ import {
panelsBlockHeight, panelHeight, captionBand, legendLineHeight, footerBand,
docSize, legendColumns, legendRowCount, toSpec, offsetShape, copyShapeSpec, autoLayoutRows, TWEET_GUIDES,
autoCoords, formatCoords, resolveSourceUrls, autoSource, autoSourceUrls,
+ normalizeSources, statedSources,
proofCoordsText, proofSource, orderedFeatureColors, legendLines,
dedupeBySrc, satPanelInput, mediaPanelInput,
SIG_MARGIN, SIG_SCALE, newSignature, signatureBox, signatureOffset, signaturePairPositions,
@@ -20,6 +21,8 @@ import {
normalizeFrame, newFrame, FRAME_COLOR, FRAME_WIDTH, FRAME_WIDTH_MAX,
newPaste, pasteBoxes, pasteInsertScale, clampPasteScale, clampPaste,
surfaces, surfaceHitTest, PASTE_SCALE_MAX, PASTE_SHARE,
+ specPoints, statePoints, proofCoordsLines, coordsPlateLines, coordsPostLines,
+ footerLines, footerBand,
} from './composer.js';
// natural is [width, height]; PANEL_H drives the per-row scale.
@@ -662,13 +665,95 @@ describe('source — always a link, traced through the derivation chain', () =>
{ meta: { kind: 'media', source_url: 'https://t.me/b/2' } },
];
expect(autoSourceUrls(panels)).toEqual(['https://x.com/a/1', 'https://t.me/b/2']);
- expect(autoSource(panels)).toBe('https://x.com/a/1 · https://t.me/b/2');
+ expect(autoSource(panels)).toBe('https://x.com/a/1\nhttps://t.me/b/2');
});
it('prefers a manual source override over the auto value', () => {
const panels = [{ meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } }];
expect(proofSource({ panels })).toBe('https://x.com/a/1');
- expect(proofSource({ panels, source: ' https://manual ' })).toBe('https://manual');
+ expect(proofSource({ panels, sources: [' https://manual '] })).toBe('https://manual');
+ });
+
+ it('states every address it was given, on one line', () => {
+ // A proof read from a thread rests on the post, the photos beside it and the clip
+ // under those. The line stays a line: a plate, a post and a report read text.
+ expect(proofSource({ sources: ['https://x.com/a/1', 'https://x.com/a/2'] }))
+ .toBe('https://x.com/a/1\nhttps://x.com/a/2');
+ // Blanks left by an abandoned row, and an address stated twice, are not sources.
+ expect(proofSource({ sources: ['https://x.com/a/1', ' ', 'https://x.com/a/1'] }))
+ .toBe('https://x.com/a/1');
+ });
+
+ it('takes an emptied list as an answer, not as a blank to fill in', () => {
+ // Emptying every box says the proof has no public source — the footage was handed
+ // over privately, and that is not the same as never having said anything. Falling
+ // back to the panels there put addresses back on a proof somebody had just taken
+ // them off, and carried them into the post behind their back.
+ const panels = [{ meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } }];
+ expect(proofSource({ panels, sources: [] })).toBe('');
+ expect(proofSource({ panels, sources: [''] })).toBe(''); // a box cleared of its text
+ expect(proofSource({ panels, sources: null })).toBe('https://x.com/a/1');
+ expect(proofSource({ panels })).toBe('https://x.com/a/1');
+ // And a proof saved before any of this carried '' for "nothing stated".
+ expect(proofSource({ panels, source: '' })).toBe('https://x.com/a/1');
+ expect(statedSources([])).toEqual([]);
+ expect(statedSources(null)).toBeNull();
+ expect(statedSources('')).toBeNull();
+ });
+
+ it('reads a proof saved before the list as a list', () => {
+ // The line the composer wrote itself splits back into its parts...
+ expect(normalizeSources('https://x.com/a/1 · https://t.me/b/2'))
+ .toEqual(['https://x.com/a/1', 'https://t.me/b/2']);
+ // ...and anything else the analyst typed is one thing, not one per space.
+ expect(normalizeSources('sent by private message')).toEqual(['sent by private message']);
+ expect(normalizeSources('')).toEqual([]);
+ expect(normalizeSources(null)).toEqual([]);
+ });
+});
+
+describe('material — what a proof rests on without composing it', () => {
+ it('lets a source go and takes its files with it', () => {
+ // Removing a row left the line shorter and the graph exactly as it was, so the
+ // proof said two things: its source list named two posts and its chain named three
+ // files. The address on each file is what makes the list reconcilable at all.
+ const proof = {
+ title: 'T', panels: [], shapes: [],
+ sources: ['https://x.com/a/1', 'https://t.me/b/2'],
+ material: [
+ { path: 'media/clip.mp4', url: 'https://x.com/a/1' },
+ { path: 'media/angle.jpg', url: 'https://t.me/b/2' },
+ ],
+ };
+ expect(toSpec(proof).material.map((one) => one.path)).toEqual([
+ 'media/clip.mp4', 'media/angle.jpg',
+ ]);
+
+ proof.sources = ['https://x.com/a/1'];
+ expect(toSpec(proof).material.map((one) => one.path)).toEqual(['media/clip.mp4']);
+
+ proof.sources = [];
+ expect(toSpec(proof).material).toEqual([]);
+ });
+
+ it('keeps a file no address answers for', () => {
+ // Bare paths are what a proof saved before the pairing carried. The list cannot
+ // disown what it cannot name, so they stay.
+ const spec = toSpec({
+ title: 'T', panels: [], shapes: [],
+ sources: ['https://x.com/a/1'],
+ material: ['media/legacy.mp4', { path: 'media/clip.mp4', url: 'https://gone/1' }],
+ });
+ expect(spec.material).toEqual([{ path: 'media/legacy.mp4', url: '' }]);
+ });
+
+ it('answers to the traced addresses when the proof states none of its own', () => {
+ const panels = [{ meta: { kind: 'media', source_urls: ['https://x.com/a/1'] } }];
+ const spec = toSpec({
+ title: 'T', panels, shapes: [], sources: null,
+ material: [{ path: 'media/clip.mp4', url: 'https://x.com/a/1' }],
+ });
+ expect(spec.material.map((one) => one.path)).toEqual(['media/clip.mp4']);
});
});
@@ -681,14 +766,37 @@ describe('toSpec — coordinates + source persistence', () => {
};
const spec = toSpec(proof);
expect(spec.coords).toEqual({ lat: 3, lon: 4 });
- expect(spec.coordsText).toBeNull();
- expect(spec.source).toBeNull();
+ expect(spec.points).toEqual([]); // nothing stated: the panels answer for it
+ expect(spec.coordsText).toBe('');
+ expect(spec.sources).toBeNull();
});
it('persists manual coordinate + source overrides (trimmed)', () => {
- const spec = toSpec({ title: 'T', panels: [], shapes: [], coordsText: ' 1, 2 ', source: ' http://s ' });
- expect(spec.coordsText).toBe('1, 2');
- expect(spec.source).toBe('http://s');
+ const spec = toSpec({
+ title: 'T', panels: [], shapes: [],
+ points: [{ coords: ' 1, 2 ', label: '', pov: false }],
+ sources: [' http://s ', ' '],
+ });
+ expect(spec.points).toEqual([{ coords: '1, 2' }]);
+ expect(spec.coordsText).toBe('1, 2'); // the mirror, for a build older than the list
+ expect(spec.sources).toEqual(['http://s']);
+ });
+
+ it('states every point, and mirrors the conclusion', () => {
+ const spec = toSpec({
+ title: 'T', panels: [], shapes: [],
+ points: [
+ { coords: '64.1466, -21.9426', label: 'impact 1', pov: false },
+ { coords: '64.1502, -21.9350', label: 'cam', pov: true },
+ ],
+ });
+ expect(spec.points).toEqual([
+ { coords: '64.1466, -21.9426', label: 'impact 1' },
+ { coords: '64.1502, -21.9350', label: 'cam', pov: true },
+ ]);
+ // POV rides on its own point, so the mirror of the first says nothing about it
+ expect(spec.coordsText).toBe('64.1466, -21.9426');
+ expect(spec.pov).toBe(false);
});
});
@@ -1223,6 +1331,8 @@ describe('templateFromProof — a content-free house style', () => {
captionSize: 24, legendSize: 22, footerSize: 16,
footer: 'By the desk',
footerEnabled: false,
+ footerText: true,
+ footerCoords: false,
footerColor: '#aabbcc',
footerAlign: 'left',
captionsEnabled: false,
@@ -1666,3 +1776,119 @@ describe('pasted images', () => {
expect(toSpec({ title: 'x', panels: [], shapes: [], notes: {} }).pastes).toEqual([]);
});
});
+
+
+describe('the points a proof states', () => {
+ it('reads a spec written before the list as the one point it holds', () => {
+ expect(specPoints({ coordsText: '64.1466, -21.9426', pov: true })).toEqual([
+ { coords: '64.1466, -21.9426', label: '', pov: true },
+ ]);
+ expect(specPoints({})).toEqual([]);
+ });
+
+ it('lights one point at most, because a camera stood in one place', () => {
+ const points = specPoints({
+ points: [{ coords: 'a', pov: true }, { coords: 'b', pov: true }],
+ });
+ expect(points.map((one) => one.pov)).toEqual([true, false]);
+ });
+
+ it('drops the list when the mirror says something else', () => {
+ // an older build corrected the field and left the list alone: what it says
+ // is the newer answer
+ expect(specPoints({
+ points: [{ coords: '64.1466, -21.9426' }, { coords: '64.1481, -21.9401' }],
+ coordsText: '48.8584, 2.2945',
+ })).toEqual([{ coords: '48.8584, 2.2945', label: '', pov: false }]);
+ });
+
+ it('keeps the list when nothing wrote the mirror at all', () => {
+ expect(specPoints({ points: [{ coords: 'a' }, { coords: 'b' }] })).toHaveLength(2);
+ });
+
+ it('writes the list and the mirror together', () => {
+ const spec = statePoints({}, [
+ { coords: ' 64.1466, -21.9426 ', label: ' impact 1 ', pov: false },
+ { coords: '', label: 'dropped', pov: false },
+ { coords: '64.1502, -21.9350', label: '', pov: true },
+ ]);
+ expect(spec.points).toEqual([
+ { coords: '64.1466, -21.9426', label: 'impact 1' },
+ { coords: '64.1502, -21.9350', pov: true },
+ ]);
+ expect(spec.coordsText).toBe('64.1466, -21.9426');
+ expect(spec.pov).toBe(false);
+ });
+
+ it('falls back to what the panels give it', () => {
+ const panels = [{ id: 'p1', src: 'a.png', meta: { lat: 3, lon: 4 } }];
+ expect(proofCoordsLines({ panels })).toEqual([{ coords: '3.000000, 4.000000', label: '' }]);
+ });
+});
+
+describe('the coordinates a plate prints', () => {
+ const lines = [
+ { coords: '64.1466, -21.9426', label: '' },
+ { coords: '64.1481, -21.9401', label: '' },
+ { coords: '64.1502, -21.9350', label: 'caméra' },
+ ];
+
+ it('joins the unnamed points, so three impacts cost one line', () => {
+ expect(coordsPlateLines(lines.slice(0, 2))).toEqual(['64.1466, -21.9426 · 64.1481, -21.9401']);
+ });
+
+ it('gives a named point its own line, and leaves the rest joined', () => {
+ expect(coordsPlateLines(lines)).toEqual([
+ '64.1466, -21.9426 · 64.1481, -21.9401',
+ 'caméra — 64.1502, -21.9350',
+ ]);
+ });
+
+ it('says nothing on the plate unless the proof asks', () => {
+ const proof = { panels: [], points: [{ coords: '1, 2' }], footer: 'Imagery © Esri' };
+ expect(footerLines(proof)).toEqual(['Imagery © Esri']);
+ expect(footerLines({ ...proof, footerCoords: true })).toEqual(['1, 2', 'Imagery © Esri']);
+ });
+
+ it('measures the band at the number of lines it will draw', () => {
+ expect(footerBand(15, 3)).toBe(footerBand(15) * 3);
+ expect(footerBand(15, 0)).toBe(footerBand(15)); // never less than the attribution
+ });
+
+ it('leaves a post one point per line, since a tweet has no height to save', () => {
+ expect(coordsPostLines(lines)).toEqual([
+ '64.1466, -21.9426',
+ '64.1481, -21.9401',
+ 'caméra — 64.1502, -21.9350',
+ ]);
+ });
+});
+
+
+describe('a house style and the footer switches', () => {
+ it('carries both, so a saved style keeps what the plate prints', () => {
+ const t = templateFromProof({ panels: [], footerCoords: true, footerText: false });
+ expect(t.footerCoords).toBe(true);
+ expect(t.footerText).toBe(false);
+ });
+
+ it('leaves a proof alone when an older style says nothing about them', () => {
+ // a template saved before these existed must not take a proof's coordinates
+ // off its plate on the way in
+ const proof = { panels: [], footerCoords: true, footerText: false };
+ applyProofStyle(proof, { bg: '#101418' });
+ expect(proof.footerCoords).toBe(true);
+ expect(proof.footerText).toBe(false);
+ });
+
+ it('takes no band at all when the footer prints nothing', () => {
+ const panels = [{ id: 'p1', src: 'a.png', natural: [100, 100] }];
+ const bare = docSize(panels, [], {}, { footerEnabled: true, footerLines: 0 });
+ const withOne = docSize(panels, [], {}, { footerEnabled: true, footerLines: 1 });
+ expect(withOne.height - bare.height).toBe(footerBand());
+ });
+
+ it('prints nothing when both switches are off', () => {
+ expect(footerLines({ panels: [], footerText: false })).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/coords.js b/frontend/src/lib/coords.js
index 795830e..b6a9796 100644
--- a/frontend/src/lib/coords.js
+++ b/frontend/src/lib/coords.js
@@ -16,6 +16,25 @@ const EP2 = E2 / (1 - E2); // second eccentricity squared
const rad = (deg) => (deg * Math.PI) / 180;
+/**
+ * A longitude folded back into [-180, 180].
+ *
+ * Leaflet keeps counting past the antimeridian as the analyst pans, so a map
+ * centre can read 187° after crossing it. Every coordinate the API accepts is
+ * bounded to ±180, so the unwrapped value is refused rather than understood.
+ */
+export function wrapLon(lon) {
+ const value = Number(lon);
+ if (!Number.isFinite(value)) return value;
+ // Returned untouched when it is already a longitude: the modulo below is
+ // floating-point arithmetic, and 2.2945 must not come back as
+ // 2.294499999999971 — this value is written into captures and proofs.
+ if (value >= -180 && value <= 180) return value;
+ const wrapped = ((value + 180) % 360 + 360) % 360 - 180;
+ // 180 and -180 name the same meridian; keep the sign the analyst panned toward
+ return wrapped === -180 && value > 0 ? 180 : wrapped;
+}
+
/** Decimal degrees, 6 dp (~0.11 m) — the app's native precision. */
export function formatDD(lat, lon) {
return `${Number(lat).toFixed(6)}, ${Number(lon).toFixed(6)}`;
@@ -57,7 +76,9 @@ export function utmZone(lat, lon) {
if (lon < 33) return 35;
return 37;
}
- return Math.floor((lon + 180) / 6) + 1;
+ // Zone 60 ends *at* 180°: without the clamp the antimeridian answers 61, a
+ // zone that does not exist. Mirrors engine/coords.utm_zone.
+ return Math.min(60, Math.floor((lon + 180) / 6) + 1);
}
// Latitude bands, 8° each from 80°S; I and O are skipped to avoid reading as
diff --git a/frontend/src/lib/coords.test.js b/frontend/src/lib/coords.test.js
index d51ad70..a5f267a 100644
--- a/frontend/src/lib/coords.test.js
+++ b/frontend/src/lib/coords.test.js
@@ -7,6 +7,7 @@ import {
latBand,
parseHomeView,
utmZone,
+ wrapLon,
} from './coords.js';
describe('formatDD', () => {
@@ -175,3 +176,35 @@ describe('parseHomeView', () => {
expect(parseHomeView({ lat: 'north', lon: '2.2945', zoom: 16 })).toBeNull();
});
});
+
+describe('utmZone', () => {
+ it('stops at zone 60, which is where the grid ends', () => {
+ // Zone 60 ends *at* 180°, so the division that assumes an open interval
+ // answered 61 on the antimeridian — a zone no projection has.
+ expect(utmZone(0, 180)).toBe(60);
+ expect(utmZone(0, 179.999)).toBe(60);
+ expect(utmZone(0, -180)).toBe(1);
+ expect(utmZone(0, 0)).toBe(31);
+ });
+});
+
+describe('wrapLon', () => {
+ it('folds a longitude Leaflet kept counting past the date line', () => {
+ // Panning west across the antimeridian leaves the map centre at 187°, which
+ // every API bound refuses — Capture answered 422 and the tool went dead.
+ expect(wrapLon(187)).toBeCloseTo(-173, 10);
+ expect(wrapLon(-187)).toBeCloseTo(173, 10);
+ expect(wrapLon(540)).toBeCloseTo(180, 10);
+ });
+
+ it('leaves an ordinary longitude exactly as it is', () => {
+ expect(wrapLon(2.2945)).toBe(2.2945);
+ expect(wrapLon(-180)).toBe(-180);
+ expect(wrapLon(180)).toBe(180);
+ expect(wrapLon(0)).toBe(0);
+ });
+
+ it('passes a non-number through rather than inventing a meridian', () => {
+ expect(Number.isNaN(wrapLon('north'))).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/dismiss.js b/frontend/src/lib/dismiss.js
index abb99e2..f6128d9 100644
--- a/frontend/src/lib/dismiss.js
+++ b/frontend/src/lib/dismiss.js
@@ -5,11 +5,17 @@
* stays open while the press lands on a map or a canvas that swallows the click, and
* the same press then means two things. Returns the teardown, so the whole use is
* `$effect(() => open ? closeOnOutsidePointer(element, () => (open = false)) : undefined)`.
+ *
+ * Several elements may be given, and that is not a nicety: a popover drawn away from
+ * the control that opens it — one hung off a heading inside a scroller, say, and
+ * rendered outside it so the scroller cannot clip it — has a trigger the press must
+ * not count as *outside*, or the click closes and reopens it in one gesture.
*/
export function closeOnOutsidePointer(element, close) {
if (typeof document === 'undefined') return undefined;
+ const parts = (Array.isArray(element) ? element : [element]).filter(Boolean);
const outside = (event) => {
- if (!element?.contains(event.target)) close();
+ if (!parts.some((part) => part.contains(event.target))) close();
};
document.addEventListener('pointerdown', outside);
return () => document.removeEventListener('pointerdown', outside);
diff --git a/frontend/src/lib/entityTypes.svelte.js b/frontend/src/lib/entityTypes.svelte.js
index 23db6bd..2316a44 100644
--- a/frontend/src/lib/entityTypes.svelte.js
+++ b/frontend/src/lib/entityTypes.svelte.js
@@ -129,6 +129,17 @@ export function creatableTypes() {
return registry.types.filter((entry) => entry.manual);
}
+/** Every type a sheet row may be promoted into, in menu order.
+ *
+ * Not the same list as `creatableTypes`, and reading one for the other is what put a
+ * `claim` in the promote dialog and left `place` out of it: a place is born from the
+ * map so it is never *created* by hand, but a column of coordinates is the other
+ * honest way to have one. The registry answers both questions rather than the browser
+ * guessing from `manual`. */
+export function promotableTypes() {
+ return registry.types.filter((entry) => entry.promotable);
+}
+
/** Whether this type is entered as a graph record rather than born from a tool. */
export function isManualEntityType(type) {
return Boolean(entryFor(type)?.manual);
diff --git a/frontend/src/lib/exportDest.js b/frontend/src/lib/exportDest.js
index 93e0bc7..145e619 100644
--- a/frontend/src/lib/exportDest.js
+++ b/frontend/src/lib/exportDest.js
@@ -1,6 +1,7 @@
/**
- * Export destinations: where the notes PDFs, the media copies and the proof
- * PNGs land, and the folder browser that lets the analyst say so.
+ * Export destinations: where the notes PDFs, the media copies, the proof PNGs, the
+ * analysis plates and the sheet CSVs land, and the folder browser that lets the
+ * analyst say so.
*
* The destination is remembered per kind, app-wide, in settings — a case folder
* is not the right home for it, since the whole point is that the analyst files
@@ -14,7 +15,7 @@
import { api } from './api.js';
/** The exports that remember a folder. Mirrors `KINDS` in engine/exportdir.py. */
-export const KINDS = ['notes', 'media', 'proofs'];
+export const KINDS = ['notes', 'media', 'proofs', 'views', 'sheets'];
/** What to call the default in the UI, once per kind so the wording can't drift. */
export const CASE_FOLDER_LABEL = "the case's exports folder";
diff --git a/frontend/src/lib/exportDest.test.js b/frontend/src/lib/exportDest.test.js
index c31ce0e..cef4e75 100644
--- a/frontend/src/lib/exportDest.test.js
+++ b/frontend/src/lib/exportDest.test.js
@@ -28,6 +28,8 @@ describe('export destinations', () => {
notes: '/reports',
media: '',
proofs: '',
+ views: '',
+ sheets: '',
});
expect(api.get).toHaveBeenCalledWith('/api/settings');
});
@@ -39,6 +41,8 @@ describe('export destinations', () => {
notes: '',
media: '/evidence',
proofs: '',
+ views: '',
+ sheets: '',
});
expect(api.put).toHaveBeenCalledWith('/api/settings/prefs', {
export_dirs: { media: '/evidence' },
diff --git a/frontend/src/lib/extensionPopup.test.js b/frontend/src/lib/extensionPopup.test.js
new file mode 100644
index 0000000..2c55209
--- /dev/null
+++ b/frontend/src/lib/extensionPopup.test.js
@@ -0,0 +1,132 @@
+// @vitest-environment happy-dom
+/**
+ * Tests for the capture extension's popup (extension/popup.js).
+ *
+ * Like extension.test.js next door, the popup has no exports: the suite loads
+ * popup.html into the document, stubs `chrome` and `fetch`, evaluates the source
+ * and reads the resulting DOM.
+ *
+ * What is worth pinning here is the unreachable case. The popup asks the app to
+ * read the URL before it draws anything, so a stopped app is caught upstream and
+ * these buttons are never wired at all. The window this covers is the narrow one:
+ * the app answered the first request and was gone by the second.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const ext = join(here, '../../../extension');
+const source = readFileSync(join(ext, 'popup.js'), 'utf8');
+const html = readFileSync(join(ext, 'popup.html'), 'utf8');
+
+const $ = (id) => document.getElementById(id);
+
+/** Run the popup against a tab, with `fetch` answering per URL fragment. */
+async function runPopup({ tabUrl, answers }) {
+ // Body only, without the <script src> happy-dom refuses to fetch: the source is
+ // evaluated below by hand, with the globals a popup really has.
+ document.body.innerHTML = html
+ .replace(/[\s\S]*<body[^>]*>/, '')
+ .replace(/<\/body>[\s\S]*/, '')
+ .replace(/<script[\s\S]*?<\/script>/g, '');
+
+ // happy-dom ships no `Option` constructor; the popup fills its case pickers with it.
+ globalThis.Option = function Option(text, value) {
+ const option = document.createElement('option');
+ option.textContent = text;
+ option.value = value ?? text;
+ return option;
+ };
+
+ globalThis.chrome = {
+ tabs: { query: vi.fn(async () => [{ id: 7, url: tabUrl }]), sendMessage: vi.fn(async () => {}) },
+ storage: {
+ local: {
+ get: vi.fn(async (defaults) => ({
+ ...defaults,
+ backendUrl: 'http://127.0.0.1:8477',
+ token: 'tok-123',
+ })),
+ set: vi.fn(),
+ },
+ },
+ runtime: { getManifest: () => ({ version: '0.2.9' }), sendMessage: vi.fn(async () => ({ ok: true })) },
+ };
+
+ globalThis.fetch = vi.fn(async (url) => {
+ for (const [fragment, answer] of Object.entries(answers)) {
+ if (String(url).includes(fragment)) return answer();
+ }
+ throw new Error('unexpected fetch');
+ });
+
+ const run = new Function('browser', `${source}\n//# sourceURL=popup.js`);
+ run(undefined);
+ // init() is async and awaits two fetches before it wires the buttons
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+const ok = (body) => () => ({ ok: true, status: 200, json: async () => body });
+const down = () => {
+ throw new Error('network');
+};
+
+beforeEach(() => {
+ document.body.innerHTML = '';
+ vi.restoreAllMocks();
+});
+
+describe('a map page whose app goes away mid-load', () => {
+ const mapPage = {
+ tabUrl: 'https://www.google.fr/maps/@48.85,2.29,17z',
+ answers: {
+ '/parse': ok({ site: 'google-maps', label: 'Google Maps', lat: 48.85, lon: 2.29, zoom: 17 }),
+ '/cases': down,
+ },
+ };
+
+ it('greys out every button, so the error message is the only story', async () => {
+ await runPopup(mapPage);
+
+ expect($('save-place').disabled).toBe(true);
+ expect($('capture-area').disabled).toBe(true);
+ expect($('status').textContent).toContain('Cannot reach Azimut');
+ });
+
+ it('leaves nothing that answers a click with silence', async () => {
+ await runPopup(mapPage);
+
+ const live = ['save-place', 'capture-area'].filter((id) => !$(id).disabled);
+ expect(live).toEqual([]);
+ });
+});
+
+describe('a page that is not a map, whose app goes away mid-load', () => {
+ it('greys out the bookmark button too', async () => {
+ await runPopup({
+ tabUrl: 'https://example.com/article',
+ answers: { '/parse': ok({ site: null }), '/cases': down },
+ });
+
+ expect($('save-bookmark').disabled).toBe(true);
+ expect($('status').textContent).toContain('Cannot reach Azimut');
+ });
+});
+
+describe('a map page with the app answering', () => {
+ it('leaves capture reachable, and holds the place button for its coordinates', async () => {
+ await runPopup({
+ tabUrl: 'https://www.google.fr/maps/@48.85,2.29,17z',
+ answers: {
+ '/parse': ok({ site: 'google-maps', label: 'Google Maps', lat: 48.85, lon: 2.29, zoom: 17 }),
+ '/cases': ok([{ id: 'c1', name: 'Case one' }]),
+ },
+ });
+
+ expect($('capture-area').disabled).toBe(false);
+ expect($('save-place').disabled).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.js
index 2986b9c..fe463f3 100644
--- a/frontend/src/lib/geoTree.js
+++ b/frontend/src/lib/geoTree.js
@@ -55,6 +55,8 @@ function savedText(row) {
: `${row.lat}, ${row.lon}\n${Number(row.lat).toFixed(4)}, ${Number(row.lon).toFixed(4)}`;
return [
row.title,
+ // what the analyst called this point, when a proof states several
+ row.label,
row.notes,
row.provider,
row.site,
diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.js
index 8a00ff6..76e39c2 100644
--- a/frontend/src/lib/geoTree.test.js
+++ b/frontend/src/lib/geoTree.test.js
@@ -301,3 +301,15 @@ describe('addressing a row in the tree', () => {
]);
});
});
+
+describe('a proof of several points', () => {
+ it('finds a row by the name its point was given', () => {
+ // three rows under one title: the label is what tells them apart
+ const rows = [
+ { id: 'p', kind: 'proof', title: 'Harbour strike', label: 'impact 2', geo: {} },
+ { id: 'p', kind: 'proof', title: 'Harbour strike', label: 'caméra', geo: {} },
+ ];
+ expect(filterSaved(rows, { query: 'caméra' })).toHaveLength(1);
+ expect(filterSaved(rows, { query: 'harbour' })).toHaveLength(2);
+ });
+});
diff --git a/frontend/src/lib/graph.js b/frontend/src/lib/graph.js
index ff4d9f2..3bf3985 100644
--- a/frontend/src/lib/graph.js
+++ b/frontend/src/lib/graph.js
@@ -997,7 +997,12 @@ export function nodeRadius(degree) {
*/
export function shortLabel(label, max = 22) {
const text = String(label ?? '').trim();
- return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
+ // Cut by code point rather than by UTF-16 unit. A slice through a surrogate pair —
+ // an emoji in an account's name is enough — leaves half of one behind, which is not
+ // a character: the canvas draws a blank box and an SVG export cannot be encoded at
+ // all, so the whole plate used to fail on one label.
+ const glyphs = [...text];
+ return glyphs.length <= max ? text : `${glyphs.slice(0, max - 1).join('')}…`;
}
/**
diff --git a/frontend/src/lib/graph.test.js b/frontend/src/lib/graph.test.js
index 996b784..59251f8 100644
--- a/frontend/src/lib/graph.test.js
+++ b/frontend/src/lib/graph.test.js
@@ -828,6 +828,10 @@ describe('node drawing', () => {
});
it('survives a label that is not a string', () => {
+ // An emoji is two UTF-16 units: cutting between them leaves half a character,
+ // which no canvas can draw and no file can carry.
+ expect(shortLabel(`${'x'.repeat(20)}🏴war`)).toBe(`${'x'.repeat(20)}🏴…`);
+ expect([...shortLabel(`${'x'.repeat(21)}🏴war`)].every((glyph) => glyph.codePointAt(0) < 0xd800 || glyph.codePointAt(0) > 0xdfff)).toBe(true);
expect(shortLabel(null)).toBe('');
expect(shortLabel(42)).toBe('42');
});
diff --git a/frontend/src/lib/graphPlate.js b/frontend/src/lib/graphPlate.js
new file mode 100644
index 0000000..8c9eede
--- /dev/null
+++ b/frontend/src/lib/graphPlate.js
@@ -0,0 +1,185 @@
+/**
+ * The Graph, serialised as SVG.
+ *
+ * Konva draws the screen and cannot write a vector file, so this module walks the same
+ * scene the canvas is built from — `placed`, the drawable links, the parallel bends —
+ * and writes it out. It is a second *serialiser* over one set of coordinates, not a
+ * second layout: nothing here decides where a node goes, so the file and the screen
+ * cannot disagree about the drawing.
+ *
+ * What the plate deliberately leaves out: the cards, their photos and every mark that
+ * belongs to working the graph — hover, selection, pins, folds in progress. A plate is
+ * the reading, not the session. Dots and names is what the drawing looks like framed,
+ * and a file carrying two hundred base64 thumbnails is not a file anybody opens twice.
+ */
+
+import {
+ edgeMidpoint,
+ edgePoints,
+ edgeStyle,
+ extent,
+ nodeRadius,
+ shortLabel,
+} from './graph.js';
+import {
+ PLATE_COLOURS,
+ familyColour,
+ plateDocument,
+ round,
+ svgCircle,
+ svgPath,
+ svgText,
+} from './plate.js';
+
+/** Room around the drawing: a name is 140 wide under its dot, so the outer nodes need
+ * half of that on each side or the labels leave the page. */
+export const PLATE_ROOM = { x: 76, top: 30, bottom: 34 };
+
+/**
+ * Past this many edges the verbs stop being written.
+ *
+ * On screen a verb appears when its edge is lit, so the picture is never a wall of
+ * words. A plate has no pointer, so the choice is made once for the whole drawing:
+ * under the limit every edge says what it says, and above it the strokes and the
+ * legend carry the reading, which is what a dense case is legible as anyway.
+ */
+export const VERB_LIMIT = 60;
+
+const ARROW = 'plate-arrow';
+
+const ARROW_DEF =
+ `<marker id="${ARROW}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="5"`
+ + ` markerHeight="5" orient="auto-start-reverse">`
+ + `<path d="M 0 0 L 10 5 L 0 10 z" fill="${PLATE_COLOURS.label}" /></marker>`;
+
+/**
+ * The path an edge is drawn along, in plate coordinates.
+ *
+ * A straight edge is two points and a line. A bowed one is three, and the middle one
+ * is a point the curve **passes through** — Konva's tension spline does — while a
+ * quadratic's control point is one it only leans towards. So the control is pulled back
+ * out of the midpoint (`2·mid − (start+end)/2`), which puts the curve back on it.
+ */
+export function edgeDefinition(points) {
+ const at = (index) => round(points[index]);
+ if (points.length < 6) return `M ${at(0)} ${at(1)} L ${at(2)} ${at(3)}`;
+ const controlX = 2 * points[2] - (points[0] + points[4]) / 2;
+ const controlY = 2 * points[3] - (points[1] + points[5]) / 2;
+ return `M ${at(0)} ${at(1)} Q ${round(controlX)} ${round(controlY)} ${at(4)} ${at(5)}`;
+}
+
+/**
+ * The drawing on its own, sized to what it holds.
+ *
+ * `hidden`, when given, is the set of nodes still on screen — the graph hides by
+ * painting rather than by relaying out, so the plate applies the same rule the canvas
+ * does: a node not in it is left out, and an edge survives only when both of its ends
+ * do. A line running to a node that is not there reads as the case continuing off the
+ * page when it does not.
+ */
+export function graphDrawing({
+ placed = [],
+ edges = [],
+ bends = new Map(),
+ byId = new Map(),
+ hidden = null,
+ chainTypes = [],
+ verbOf = (link) => link.type,
+ verbs = 'auto',
+} = {}) {
+ const kept = placed.filter((node) => !hidden || hidden.has(node.id));
+ const positions = new Map(kept.map((node) => [node.id, node]));
+ const drawable = edges.filter(
+ (link) => positions.has(link.from) && positions.has(link.to),
+ );
+ const box = extent(kept);
+ const radiusOf = (id) => nodeRadius(byId.get(id)?.degree);
+ const widest = kept.reduce((most, node) => Math.max(most, radiusOf(node.id)), 0);
+ const width = Math.max(1, box.maxX - box.minX) + PLATE_ROOM.x * 2;
+ // The bottom edge carries the widest dot *and* the name hanging under it, which is
+ // the one side of the drawing that is taller than the nodes themselves.
+ const height =
+ Math.max(1, box.maxY - box.minY) + PLATE_ROOM.top + widest + PLATE_ROOM.bottom;
+ const shift = (node) => ({
+ x: node.x - box.minX + PLATE_ROOM.x,
+ y: node.y - box.minY + PLATE_ROOM.top,
+ });
+ const named = verbs === true || (verbs === 'auto' && drawable.length <= VERB_LIMIT);
+
+ const wires = [];
+ const words = [];
+ for (const link of drawable) {
+ const from = shift(positions.get(link.from));
+ const to = shift(positions.get(link.to));
+ const style = edgeStyle(link, chainTypes);
+ const points = edgePoints(
+ from, to, radiusOf(link.from), radiusOf(link.to), bends.get(link.id) ?? 0,
+ );
+ wires.push(svgPath(edgeDefinition(points), {
+ stroke: PLATE_COLOURS.label,
+ width: style.width ?? 1.3,
+ dash: (style.dash ?? []).join(' ') || undefined,
+ marker: `url(#${ARROW})`,
+ opacity: 0.85,
+ }));
+ if (!named) continue;
+ const verb = String(verbOf(link) ?? '').trim();
+ if (!verb) continue;
+ const at = edgeMidpoint(points, 9);
+ words.push(svgText(verb, {
+ x: at.x, y: at.y, size: 9, anchor: 'middle', fill: PLATE_COLOURS.hint, halo: 2.5,
+ }));
+ }
+
+ const dots = [];
+ const names = [];
+ for (const node of kept) {
+ const data = byId.get(node.id) ?? {};
+ const at = shift(node);
+ const radius = radiusOf(node.id);
+ dots.push(svgCircle({
+ x: at.x, y: at.y, r: radius,
+ fill: familyColour(data.family),
+ stroke: PLATE_COLOURS.paper,
+ strokeWidth: 1.5,
+ // A proposal is drawn as one everywhere it appears (ONTOLOGY §4).
+ ...(data.status === 'suggested' ? { dash: '3 3' } : {}),
+ }));
+ names.push(svgText(shortLabel(data.label ?? node.id), {
+ // Konva places a text box by its top; SVG by its baseline, hence the drop.
+ x: at.x, y: at.y + radius + 14, size: 11, anchor: 'middle',
+ fill: PLATE_COLOURS.label, halo: 3,
+ }));
+ }
+
+ return {
+ defs: ARROW_DEF,
+ // Edges first, then their words, then the nodes: the same order the canvas draws
+ // in, so a dot always covers the line that reaches it.
+ body: [...wires, ...words, ...dots, ...names].filter(Boolean).join('\n'),
+ width: Math.round(width),
+ height: Math.round(height),
+ nodes: kept.length,
+ links: drawable.length,
+ verbsDrawn: named,
+ };
+}
+
+/**
+ * The whole plate: the drawing under its header, above its legend.
+ *
+ * The header states what the drawing holds, because the reader cannot count dots and has
+ * no way of telling an absence of verbs from a density that dropped them.
+ */
+export function graphPlate({ meta = {}, families = [], strokes = [], ...scene } = {}) {
+ const drawing = graphDrawing(scene);
+ const tally = [
+ `${drawing.nodes} node${drawing.nodes === 1 ? '' : 's'}`,
+ `${drawing.links} link${drawing.links === 1 ? '' : 's'}`,
+ drawing.verbsDrawn ? '' : 'verbs left off at this density',
+ ].filter(Boolean).join(' · ');
+ return {
+ ...plateDocument({ meta: { ...meta, tally }, families, strokes, drawing }),
+ drawing,
+ };
+}
diff --git a/frontend/src/lib/graphPlate.test.js b/frontend/src/lib/graphPlate.test.js
new file mode 100644
index 0000000..8c01ae4
--- /dev/null
+++ b/frontend/src/lib/graphPlate.test.js
@@ -0,0 +1,198 @@
+import { describe, expect, it } from 'vitest';
+import {
+ EDGE_KINDS,
+ arrange,
+ drawableLinks,
+ edgePoints,
+ extent,
+ nodeRadius,
+ parallelBends,
+ positionsById,
+} from './graph.js';
+import { PLATE_COLOURS } from './plate.js';
+import { PLATE_ROOM, VERB_LIMIT, edgeDefinition, graphDrawing, graphPlate } from './graphPlate.js';
+
+const NODES = [
+ { id: 'e_truck', label: 'White pickup with a very long name indeed', family: 'asset', degree: 3, status: 'confirmed' },
+ { id: 'e_team', label: 'Checkpoint team', family: 'actor', degree: 2, status: 'confirmed' },
+ { id: 'e_quay', label: 'Quay 4', family: 'place', degree: 1, status: 'suggested' },
+];
+
+const LINKS = [
+ { id: 'l1', from: 'e_team', to: 'e_truck', type: 'owns' },
+ { id: 'l2', from: 'e_team', to: 'e_truck', type: 'mentions' },
+ { id: 'l3', from: 'e_truck', to: 'e_quay', type: 'located-at', provenance: { status: 'suggested' } },
+];
+
+/** The scene a surface hands over: exactly what Graph.svelte derives for Konva. */
+function scene(extra = {}) {
+ const placed = arrange(NODES, 'rings', LINKS);
+ const positions = positionsById(placed);
+ const edges = drawableLinks(LINKS, positions);
+ return {
+ placed,
+ edges,
+ bends: parallelBends(edges),
+ byId: new Map(NODES.map((node) => [node.id, node])),
+ verbOf: (link) => link.type,
+ ...extra,
+ };
+}
+
+describe('serialising the graph', () => {
+ it('draws a dot and a name per node, and an arrow per drawable edge', () => {
+ const drawing = graphDrawing(scene());
+
+ expect(drawing.nodes).toBe(3);
+ expect(drawing.links).toBe(3);
+ expect(drawing.body.match(/<circle/g)).toHaveLength(3);
+ expect(drawing.body.match(/<path/g)).toHaveLength(3);
+ expect(drawing.body.match(/marker-end="url\(#plate-arrow\)"/g)).toHaveLength(3);
+ expect(drawing.defs).toContain('<marker id="plate-arrow"');
+ });
+
+ it('gives every node its family hue, and a proposal its dashed rim', () => {
+ const { body } = graphDrawing(scene());
+
+ expect(body).toContain(`fill="${PLATE_COLOURS.family.asset}"`);
+ expect(body).toContain(`fill="${PLATE_COLOURS.family.actor}"`);
+ expect(body).toContain(`fill="${PLATE_COLOURS.family.place}"`);
+ // e_quay is suggested; the other two are not.
+ expect(body.match(/stroke-dasharray="3 3"/g)).toHaveLength(1);
+ });
+
+ it('shortens a name the way the canvas does, rather than measuring text', () => {
+ const { body } = graphDrawing(scene());
+
+ expect(body).toContain('White pickup with a v…');
+ expect(body).not.toContain('White pickup with a very long name indeed');
+ });
+
+ it('haloes the names and the verbs, which is what makes them readable on the lines', () => {
+ const { body } = graphDrawing(scene());
+ // The canvas does the same with `fillAfterStrokeEnabled`; without it every name
+ // sitting on an edge is read through it.
+ expect(body.match(/paint-order="stroke"/g).length).toBe(3 + 3); // 3 names, 3 verbs
+ });
+
+ it('strokes each kind of edge with the registry’s own pattern', () => {
+ const { body } = graphDrawing(scene());
+ const mention = EDGE_KINDS.find((entry) => entry.kind === 'mention');
+ const proposed = EDGE_KINDS.find((entry) => entry.kind === 'proposed');
+
+ expect(body).toContain(`stroke-dasharray="${mention.dash.join(' ')}"`);
+ expect(body).toContain(`stroke-dasharray="${proposed.dash.join(' ')}"`);
+ });
+
+ it('writes the verbs while the drawing is small enough to read them', () => {
+ const drawn = graphDrawing(scene());
+ expect(drawn.verbsDrawn).toBe(true);
+ expect(drawn.body).toContain('>owns<');
+ expect(drawn.body).toContain('>located-at<');
+
+ const dense = graphDrawing(scene({
+ edges: Array.from({ length: VERB_LIMIT + 1 }, (_, index) => ({
+ id: `x${index}`, from: 'e_team', to: 'e_truck', type: 'owns',
+ })),
+ }));
+ expect(dense.verbsDrawn).toBe(false);
+ expect(dense.body).not.toContain('>owns<');
+ });
+
+ it('bows parallel edges through their midpoint, not past it', () => {
+ // A quadratic leans towards its control point; Konva's tension curve passes
+ // through the middle point. The control is pulled back so both agree.
+ expect(edgeDefinition([0, 0, 50, 20, 100, 0])).toBe('M 0 0 Q 50 40 100 0');
+ expect(edgeDefinition([0, 0, 100, 0])).toBe('M 0 0 L 100 0');
+
+ const { body } = graphDrawing(scene());
+ // l1 and l2 join the same pair, so exactly one of the two is straight.
+ expect(body.match(/ Q /g)).toHaveLength(2);
+ });
+
+ it('keeps hidden nodes out, and the edges that would point at them', () => {
+ const drawing = graphDrawing(scene({ hidden: new Set(['e_team', 'e_truck']) }));
+
+ expect(drawing.nodes).toBe(2);
+ expect(drawing.links).toBe(2); // l1 and l2 survive; l3 lost its far end
+ expect(drawing.body).not.toContain('Quay 4');
+ });
+
+ it('sizes the drawing to hold the outermost name, not just the dots', () => {
+ const drawing = graphDrawing(scene());
+ const placed = arrange(NODES, 'rings', LINKS);
+ const box = extent(placed);
+ const widest = Math.max(...NODES.map((node) => nodeRadius(node.degree)));
+
+ // A ring puts every node on one row, so the vertical span is the floor of 1 the
+ // sizing keeps rather than a zero-height drawing.
+ expect(drawing.width).toBe(
+ Math.round(Math.max(1, box.maxX - box.minX) + PLATE_ROOM.x * 2)
+ );
+ expect(drawing.height).toBe(
+ Math.round(
+ Math.max(1, box.maxY - box.minY) + PLATE_ROOM.top + widest + PLATE_ROOM.bottom
+ )
+ );
+ });
+
+ it('draws nothing rather than throwing on an empty reading', () => {
+ const drawing = graphDrawing({});
+ expect(drawing.body).toBe('');
+ expect(drawing.nodes).toBe(0);
+ });
+});
+
+describe('the graph plate', () => {
+ it('frames the drawing with its header and legend', () => {
+ const { svg, width, height, drawing } = graphPlate({
+ meta: {
+ caseName: 'Bakhmut convoy', surface: 'Graph', lens: 'All connections',
+ view: 'Rooftop match', at: '2026-08-13T20:10:00Z',
+ },
+ families: [{ family: 'asset', count: 1 }, { family: 'actor', count: 1 }],
+ strokes: EDGE_KINDS.filter((entry) => ['stated', 'mention'].includes(entry.kind)),
+ ...scene(),
+ });
+
+ expect(svg).toContain('Rooftop match');
+ expect(svg).toContain('Bakhmut convoy · Graph · All connections');
+ expect(svg).toContain('mentions');
+ expect(svg).toContain(`viewBox="0 0 ${width} ${height}"`);
+ expect(height).toBeGreaterThan(drawing.height);
+ expect(svg).not.toMatch(/var\(--/);
+ });
+
+ it('counts what it drew, and says when the verbs were dropped', () => {
+ // A reader cannot count dots, and cannot tell a drawing with no verbs from one whose
+ // verbs were left off to stay legible.
+ const { svg } = graphPlate({ meta: { view: 'Rooftop match' }, ...scene() });
+ expect(svg).toContain('3 nodes · 3 links');
+ expect(svg).not.toContain('verbs left off');
+
+ const dense = graphPlate({
+ meta: {},
+ ...scene({
+ edges: Array.from({ length: VERB_LIMIT + 1 }, (_, index) => ({
+ id: `x${index}`, from: 'e_team', to: 'e_truck', type: 'owns',
+ })),
+ }),
+ });
+ expect(dense.svg).toContain('verbs left off at this density');
+ });
+
+ it('reads the same coordinates the canvas is built from', () => {
+ // The one guarantee worth a test: no layout happens here. Every point in the file
+ // is `edgePoints` over `arrange`, translated — so the file cannot drift from the
+ // screen without the shared module moving first.
+ const built = scene();
+ const first = built.edges[0];
+ const points = edgePoints(
+ built.placed.find((node) => node.id === first.from),
+ built.placed.find((node) => node.id === first.to),
+ nodeRadius(3), nodeRadius(2), built.bends.get(first.id),
+ );
+ expect(points).toHaveLength(6);
+ expect(graphDrawing(built).body).toContain('<path');
+ });
+});
diff --git a/frontend/src/lib/gridSelect.js b/frontend/src/lib/gridSelect.js
index 4e60d6a..2d490f0 100644
--- a/frontend/src/lib/gridSelect.js
+++ b/frontend/src/lib/gridSelect.js
@@ -1,7 +1,8 @@
/**
- * Pure selection math for the desktop organizer's tile grid — kept out of the
- * component so it's unit-tested without a DOM. The component measures tile
- * rects (getBoundingClientRect) and drives these; nothing here touches the DOM.
+ * Pure selection math for the surfaces that let an analyst pick several things at
+ * once — the organizer's tile grid, the board's ticked rows — kept out of the
+ * components so it's unit-tested without a DOM. A component measures tile rects
+ * (getBoundingClientRect) and drives these; nothing here touches the DOM.
*/
/**
@@ -53,3 +54,28 @@ export function toggleSelection(selected, id, { shift = false, meta = false } =
}
return { selected: [id], anchor: id };
}
+
+/**
+ * Next selection after ticking `id`'s box, given the visual `order` of ids.
+ *
+ * A checkbox is not a tile, so there is no plain-click-replaces-everything here:
+ * ticking one box never clears the others. Shift carries the whole run from the
+ * last box touched to whatever the clicked box just became, which is what makes
+ * un-ticking a run as quick as filling one.
+ * Returns `{ selected, anchor }`; pass the anchor back in on the next call.
+ */
+export function toggleCheck(selected, id, { shift = false } = {}, order = [], anchor = null) {
+ const set = new Set(selected);
+ const on = !set.has(id);
+ let run = [id];
+ if (shift && anchor && anchor !== id) {
+ const a = order.indexOf(anchor);
+ const b = order.indexOf(id);
+ if (a !== -1 && b !== -1) run = order.slice(Math.min(a, b), Math.max(a, b) + 1);
+ }
+ for (const item of run) {
+ if (on) set.add(item);
+ else set.delete(item);
+ }
+ return { selected: [...set], anchor: id };
+}
diff --git a/frontend/src/lib/gridSelect.test.js b/frontend/src/lib/gridSelect.test.js
index f2dc9f2..f5fe9c0 100644
--- a/frontend/src/lib/gridSelect.test.js
+++ b/frontend/src/lib/gridSelect.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { marqueeHits, marqueeRect, toggleSelection } from './gridSelect.js';
+import { marqueeHits, marqueeRect, toggleCheck, toggleSelection } from './gridSelect.js';
const rect = (id, left, top, right, bottom) => ({ id, left, top, right, bottom });
@@ -76,3 +76,50 @@ describe('toggleSelection', () => {
});
});
});
+
+describe('toggleCheck', () => {
+ const order = ['a', 'b', 'c', 'd'];
+
+ it('ticking a box never clears the boxes already ticked', () => {
+ expect(toggleCheck(['a'], 'c', {}, order, 'a')).toEqual({
+ selected: ['a', 'c'],
+ anchor: 'c',
+ });
+ });
+
+ it('clicking a ticked box unticks that one alone', () => {
+ expect(toggleCheck(['a', 'b'], 'a', {}, order, 'b').selected).toEqual(['b']);
+ });
+
+ it('shift ticks the whole run from the last box touched', () => {
+ expect(toggleCheck(['a'], 'd', { shift: true }, order, 'a')).toEqual({
+ selected: ['a', 'b', 'c', 'd'],
+ anchor: 'd',
+ });
+ });
+
+ it('shift on a ticked box unticks the run, so a mis-drag is one gesture back', () => {
+ expect(
+ toggleCheck(['a', 'b', 'c', 'd'], 'c', { shift: true }, order, 'a').selected
+ ).toEqual(['d']);
+ });
+
+ it('runs the other way too', () => {
+ expect(toggleCheck(['d'], 'b', { shift: true }, order, 'd').selected).toEqual([
+ 'd',
+ 'b',
+ 'c',
+ ]);
+ });
+
+ it('shift with no anchor is a plain tick', () => {
+ expect(toggleCheck([], 'c', { shift: true }, order, null)).toEqual({
+ selected: ['c'],
+ anchor: 'c',
+ });
+ });
+
+ it('keeps a tick the current order no longer lists, since it is still going', () => {
+ expect(toggleCheck(['gone'], 'a', {}, order, null).selected).toEqual(['gone', 'a']);
+ });
+});
diff --git a/frontend/src/lib/konvaGesture.js b/frontend/src/lib/konvaGesture.js
new file mode 100644
index 0000000..54280e7
--- /dev/null
+++ b/frontend/src/lib/konvaGesture.js
@@ -0,0 +1,30 @@
+/**
+ * End a gesture Konva still believes is running. Its Transformer closes a
+ * corner-resize on a window `mouseup` and on nothing else, so a release the
+ * page never sees — the button let go outside the window, the tab alt-tabbed
+ * away — leaves the resize live. The shape then keeps resizing under a bare
+ * pointer with no button held, and the new size is never committed, so what is
+ * drawn, the frame around it and the numbers beside it all stop agreeing.
+ * Ending it by hand fires the same transformend/dragend the commit path
+ * already listens to, so the release still lands.
+ *
+ * A gesture that ended normally has cleared both flags before this runs, so
+ * nothing here touches it.
+ */
+export function closeStrandedGesture({ transformer, stage, isDragging }) {
+ let closed = false;
+ if (transformer?.isTransforming()) {
+ transformer.stopTransform();
+ closed = true;
+ }
+ // stopTransform releases the anchor it was dragging, so what the sweep finds
+ // is a stranded node drag — a panel moved in the composer's free layout, a
+ // signature dragged across the template preview.
+ if (isDragging()) {
+ for (const node of stage.find((n) => n.isDragging())) {
+ node.stopDrag();
+ closed = true;
+ }
+ }
+ return closed;
+}
diff --git a/frontend/src/lib/konvaGesture.test.js b/frontend/src/lib/konvaGesture.test.js
new file mode 100644
index 0000000..683e6d1
--- /dev/null
+++ b/frontend/src/lib/konvaGesture.test.js
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from 'vitest';
+import { closeStrandedGesture } from './konvaGesture.js';
+
+/** Konva's transformer, reduced to the two calls the gesture close makes. */
+function fakeTransformer(transforming) {
+ return {
+ isTransforming: () => transforming,
+ stopTransform: vi.fn(function () {
+ transforming = false;
+ }),
+ };
+}
+
+/** A stage whose `find` answers a predicate, the way Konva's does. */
+function fakeStage(nodes) {
+ return { find: (match) => nodes.filter(match) };
+}
+
+function fakeNode(dragging) {
+ return {
+ isDragging: () => dragging,
+ stopDrag: vi.fn(function () {
+ dragging = false;
+ }),
+ };
+}
+
+describe('closeStrandedGesture', () => {
+ it('leaves a settled gesture alone', () => {
+ const transformer = fakeTransformer(false);
+ const node = fakeNode(false);
+ const closed = closeStrandedGesture({
+ transformer,
+ stage: fakeStage([node]),
+ isDragging: () => false,
+ });
+ expect(closed).toBe(false);
+ expect(transformer.stopTransform).not.toHaveBeenCalled();
+ expect(node.stopDrag).not.toHaveBeenCalled();
+ });
+
+ it('ends a resize the release never closed', () => {
+ // Konva ends a corner-resize on a window mouseup and on nothing else. Left
+ // running, it resizes the panel under a pointer with no button held and
+ // never commits the scale.
+ const transformer = fakeTransformer(true);
+ const closed = closeStrandedGesture({
+ transformer,
+ stage: fakeStage([]),
+ isDragging: () => false,
+ });
+ expect(closed).toBe(true);
+ expect(transformer.stopTransform).toHaveBeenCalledTimes(1);
+ });
+
+ it('ends a stranded drag, and only the nodes still dragging', () => {
+ const dragged = fakeNode(true);
+ const settled = fakeNode(false);
+ const closed = closeStrandedGesture({
+ transformer: fakeTransformer(false),
+ stage: fakeStage([settled, dragged]),
+ isDragging: () => true,
+ });
+ expect(closed).toBe(true);
+ expect(dragged.stopDrag).toHaveBeenCalledTimes(1);
+ expect(settled.stopDrag).not.toHaveBeenCalled();
+ });
+
+ it('does not walk the document when nothing is being dragged', () => {
+ // The close runs on every release, and a proof holds a node per annotation.
+ const find = vi.fn(() => []);
+ closeStrandedGesture({
+ transformer: fakeTransformer(false),
+ stage: { find },
+ isDragging: () => false,
+ });
+ expect(find).not.toHaveBeenCalled();
+ });
+
+ it('survives a canvas that has no transformer yet', () => {
+ expect(() =>
+ closeStrandedGesture({ transformer: null, stage: fakeStage([]), isDragging: () => false })
+ ).not.toThrow();
+ });
+});
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 3cfb8f8..424881c 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -19,6 +19,20 @@ function recorded(value) {
return value === null || value === undefined || value === '' ? NaN : Number(value);
}
+/**
+ * The name a tool reopens an artifact by, read off the path the case recorded.
+ *
+ * Tools are handed a bare stem — the same one the save route slugified — never a
+ * path. Deriving it by stripping a hard-coded folder prefix meant the three
+ * artifact folders that later moved (`proofs/.meta/`, `.drafts/`, `.inspect/`)
+ * silently handed over a name with a directory still glued to it, which no route
+ * could match. Taking the last segment tracks the layout wherever it goes.
+ */
+function specName(path) {
+ if (typeof path !== 'string') return '';
+ return path.split('/').pop().replace(/\.json$/, '');
+}
+
/** Tool a given entity type opens in (also gates the "Open in tool" button). */
export const ENTITY_TOOL = {
media: 'media',
@@ -64,22 +78,19 @@ export function openEntity(entity) {
return;
}
if (entity.type === 'proof') {
- const spec = entity.attrs?.spec ?? '';
- const name = spec.replace(/^proofs\//, '').replace(/\.json$/, '');
+ const name = specName(entity.attrs?.spec);
if (name) uiState.openProof = name;
uiState.tool = 'proof';
return;
}
if (entity.type === 'post') {
- const draft = entity.attrs?.draft ?? '';
- const name = draft.replace(/^exports\//, '').replace(/\.json$/, '');
+ const name = specName(entity.attrs?.draft);
if (name) uiState.openDraft = name;
uiState.tool = 'post';
return;
}
if (entity.type === 'inspect-session') {
- const spec = entity.attrs?.spec ?? '';
- const name = spec.replace(/^inspect\//, '').replace(/\.json$/, '');
+ const name = specName(entity.attrs?.spec);
if (name) uiState.openInspect = name;
uiState.tool = 'inspect';
return;
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index fc99bb7..2f1854a 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -128,3 +128,38 @@ describe('a file the app cannot display', () => {
expect(opensInFileManager(null)).toBe(false);
});
});
+
+describe('reopening an artifact in its tool', () => {
+ // The tools take the bare stem the save route slugified. These paths are the
+ // ones the backend records today (`layout.proof_spec_rel` and friends); the
+ // folder prefixes moved once already, and stripping them by name meant every
+ // one of these handed over a name with a directory still glued to it.
+ it('names a proof by its spec file, wherever the spec folder sits', () => {
+ openEntity({ type: 'proof', attrs: { spec: 'proofs/.meta/Rooftop angle.json' } });
+
+ expect(uiState.openProof).toBe('Rooftop angle');
+ expect(uiState.tool).toBe('proof');
+ });
+
+ it('names a post draft by its draft file', () => {
+ openEntity({ type: 'post', attrs: { draft: '.drafts/Quay thread.json' } });
+
+ expect(uiState.openDraft).toBe('Quay thread');
+ expect(uiState.tool).toBe('post');
+ });
+
+ it('names an inspect session by its spec file', () => {
+ openEntity({ type: 'inspect-session', attrs: { spec: '.inspect/Bridge pass.json' } });
+
+ expect(uiState.openInspect).toBe('Bridge pass');
+ expect(uiState.tool).toBe('inspect');
+ });
+
+ it('opens the tool empty rather than on a name it could not read', () => {
+ uiState.openProof = null;
+ openEntity({ type: 'proof', attrs: {} });
+
+ expect(uiState.openProof).toBeNull();
+ expect(uiState.tool).toBe('proof');
+ });
+});
diff --git a/frontend/src/lib/notesExport.js b/frontend/src/lib/notesExport.js
index 37fcff7..5782c97 100644
--- a/frontend/src/lib/notesExport.js
+++ b/frontend/src/lib/notesExport.js
@@ -23,10 +23,23 @@ const MAX_DIAGRAM_EDGE = 2400;
* Diagrams are rendered with HTML labels off (see lib/mermaid.js), because a
* `<foreignObject>` is HTML inside the picture and browsers refuse to rasterise
* one out of an image element — the diagram would come back with empty boxes.
+ *
+ * `scale` and `maxEdge` are the diagram's own numbers by default. An analysis plate
+ * (lib/plateExport.js) is a whole page rather than a figure on one, so it raises the
+ * ceiling; the pair stays here because there is one way to turn an SVG into pixels.
+ */
+/**
+ * The scale a rasterisation will actually use: what was asked for, or what the edge cap
+ * leaves of it. Exported so a caller can say the real number before offering the image
+ * rather than promising a factor the canvas will not give.
*/
-export function rasterise(svg, { width, height }) {
+export function rasterScale({ width, height, scale = DIAGRAM_SCALE, maxEdge = MAX_DIAGRAM_EDGE }) {
+ return Math.min(scale, maxEdge / Math.max(width, height, 1));
+}
+
+export function rasterise(svg, { width, height, scale: wanted = DIAGRAM_SCALE, maxEdge = MAX_DIAGRAM_EDGE }) {
return new Promise((resolve, reject) => {
- const scale = Math.min(DIAGRAM_SCALE, MAX_DIAGRAM_EDGE / Math.max(width, height, 1));
+ const scale = rasterScale({ width, height, scale: wanted, maxEdge });
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(width * scale));
canvas.height = Math.max(1, Math.round(height * scale));
diff --git a/frontend/src/lib/overlayStack.js b/frontend/src/lib/overlayStack.js
new file mode 100644
index 0000000..9140248
--- /dev/null
+++ b/frontend/src/lib/overlayStack.js
@@ -0,0 +1,33 @@
+// Which overlay answers the Escape key.
+//
+// Escape is heard on the window, so without a shared order every open overlay answers one
+// press: a confirmation opened from inside a modal — removing a relation without losing the
+// entity window that sent you there — would close both and take the work with it. Only the
+// last one opened acts, which is what Escape means to whoever pressed it.
+//
+// Modals and confirmations share this one stack rather than keeping their own, because they
+// nest in both directions and a per-component stack cannot see the other kind.
+//
+// A plain array and not `$state`: it is read when a key is pressed, never while rendering,
+// and a reactive array that an effect both pushes to and depends on is an effect that
+// re-runs itself for good.
+const stack = [];
+
+/**
+ * Join the stack, and leave it when the caller is torn down.
+ *
+ * `self` is any stable object identity; the caller keeps it and passes it back to
+ * `isTopOverlay`. Returns the cleanup, so it reads as the body of an `$effect`.
+ */
+export function joinOverlays(self) {
+ stack.push(self);
+ return () => {
+ const at = stack.indexOf(self);
+ if (at !== -1) stack.splice(at, 1);
+ };
+}
+
+/** True when `self` is the overlay a key press belongs to. */
+export function isTopOverlay(self) {
+ return stack.at(-1) === self;
+}
diff --git a/frontend/src/lib/plate.js b/frontend/src/lib/plate.js
new file mode 100644
index 0000000..65c9954
--- /dev/null
+++ b/frontend/src/lib/plate.js
@@ -0,0 +1,339 @@
+/**
+ * The plate an analysis reading is exported as: a header, the drawing, a legend.
+ *
+ * Neither surface can hand over its own pixels usefully — the Graph draws on a Konva
+ * canvas, which serialises no SVG, and the Timeline is HTML — so both are serialised
+ * from the same scene their screen rendering already computes. What this module owns
+ * is the frame around that drawing: an export is not a screenshot, it is a plate that
+ * states which case, which lens, which question, which window and which clock the
+ * reading was made under. A picture nobody can source is not evidence of anything.
+ *
+ * Pure on purpose: no DOM, no case, no fetch. The drawing arrives as a serialised body
+ * plus its intrinsic size, and leaves inside a document.
+ */
+
+import { exactStamp } from './analysisViews.js';
+
+/**
+ * The plate's own geometry, in SVG user units (a unit is a pixel at 1:1).
+ *
+ * Fixed rather than measured: text metrics are a browser's answer and this module has
+ * to give the same one under a test. Every column is wide enough for the wording the
+ * legend actually holds, and a label too long for its column is truncated by the
+ * caller, not wrapped here.
+ */
+export const PLATE = {
+ pad: 28,
+ titleSize: 17,
+ metaSize: 11,
+ legendSize: 11,
+ legendRow: 20,
+ legendColumn: 168,
+ swatch: 26,
+ minWidth: 760,
+ maxWidth: 4800,
+ /** Roughly what one character costs at each size, for the two places that have to
+ * know before drawing: the title, which shares its line with the stamp, and a label
+ * cut to the room beside it. Measured text is a browser's answer; a plate needs the
+ * same one under a test. */
+ titleChar: 9.4,
+ metaChar: 5.7,
+};
+
+/**
+ * The plate is always drawn on the daylight palette, whatever the analyst reads in.
+ *
+ * Two reasons, and neither is taste: a plate is meant to be filed, printed or pasted
+ * into a document that is white, and an export whose colours follow a local preference
+ * is an export two analysts cannot compare. The values mirror `:root[data-theme='light']`
+ * in `app.css` — `plate.test.js` fails when they drift — and they are literal, because
+ * a `var(--…)` means nothing in a file opened outside the app.
+ */
+export const PLATE_COLOURS = {
+ paper: '#ffffff',
+ ink: '#1e1e1e',
+ label: '#5c5c5c',
+ hint: '#8a8a8a',
+ rule: '#e3e3e3',
+ accent: '#e8a33d',
+ family: {
+ actor: '#3f6ea8',
+ asset: '#2f7f72',
+ class: '#85661a',
+ identifier: '#6f57a0',
+ collected: '#a35f34',
+ document: '#5b6674',
+ place: '#4a7f36',
+ claim: '#a35470',
+ },
+};
+
+/** A stack every renderer has, since the app's own face may not be installed where the
+ * plate is opened. Oxanium is deliberately absent: a missing face shifts every label. */
+export const PLATE_FONT = "'Helvetica Neue', Helvetica, Arial, sans-serif";
+
+export function escapeXml(value) {
+ return String(value ?? '')
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+}
+
+/**
+ * Cut a string to the room it has, by code point.
+ *
+ * By code point because half a surrogate pair is not a character, and a plate carrying
+ * one cannot be written out as UTF-8. `charWidth` is the caller's own metric: a title
+ * and a lane label are not the same face.
+ */
+export function fitText(text, room, charWidth = PLATE.metaChar) {
+ const clean = String(text ?? '').trim();
+ const chars = Math.floor(Math.max(0, room) / charWidth);
+ if (chars <= 1) return '';
+ const glyphs = [...clean];
+ return glyphs.length <= chars ? clean : `${glyphs.slice(0, chars - 1).join('')}…`;
+}
+
+/** Coordinates at two decimals: a plate is not a place to ship 14 of them. */
+export function round(value) {
+ return Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
+}
+
+const attrs = (pairs) =>
+ Object.entries(pairs)
+ .filter(([, value]) => value !== undefined && value !== null && value !== '')
+ .map(([key, value]) => `${key}="${escapeXml(value)}"`)
+ .join(' ');
+
+/**
+ * `halo` paints the label's own outline in the paper colour first, which is what makes
+ * a name readable where it crosses a line. The canvas does the same thing with
+ * `fillAfterStrokeEnabled`; without it the graph's names are read through the edges
+ * they sit on.
+ */
+export function svgText(text, {
+ x, y, size = PLATE.metaSize, fill = PLATE_COLOURS.ink, weight, anchor, opacity, halo,
+} = {}) {
+ const clean = String(text ?? '');
+ if (!clean.trim()) return '';
+ return `<text ${attrs({
+ x: round(x),
+ y: round(y),
+ 'font-size': size,
+ 'font-weight': weight,
+ 'text-anchor': anchor,
+ fill,
+ 'fill-opacity': opacity,
+ stroke: halo ? PLATE_COLOURS.paper : undefined,
+ 'stroke-width': halo ? halo : undefined,
+ 'stroke-linejoin': halo ? 'round' : undefined,
+ 'paint-order': halo ? 'stroke' : undefined,
+ })}>${escapeXml(clean)}</text>`;
+}
+
+export function svgLine({ x1, y1, x2, y2, stroke = PLATE_COLOURS.rule, width = 1, dash }) {
+ return `<line ${attrs({
+ x1: round(x1), y1: round(y1), x2: round(x2), y2: round(y2),
+ stroke, 'stroke-width': width, 'stroke-dasharray': dash,
+ })} />`;
+}
+
+export function svgRect({ x, y, width, height, fill, stroke, radius, opacity, strokeWidth, dash }) {
+ return `<rect ${attrs({
+ x: round(x), y: round(y), width: round(width), height: round(height),
+ rx: radius, fill, 'fill-opacity': opacity, stroke,
+ 'stroke-width': strokeWidth, 'stroke-dasharray': dash,
+ })} />`;
+}
+
+export function svgCircle({ x, y, r, fill, stroke, strokeWidth, opacity, dash }) {
+ return `<circle ${attrs({
+ cx: round(x), cy: round(y), r: round(r), fill, 'fill-opacity': opacity,
+ stroke, 'stroke-width': strokeWidth, 'stroke-dasharray': dash,
+ })} />`;
+}
+
+export function svgPath(d, { stroke, fill = 'none', width, dash, cap = 'round', marker, opacity } = {}) {
+ return `<path ${attrs({
+ d, fill, stroke, 'stroke-width': width, 'stroke-dasharray': dash,
+ 'stroke-linecap': cap, 'stroke-opacity': opacity, 'marker-end': marker,
+ })} />`;
+}
+
+/**
+ * The header block: what this reading is, and of what.
+ *
+ * Everything here is a statement the drawing cannot make about itself. The title is
+ * the saved view's name when one is open, because that is what the analyst will look
+ * for; without one it is the surface and its lens, which is what they were looking at.
+ */
+export function plateHeader(meta = {}, width = PLATE.minWidth) {
+ const pad = PLATE.pad;
+ const wanted = String(meta.view || meta.title || '').trim() || 'Untitled reading';
+ const facts = [meta.caseName, meta.surface, meta.lens].map((part) => String(part ?? '').trim());
+ const line = facts.filter(Boolean).join(' · ');
+ const question = String(meta.question ?? '').trim();
+ const reading = [
+ meta.window ? `Fact time ${meta.window}` : '',
+ meta.clock ? `Clock ${meta.clock}` : '',
+ ].filter(Boolean).join(' · ');
+
+ const stamp = exactStamp(meta.at);
+ const stamped = stamp ? `Exported ${stamp}` : '';
+ // The stamp sits at the right edge on the title's own baseline, so the title is cut to
+ // what is left of the line rather than run underneath it. A view can be named with 80
+ // characters, which is wider than a small plate.
+ const room = width - pad * 2 - (stamped ? stamped.length * PLATE.metaChar + 20 : 0);
+ const title = fitText(wanted, Math.max(room, PLATE.titleSize * 6), PLATE.titleChar) || wanted;
+ const parts = [];
+ let y = pad + PLATE.titleSize;
+ parts.push(svgText(title, { x: pad, y, size: PLATE.titleSize, weight: '600' }));
+ if (stamped) {
+ parts.push(svgText(stamped, {
+ x: width - pad, y, anchor: 'end', fill: PLATE_COLOURS.hint,
+ }));
+ }
+ if (line) {
+ y += 17;
+ parts.push(svgText(line, { x: pad, y, fill: PLATE_COLOURS.label }));
+ }
+ if (question) {
+ y += 15;
+ parts.push(svgText(`Question: ${question}`, { x: pad, y, fill: PLATE_COLOURS.label }));
+ }
+ if (reading) {
+ y += 15;
+ parts.push(svgText(reading, { x: pad, y, fill: PLATE_COLOURS.label }));
+ }
+ // What the drawing leaves out, when the surface knows of something: entries with no
+ // date, nodes hidden by a focus. A reading that quietly omits is a reading nobody can
+ // check.
+ if (String(meta.aside ?? '').trim()) {
+ y += 15;
+ parts.push(svgText(meta.aside, { x: pad, y, fill: PLATE_COLOURS.hint }));
+ }
+ // What the drawing does hold, counted: how much is on the page, and any convention it
+ // dropped to stay readable. The surface writes it, since only it knows what it drew.
+ if (String(meta.tally ?? '').trim()) {
+ y += 15;
+ parts.push(svgText(meta.tally, { x: pad, y, fill: PLATE_COLOURS.hint }));
+ }
+ y += 14;
+ parts.push(svgLine({ x1: pad, y1: y, x2: width - pad, y2: y }));
+ return { svg: parts.filter(Boolean).join('\n'), height: y };
+}
+
+/**
+ * The legend: the hues, then the strokes.
+ *
+ * Both come from the registry the drawing itself reads — families in their own order,
+ * edge kinds with the wording the tool uses on screen — so a plate never invents a
+ * vocabulary. An unexplained dash pattern is decoration, which is the whole reason
+ * this block exists.
+ */
+export function plateLegend({ families = [], strokes = [] } = {}, width = PLATE.minWidth, top = 0) {
+ const pad = PLATE.pad;
+ const usable = Math.max(PLATE.legendColumn, width - pad * 2);
+ const columns = Math.max(1, Math.floor(usable / PLATE.legendColumn));
+ const parts = [svgLine({ x1: pad, y1: top, x2: width - pad, y2: top })];
+ let y = top + 18;
+
+ const place = (entries, draw) => {
+ entries.forEach((entry, index) => {
+ const column = index % columns;
+ if (column === 0 && index) y += PLATE.legendRow;
+ parts.push(draw(entry, pad + column * PLATE.legendColumn, y));
+ });
+ if (entries.length) y += PLATE.legendRow;
+ };
+
+ // A family names its own hue; a timeline track carries one the analyst chose, so an
+ // entry may state it outright rather than be looked up.
+ place(families, (entry, x, at) => [
+ svgCircle({ x: x + 5, y: at - 4, r: 5, fill: entry.colour ?? familyColour(entry.family) }),
+ svgText(
+ entry.count === undefined ? entry.family : `${entry.family} · ${entry.count}`,
+ { x: x + 16, y: at, size: PLATE.legendSize, fill: PLATE_COLOURS.label },
+ ),
+ ].join(''));
+
+ // A convention drawn as a line where it is one, and as the mark itself where it is
+ // not: a legend claiming a point is a stroke explains the wrong thing.
+ place(strokes, (entry, x, at) => [
+ entry.shape === 'dot'
+ ? svgCircle({ x: x + PLATE.swatch / 2, y: at - 4, r: 4, fill: PLATE_COLOURS.label })
+ : svgLine({
+ x1: x, y1: at - 4, x2: x + PLATE.swatch, y2: at - 4,
+ stroke: PLATE_COLOURS.label,
+ width: entry.width ?? 1.4,
+ dash: (entry.dash ?? []).join(' ') || undefined,
+ }),
+ svgText(entry.label, {
+ x: x + PLATE.swatch + 7, y: at, size: PLATE.legendSize, fill: PLATE_COLOURS.label,
+ }),
+ ].join(''));
+
+ return { svg: parts.join('\n'), height: Math.max(0, y - top) };
+}
+
+export function familyColour(family) {
+ return PLATE_COLOURS.family[family] ?? PLATE_COLOURS.family.document;
+}
+
+/**
+ * Frame one drawing into a complete document.
+ *
+ * The drawing arrives already serialised in its own coordinate space, with the size it
+ * needs; the plate widens to hold it, up to a cap no reader benefits from crossing. It
+ * is placed under the header rather than scaled to fit: the whole point of a vector
+ * file is that the zoom belongs to whoever opens it.
+ */
+export function plateDocument({ meta = {}, families = [], strokes = [], drawing } = {}) {
+ const pad = PLATE.pad;
+ const body = drawing?.body ?? '';
+ const width = Math.min(
+ PLATE.maxWidth,
+ Math.max(PLATE.minWidth, Math.round((drawing?.width ?? 0) + pad * 2)),
+ );
+ const header = plateHeader(meta, width);
+ const drawTop = header.height + 18;
+ const drawHeight = Math.max(120, Math.round(drawing?.height ?? 0));
+ const legend = plateLegend({ families, strokes }, width, drawTop + drawHeight + 18);
+ const height = Math.round(drawTop + drawHeight + 18 + legend.height + pad);
+ const offset = Math.max(pad, Math.round((width - (drawing?.width ?? 0)) / 2));
+
+ const svg = [
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"`
+ + ` viewBox="0 0 ${width} ${height}" font-family="${escapeXml(PLATE_FONT)}">`,
+ svgRect({ x: 0, y: 0, width, height, fill: PLATE_COLOURS.paper }),
+ drawing?.defs ? `<defs>${drawing.defs}</defs>` : '',
+ header.svg,
+ `<g transform="translate(${round(offset)} ${round(drawTop)})">`,
+ body,
+ '</g>',
+ legend.svg,
+ '</svg>',
+ ].filter(Boolean).join('\n');
+
+ return { svg, width, height };
+}
+
+/**
+ * The name to suggest for the file.
+ *
+ * Stem from the reading rather than the tool, because a folder holding a month of
+ * exports is read by what they are about. The stamp is the export's own minute, in
+ * UTC, so two plates of the same reading do not collide.
+ */
+export function plateFilename({ surface = 'graph', view = '', lens = '', at } = {}) {
+ const slug = (value) => String(value ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60);
+ const stem = slug(view) || slug(lens) || 'reading';
+ const stamp = exactStamp(at).replace(/[^0-9]/g, '').slice(0, 12) || 'undated';
+ return `${slug(surface) || 'plate'}-${stem}-${stamp}`;
+}
diff --git a/frontend/src/lib/plate.test.js b/frontend/src/lib/plate.test.js
new file mode 100644
index 0000000..7b7f8c6
--- /dev/null
+++ b/frontend/src/lib/plate.test.js
@@ -0,0 +1,217 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { FAMILY_ORDER, EDGE_KINDS } from './graph.js';
+import {
+ PLATE,
+ PLATE_COLOURS,
+ PLATE_FONT,
+ escapeXml,
+ familyColour,
+ fitText,
+ plateDocument,
+ plateFilename,
+ plateHeader,
+ plateLegend,
+ svgText,
+} from './plate.js';
+
+const css = readFileSync(new URL('../app.css', import.meta.url), 'utf8');
+
+/** The declarations under `:root[data-theme='light']`, as `{ token: value }`.
+ * Comments are stripped first: they sit after the semicolon and would otherwise be
+ * read as the head of the next declaration. */
+function lightTokens() {
+ const plain = css.replace(/\/\*[\s\S]*?\*\//g, '');
+ const block = plain.slice(plain.indexOf(":root[data-theme='light']"));
+ const body = block.slice(block.indexOf('{') + 1, block.indexOf('}'));
+ const tokens = {};
+ for (const line of body.split(';')) {
+ const [name, value] = line.split(':');
+ if (name?.trim().startsWith('--')) tokens[name.trim()] = (value ?? '').trim();
+ }
+ return tokens;
+}
+
+const meta = {
+ caseName: 'Bakhmut convoy',
+ surface: 'Graph',
+ view: 'Rooftop match',
+ lens: 'All connections',
+ question: 'AB-123 · Type: Vehicle',
+ window: '23 Aug – 1 Oct 2026',
+ clock: 'Asia/Tokyo',
+ at: '2026-08-13T20:10:31Z',
+};
+
+describe('the exported palette', () => {
+ it('is the daylight one, and does not drift from app.css', () => {
+ const light = lightTokens();
+ expect(PLATE_COLOURS.paper).toBe(light['--bg-1']);
+ expect(PLATE_COLOURS.ink).toBe(light['--text-1']);
+ expect(PLATE_COLOURS.label).toBe(light['--text-2']);
+ expect(PLATE_COLOURS.hint).toBe(light['--text-3']);
+ expect(PLATE_COLOURS.accent).toBe(light['--accent']);
+ for (const family of FAMILY_ORDER) {
+ expect(PLATE_COLOURS.family[family]).toBe(light[`--graph-${family}`]);
+ }
+ });
+
+ it('names every family the graph can draw', () => {
+ expect(Object.keys(PLATE_COLOURS.family).sort()).toEqual([...FAMILY_ORDER].sort());
+ expect(familyColour('nonsense')).toBe(PLATE_COLOURS.family.document);
+ });
+
+ it('ships no CSS variable and no app-only font into a file', () => {
+ const { svg } = plateDocument({
+ meta,
+ families: [{ family: 'actor', count: 3 }],
+ strokes: EDGE_KINDS.slice(0, 2),
+ drawing: { width: 900, height: 400, body: '<g />' },
+ });
+ expect(svg).not.toMatch(/var\(--/);
+ expect(svg).not.toMatch(/Oxanium/);
+ expect(PLATE_FONT).not.toMatch(/Oxanium/);
+ });
+});
+
+describe('the plate header', () => {
+ it('states the reading, the case and the clock it was read on', () => {
+ const { svg, height } = plateHeader(meta, 900);
+ expect(svg).toContain('Rooftop match');
+ expect(svg).toContain('Bakhmut convoy · Graph · All connections');
+ expect(svg).toContain('Question: AB-123 · Type: Vehicle');
+ expect(svg).toContain('Fact time 23 Aug – 1 Oct 2026 · Clock Asia/Tokyo');
+ expect(svg).toContain('Exported 2026-08-13 20:10 UTC');
+ expect(height).toBeGreaterThan(PLATE.pad);
+ });
+
+ it('falls back to the surface when no view is open, and never to a blank title', () => {
+ const { svg } = plateHeader({ title: 'Graph · All connections', caseName: 'Case' }, 900);
+ expect(svg).toContain('Graph · All connections');
+ expect(plateHeader({}, 900).svg).toContain('Untitled reading');
+ });
+
+ it('cuts a long title to the room the stamp leaves it', () => {
+ // A view can be named with 80 characters and the stamp keeps the right edge of the
+ // same line, so on a small plate the title is what has to give way.
+ const long = 'Rooftop match against every convoy sighting on the western approach';
+ const tight = plateHeader({ ...meta, view: long }, PLATE.minWidth).svg;
+
+ expect(tight).not.toContain(long);
+ expect(tight).toContain('…');
+ expect(tight).toContain('Exported 2026-08-13 20:10 UTC');
+ // Given the room, nothing is cut.
+ expect(plateHeader({ ...meta, view: long }, 2000).svg).toContain(long);
+ });
+
+ it('states what the drawing holds when the surface has counted it', () => {
+ const { svg } = plateHeader({ ...meta, tally: '182 nodes · 240 links' }, 900);
+ expect(svg).toContain('182 nodes · 240 links');
+ });
+
+ it('leaves out a line it has nothing to say on', () => {
+ const { svg } = plateHeader({ view: 'Bare', caseName: 'Case' }, 900);
+ expect(svg).not.toContain('Question:');
+ expect(svg).not.toContain('Fact time');
+ expect(svg).not.toContain('Exported');
+ });
+});
+
+describe('the plate legend', () => {
+ it('draws a hue per family and the dash pattern of every stroke on show', () => {
+ const { svg, height } = plateLegend(
+ { families: [{ family: 'actor', count: 2 }, { family: 'place', count: 5 }], strokes: EDGE_KINDS },
+ 900,
+ 500,
+ );
+ expect(svg).toContain(PLATE_COLOURS.family.actor);
+ expect(svg).toContain('actor · 2');
+ expect(svg).toContain('stated relation');
+ // 8, 5 is the stated relation's own pattern in EDGE_KINDS — the wording and the
+ // dashes both come from the registry rather than from a second table here.
+ expect(svg).toContain('stroke-dasharray="8 5"');
+ expect(height).toBeGreaterThan(PLATE.legendRow);
+ });
+
+ it('says nothing when there is nothing to explain', () => {
+ const { svg, height } = plateLegend({}, 900, 100);
+ expect(svg).toContain('<line');
+ expect(height).toBe(18);
+ });
+
+ it('flows into as many columns as the plate is wide', () => {
+ const families = FAMILY_ORDER.map((family) => ({ family, count: 1 }));
+ const narrow = plateLegend({ families }, PLATE.legendColumn + PLATE.pad * 2, 0);
+ const wide = plateLegend({ families }, 2000, 0);
+ expect(narrow.height).toBeGreaterThan(wide.height);
+ });
+});
+
+describe('framing a drawing', () => {
+ it('widens to the drawing, holds it under the header and closes the document', () => {
+ const { svg, width, height } = plateDocument({
+ meta,
+ families: [{ family: 'actor', count: 1 }],
+ strokes: [EDGE_KINDS[0]],
+ drawing: { width: 1200, height: 800, body: '<circle cx="1" cy="2" r="3" />', defs: '<marker id="m" />' },
+ });
+ expect(width).toBe(1200 + PLATE.pad * 2);
+ expect(svg.startsWith('<svg xmlns="http://www.w3.org/2000/svg"')).toBe(true);
+ expect(svg).toContain(`viewBox="0 0 ${width} ${height}"`);
+ expect(svg).toContain('<defs><marker id="m" /></defs>');
+ expect(svg).toContain('<circle cx="1" cy="2" r="3" />');
+ expect(svg.trimEnd().endsWith('</svg>')).toBe(true);
+ });
+
+ it('never shrinks below a readable plate, nor past a size no reader gains from', () => {
+ expect(plateDocument({ drawing: { width: 10, height: 10, body: '' } }).width)
+ .toBe(PLATE.minWidth);
+ expect(plateDocument({ drawing: { width: 99_999, height: 10, body: '' } }).width)
+ .toBe(PLATE.maxWidth);
+ });
+});
+
+describe('serialising text', () => {
+ it('escapes what a label may hold, so one entity name cannot break the file', () => {
+ expect(escapeXml('Quay & <script>alert("x")</script>')).toBe(
+ 'Quay &amp; &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;'
+ );
+ expect(svgText('a & b', { x: 1, y: 2 })).toContain('a &amp; b');
+ });
+
+ it('haloes a label that has to survive crossing a line', () => {
+ const drawn = svgText('Quay 4', { x: 1, y: 2, halo: 3 });
+ expect(drawn).toContain(`stroke="${PLATE_COLOURS.paper}"`);
+ expect(drawn).toContain('paint-order="stroke"');
+ expect(svgText('Quay 4', { x: 1, y: 2 })).not.toContain('paint-order');
+ });
+
+ it('writes nothing for a label with nothing in it', () => {
+ expect(svgText(' ', { x: 1, y: 2 })).toBe('');
+ expect(svgText(null, { x: 1, y: 2 })).toBe('');
+ });
+
+ it('cuts to the room it is given, and never through a surrogate pair', () => {
+ expect(fitText('Checkpoint standing', 1000)).toBe('Checkpoint standing');
+ expect(fitText('Checkpoint standing', 30)).toBe('Chec…');
+ expect(fitText('Checkpoint standing', 3)).toBe('');
+ // Half of a pair is not a character, and a plate holding one cannot be written out.
+ expect(fitText('🏴🏴🏴🏴', 18)).toBe('🏴🏴…');
+ expect(fitText(null, 100)).toBe('');
+ // The face matters: a title costs more per character than a lane label.
+ expect(fitText('Checkpoint standing', 60, PLATE.titleChar)).toBe('Check…');
+ });
+});
+
+describe('naming the file', () => {
+ it('is named after the reading, stamped to the minute', () => {
+ expect(plateFilename({ surface: 'Graph', view: 'Rooftop match', at: meta.at }))
+ .toBe('graph-rooftop-match-202608132010');
+ });
+
+ it('falls back to the lens, then to a name that is still a name', () => {
+ expect(plateFilename({ surface: 'graph', lens: 'All connections', at: meta.at }))
+ .toBe('graph-all-connections-202608132010');
+ expect(plateFilename({ at: meta.at })).toBe('graph-reading-202608132010');
+ });
+});
diff --git a/frontend/src/lib/plateExport.js b/frontend/src/lib/plateExport.js
new file mode 100644
index 0000000..41ee6c3
--- /dev/null
+++ b/frontend/src/lib/plateExport.js
@@ -0,0 +1,67 @@
+/**
+ * Getting a plate out of the tab: to a file, or onto the clipboard.
+ *
+ * The document itself is written by the surfaces (`lib/graphPlate.js`,
+ * `lib/timelinePlate.js`); what is left here is where it goes. The file is posted back
+ * for the backend to write, the way the notes PDF is: an export lands in the folder the
+ * analyst chose for this kind of work, and the browser has no way to write there.
+ *
+ * The clipboard gets a PNG, never the SVG. Nothing pastes an SVG — not a document, not
+ * a chat — so a "Copy image" that copied the vector would copy nothing anybody could
+ * use. The pixels come from the same page the file holds, rasterised here.
+ */
+
+import { api } from './api.js';
+import { rasterScale, rasterise } from './notesExport.js';
+
+/** Twice the page, so a raster of a vector plate is not soft, and capped where a
+ * browser canvas stops being dependable. */
+export const PLATE_SCALE = 2;
+export const PLATE_MAX_EDGE = 4000;
+
+/**
+ * What the raster of this plate will really be, as a factor of the page.
+ *
+ * The cap bites well before the largest plate: a page wider than 2000 units comes back
+ * under 2×, and the widest one comes back smaller than itself. The dialog asks for this
+ * number rather than promising a factor the canvas will not give.
+ */
+export const plateScale = ({ width, height }) =>
+ rasterScale({ width, height, scale: PLATE_SCALE, maxEdge: PLATE_MAX_EDGE });
+
+export function plateToPng(svg, { width, height }) {
+ return rasterise(svg, { width, height, scale: PLATE_SCALE, maxEdge: PLATE_MAX_EDGE });
+}
+
+/** Write the plate into the destination saved for analysis views. */
+export async function writePlate(caseId, plate, { format = 'svg', toPng = plateToPng } = {}) {
+ const { svg, width, height, filename } = plate;
+ const body = format === 'png'
+ ? { filename, format, png: await toPng(svg, { width, height }) }
+ : { filename, format, svg };
+ return api.post(`/api/cases/${caseId}/plates`, body);
+}
+
+export const revealPlates = (caseId) => api.post(`/api/cases/${caseId}/plates/reveal`);
+
+export function pngBlob(base64) {
+ const binary = atob(base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
+ return new Blob([bytes], { type: 'image/png' });
+}
+
+/**
+ * Put the plate on the clipboard as an image.
+ *
+ * A browser that cannot write an image says so rather than reporting a copy that did
+ * not happen: the analyst would paste the last thing they copied and never know.
+ */
+export async function copyPlateImage(plate, { toPng = plateToPng, clipboard } = {}) {
+ const target = clipboard ?? (typeof navigator === 'undefined' ? null : navigator.clipboard);
+ if (!target?.write || typeof ClipboardItem === 'undefined') {
+ throw new Error('this browser cannot copy an image');
+ }
+ const base64 = await toPng(plate.svg, { width: plate.width, height: plate.height });
+ await target.write([new ClipboardItem({ 'image/png': pngBlob(base64) })]);
+}
diff --git a/frontend/src/lib/plateExport.test.js b/frontend/src/lib/plateExport.test.js
new file mode 100644
index 0000000..a570d3a
--- /dev/null
+++ b/frontend/src/lib/plateExport.test.js
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const post = vi.fn(() => Promise.resolve({ file: 'graph.svg', path: '/reports' }));
+vi.mock('./api.js', () => ({ api: { post } }));
+
+const {
+ PLATE_MAX_EDGE, PLATE_SCALE, copyPlateImage, plateScale, pngBlob, revealPlates, writePlate,
+} = await import('./plateExport.js');
+
+const PLATE = {
+ svg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>',
+ width: 900,
+ height: 600,
+ filename: 'graph-rooftop-202608132010',
+};
+
+/** One pixel of PNG, base64 — enough to prove what travels, not what it looks like. */
+const PNG64 = 'iVBORw0KGgo=';
+
+beforeEach(() => post.mockClear());
+
+describe('writing a plate out', () => {
+ it('posts the vector page as it stands', async () => {
+ await writePlate('case-a', PLATE);
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/plates', {
+ filename: PLATE.filename, format: 'svg', svg: PLATE.svg,
+ });
+ });
+
+ it('rasterises first when an image was asked for, and sends no markup', async () => {
+ const toPng = vi.fn(() => Promise.resolve(PNG64));
+
+ await writePlate('case-a', PLATE, { format: 'png', toPng });
+
+ expect(toPng).toHaveBeenCalledWith(PLATE.svg, { width: 900, height: 600 });
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/plates', {
+ filename: PLATE.filename, format: 'png', png: PNG64,
+ });
+ });
+
+ it('asks for the folder without naming it', async () => {
+ await revealPlates('case-a');
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/plates/reveal');
+ });
+});
+
+describe('the scale a raster can promise', () => {
+ it('is twice the page only while the page is small enough for it', () => {
+ expect(plateScale({ width: 900, height: 600 })).toBe(PLATE_SCALE);
+ // Past half the edge cap the ceiling bites, and the widest plate a reading can make
+ // comes back smaller than itself. A dialog offering "twice the page" would be lying.
+ expect(plateScale({ width: 3000, height: 2200 })).toBeCloseTo(PLATE_MAX_EDGE / 3000, 5);
+ expect(plateScale({ width: 4800, height: 2000 })).toBeLessThan(1);
+ expect(plateScale({ width: 0, height: 0 })).toBe(PLATE_SCALE);
+ });
+});
+
+describe('copying a plate', () => {
+ it('puts pixels on the clipboard, because an SVG pastes nowhere', async () => {
+ const written = [];
+ const clipboard = { write: (items) => (written.push(items), Promise.resolve()) };
+ vi.stubGlobal('ClipboardItem', class { constructor(parts) { this.parts = parts; } });
+
+ await copyPlateImage(PLATE, { clipboard, toPng: () => Promise.resolve(PNG64) });
+
+ expect(written).toHaveLength(1);
+ expect(written[0][0].parts['image/png']).toBeInstanceOf(Blob);
+ expect(written[0][0].parts['image/png'].type).toBe('image/png');
+ });
+
+ it('says a browser cannot copy rather than reporting a copy that never happened', async () => {
+ vi.stubGlobal('ClipboardItem', undefined);
+ await expect(copyPlateImage(PLATE, { clipboard: {} })).rejects.toThrow('cannot copy an image');
+ });
+
+ it('decodes base64 into the bytes a PNG starts with', () => {
+ const blob = pngBlob(PNG64);
+ expect(blob.type).toBe('image/png');
+ expect(blob.size).toBe(8);
+ });
+});
diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.js
index ab9aa86..1778267 100644
--- a/frontend/src/lib/post.js
+++ b/frontend/src/lib/post.js
@@ -99,6 +99,7 @@ export function postReportMarkdown({
place,
plusCode,
coordinates,
+ points = [],
dms,
mapLinks = {},
description,
@@ -138,14 +139,21 @@ export function postReportMarkdown({
...location.map(([label, value]) => `| ${label} | ${value} |`),
].join('\n'));
}
- if (clean(description)) sections.push(`## Assessment\n\n${clean(description)}`);
- if (clean(source)) {
- const sourceText = clean(source);
- const sourceValue = /^https?:\/\//i.test(sourceText)
- ? `[Open original source](${sourceText})`
- : sourceText;
- sections.push(`## Source\n\n${sourceValue}`);
+ // Every point the proof argues, once there is more than one. Location above
+ // is the conclusion — the address the post is written about — and this is the
+ // rest of what the picture shows, which a tweet has no room to name.
+ const listed = (points ?? []).filter((one) => clean(one?.coords));
+ if (listed.length > 1) {
+ sections.push([
+ '## Points',
+ '',
+ '| Point | Coordinates |',
+ '| --- | --- |',
+ ...listed.map((one, i) => `| ${cell(one.label) || `Point ${i + 1}`} | ${inlineCode(one.coords)} |`),
+ ].join('\n'));
}
+ if (clean(description)) sections.push(`## Assessment\n\n${clean(description)}`);
+ if (clean(source)) sections.push(`## Source\n\n${sourceSection(source)}`);
const mediaByPath = new Map(
mediaEntities
.filter((entity) => entity?.id && entity?.attrs?.path)
@@ -343,13 +351,59 @@ export const DEFAULT_TWEET_BODY = [
'Source: #source',
].join('\n');
+/** What separates a point's name from its coordinates, on the one line it gets. */
+export const POINT_SEPARATOR = ' — ';
+
+/** One coordinate line split into its optional name and its coordinates. */
+export function splitPointLine(line) {
+ const text = String(line ?? '').trim();
+ const at = text.indexOf(POINT_SEPARATOR);
+ if (at < 0) return { label: '', coords: text };
+ return {
+ label: text.slice(0, at).trim(),
+ coords: text.slice(at + POINT_SEPARATOR.length).trim(),
+ };
+}
+
+/** The lines a coordinate block holds, dropping the empty ones. */
+export function pointLines(text) {
+ return String(text ?? '')
+ .split('\n')
+ .map(splitPointLine)
+ .filter((one) => one.coords);
+}
+
+/**
+ * The coordinates a post carries, one point per line.
+ *
+ * A proof shows more than one place often enough — three impacts, a building,
+ * the camera — and the analyst reads the numbers, so the tweet carries all of
+ * them rather than the conclusion alone. The first line is the one the post
+ * resolved, so it reads in decimal as it always has; the rest read as they were
+ * written, and a name keeps its line either way.
+ */
+export function postCoordinates(text, { lat, lon } = {}) {
+ const lines = pointLines(text);
+ if (lat != null && lon != null) {
+ const decimal = `${Number(lat).toFixed(6)}, ${Number(lon).toFixed(6)}`;
+ if (lines.length) lines[0] = { ...lines[0], coords: decimal };
+ else lines.push({ label: '', coords: decimal });
+ }
+ return lines
+ .map((one) => (one.label ? `${one.label}${POINT_SEPARATOR}${one.coords}` : one.coords))
+ .join('\n');
+}
+
/** Resolve the live draft into the string each token stands for ('' when absent). */
-export function tweetFields({ place, plusCode, description, lat, lon, mention, source } = {}) {
+export function tweetFields({
+ place, plusCode, description, lat, lon, coordsText, mention, source,
+} = {}) {
return {
place: place?.trim() ?? '',
+ // Place and plus code are one point's address, and that point is the
+ // conclusion: the header of a tweet is about the proof, not about impact 2.
plusCode: plusCode ?? '',
- coordinates:
- lat != null && lon != null ? `${Number(lat).toFixed(6)}, ${Number(lon).toFixed(6)}` : '',
+ coordinates: postCoordinates(coordsText, { lat, lon }),
description: description?.trim() ?? '',
mention: mention?.trim() ?? '',
source: source?.trim() ?? '',
@@ -399,12 +453,40 @@ export function templateUsesPostField(body, field) {
return tokens.some((token) => lowerBody.includes(token));
}
+//: What an address looks like inside a source line. The composer joins several with
+//: its own separator, so the middle dot ends one as surely as a space does.
+const SOURCE_URL = /https?:\/\/[^\s·]+/gi;
+
+/** Every address a proof's source line holds, in the order it holds them. */
+export function sourceUrls(sourceLine) {
+ return String(sourceLine ?? '').match(SOURCE_URL) ?? [];
+}
+
+/**
+ * The Source section's body: a link per address, or the line as it stands.
+ *
+ * A line that is nothing but addresses becomes one link each, because wrapping the
+ * whole line in a single href made a dead link the moment a proof rested on two
+ * posts. A line carrying anything else is prose the analyst typed, and prose is
+ * printed rather than linked.
+ */
+export function sourceSection(sourceLine) {
+ const text = String(sourceLine ?? '').trim();
+ const urls = sourceUrls(text);
+ if (!urls.length) return text;
+ if (text.replace(SOURCE_URL, ' ').replace(/[\s·,;|]+/g, '')) return text;
+ if (urls.length === 1) return `[Open original source](${urls[0]})`;
+ // A list, because Markdown needs one to break a line at all and a reader needs one to
+ // tell four sources apart.
+ return urls.map((url) => `- [${url}](${url})`).join('\n');
+}
+
/**
* Find original downloaded media behind a proof whose source matches the proof
* source line. Derived PNGs, collages and satellite captures are excluded.
*/
export function proofSourceMediaPaths(caseData, proofPng, proofSource, mediaItems = []) {
- const wantedUrls = new Set(String(proofSource ?? '').match(/https?:\/\/[^\s·]+/gi) ?? []);
+ const wantedUrls = new Set(sourceUrls(proofSource));
if (!wantedUrls.size) return [];
const entities = Array.isArray(caseData?.entities) ? caseData.entities : [];
const links = Array.isArray(caseData?.links) ? caseData.links : [];
diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.js
index ac57d09..1672dbf 100644
--- a/frontend/src/lib/post.test.js
+++ b/frontend/src/lib/post.test.js
@@ -5,7 +5,9 @@ import {
applyPostTemplateStructure, normalizePostMediaPickerTarget, normPostTemplate, postMediaForType,
postCharacterCount, postComposeUrl, postReportMarkdown, postTarget,
proofSourceMediaPaths, renumberMediaTweetText, retargetMediaTweetText,
+ sourceSection, sourceUrls,
templateFromPost, templateUsesPostField, togglePostMedia,
+ pointLines, postCoordinates, splitPointLine,
} from './post.js';
const full = {
@@ -380,6 +382,42 @@ describe('post targets', () => {
});
});
+describe('sourceSection — a proof resting on more than one post', () => {
+ it('links every address when the line is nothing but addresses', () => {
+ // The composer hands over one address per line, so this is the ordinary shape of a
+ // proof built from two posts. A run separated by dots is what proofs saved before
+ // that carried, and it reads the same.
+ const listed = [
+ '- [https://x.com/a/1](https://x.com/a/1)',
+ '- [https://t.me/b/2](https://t.me/b/2)',
+ ].join('\n');
+ expect(sourceSection('https://x.com/a/1\nhttps://t.me/b/2')).toBe(listed);
+ expect(sourceSection('https://x.com/a/1 · https://t.me/b/2')).toBe(listed);
+ // One address keeps the reading it always had.
+ expect(sourceSection('https://x.com/a/1')).toBe('[Open original source](https://x.com/a/1)');
+ });
+
+ it('prints prose instead of linking it', () => {
+ expect(sourceSection('handed to me on a stick')).toBe('handed to me on a stick');
+ // A line that starts with an address and goes on saying something used to be
+ // wrapped whole in one href, which is a dead link either way.
+ expect(sourceSection('https://x.com/a/1 reposted from elsewhere')).toBe(
+ 'https://x.com/a/1 reposted from elsewhere',
+ );
+ expect(sourceSection('')).toBe('');
+ });
+
+ it('keeps the report and the media matcher reading the same line', () => {
+ const line = 'https://x.com/a/1\nhttps://t.me/b/2';
+ const report = postReportMarkdown({ title: 'Two posts', source: line });
+ expect(report).toContain('- [https://x.com/a/1](https://x.com/a/1)');
+ expect(report).toContain('- [https://t.me/b/2](https://t.me/b/2)');
+ expect(report).not.toContain(`(${line})`); // the one broken href this replaces
+ // And the matcher reads the same block the report just rendered.
+ expect(sourceUrls(line)).toEqual(['https://x.com/a/1', 'https://t.me/b/2']);
+ });
+});
+
describe('postReportMarkdown', () => {
it('renders a structured report with links, maps and embedded case media', () => {
const report = postReportMarkdown({
@@ -415,3 +453,71 @@ describe('postReportMarkdown', () => {
expect(postReportMarkdown()).toBe('# Untitled report\n');
});
});
+
+
+describe('the points a post carries', () => {
+ it('reads a line with a name and a line without', () => {
+ expect(splitPointLine('impact 2 — 64.148100, -21.940100')).toEqual({
+ label: 'impact 2', coords: '64.148100, -21.940100',
+ });
+ expect(splitPointLine(' 64.148100, -21.940100 ')).toEqual({
+ label: '', coords: '64.148100, -21.940100',
+ });
+ });
+
+ it('drops the blank lines a pasted block leaves behind', () => {
+ expect(pointLines('64.1466, -21.9426\n\n \nb — 1, 2')).toEqual([
+ { label: '', coords: '64.1466, -21.9426' },
+ { label: 'b', coords: '1, 2' },
+ ]);
+ });
+
+ it('reads the resolved point in decimal and the rest as written', () => {
+ // the first line is the one the post looked up, so it reads as it always has
+ expect(postCoordinates('64°08\'48"N 21°56\'33"W\nimpact 2 — 64.1481, -21.9401', {
+ lat: 64.1466, lon: -21.9426,
+ })).toBe('64.146600, -21.942600\nimpact 2 — 64.1481, -21.9401');
+ });
+
+ it('keeps the name of the point it resolved', () => {
+ expect(postCoordinates('caméra — 64.1466, -21.9426', { lat: 64.1466, lon: -21.9426 }))
+ .toBe('caméra — 64.146600, -21.942600');
+ });
+
+ it('carries one point exactly as it did before the list', () => {
+ expect(tweetFields({ lat: 48.85, lon: 2.35 }).coordinates).toBe('48.850000, 2.350000');
+ });
+
+ it('carries every point into the tweet, one per line', () => {
+ const fields = tweetFields({
+ lat: 64.1466, lon: -21.9426,
+ coordsText: 'impact 1 — 64.1466, -21.9426\nimpact 2 — 64.1481, -21.9401',
+ });
+ expect(fields.coordinates).toBe(
+ 'impact 1 — 64.146600, -21.942600\nimpact 2 — 64.1481, -21.9401'
+ );
+ });
+
+ it('tables the points in the report, once there is more than one', () => {
+ const report = postReportMarkdown({
+ title: 'Harbour strike',
+ coordinates: '64.146600, -21.942600',
+ points: [
+ { label: 'impact 1', coords: '64.1466, -21.9426' },
+ { label: '', coords: '64.1481, -21.9401' },
+ ],
+ });
+ expect(report).toContain('## Points');
+ expect(report).toContain('| impact 1 | `64.1466, -21.9426` |');
+ expect(report).toContain('| Point 2 | `64.1481, -21.9401` |'); // unnamed takes its rank
+ });
+
+ it('leaves a single-point report the shape it had', () => {
+ const report = postReportMarkdown({
+ title: 'One point',
+ coordinates: '64.146600, -21.942600',
+ points: [{ label: '', coords: '64.1466, -21.9426' }],
+ });
+ expect(report).not.toContain('## Points');
+ });
+});
diff --git a/frontend/src/lib/proofEdits.js b/frontend/src/lib/proofEdits.js
index 2e0d3a5..d4ffed0 100644
--- a/frontend/src/lib/proofEdits.js
+++ b/frontend/src/lib/proofEdits.js
@@ -35,6 +35,26 @@ export function nudgeShape(shape, dx, dy) {
return { x: (shape.x ?? 0) + dx, y: (shape.y ?? 0) + dy };
}
+/**
+ * A polyline with a 2×3 affine matrix folded into every vertex.
+ *
+ * `[a, b, c, d, e, f]` is the shape Konva hands back for a node's own
+ * transform: x' = ax + cy + e, y' = bx + dy + f. A freehand stroke is only its
+ * samples — there is no width, no radius and no origin to write a resize into —
+ * so a corner drag has nowhere to live but the points themselves. Folding it in
+ * is what lets the next gesture start from what is drawn instead of from a node
+ * still carrying the last one.
+ */
+export function pointsWithTransform(points, [a, b, c, d, e, f]) {
+ const out = [];
+ for (let i = 0; i < points.length; i += 2) {
+ const x = points[i];
+ const y = points[i + 1];
+ out.push(a * x + c * y + e, b * x + d * y + f);
+ }
+ return out;
+}
+
/**
* The legend after an element is deleted.
*
@@ -106,3 +126,48 @@ export function viewCentrePoint(view, stage) {
y: (view.height / 2 - stage.y) / stage.scaleY,
};
}
+
+/**
+ * The padding between a boxed label's frame and its glyph, in the label's own
+ * pixels.
+ *
+ * Read twice: once to draw the box, once to place the inline editor over the
+ * glyph inside it. A number that lived in only one of those two put the editor
+ * a few pixels off whatever it was editing.
+ */
+export function textBoxPad(fontSize) {
+ return Math.round((fontSize ?? 28) * 0.28);
+}
+
+/**
+ * Kinds a fill applies to: the closed ones, plus symbols.
+ *
+ * On a symbol the fill is not inside the glyph but behind it — a disc in the
+ * same colour, which is what makes a thin stroked mark survive being laid over
+ * aerial imagery. It rides on this control rather than a second one because it
+ * answers the same question: how much of its own colour does this element put
+ * between the reader and the picture.
+ */
+export function canFill(kind) {
+ return kind === 'rect' || kind === 'ellipse' || kind === 'icon';
+}
+
+/**
+ * The paint a filled shape uses, or null when it has no fill.
+ *
+ * A fill is the element's own colour at a chosen opacity, never a second colour:
+ * the legend is keyed on colour, so a box outlined in one and filled in another
+ * would claim two features where the analyst meant one. Konva has no fill
+ * opacity of its own — node opacity would fade the stroke with it — so the alpha
+ * rides in the colour. Anything that is not a hex colour gets no fill rather
+ * than an opaque one, since a fill that was not asked for hides the evidence.
+ */
+export function fillPaint(color, opacity) {
+ const alpha = Number(opacity);
+ if (!Number.isFinite(alpha) || alpha <= 0) return null;
+ const match = /^#([0-9a-f]{3}|[0-9a-f]{6})$/.exec(String(color ?? '').trim().toLowerCase());
+ if (!match) return null;
+ const digits = match[1].length === 3 ? match[1].replace(/./g, (c) => c + c) : match[1];
+ const [r, g, b] = [0, 2, 4].map((i) => parseInt(digits.slice(i, i + 2), 16));
+ return `rgba(${r}, ${g}, ${b}, ${Math.min(1, alpha)})`;
+}
diff --git a/frontend/src/lib/proofEdits.test.js b/frontend/src/lib/proofEdits.test.js
index 8142f48..4f64204 100644
--- a/frontend/src/lib/proofEdits.test.js
+++ b/frontend/src/lib/proofEdits.test.js
@@ -1,13 +1,17 @@
import { describe, expect, it } from 'vitest';
import { PANEL_H } from './composer.js';
import {
+ canFill,
+ fillPaint,
movedBy,
nextPanelRow,
notesAfterRemoval,
nudgeShape,
PANEL_SCALE_MAX,
PANEL_SCALE_MIN,
+ pointsWithTransform,
scaleFromNode,
+ textBoxPad,
viewCentrePoint,
} from './proofEdits.js';
@@ -162,3 +166,76 @@ describe('viewCentrePoint', () => {
expect(point).toEqual({ x: 200, y: 150 });
});
});
+
+describe('a shape fill', () => {
+ it('applies to the closed kinds only', () => {
+ expect(canFill('rect')).toBe(true);
+ expect(canFill('ellipse')).toBe(true);
+ expect(['line', 'arrow', 'curve', 'freehand', 'text'].map(canFill)).toEqual(
+ [false, false, false, false, false]
+ );
+ expect(canFill(undefined)).toBe(false);
+ });
+
+ it('is the shape colour carrying the chosen opacity', () => {
+ expect(fillPaint('#40c4ff', 0.25)).toBe('rgba(64, 196, 255, 0.25)');
+ expect(fillPaint('#FFFFFF', 1)).toBe('rgba(255, 255, 255, 1)');
+ expect(fillPaint('#fff', 0.5)).toBe('rgba(255, 255, 255, 0.5)');
+ });
+
+ it('is nothing at all until an opacity is asked for', () => {
+ expect(fillPaint('#40c4ff', 0)).toBeNull();
+ expect(fillPaint('#40c4ff', undefined)).toBeNull();
+ expect(fillPaint('#40c4ff', -1)).toBeNull();
+ });
+
+ it('refuses a colour it cannot read rather than painting over the evidence', () => {
+ expect(fillPaint('red', 0.5)).toBeNull();
+ expect(fillPaint(null, 0.5)).toBeNull();
+ });
+
+ it('never paints past opaque', () => {
+ expect(fillPaint('#000000', 4)).toBe('rgba(0, 0, 0, 1)');
+ });
+});
+
+describe('pointsWithTransform', () => {
+ // Konva hands back [a, b, c, d, e, f]: x' = ax + cy + e, y' = bx + dy + f.
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
+
+ it('leaves a stroke alone when nothing moved it', () => {
+ expect(pointsWithTransform([0, 0, 10, 4], IDENTITY)).toEqual([0, 0, 10, 4]);
+ });
+
+ it('folds a corner drag into every sample, not just the first', () => {
+ // doubled, then moved 5 right and 1 down
+ expect(pointsWithTransform([0, 0, 10, 4, 20, 8], [2, 0, 0, 2, 5, 1]))
+ .toEqual([5, 1, 25, 9, 45, 17]);
+ });
+
+ it('folds a quarter turn in as well, since a stroke has no origin to keep one against', () => {
+ const quarter = [0, 1, -1, 0, 0, 0]; // 90° clockwise about the panel origin
+ expect(pointsWithTransform([1, 0, 0, 2], quarter)).toEqual([0, 1, -2, 0]);
+ });
+
+ it('answers with a new list rather than editing the one it was given', () => {
+ const points = [1, 2, 3, 4];
+ expect(pointsWithTransform(points, [3, 0, 0, 3, 0, 0])).not.toBe(points);
+ expect(points).toEqual([1, 2, 3, 4]);
+ });
+
+ it('has nothing to fold into an empty stroke', () => {
+ expect(pointsWithTransform([], [2, 0, 0, 2, 5, 5])).toEqual([]);
+ });
+});
+
+describe('textBoxPad', () => {
+ it('grows with the label, so a frame reads the same at any size', () => {
+ expect(textBoxPad(28)).toBe(8);
+ expect(textBoxPad(100)).toBe(28);
+ });
+
+ it('answers for a label that never stated a size', () => {
+ expect(textBoxPad(undefined)).toBe(textBoxPad(28));
+ });
+});
diff --git a/frontend/src/lib/proofIcons.js b/frontend/src/lib/proofIcons.js
new file mode 100644
index 0000000..a742f88
--- /dev/null
+++ b/frontend/src/lib/proofIcons.js
@@ -0,0 +1,165 @@
+/**
+ * The symbols a proof can stamp onto a panel.
+ *
+ * These are document content, not interface furniture, which is why they live
+ * here and not in `Icon.svelte`: one is drawn into the exported picture and has
+ * to survive a save, the other only ever decorates a button. They share a
+ * geometry — a 24×24 box, stroke-based, round caps — so a symbol reads as part
+ * of the same drawing as the boxes and arrows beside it.
+ *
+ * Two rules hold the set together:
+ *
+ * A symbol takes the active colour like every other annotation, so it joins the
+ * legend by colour and claims no vocabulary of its own. The legend is keyed on
+ * colour (`featureColors`), and a symbol that meant something the legend could
+ * not say would leave the reader with two systems and no way to tell which one
+ * the analyst meant.
+ *
+ * A symbol scales but never deforms. Its box is square and `size` is that box's
+ * side, so there is one dimension to change and stretching is not expressible.
+ */
+
+/** Side of the box every path is drawn in. */
+export const ICON_BOX = 24;
+
+/** Placed side, in screen pixels at panel scale 1 — see `iconSizeFor`. */
+export const ICON_SIZE_DEFAULT = 56;
+
+export const ICON_SIZE_MIN = 12;
+
+/**
+ * Solid symbols carry no stroke: their shape *is* the mark. A pin outlined at
+ * 1px vanishes over noisy imagery, and a burst reads as a burst only when it is
+ * filled. They ignore the stroke-width control, which is why it hides for them
+ * rather than sitting there doing nothing.
+ */
+const SOLID = new Set(['point', 'impact', 'nord']);
+
+/**
+ * Where the symbol sits on the point it names, in fractions of its box.
+ *
+ * Centre for everything that marks an area. The pin is the exception and the
+ * reason the field exists: a pin means *this pixel*, so it hangs from its tip.
+ * Anchored at its centre it would slide off the thing it points at every time
+ * the analyst resized it.
+ */
+const ANCHORS = { point: [0.5, 22.4 / ICON_BOX] };
+
+export const PROOF_ICONS = [
+ {
+ name: 'point',
+ label: 'Point',
+ path: 'M12 22.4s7.3-7.2 7.3-12.1a7.3 7.3 0 0 0-14.6 0C4.7 15.2 12 22.4 12 22.4Zm0-9.2a2.9 2.9 0 1 0 0-5.8 2.9 2.9 0 0 0 0 5.8Z',
+ },
+ {
+ name: 'impact',
+ label: 'Impact',
+ path: 'M12 1.5 13.8 7.6 17.7 6.3 16.4 10.2 22 12 16.4 13.8 18.2 18.2 13.8 16.4 12 22.5 10.2 16.4 6.2 17.8 7.6 13.8 2.4 12 7.6 10.2 5.9 5.9 10.2 7.6Z',
+ },
+ {
+ name: 'vehicle',
+ label: 'Vehicle',
+ path: 'M2.3 16.4v-2.9a1 1 0 0 1 .7-1l3.4-.9 2.5-3.3a1.5 1.5 0 0 1 1.2-.6h4.2a1.5 1.5 0 0 1 1.1.5l3 3.4 3.4.9a1 1 0 0 1 .7 1v2.9M2.3 16.4h2.5M9.2 16.4h5.6M19.2 16.4h3.3M4.8 17.2a2.2 2.2 0 1 0 4.4 0 2.2 2.2 0 0 0-4.4 0Zm10 0a2.2 2.2 0 1 0 4.4 0 2.2 2.2 0 0 0-4.4 0Z',
+ },
+ {
+ name: 'truck',
+ label: 'Truck',
+ path: 'M7.4 15.5V6a.8.8 0 0 1 .8-.8h13.2a.8.8 0 0 1 .8.8v9.5M7.4 8.1H4.75a1 1 0 0 0-.75.34L1.35 10.84a1 1 0 0 0-.25.66v3.2a.8.8 0 0 0 .8.8h.7M6.6 15.5h8.9M19.5 15.5h2.7M2.6 16.6a2 2 0 1 0 4 0 2 2 0 0 0-4 0Zm12.9 0a2 2 0 1 0 4 0 2 2 0 0 0-4 0Z',
+ },
+ {
+ name: 'tank',
+ label: 'Tank',
+ path: 'M4.3 15.4h15.4a2.1 2.1 0 1 1 0 4.2H4.3a2.1 2.1 0 1 1 0-4.2ZM7.3 17.5h.01M12 17.5h.01M16.7 17.5h.01M2.9 15.4v-2.6a.9.9 0 0 1 .6-.85l2.8-.95h13.4a.9.9 0 0 1 .9.9v3.5M9 11V9a1 1 0 0 1 1-1h4.6a1 1 0 0 1 1 1v2M9 9.4H2.4',
+ },
+ {
+ name: 'person',
+ label: 'Person',
+ path: 'M12 2a2.4 2.4 0 1 1 0 4.8 2.4 2.4 0 0 1 0-4.8ZM12 6.8v7.2M12 9.2 7.9 12.2M12 9.2l4.1 3M12 14 8.7 21.4M12 14l3.3 7.4',
+ },
+ {
+ name: 'building',
+ label: 'Building',
+ path: 'M5.2 20.5V4.3a.9.9 0 0 1 .9-.9h11.8a.9.9 0 0 1 .9.9v16.2M3.6 20.5h16.8M8.2 7.3h1.9M13.9 7.3h1.9M8.2 11.1h1.9M13.9 11.1h1.9M10.1 20.5v-4.3h3.8v4.3',
+ },
+ {
+ name: 'drone',
+ label: 'Drone',
+ path: 'M9.2 10.4h5.6a.6.6 0 0 1 .6.6v2a.6.6 0 0 1-.6.6H9.2a.6.6 0 0 1-.6-.6v-2a.6.6 0 0 1 .6-.6ZM8.6 10.4 7 7.8M15.4 10.4 17 7.8M8.6 13.6 7 16.2M15.4 13.6 17 16.2M5.6 3a2.6 2.6 0 1 0 0 5.2 2.6 2.6 0 0 0 0-5.2Zm12.8 0a2.6 2.6 0 1 0 0 5.2 2.6 2.6 0 0 0 0-5.2ZM5.6 15.8a2.6 2.6 0 1 0 0 5.2 2.6 2.6 0 0 0 0-5.2Zm12.8 0a2.6 2.6 0 1 0 0 5.2 2.6 2.6 0 0 0 0-5.2Z',
+ },
+ {
+ name: 'camera',
+ label: 'Camera',
+ path: 'M3.2 8.4h4.2l1.6-2.8h6l1.6 2.8h4.2a1 1 0 0 1 1 1v9.6a1 1 0 0 1-1 1H3.2a1 1 0 0 1-1-1V9.4a1 1 0 0 1 1-1ZM12 10.1a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z',
+ },
+ {
+ name: 'antenna',
+ label: 'Antenna',
+ path: 'M12 5.2a1.2 1.2 0 1 1 0 2.4 1.2 1.2 0 0 1 0-2.4ZM9 21 11.4 7.6M15 21 12.6 7.6M9.7 17h4.6M10.4 13h3.2M7.8 21h8.4M9.9 4.3a3 3 0 0 0 0 4.2M14.1 4.3a3 3 0 0 1 0 4.2M8.2 2.6a5.4 5.4 0 0 0 0 7.6M15.8 2.6a5.4 5.4 0 0 1 0 7.6',
+ },
+ {
+ // Two-tone needle: the whole silhouette filled, the left half punched back
+ // out with the even-odd rule, which is how a compass rose reads north.
+ name: 'nord',
+ label: 'North',
+ path: 'M12 2 16.7 20.4 12 17 7.3 20.4ZM11.85 5.2 9 17.6 11.85 15.2Z',
+ },
+];
+
+const BY_NAME = new Map(PROOF_ICONS.map((entry) => [entry.name, entry]));
+
+/** The symbol by name, or null — a spec may name one this build dropped. */
+export function iconByName(name) {
+ return BY_NAME.get(name) ?? null;
+}
+
+/** Whether the symbol is a filled silhouette, so has no stroke to set. */
+export function isSolidIcon(name) {
+ return SOLID.has(name);
+}
+
+/** Anchor of the symbol within its box, in fractions of the side. */
+export function iconAnchor(name) {
+ return ANCHORS[name] ?? [0.5, 0.5];
+}
+
+/**
+ * Top-left of the box, given the anchor point the shape stores.
+ *
+ * The shape keeps the point it names, not the corner it happens to occupy, so
+ * resizing a pin leaves its tip where the analyst put it.
+ */
+export function iconOrigin(name, size) {
+ const [ax, ay] = iconAnchor(name);
+ return { x: -ax * size, y: -ay * size };
+}
+
+/** Box a placed symbol covers, in the surface's natural pixels. */
+export function iconBox(shape) {
+ const size = shape.size ?? ICON_SIZE_DEFAULT;
+ const origin = iconOrigin(shape.name, size);
+ return { x: (shape.x ?? 0) + origin.x, y: (shape.y ?? 0) + origin.y, w: size, h: size };
+}
+
+/**
+ * Placed side in natural pixels, so a symbol reads the same on a 4000px frame
+ * and an 800px one. Mirrors how stroke width is normalised by `baseScale`.
+ */
+export function iconSizeFor(baseScale) {
+ return ICON_SIZE_DEFAULT / (baseScale || 1);
+}
+
+/**
+ * Ink for the glyph over a badge disc of `discOpacity`.
+ *
+ * White on a solid disc, dark on a pale one, and the shape's own colour once the
+ * disc is too sheer to carry either — a white glyph on a 20%-opaque disc is a
+ * white glyph on whatever is underneath, which on aerial imagery is nothing.
+ */
+export function glyphInk(color, discOpacity) {
+ if (!(discOpacity > 0.45)) return color;
+ if (typeof color !== 'string' || !/^#[0-9a-f]{6}$/i.test(color)) return '#ffffff';
+ const r = parseInt(color.slice(1, 3), 16);
+ const g = parseInt(color.slice(3, 5), 16);
+ const b = parseInt(color.slice(5, 7), 16);
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.62 ? '#14161a' : '#ffffff';
+}
diff --git a/frontend/src/lib/proofIcons.test.js b/frontend/src/lib/proofIcons.test.js
new file mode 100644
index 0000000..4244771
--- /dev/null
+++ b/frontend/src/lib/proofIcons.test.js
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest';
+import {
+ ICON_BOX,
+ ICON_SIZE_DEFAULT,
+ PROOF_ICONS,
+ glyphInk,
+ iconAnchor,
+ iconBox,
+ iconByName,
+ iconOrigin,
+ iconSizeFor,
+ isSolidIcon,
+} from './proofIcons.js';
+
+describe('the symbol set', () => {
+ it('names every symbol once', () => {
+ const names = PROOF_ICONS.map((entry) => entry.name);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ it('keeps every path inside the shared box', () => {
+ for (const entry of PROOF_ICONS) {
+ // SVG packs numbers without separators — "-.75.34" is two of them — so
+ // the tokenizer has to allow a leading dot and no leading digit.
+ const numbers = entry.path.match(/-?(?:\d*\.\d+|\d+\.?)/g).map(Number);
+ // Arc flags and radii ride in the same stream, so this is a sanity bound
+ // rather than a bounding box: nothing may carry a coordinate that could
+ // only come from a path drawn for a different canvas.
+ expect(Math.max(...numbers)).toBeLessThanOrEqual(ICON_BOX);
+ expect(Math.min(...numbers)).toBeGreaterThanOrEqual(-ICON_BOX);
+ }
+ });
+
+ it('starts every path with a move, so none inherits the last one’s pen', () => {
+ for (const entry of PROOF_ICONS) expect(entry.path.startsWith('M')).toBe(true);
+ });
+
+ it('closes the paths that are filled rather than stroked', () => {
+ for (const entry of PROOF_ICONS) {
+ if (isSolidIcon(entry.name)) expect(entry.path).toMatch(/[Zz]$/);
+ }
+ });
+
+ it('answers by name and refuses one it does not carry', () => {
+ expect(iconByName('tank').label).toBe('Tank');
+ expect(iconByName('battleship')).toBeNull();
+ });
+});
+
+describe('where a symbol sits', () => {
+ it('centres everything that marks an area', () => {
+ expect(iconAnchor('tank')).toEqual([0.5, 0.5]);
+ expect(iconOrigin('tank', 100)).toEqual({ x: -50, y: -50 });
+ });
+
+ it('hangs the pin from its tip, not its middle', () => {
+ const [, ay] = iconAnchor('point');
+ expect(ay).toBeGreaterThan(0.9);
+ expect(iconOrigin('point', 100).y).toBeLessThan(-90);
+ });
+
+ it('keeps the pin’s tip still while it is resized', () => {
+ const pin = { name: 'point', x: 300, y: 200 };
+ const small = iconBox({ ...pin, size: 40 });
+ const large = iconBox({ ...pin, size: 120 });
+ // the tip is the anchor, so it reads the same out of both boxes
+ const tipOf = (box) => ({ x: box.x + box.w / 2, y: box.y + box.h * (22.4 / ICON_BOX) });
+ expect(tipOf(small).x).toBeCloseTo(tipOf(large).x);
+ expect(tipOf(small).y).toBeCloseTo(tipOf(large).y);
+ });
+
+ it('sizes a symbol against the panel, like stroke width', () => {
+ expect(iconSizeFor(1)).toBe(ICON_SIZE_DEFAULT);
+ expect(iconSizeFor(2)).toBe(ICON_SIZE_DEFAULT / 2);
+ expect(iconSizeFor(0)).toBe(ICON_SIZE_DEFAULT);
+ });
+});
+
+describe('ink over a badge disc', () => {
+ it('leaves the glyph its own colour when there is no disc to sit on', () => {
+ expect(glyphInk('#ff5252', 0)).toBe('#ff5252');
+ expect(glyphInk('#ff5252', undefined)).toBe('#ff5252');
+ });
+
+ it('keeps the glyph coloured while the disc is too sheer to carry white', () => {
+ expect(glyphInk('#ff5252', 0.3)).toBe('#ff5252');
+ });
+
+ it('turns white on a solid dark disc and dark on a pale one', () => {
+ // the palette straddles the threshold: red and magenta take white, the
+ // yellow/green/white end takes dark ink
+ expect(glyphInk('#ff5252', 1)).toBe('#ffffff');
+ expect(glyphInk('#69f0ae', 1)).toBe('#14161a');
+ expect(glyphInk('#ffffff', 1)).toBe('#14161a');
+ expect(glyphInk('#ffd740', 1)).toBe('#14161a');
+ });
+
+ it('falls back to white rather than painting a glyph with a gradient string', () => {
+ expect(glyphInk('rgba(0,0,0,.4)', 1)).toBe('#ffffff');
+ });
+});
diff --git a/frontend/src/lib/relations.svelte.js b/frontend/src/lib/relations.svelte.js
index c8f75a7..edbfd4b 100644
--- a/frontend/src/lib/relations.svelte.js
+++ b/frontend/src/lib/relations.svelte.js
@@ -270,3 +270,32 @@ export function saveRelation(caseId, subjectId, choice) {
choice.direction === 'out' ? [subjectId, choice.entityId] : [choice.entityId, subjectId];
return api.post(`/api/cases/${caseId}/links`, { from_id, to_id, type: choice.type });
}
+
+/**
+ * What to ask before an edge is taken back, or `null` when nothing needs asking.
+ *
+ * Two acts wear one button today, and only one of them is irreversible.
+ *
+ * **Dismissing a proposal** is the review gesture these panels exist for. A tool suggested
+ * it, nobody stated it, and refusing it costs the analyst nothing — so it stays one click.
+ *
+ * **Removing a stated relation** is the case retracting its own claim. `remove_relation`
+ * drops the row outright: no Trash holds it, no toast can undo it, and re-filing one later
+ * mints a new id, a new date and a new author (docs/UI.md §Graph). It was the only
+ * permanent write in the app that asked nothing, sitting next to *Confirm* and the rating
+ * in a panel opened to **read** an edge.
+ *
+ * Worded here rather than in each panel so the three surfaces that offer the act — the
+ * Details relations, a Claim's connectors, the Graph's edge — cannot word it three ways.
+ */
+export function retractionWarning(link, action = 'relation') {
+ if (link?.provenance?.status === 'suggested') return null;
+ const noun = action === 'mention' ? 'mention' : 'relation';
+ return {
+ title: `Remove this ${noun}?`,
+ message: 'The case stops stating it.',
+ detail:
+ 'Nothing holds a removed edge. Filing it again later is a new statement, with a new date and a new author.',
+ confirmLabel: 'Remove',
+ };
+}
diff --git a/frontend/src/lib/relations.test.js b/frontend/src/lib/relations.test.js
index eb2cccd..da02486 100644
--- a/frontend/src/lib/relations.test.js
+++ b/frontend/src/lib/relations.test.js
@@ -477,4 +477,17 @@ describe('directed and media-aware endpoints', () => {
expect(relations.isCurrentConnection(subject, current)).toBe(true);
expect(relations.isCurrentConnection(subject, older)).toBe(false);
});
+
+ it('asks before a stated edge is taken back, and never before a proposal', () => {
+ // The words live here so the three surfaces that offer the act cannot word it three
+ // ways, and the split is what keeps the review gesture one click: a tool's proposal
+ // costs the analyst nothing to refuse, their own statement is held nowhere afterwards.
+ expect(relations.retractionWarning({ provenance: { status: 'suggested' } })).toBe(null);
+
+ const stated = relations.retractionWarning({ provenance: { status: 'confirmed' } });
+ expect(stated.title).toBe('Remove this relation?');
+ expect(stated.detail).toContain('Nothing holds a removed edge');
+
+ expect(relations.retractionWarning({}, 'mention').title).toBe('Remove this mention?');
+ });
});
diff --git a/frontend/src/lib/satSuggest.js b/frontend/src/lib/satSuggest.js
new file mode 100644
index 0000000..39a2f6d
--- /dev/null
+++ b/frontend/src/lib/satSuggest.js
@@ -0,0 +1,203 @@
+/**
+ * What the Satellite search bar proposes while the analyst types.
+ *
+ * Four sources, in the order they can answer. The first three cost nothing —
+ * the saved index is already in memory, the coordinate parse and the city
+ * gazetteer are a localhost call over data on disk — so they fill the list on
+ * the keystroke. Places come from a geocoder that forbids autocomplete, so they
+ * are asked for only once typing stops, and they arrive last, underneath.
+ *
+ * Pure and synchronous: the component fetches, this decides what the list says.
+ */
+
+import { filterSaved, oneEach } from './geoTree.js';
+import { haversine, formatDistance } from './measure.js';
+
+/** How many recent picks are remembered, and where. */
+export const RECENTS_KEY = 'azimut:satelliteRecents';
+const RECENTS_MAX = 8;
+
+/** Below this, a geocoder query is too vague to be worth a slot. */
+export const REMOTE_MIN_CHARS = 3;
+
+const GROUP_LABELS = {
+ coords: 'Coordinates',
+ saved: 'Saved in this case',
+ cities: 'Cities',
+ places: 'Places',
+ recents: 'Recent',
+};
+
+/** Saved items this query names, nearest-first is *not* the point here — the
+ * index is newest-first and that is what the panel shows, so the head of that
+ * order is what the bar offers. */
+export function matchSaved(rows, query, limit = 4) {
+ if (!String(query ?? '').trim()) return [];
+ return oneEach(filterSaved(rows, { query }))
+ .filter((row) => row.lat != null && row.lon != null)
+ .slice(0, limit)
+ .map((row) => ({
+ key: `saved:${row.id}`,
+ group: 'saved',
+ label: row.title || 'Untitled',
+ detail: [row.country_en || row.geo?.country, row.geo?.region].filter(Boolean).join(', '),
+ lat: Number(row.lat),
+ lon: Number(row.lon),
+ row,
+ }));
+}
+
+/** A city from the bundled gazetteer, as a line to read. */
+function cityItem(city) {
+ return {
+ key: `city:${city.country}:${city.name}:${city.lat},${city.lon}`,
+ group: 'cities',
+ label: city.name,
+ detail: [city.region, city.country_name].filter(Boolean).join(', '),
+ lat: Number(city.lat),
+ lon: Number(city.lon),
+ zoom: 12,
+ };
+}
+
+/** A geocoder match. Its display name is the whole address, so the head of it
+ * is the label and the rest is the detail — one line either way. */
+function placeItem(place) {
+ const parts = String(place.display_name ?? '').split(',');
+ return {
+ key: `place:${place.lat},${place.lon}:${place.display_name}`,
+ group: 'places',
+ label: parts[0]?.trim() || String(place.display_name ?? ''),
+ detail: parts.slice(1).join(',').trim(),
+ lat: Number(place.lat),
+ lon: Number(place.lon),
+ zoom: 15,
+ };
+}
+
+/** The rows an empty bar shows: where this analyst went last. */
+export function recentItems(recents, limit = RECENTS_MAX) {
+ return (recents ?? []).slice(0, limit).map((entry, at) => ({
+ key: `recent:${at}:${entry.label}`,
+ group: 'recents',
+ label: entry.label,
+ detail: entry.detail ?? '',
+ lat: Number(entry.lat),
+ lon: Number(entry.lon),
+ zoom: entry.zoom,
+ }));
+}
+
+/**
+ * The grouped list under the bar. Empty groups are dropped, so nothing renders
+ * a header over nothing, and a duplicate point is kept once — a city already
+ * saved in the case is the saved row, not a second line under Cities.
+ */
+export function buildGroups({
+ query = '',
+ coords = null,
+ saved = [],
+ cities = [],
+ places = [],
+ recents = [],
+ centre = null,
+ units = 'metric',
+} = {}) {
+ if (!String(query).trim()) {
+ const rows = recentItems(recents);
+ return rows.length ? [{ id: 'recents', label: GROUP_LABELS.recents, items: rows }] : [];
+ }
+ const groups = [];
+ if (coords) {
+ groups.push({
+ id: 'coords',
+ label: GROUP_LABELS.coords,
+ items: [
+ {
+ key: `coords:${coords.lat},${coords.lon}`,
+ group: 'coords',
+ label: `${Number(coords.lat).toFixed(5)}, ${Number(coords.lon).toFixed(5)}`,
+ detail: 'Go to these coordinates',
+ lat: Number(coords.lat),
+ lon: Number(coords.lon),
+ zoom: 16,
+ },
+ ],
+ });
+ }
+ const seen = new Set();
+ const fresh = (items) =>
+ items.filter((item) => {
+ // ~100 m: the same town from two sources, not two neighbouring things
+ const at = `${item.lat.toFixed(3)},${item.lon.toFixed(3)}`;
+ return !seen.has(at) && seen.add(at);
+ });
+ for (const [id, items] of [
+ ['saved', saved],
+ ['cities', cities.map(cityItem)],
+ ['places', places.map(placeItem)],
+ ]) {
+ const rows = fresh(items);
+ if (rows.length) groups.push({ id, label: GROUP_LABELS[id], items: rows });
+ }
+ if (!centre) return groups;
+ return groups.map((group) => ({
+ ...group,
+ items: withDistance(group.items, centre, units),
+ }));
+}
+
+/** How far each row is from the map centre, for deciding between two Springfields. */
+function withDistance(items, centre, units) {
+ return items.map((item) =>
+ Number.isFinite(item.lat) && Number.isFinite(item.lon)
+ ? {
+ ...item,
+ away: formatDistance(haversine(centre, { lat: item.lat, lon: item.lon }), units),
+ }
+ : item
+ );
+}
+
+/** The groups as one list, which is what arrow keys walk. */
+export function flatten(groups) {
+ return (groups ?? []).flatMap((group) => group.items);
+}
+
+/** Move the highlight, wrapping at both ends. `-1` means nothing is highlighted. */
+export function step(at, delta, count) {
+ if (!count) return -1;
+ if (at < 0) return delta > 0 ? 0 : count - 1;
+ return (at + delta + count) % count;
+}
+
+export function readRecents() {
+ try {
+ const raw = JSON.parse(localStorage.getItem(RECENTS_KEY) ?? '[]');
+ return Array.isArray(raw) ? raw.filter((entry) => entry && entry.label) : [];
+ } catch {
+ return []; // absent or unreadable store (private mode) — non-fatal
+ }
+}
+
+/** Remember a pick, newest first, one entry per place. */
+export function pushRecent(item) {
+ if (!item?.label || !Number.isFinite(item.lat) || !Number.isFinite(item.lon)) return readRecents();
+ const entry = {
+ label: item.label,
+ detail: item.detail ?? '',
+ lat: item.lat,
+ lon: item.lon,
+ zoom: item.zoom,
+ };
+ const kept = [entry, ...readRecents().filter((old) => old.label !== entry.label)].slice(
+ 0,
+ RECENTS_MAX
+ );
+ try {
+ localStorage.setItem(RECENTS_KEY, JSON.stringify(kept));
+ } catch {
+ /* store unavailable — the list just does not persist */
+ }
+ return kept;
+}
diff --git a/frontend/src/lib/satSuggest.test.js b/frontend/src/lib/satSuggest.test.js
new file mode 100644
index 0000000..7d00676
--- /dev/null
+++ b/frontend/src/lib/satSuggest.test.js
@@ -0,0 +1,189 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ RECENTS_KEY,
+ buildGroups,
+ flatten,
+ matchSaved,
+ pushRecent,
+ readRecents,
+ recentItems,
+ step,
+} from './satSuggest.js';
+
+function storage() {
+ const values = new Map();
+ return {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ };
+}
+
+const savedRow = (id, opts = {}) => ({
+ id,
+ kind: 'place',
+ title: id,
+ lat: 48.0159,
+ lon: 37.8029,
+ notes: '',
+ fetched_at: '2026-07-20T09:12:04Z',
+ geo: { state: 'ok', country: 'Україна', country_code: 'ua', region: 'Donetsk' },
+ country_en: 'Ukraine',
+ continent: 'Europe',
+ ...opts,
+});
+
+const city = (name, opts = {}) => ({
+ name,
+ region: 'Donetsk',
+ country: 'ua',
+ country_name: 'Ukraine',
+ lat: 48.7311,
+ lon: 37.5678,
+ population: 147145,
+ ...opts,
+});
+
+describe('matchSaved', () => {
+ it('finds saved work by title, note or place, and carries the row along', () => {
+ const rows = [savedRow('checkpoint north'), savedRow('bridge', { lat: 52.23, lon: 21.01 })];
+ const [hit] = matchSaved(rows, 'checkp');
+ expect(hit.label).toBe('checkpoint north');
+ expect(hit.detail).toBe('Ukraine, Donetsk');
+ expect(hit.row.id).toBe('checkpoint north');
+ });
+
+ it('leaves out what has no point to fly to', () => {
+ const rows = [savedRow('screenshot', { lat: null, lon: null })];
+ expect(matchSaved(rows, 'screen')).toEqual([]);
+ });
+
+ it('proposes nothing for an empty query', () => {
+ expect(matchSaved([savedRow('a')], ' ')).toEqual([]);
+ });
+});
+
+describe('buildGroups', () => {
+ it('offers recents, and only recents, while the bar is empty', () => {
+ const groups = buildGroups({ query: '', recents: [{ label: 'Kyiv', lat: 50.45, lon: 30.52 }] });
+ expect(groups.map((g) => g.id)).toEqual(['recents']);
+ expect(groups[0].items[0].label).toBe('Kyiv');
+ });
+
+ it('says nothing at all when there is nothing to say', () => {
+ expect(buildGroups({ query: '' })).toEqual([]);
+ expect(buildGroups({ query: 'zzz' })).toEqual([]);
+ });
+
+ it('puts coordinates first, then saved work, then cities, then the geocoder', () => {
+ const groups = buildGroups({
+ query: 'kram',
+ coords: { lat: 50.4501, lon: 30.5234 },
+ saved: matchSaved([savedRow('kramatorsk checkpoint')], 'kram'),
+ cities: [city('Kramatorsk')],
+ places: [{ lat: 48.74, lon: 37.6, display_name: 'Kramatorska Street, Sloviansk' }],
+ });
+ expect(groups.map((g) => g.id)).toEqual(['coords', 'saved', 'cities', 'places']);
+ expect(groups[0].items[0].label).toBe('50.45010, 30.52340');
+ expect(groups[3].items[0].label).toBe('Kramatorska Street');
+ expect(groups[3].items[0].detail).toBe('Sloviansk');
+ });
+
+ it('drops a group rather than heading an empty one', () => {
+ const groups = buildGroups({ query: 'kram', cities: [city('Kramatorsk')] });
+ expect(groups.map((g) => g.id)).toEqual(['cities']);
+ });
+
+ it('keeps one line per place when two sources name the same point', () => {
+ // the city is already saved in the case: it is the saved row, not a second line
+ const groups = buildGroups({
+ query: 'kram',
+ saved: matchSaved([savedRow('Kramatorsk', { lat: 48.7311, lon: 37.5678 })], 'kram'),
+ cities: [city('Kramatorsk')],
+ });
+ expect(groups.map((g) => g.id)).toEqual(['saved']);
+ });
+
+ it('states how far each match is from the map centre', () => {
+ const [group] = buildGroups({
+ query: 'kram',
+ cities: [city('Kramatorsk')],
+ centre: { lat: 50.4547, lon: 30.5238 },
+ });
+ expect(group.items[0].away).toMatch(/km$/);
+ });
+
+ it('follows the unit preference', () => {
+ const imperial = buildGroups({
+ query: 'kram',
+ cities: [city('Kramatorsk')],
+ centre: { lat: 50.4547, lon: 30.5238 },
+ units: 'imperial',
+ });
+ expect(imperial[0].items[0].away).toMatch(/mi$/);
+ });
+
+ it('gives a city a wider zoom than a street', () => {
+ const groups = buildGroups({
+ query: 'kram',
+ cities: [city('Kramatorsk')],
+ places: [{ lat: 1, lon: 2, display_name: 'Kramatorska Street, Sloviansk' }],
+ });
+ expect(groups[0].items[0].zoom).toBeLessThan(groups[1].items[0].zoom);
+ });
+});
+
+describe('keyboard walking', () => {
+ it('flattens the groups into the order the arrows follow', () => {
+ const groups = buildGroups({
+ query: 'kram',
+ coords: { lat: 1, lon: 2 },
+ cities: [city('Kramatorsk')],
+ });
+ expect(flatten(groups).map((item) => item.group)).toEqual(['coords', 'cities']);
+ });
+
+ it('wraps at both ends and starts from either', () => {
+ expect(step(-1, 1, 3)).toBe(0);
+ expect(step(-1, -1, 3)).toBe(2);
+ expect(step(2, 1, 3)).toBe(0);
+ expect(step(0, -1, 3)).toBe(2);
+ });
+
+ it('highlights nothing when there is nothing to highlight', () => {
+ expect(step(-1, 1, 0)).toBe(-1);
+ });
+});
+
+describe('recents', () => {
+ beforeEach(() => vi.stubGlobal('localStorage', storage()));
+
+ it('remembers a pick, newest first', () => {
+ pushRecent({ label: 'Kyiv', detail: 'Ukraine', lat: 50.45, lon: 30.52, zoom: 12 });
+ pushRecent({ label: 'Kramatorsk', detail: 'Donetsk, Ukraine', lat: 48.73, lon: 37.57 });
+ expect(readRecents().map((entry) => entry.label)).toEqual(['Kramatorsk', 'Kyiv']);
+ });
+
+ it('keeps one entry per place rather than a pile of repeats', () => {
+ pushRecent({ label: 'Kyiv', lat: 50.45, lon: 30.52 });
+ pushRecent({ label: 'Lviv', lat: 49.84, lon: 24.03 });
+ pushRecent({ label: 'Kyiv', lat: 50.45, lon: 30.52 });
+ expect(readRecents().map((entry) => entry.label)).toEqual(['Kyiv', 'Lviv']);
+ });
+
+ it('caps the list', () => {
+ for (let n = 0; n < 12; n += 1) pushRecent({ label: `city ${n}`, lat: n, lon: n });
+ expect(readRecents()).toHaveLength(8);
+ });
+
+ it('refuses an entry with no point to return to', () => {
+ pushRecent({ label: 'nowhere', lat: null, lon: null });
+ expect(readRecents()).toEqual([]);
+ });
+
+ it('survives a corrupt store', () => {
+ localStorage.setItem(RECENTS_KEY, 'not json');
+ expect(readRecents()).toEqual([]);
+ expect(recentItems(readRecents())).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/sheet.js b/frontend/src/lib/sheet.js
new file mode 100644
index 0000000..158d0b1
--- /dev/null
+++ b/frontend/src/lib/sheet.js
@@ -0,0 +1,1410 @@
+/**
+ * The grid's own logic: what a sheet shows, and what an edit does to it.
+ *
+ * A sheet is `{ columns: string[], rows: string[][] }` — deliberately the shape a
+ * CSV already has, because the server writes the file and this never does. There
+ * is exactly one CSV parser and one CSV writer in the app and both are in Python
+ * (`engine/sheets.py`); the browser sends a table and gets a table back, so an
+ * imported file and a saved grid can never become two readings of the same rows.
+ *
+ * Rows are addressed by their **key** — the value in the `id` column — and never
+ * by position. That is the whole reason the column exists: a colour or an entity
+ * link hung on "row 4" moves to the wrong row the moment the file is sorted, here
+ * or in someone else's spreadsheet.
+ */
+
+import {
+ ROW_COLOURS,
+ cellChips,
+ compareSortKeys,
+ isChipped,
+ parseNumber,
+ parseWhen,
+ readsCell,
+ sortKey,
+ sortsByRole,
+ valueTotals,
+} from './sheetRoles.js';
+
+/** The column holding each row's identity. Mirrors `engine/sheets.ID_COLUMN`. */
+export const ID_COLUMN = 'id';
+
+/**
+ * What one sheet may hold. Mirrors `engine/sheets.MAX_ROWS` and `MAX_COLUMNS`, which
+ * are the bounds that actually hold — these are here so the grid can refuse the gesture
+ * instead of letting the save carry the news.
+ *
+ * It used to only be the server's business, and the failure that produced was the worst
+ * shape available: the analyst pasted eight hundred rows onto a full sheet, the grid took
+ * them, and then every autosave from that moment on answered 422. The work was on screen,
+ * unsaved, and the only way out was to guess how much to delete.
+ */
+export const MAX_ROWS = 20_000;
+export const MAX_COLUMNS = 64;
+
+/**
+ * Whether a table with this much more in it would still be one the file can hold.
+ *
+ * Returns null when there is room, and otherwise the sentence to say. Asked *before* the
+ * edit, by every gesture that grows the sheet, because the honest moment to refuse a
+ * paste is while the analyst still has it on the clipboard.
+ */
+export function tooBigBy(table, { rows = 0, columns = 0 } = {}) {
+ const willRows = (table?.rows?.length ?? 0) + rows;
+ const willColumns = (table?.columns?.length ?? 0) + columns;
+ if (willColumns > MAX_COLUMNS) {
+ return `A sheet holds ${MAX_COLUMNS} columns, and this one already has ${table.columns.length}.`;
+ }
+ if (willRows > MAX_ROWS) {
+ const room = Math.max(0, MAX_ROWS - (table?.rows?.length ?? 0));
+ return room
+ ? `A sheet holds ${MAX_ROWS.toLocaleString()} rows, so there is room for ${room.toLocaleString()} more.`
+ : `This sheet is full at ${MAX_ROWS.toLocaleString()} rows.`;
+ }
+ return null;
+}
+
+/** The colours the grid offers, for a row and for a value's chip alike. Defined next door
+ * because the vocabulary editor validates against it and this module is the one that
+ * imports that one; re-exported here so every existing caller is unaffected. */
+export { ROW_COLOURS } from './sheetRoles.js';
+
+/** Past this many distinct values a column is prose, not a set of answers: no
+ * chips, no value menu. Same idea as the Board's bound on offered facet values. */
+const MAX_CHOICE_VALUES = 40;
+
+/** The sidecar shape written today. Mirrors `engine/sheets.META_VERSION`: version 2 is
+ * where roles arrive, the first thing the sidecar knows that changes what a cell
+ * *means* rather than how it looks; version 3 adds what a cell said when the case took
+ * it, which is what lets a promoted row say it has moved on since; version 4 adds the
+ * **question** — the search and the filters — with the colour legend, the pinned row and
+ * the row height, so a sheet reopens on the reading it was left on. */
+export const META_VERSION = 4;
+
+export function emptyMeta() {
+ return {
+ version: META_VERSION,
+ widths: {},
+ hidden: [],
+ sort: null,
+ colours: {},
+ links: {},
+ frozen: null,
+ roles: {},
+ notes: {},
+ progress: null,
+ promoted: {},
+ query: '',
+ filters: {},
+ legend: {},
+ pinned: null,
+ tall: false,
+ };
+}
+
+/** How tall a row is drawn, in pixels: one line, or the four a note needs. Fixed either
+ * way, because only the rows on screen are in the DOM and the arithmetic that decides
+ * which those are is one division. */
+export const ROW_HEIGHTS = { short: 30, tall: 78 };
+
+export function rowHeight(meta) {
+ return meta?.tall ? ROW_HEIGHTS.tall : ROW_HEIGHTS.short;
+}
+
+/** The width the grid draws a column at when the sidecar holds none. Mirrored in
+ * the component's own default, and needed here because the sticky offsets of the
+ * frozen columns are arithmetic on widths. */
+export const DEFAULT_WIDTH = 160;
+
+/** The gutter that holds the tick box, in pixels. The first sticky offset. */
+export const GUTTER_WIDTH = 34;
+
+/** Where the key column sits. Always 0 on a table the server wrote, but a column
+ * the analyst moved is a change away, so nothing here assumes it. */
+export function keyIndex(columns) {
+ const at = (columns ?? []).findIndex((name) => String(name).toLowerCase() === ID_COLUMN);
+ return at === -1 ? 0 : at;
+}
+
+export function rowKey(columns, row) {
+ return String(row?.[keyIndex(columns)] ?? '');
+}
+
+/** The columns drawn, with the index each one reads from. The key column is
+ * always drawn: it is the row's handle, and hiding it hides why a colour
+ * survived a re-sort. */
+export function visibleColumns(columns, meta) {
+ const hidden = new Set(meta?.hidden ?? []);
+ const key = keyIndex(columns);
+ return (columns ?? [])
+ .map((name, index) => ({ name, index }))
+ .filter((column) => column.index === key || !hidden.has(column.name));
+}
+
+const NUMBER = /^-?\d+(?:[.,]\d+)?$/;
+
+function asNumber(value) {
+ return NUMBER.test(String(value).trim())
+ ? Number(String(value).trim().replace(',', '.'))
+ : null;
+}
+
+export function isBlank(value) {
+ return !String(value ?? '').trim();
+}
+
+/** Links inside one cell. A cell holds several often enough — a source and its
+ * archive copy — that returning a list rather than the first one is the honest
+ * answer. Trailing punctuation is left behind: a URL at the end of a sentence is
+ * not a URL with a full stop in it. */
+export function urlsIn(value) {
+ const found = String(value ?? '').match(/\bhttps?:\/\/[^\s<>"'()[\]]+/gi) ?? [];
+ return found.map((url) => url.replace(/[.,;:!?]+$/, ''));
+}
+
+/** What a link is shown as in a cell thirty pixels tall: its host, without the
+ * `www.`, plus a mark when the path carries more than the host does. A hundred and
+ * twenty characters of query string in a grid is a cell that says nothing. */
+export function linkLabel(url) {
+ try {
+ const parsed = new URL(url);
+ const host = parsed.hostname.replace(/^www\./, '');
+ return parsed.pathname && parsed.pathname !== '/' ? `${host}/…` : host;
+ } catch {
+ return String(url ?? '');
+ }
+}
+
+/**
+ * Two filled cells, ordered.
+ *
+ * Numbers compare as numbers, so 9 comes before 10, and everything else compares
+ * the way a person reads it — `numeric` makes `AB-2` precede `AB-10`.
+ *
+ * Blank cells are not this function's business: `visibleRows` holds them at the
+ * bottom in **both** directions, because blank is "no answer yet" and a
+ * descending sort that opens on a screen of nothing has buried the rows the
+ * analyst asked to see.
+ */
+/**
+ * The collator the whole grid sorts words with, built once.
+ *
+ * `localeCompare(other, undefined, options)` builds one of these **per call**. A sort
+ * asks around a quarter of a million comparisons on a full sheet, and almost all of them
+ * land here: a status column holds four words over twenty thousand rows, so the role
+ * settles nothing and the words decide. Measured at 3.8 s of collator building per pass
+ * against 92 ms once it is shared.
+ */
+const COLLATOR = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
+
+export function compareCells(a, b) {
+ const left = String(a ?? '');
+ const right = String(b ?? '');
+ // Cheap and by far the commonest exit: two rows agreeing on the key being sorted.
+ if (left === right) return 0;
+ const [x, y] = [asNumber(left), asNumber(right)];
+ if (x !== null && y !== null) return x === y ? 0 : x < y ? -1 : 1;
+ return COLLATOR.compare(left, right);
+}
+
+/**
+ * One row as the lowercase text the search reads, cached against the row itself.
+ *
+ * The cache is what makes a search over twenty thousand rows typeable rather than a
+ * stutter per keystroke: joining and folding a fourteen-column row allocates two strings,
+ * and the old code did that for every row on every letter. A `WeakMap` keyed on the row
+ * array needs no invalidation — every edit in this module builds a **new** row array, so
+ * an edited row simply misses and a deleted one is collected.
+ */
+const HAYSTACK = new WeakMap();
+
+function rowText(row) {
+ if (!row) return '';
+ const held = HAYSTACK.get(row);
+ if (held !== undefined) return held;
+ const text = row.join('\n').toLowerCase();
+ HAYSTACK.set(row, text);
+ return text;
+}
+
+/** A typed query cut into the words every row has to answer. Split once by the
+ * caller that sweeps a column, rather than once per row: on twenty thousand rows
+ * it was twenty thousand regex splits per keystroke. */
+export function searchTerms(query) {
+ return String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+}
+
+/** Whether one row answers the typed terms. Every term has to appear somewhere in the
+ * row, matching the Board's rule so one box does not behave two ways. Takes the terms
+ * already split, because the caller sweeping a column splits them once. */
+export function answersTerms(row, terms) {
+ if (!terms.length) return true;
+ const text = rowText(row);
+ return terms.every((term) => text.includes(term));
+}
+
+/**
+ * One cell cut into the parts the search matched and the parts it did not.
+ *
+ * A grid that filters to 23 rows out of 1 204 and then leaves the analyst to find the
+ * word in each of them has done half the job — on a fourteen-column binder the match is
+ * often in a column that is off screen. Every term is marked, overlaps included, which is
+ * why this walks a mask rather than splitting on a pattern: `quai` and `quais` both
+ * matching one word must not produce two nested marks.
+ */
+export function highlightParts(value, query) {
+ const text = String(value ?? '');
+ const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ if (!text || !terms.length) return [{ text, hit: false }];
+ const lower = text.toLowerCase();
+ const marked = new Array(text.length).fill(false);
+ for (const term of terms) {
+ let at = lower.indexOf(term);
+ while (at !== -1) {
+ for (let index = at; index < at + term.length; index += 1) marked[index] = true;
+ at = lower.indexOf(term, at + 1);
+ }
+ }
+ const parts = [];
+ let start = 0;
+ for (let index = 1; index <= text.length; index += 1) {
+ if (index === text.length || marked[index] !== marked[start]) {
+ parts.push({ text: text.slice(start, index), hit: marked[start] });
+ start = index;
+ }
+ }
+ return parts;
+}
+
+// -- what is asked of a column ------------------------------------------------
+//
+// A chosen value answers "which ones say this". The other questions an analyst asks
+// of a worklist are "which ones have nothing here yet", "which ones mention this"
+// and "which ones do not", and none of them is a value: `To be found`, `-`, `?` and
+// an empty cell all mean the same thing to the person filtering, and no list of
+// values catches them. So a column's filter is a small record rather than a set, and
+// the four parts read together.
+//
+// `contains` is the one a prose column has nothing else to offer. Past
+// `MAX_CHOICE_VALUES` distinct values there is no list to tick, so a column of
+// sources or of notes could be *excluded* by a word and never *kept* by one — the
+// half of the question that was missing.
+
+/** What a column can be asked about its cells, beyond which values they hold. `unreadable`
+ * is the one a permissive role owes the analyst: a column that accepts `about 12` has to
+ * be able to show which cells that is. */
+const FILL_ASKS = ['blank', 'filled', 'unreadable'];
+
+/** One column's filter, in the one shape the rest of this module reads. A bare Set
+ * is accepted because chosen values are the common case and the caller that only
+ * has those should not have to build a record; a plain **array** is accepted because
+ * that is the shape the sidecar holds, JSON having no set. */
+export function normalizeFilter(entry) {
+ if (!entry) return null;
+ if (entry instanceof Set) {
+ return { ...noFilter(), values: entry.size ? entry : null };
+ }
+ const held = Array.isArray(entry.values) ? new Set(entry.values) : entry.values;
+ const values = held instanceof Set && held.size ? held : null;
+ const fill = FILL_ASKS.includes(entry.fill) ? entry.fill : null;
+ return {
+ values,
+ fill,
+ contains: String(entry.contains ?? ''),
+ without: String(entry.without ?? ''),
+ from: String(entry.from ?? ''),
+ to: String(entry.to ?? ''),
+ };
+}
+
+/** The blank filter every editing function starts from, so none of them has to
+ * restate the parts a column can be asked about. */
+function noFilter() {
+ return { values: null, fill: null, contains: '', without: '', from: '', to: '' };
+}
+
+export function isFilterActive(entry) {
+ const filter = normalizeFilter(entry);
+ return Boolean(
+ filter &&
+ (filter.values || filter.fill || filter.contains || filter.without || filter.from || filter.to),
+ );
+}
+
+/**
+ * A cell as the one number a range is compared on, or null when it holds nothing a
+ * range can order.
+ *
+ * The column's own lens decides what that number is: a date column compares moments, a
+ * number column compares numbers, and a column that declares nothing still answers when
+ * its cells are plainly numbers — a distance typed into a fresh column is a distance
+ * before anybody gets around to declaring it one.
+ */
+function rangeValue(cell, role) {
+ const body = String(cell ?? '').trim();
+ if (!body) return null;
+ if (role?.kind === 'when') return parseWhen(body, role)?.key ?? null;
+ return parseNumber(body);
+}
+
+/**
+ * Whether one cell answers one column's filter. Every part has to hold: they are
+ * clauses of one question, not alternatives.
+ *
+ * The role is what makes a **list** column filterable at all. `Buk-M2E, ZU23-2` is two
+ * answers in one cell, and comparing the whole cell against a chosen value found neither
+ * of them — so clicking a chip in the grid narrowed the sheet to nothing. With the role,
+ * a cell matches when *any* of its values was asked for, which is what a chip means. A
+ * quantity is not part of the value: `2x S-125` answers `S-125`.
+ */
+export function matchesFilter(cell, entry, role = null) {
+ const filter = normalizeFilter(entry);
+ if (!filter) return true;
+ const value = String(cell ?? '');
+ if (filter.values) {
+ const held = isChipped(role)
+ ? cellChips(value, role).map((chip) => chip.value)
+ : [value];
+ // A cell holding nothing answers the blank entry of the value list, which is what
+ // the menu offers it as.
+ const answers = held.length ? held : [''];
+ if (!answers.some((held_) => filter.values.has(held_))) return false;
+ }
+ if (filter.fill === 'blank' && !isBlank(value)) return false;
+ if (filter.fill === 'filled' && isBlank(value)) return false;
+ if (filter.fill === 'unreadable' && (isBlank(value) || readsCell(role, value))) return false;
+ // Both read the cell as it is written, not as the role reads it: a word asked for
+ // in a column of sources is looked for in what the file says.
+ if (filter.contains && !value.toLowerCase().includes(filter.contains.toLowerCase())) return false;
+ if (filter.without && value.toLowerCase().includes(filter.without.toLowerCase())) return false;
+ // A bound is the question a list of values cannot ask: *before this date*, *under
+ // five kilometres*. A cell the column cannot read as a quantity is out — including an
+ // empty one, because "no answer yet" is not below a bound, it is unknown.
+ if (filter.from || filter.to) {
+ const held = rangeValue(value, role);
+ if (held === null) return false;
+ const low = rangeValue(filter.from, role);
+ const high = rangeValue(filter.to, role);
+ if (low !== null && held < low) return false;
+ if (high !== null && held > high) return false;
+ }
+ return true;
+}
+
+/** Replace one column's filter, dropping the column entirely when nothing is left
+ * to ask — so `filters` never accumulates empty records the chips would show. */
+function withFilter(filters, column, filter) {
+ const next = { ...(filters ?? {}) };
+ if (isFilterActive(filter)) next[column] = filter;
+ else delete next[column];
+ return next;
+}
+
+export function toggleFilterValue(filters, column, value) {
+ const filter = normalizeFilter(filters?.[column]) ?? noFilter();
+ const values = new Set(filter.values ?? []);
+ if (!values.delete(value)) values.add(value);
+ return withFilter(filters, column, { ...filter, values });
+}
+
+/** Keep only the rows holding this value, whatever else was asked of the column.
+ * What a cell offers: the answer under the pointer is the whole question, so a
+ * second value ticked in the menu is not carried along with it. */
+export function onlyFilterValue(filters, column, value) {
+ return withFilter(filters, column, { ...noFilter(), values: new Set([value]) });
+}
+
+/** Ask for blank or for filled, or ask again to stop asking. */
+export function toggleFilterFill(filters, column, fill) {
+ const filter = normalizeFilter(filters?.[column]) ?? noFilter();
+ return withFilter(filters, column, { ...filter, fill: filter.fill === fill ? null : fill });
+}
+
+export function setFilterContains(filters, column, term) {
+ const filter = normalizeFilter(filters?.[column]) ?? noFilter();
+ return withFilter(filters, column, { ...filter, contains: String(term ?? '').trim() });
+}
+
+export function setFilterWithout(filters, column, term) {
+ const filter = normalizeFilter(filters?.[column]) ?? noFilter();
+ return withFilter(filters, column, { ...filter, without: String(term ?? '').trim() });
+}
+
+/** Ask a column for what falls between two bounds. Either end alone is a question of
+ * its own — *after March*, *under 5* — so neither is required. */
+export function setFilterRange(filters, column, { from, to } = {}) {
+ const filter = normalizeFilter(filters?.[column]) ?? noFilter();
+ return withFilter(filters, column, {
+ ...filter,
+ from: from === undefined ? filter.from : String(from ?? '').trim(),
+ to: to === undefined ? filter.to : String(to ?? '').trim(),
+ });
+}
+
+export function clearFilter(filters, column) {
+ const next = { ...(filters ?? {}) };
+ delete next[column];
+ return next;
+}
+
+/** Ask nothing of any column. One press, because a reading built out of six clauses took
+ * six presses to put down and the analyst who wants the whole sheet back wants it now. */
+export function clearFilters() {
+ return {};
+}
+
+// -- the question, written down -----------------------------------------------
+//
+// The sort and the hidden columns were always in the sidecar and the filters were not,
+// which made the sheet reopen showing all four hundred rows: half a reading survived and
+// the half that decides what is on screen died with the tab.
+//
+// The only difference between the two shapes is the chosen values: a `Set` while the grid
+// is matching cells against it, a list in the file, because JSON has no set. Both
+// directions are here, next to each other, so neither can be written from memory.
+
+/** The filters as the sidecar holds them: lists rather than sets, empty clauses dropped. */
+export function serializeFilters(filters) {
+ const out = {};
+ for (const [column, entry] of Object.entries(filters ?? {})) {
+ const filter = normalizeFilter(entry);
+ if (!filter || !isFilterActive(filter)) continue;
+ out[column] = {
+ values: [...(filter.values ?? [])],
+ fill: filter.fill,
+ contains: filter.contains,
+ without: filter.without,
+ from: filter.from,
+ to: filter.to,
+ };
+ }
+ return out;
+}
+
+/** And back: what the grid matches rows against, out of what the file held. Columns the
+ * table no longer has are dropped here rather than left to fail per cell. */
+export function readFilters(stored, columns) {
+ const known = new Set(columns ?? []);
+ const out = {};
+ for (const [column, entry] of Object.entries(stored ?? {})) {
+ if (columns && !known.has(column)) continue;
+ const filter = normalizeFilter(entry);
+ if (filter && isFilterActive(filter)) out[column] = filter;
+ }
+ return out;
+}
+
+/** Move what is asked of one column onto its new name, or drop it. What a rename owes a
+ * filter: the rows on screen must not change because a heading was spelled again. */
+export function renameFilterColumn(filters, from, to) {
+ if (!(from in (filters ?? {}))) return { ...(filters ?? {}) };
+ const next = { ...filters };
+ const entry = next[from];
+ delete next[from];
+ if (to) next[to] = entry;
+ return next;
+}
+
+/** Every active clause as its own chip, so each is removable on its own. A chip
+ * carries what it takes to undo itself and nothing else. */
+export function filterChips(filters) {
+ return Object.entries(filters ?? {}).flatMap(([column, entry]) => {
+ const filter = normalizeFilter(entry);
+ if (!filter) return [];
+ const chips = [...(filter.values ?? [])].map((value) => ({
+ column,
+ part: 'value',
+ value,
+ label: value || '(blank)',
+ }));
+ if (filter.fill) {
+ chips.push({
+ column,
+ part: 'fill',
+ value: filter.fill,
+ label: { blank: 'empty', filled: 'not empty', unreadable: 'to check' }[filter.fill],
+ });
+ }
+ if (filter.contains) {
+ chips.push({
+ column,
+ part: 'contains',
+ value: filter.contains,
+ label: `with ${filter.contains}`,
+ });
+ }
+ if (filter.without) {
+ chips.push({
+ column,
+ part: 'without',
+ value: filter.without,
+ label: `without ${filter.without}`,
+ });
+ }
+ if (filter.from) {
+ chips.push({ column, part: 'from', value: filter.from, label: `from ${filter.from}` });
+ }
+ if (filter.to) {
+ chips.push({ column, part: 'to', value: filter.to, label: `to ${filter.to}` });
+ }
+ return chips;
+ });
+}
+
+/** Remove exactly what one chip shows, leaving the column's other clauses alone. */
+export function dropChip(filters, chip) {
+ if (chip?.part === 'value') return toggleFilterValue(filters, chip.column, chip.value);
+ if (chip?.part === 'fill') return toggleFilterFill(filters, chip.column, chip.value);
+ if (chip?.part === 'contains') return setFilterContains(filters, chip.column, '');
+ if (chip?.part === 'without') return setFilterWithout(filters, chip.column, '');
+ if (chip?.part === 'from') return setFilterRange(filters, chip.column, { from: '' });
+ if (chip?.part === 'to') return setFilterRange(filters, chip.column, { to: '' });
+ return filters;
+}
+
+/** How one column's filter reads in a line, or an empty string when nothing is asked
+ * of it. The setup panel says this rather than offering the filter a second time. */
+export function filterSummary(entry) {
+ return filterChips({ column: entry })
+ .map((chip) => chip.label)
+ .join(' · ');
+}
+
+/**
+ * The row indices to draw, filtered then sorted.
+ *
+ * Indices rather than rows, so an edit still addresses the table the caller
+ * holds: the grid draws in one order and writes in another, and translating in
+ * one place is what keeps that from becoming a bug per column.
+ */
+export function visibleRows(table, view = {}) {
+ const { columns = [], rows = [] } = table ?? {};
+ const { query = '', filters = {}, sort = null, roles = null } = view;
+ // Compiled once per column rather than once per cell. `matchesFilter` normalises
+ // whatever it is handed, and handing it a raw record for each of twenty thousand rows
+ // rebuilt the same six-field object twenty thousand times.
+ const active = Object.entries(filters)
+ .filter(([, entry]) => isFilterActive(entry))
+ .map(([name, entry]) => ({
+ at: columns.indexOf(name),
+ filter: normalizeFilter(entry),
+ role: roles?.[name] ?? null,
+ }))
+ .filter((asked) => asked.at !== -1);
+
+ const terms = searchTerms(query);
+ let indices = rows
+ .map((row, index) => index)
+ .filter((index) => answersTerms(rows[index], terms))
+ .filter((index) =>
+ active.every((asked) => matchesFilter(rows[index][asked.at], asked.filter, asked.role)),
+ );
+
+ // One key, then the one under it. "By status, then by date" is how a worklist is read,
+ // and with a single key the analyst re-sorted by hand every time the first one tied.
+ const keys = [sort, sort?.then]
+ .filter(Boolean)
+ .map((key) => ({
+ at: columns.indexOf(key.column),
+ direction: key.desc ? -1 : 1,
+ // What the column knows, when it knows anything. A declared role is the whole
+ // reason a `dd/MM/yyyy` column stops sorting `01/02` before `31/01`, and it is the
+ // most visible thing a role buys — so the comparison asks the role first and falls
+ // back to reading the words only where the role has nothing to say.
+ role: roles?.[key.column] ?? null,
+ }))
+ .filter((key) => key.at !== -1);
+
+ if (keys.length) {
+ // What each key is worth, read **once per row** before anything is compared.
+ //
+ // The comparison used to read the cell itself, which put `parseWhen` inside the
+ // comparator: two calls per comparison, so a hundred and twelve thousand on a full
+ // sheet — and again on every keystroke, because this view is derived from the table
+ // and every edit rebuilds it. Measured at 802 ms per pass on twenty thousand rows,
+ // 1.1 s with a second key; reading the keys first brings it to 46 ms.
+ //
+ // Only the roles that order anything are read. A `choice` column has no ranking, so
+ // decorating it would be a pass over the sheet whose answer is thrown away.
+ const decorated = keys.map((key) =>
+ sortsByRole(key.role) ? rows.map((row) => sortKey(key.role, row[key.at])) : null,
+ );
+ indices = indices
+ .map((index, order) => ({ index, order }))
+ .sort((a, b) => {
+ for (let at = 0; at < keys.length; at += 1) {
+ const key = keys[at];
+ const left = rows[a.index][key.at];
+ const right = rows[b.index][key.at];
+ // Blank sinks whichever way the arrow points, and two blanks fall through to
+ // the next key: "no answer yet" is not a tie worth stopping on.
+ if (isBlank(left) || isBlank(right)) {
+ if (isBlank(left) && isBlank(right)) continue;
+ return isBlank(left) ? 1 : -1;
+ }
+ const read = decorated[at];
+ const byRole = read ? compareSortKeys(read[a.index], read[b.index]) : null;
+ const cells = byRole ?? compareCells(left, right);
+ if (cells !== 0) return cells * key.direction;
+ }
+ // Stable: two rows equal on every key keep the order the file has them in.
+ return a.order - b.order;
+ })
+ .map((entry) => entry.index);
+ }
+ return indices;
+}
+
+/**
+ * The distinct values of one column with their counts, commonest first, narrowed to a
+ * typed word and cut to a page.
+ *
+ * A column that is a **list** is counted value by value: `Buk-M2E, ZU23-2` is two
+ * answers, and a menu offering the pair as one entry offers something no other row will
+ * ever match. `rows` is how many rows hold the value, which is what the filter hands
+ * back.
+ *
+ * A column of a hundred and twenty cities used to answer **nothing at all** past forty
+ * distinct values — the menu said "too many to list" and the analyst was left with a
+ * word box. So the cut is now a page rather than a wall: the commonest are listed, the
+ * total says how many there are, and typing narrows the list against the whole column
+ * rather than against the page.
+ */
+export function columnValues(table, name, role = null, { term = '', limit = MAX_CHOICE_VALUES } = {}) {
+ const at = (table?.columns ?? []).indexOf(name);
+ if (at === -1) return null;
+ const all = isChipped(role)
+ ? valueTotals(table, at, role)
+ : (() => {
+ const counts = new Map();
+ for (const row of table.rows ?? []) {
+ const value = String(row[at] ?? '');
+ counts.set(value, (counts.get(value) ?? 0) + 1);
+ }
+ return [...counts.entries()]
+ .map(([value, rows]) => ({ value, rows }))
+ .sort((a, b) => b.rows - a.rows || compareCells(a.value, b.value));
+ })();
+ const wanted = String(term ?? '').trim().toLowerCase();
+ const matching = wanted
+ ? all.filter((entry) => entry.value.toLowerCase().includes(wanted))
+ : all;
+ return {
+ values: matching.slice(0, Math.max(1, limit)),
+ matching: matching.length,
+ total: all.length,
+ capped: matching.length > Math.max(1, limit),
+ };
+}
+
+// -- edits --------------------------------------------------------------------
+//
+// Every one of these returns a new table (and a new sidecar where a rename moves
+// what the sidecar keyed on a column name). Nothing mutates: the undo stack
+// snapshots what these return, and a mutating edit would rewrite its own history.
+
+/**
+ * Write several cells at once, as one edit.
+ *
+ * The one primitive behind filling a column for every ticked row, copying a cell
+ * down a selection, and undoing or redoing either: all four are a list of
+ * `{ row, column, value }` applied together. One pass over the table rather than one
+ * per cell, which on a few thousand ticked rows is the difference between a grid and
+ * a hang.
+ */
+export function setCells(table, writes) {
+ if (!writes?.length) return table;
+ const byRow = new Map();
+ for (const write of writes) {
+ if (!byRow.has(write.row)) byRow.set(write.row, []);
+ byRow.get(write.row).push(write);
+ }
+ const rows = table.rows.map((row, index) => {
+ const mine = byRow.get(index);
+ if (!mine) return row;
+ const next = [...row];
+ for (const write of mine) {
+ if (write.column >= 0 && write.column < next.length) next[write.column] = String(write.value ?? '');
+ }
+ return next;
+ });
+ return { ...table, rows };
+}
+
+/** The edits that set one column to *value* across *rowIndices*, each carrying what
+ * it replaced. Cells already holding the value are left out, so undo does not walk
+ * back through steps that changed nothing and the key column is never touched. */
+export function fillEdits(table, columnIndex, rowIndices, value) {
+ const text = String(value ?? '');
+ if (columnIndex === keyIndex(table.columns)) return [];
+ return (rowIndices ?? [])
+ .filter((index) => table.rows[index] && table.rows[index][columnIndex] !== text)
+ .map((index) => ({
+ row: index,
+ column: columnIndex,
+ before: table.rows[index][columnIndex],
+ after: text,
+ }));
+}
+
+/** Apply a recorded step in one direction: 'backward' puts the cells back the way
+ * they were, 'forward' puts them the way the edit left them. */
+export function applyEdits(table, edits, direction) {
+ const side = direction === 'backward' ? 'before' : 'after';
+ return setCells(
+ table,
+ (edits ?? []).map((edit) => ({ row: edit.row, column: edit.column, value: edit[side] })),
+ );
+}
+
+/** A row appended with a fresh key. The server mints one for a blank key too, but
+ * the grid needs something to hang a colour on before the next save. */
+export function addRow(table, key = newKey()) {
+ const cells = table.columns.map((_, index) => (index === keyIndex(table.columns) ? key : ''));
+ return { ...table, rows: [...table.rows, cells] };
+}
+
+export function newKey() {
+ const random = crypto.getRandomValues(new Uint8Array(5));
+ return `r${[...random].map((byte) => byte.toString(16).padStart(2, '0')).join('')}`;
+}
+
+/** A blank row placed *at* an index rather than at the end. What "insert above" means,
+ * and the reason it exists: a worklist gets a line added where the analyst is reading,
+ * and a row appended four hundred rows below is a row they then have to drag back. */
+export function insertRow(table, at, key = newKey()) {
+ const cells = table.columns.map((_, index) => (index === keyIndex(table.columns) ? key : ''));
+ const rows = [...table.rows];
+ rows.splice(Math.max(0, Math.min(at, rows.length)), 0, cells);
+ return { ...table, rows };
+}
+
+/**
+ * Copy rows, each one landing right under the row it came from, with a key of its own.
+ *
+ * The gesture behind it is a candidate that turns out to be two: the same address checked
+ * against two hypotheses, the same photo geolocated twice. The copy carries the cells and
+ * nothing the sidecar hangs on the original — a colour is a mark on *that* row's work, and
+ * a link is the case's answer about it, so a duplicate that inherited both would claim
+ * work that was never done on it.
+ */
+export function duplicateRows(table, indices) {
+ const wanted = [...new Set(indices ?? [])].filter((index) => table.rows[index]).sort((a, b) => a - b);
+ if (!wanted.length) return { table, keys: [] };
+ const rows = [...table.rows];
+ const keys = [];
+ const at = keyIndex(table.columns);
+ for (const index of [...wanted].reverse()) {
+ const key = newKey();
+ const copy = [...table.rows[index]];
+ copy[at] = key;
+ rows.splice(index + 1, 0, copy);
+ keys.unshift(key);
+ }
+ return { table: { ...table, rows }, keys };
+}
+
+export function removeRows(table, indices) {
+ const drop = new Set(indices);
+ return { ...table, rows: table.rows.filter((_, index) => !drop.has(index)) };
+}
+
+/**
+ * Fold several rows into the first of them, cell by cell.
+ *
+ * The other half of "this value is said twice". The grid could already *find* the rows
+ * holding one value and paint them, and then left the analyst to retype one row out of
+ * three and delete two — on an imported inbox where the same address arrives from three
+ * channels, that is the whole job.
+ *
+ * The rule is **the fullest answer wins**, per column: the longest text of the rows being
+ * folded, which is what "one of these three actually wrote the city down" looks like. It
+ * is not a merge of *facts* — nothing here decides that `Kherson` and `Cherson` are one
+ * place — so what it can lose is only a shorter version of a cell that already agreed.
+ * The surviving row keeps its own key, and with it its colour, its links and its promotion
+ * record; the rows folded into it go.
+ */
+export function mergeRows(table, indices) {
+ const wanted = [...new Set(indices ?? [])].filter((index) => table.rows[index]).sort((a, b) => a - b);
+ if (wanted.length < 2) return { table, key: null, folded: 0 };
+ const [keep, ...rest] = wanted;
+ const at = keyIndex(table.columns);
+ const merged = table.columns.map((_, column) => {
+ if (column === at) return table.rows[keep][column];
+ let best = '';
+ for (const index of wanted) {
+ const cell = String(table.rows[index][column] ?? '');
+ if (cell.trim().length > best.trim().length) best = cell;
+ }
+ return best;
+ });
+ const drop = new Set(rest);
+ return {
+ table: {
+ ...table,
+ rows: table.rows
+ .map((row, index) => (index === keep ? merged : row))
+ .filter((_, index) => !drop.has(index)),
+ },
+ key: rowKey(table.columns, table.rows[keep]),
+ folded: rest.length,
+ };
+}
+
+/**
+ * One cell's values as one row each, the rest of the row copied down.
+ *
+ * The inverse of the merge and the shape every "to be sorted" inbox arrives in: one row
+ * holding five links, or a cell reading `Buk-M2E, ZU23-2, S-300` in a worklist that wants
+ * a line per system. Splitting a column into *columns* was already here and answers a
+ * different question — a column of `city, country` is two columns, a cell of five sources
+ * is five rows.
+ *
+ * The first value stays on the original row, so its colour, its links and its key survive;
+ * the rest are fresh rows with fresh keys, placed directly under it, carrying no sidecar
+ * of their own — none of that work has been done on them yet.
+ */
+export function explodeRow(table, rowIndex, columnIndex, separator = '\n') {
+ const row = table.rows[rowIndex];
+ if (!row || columnIndex === keyIndex(table.columns)) return { table, keys: [] };
+ const parts = String(row[columnIndex] ?? '')
+ .split(separator)
+ .map((part) => part.trim())
+ .filter(Boolean);
+ if (parts.length < 2) return { table, keys: [] };
+ const at = keyIndex(table.columns);
+ const first = row.map((cell, index) => (index === columnIndex ? parts[0] : cell));
+ const keys = [];
+ const made = parts.slice(1).map((part) => {
+ const key = newKey();
+ keys.push(key);
+ return row.map((cell, index) => {
+ if (index === at) return key;
+ return index === columnIndex ? part : cell;
+ });
+ });
+ const rows = [...table.rows];
+ rows.splice(rowIndex, 1, first, ...made);
+ return { table: { ...table, rows }, keys };
+}
+
+/** A column name nothing else uses, so two "Status" columns never exist. */
+export function freeColumnName(columns, base = 'Column') {
+ const taken = new Set(columns.map((name) => String(name).toLowerCase()));
+ if (!taken.has(base.toLowerCase())) return base;
+ let index = 2;
+ while (taken.has(`${base} ${index}`.toLowerCase())) index += 1;
+ return `${base} ${index}`;
+}
+
+export function addColumn(table, name) {
+ const heading = freeColumnName(table.columns, name || 'Column');
+ return {
+ ...table,
+ columns: [...table.columns, heading],
+ rows: table.rows.map((row) => [...row, '']),
+ };
+}
+
+/**
+ * A column placed *at* an index, cells and all.
+ *
+ * The one the grid was missing: a sheet grows a column beside the one being worked on —
+ * a verdict next to the claim it judges — and the only way to get one there was to add it
+ * at the far right and drag it back across twelve headings.
+ */
+export function insertColumn(table, at, name, values = []) {
+ const heading = freeColumnName(table.columns, name || 'Column');
+ const where = Math.max(0, Math.min(at, table.columns.length));
+ const columns = [...table.columns];
+ columns.splice(where, 0, heading);
+ return {
+ columns,
+ rows: table.rows.map((row, index) => {
+ const cells = [...row];
+ cells.splice(where, 0, String(values[index] ?? ''));
+ return cells;
+ }),
+ };
+}
+
+/**
+ * A column copied beside itself, with what the sidecar knows about it.
+ *
+ * The width, the role and the note travel because they are what the column *is*, and a
+ * copy made to be rewritten wants the same lens as the original. The links do not: a link
+ * is the case's answer about one cell, and two cells claiming the same entity would be one
+ * `mentions` edge stated twice by a copy nobody has read yet.
+ */
+export function duplicateColumn(table, meta, index) {
+ const previous = table.columns[index];
+ if (previous === undefined) return { table, meta, name: null };
+ const grown = insertColumn(
+ table,
+ index + 1,
+ `${previous} copy`,
+ table.rows.map((row) => row[index]),
+ );
+ const name = grown.columns[index + 1];
+ const next = { ...emptyMeta(), ...meta };
+ const width = meta?.widths?.[previous];
+ if (width !== undefined) next.widths = { ...(next.widths ?? {}), [name]: width };
+ const role = meta?.roles?.[previous];
+ if (role) next.roles = { ...(next.roles ?? {}), [name]: { ...role } };
+ const note = meta?.notes?.[previous];
+ if (note) next.notes = { ...(next.notes ?? {}), [name]: note };
+ return { table: grown, meta: next, name };
+}
+
+/**
+ * Rename a column, and move everything the sidecar keyed on its old name.
+ *
+ * Without the second half a renamed column silently loses its width and every
+ * entity link in it — the analyst's work disappearing because they fixed a
+ * spelling.
+ */
+export function renameColumn(table, meta, index, name) {
+ const previous = table.columns[index];
+ const heading = freeColumnName(
+ table.columns.filter((_, at) => at !== index),
+ String(name ?? '').trim() || previous,
+ );
+ const columns = table.columns.map((current, at) => (at === index ? heading : current));
+ return { table: { ...table, columns }, meta: remapColumn(meta, previous, heading) };
+}
+
+export function removeColumn(table, meta, index) {
+ const name = table.columns[index];
+ return {
+ table: {
+ ...table,
+ columns: table.columns.filter((_, at) => at !== index),
+ rows: table.rows.map((row) => row.filter((_, at) => at !== index)),
+ },
+ meta: remapColumn(meta, name, null),
+ };
+}
+
+/**
+ * Move a column to another position, cells and all.
+ *
+ * The order is moved **in the table**, not remembered in the sidecar. A column order
+ * is something the collaborator opening the CSV sees, so it belongs in the file; and
+ * a sidecar list of names beside a file with its own order is two answers to one
+ * question. Nothing in the sidecar is keyed on position, so nothing has to follow.
+ */
+export function moveColumn(table, from, to) {
+ const width = table.columns.length;
+ if (from === to || from < 0 || to < 0 || from >= width || to >= width) return table;
+ const order = table.columns.map((_, index) => index);
+ order.splice(to, 0, ...order.splice(from, 1));
+ return {
+ columns: order.map((index) => table.columns[index]),
+ rows: table.rows.map((row) => order.map((index) => row[index] ?? '')),
+ };
+}
+
+/**
+ * Move everything the sidecar keyed on `from` onto `to`, or drop it when `to` is null.
+ *
+ * *Everything* is the word that cost something. This moved five of the nine keys — the
+ * width, the hidden flag, the sort, the frozen column and the links — and silently left
+ * behind the four that say what the column **is**: its role, its note, whether the sheet
+ * counts its progress there, and what its cells said when the case took them. So renaming
+ * `Status` to `État` lost its type, the panel then offered a *detected* one from the
+ * cells, and the analyst read that as the type having changed by itself. On the next save
+ * the four were cleaned away for good, and the read reported the role as dropped — a
+ * message written for a column renamed in a spreadsheet, fired by a rename made here.
+ *
+ * One helper per shape, because there are only three: a table keyed by column name, a
+ * table of rows each keyed by column name, and a lone name.
+ */
+function remapColumn(meta, from, to) {
+ const next = { ...emptyMeta(), ...meta };
+
+ // Keyed by column name: width, role, note, and what is asked of the column.
+ for (const key of ['widths', 'roles', 'notes', 'filters']) {
+ next[key] = moveKey(next[key], from, to);
+ }
+ // Keyed by row, then by column name: the promotion's record of what a cell said.
+ next.promoted = Object.fromEntries(
+ Object.entries(next.promoted ?? {})
+ .map(([key, cells]) => [key, moveKey(cells, from, to)])
+ .filter(([, cells]) => Object.keys(cells).length),
+ );
+ next.links = Object.fromEntries(
+ Object.entries(next.links ?? {})
+ .map(([key, cells]) => [key, moveKey(cells, from, to)])
+ .filter(([, cells]) => Object.keys(cells).length),
+ );
+
+ const hidden = (next.hidden ?? []).filter((name) => name !== from);
+ if (to && (meta?.hidden ?? []).includes(from)) hidden.push(to);
+ next.hidden = hidden;
+ if (next.sort?.column === from) {
+ next.sort = to ? { ...next.sort, column: to } : null;
+ }
+ if (next.sort?.then?.column === from) {
+ if (to) next.sort = { ...next.sort, then: { ...next.sort.then, column: to } };
+ else {
+ const { then: _dropped, ...rest } = next.sort;
+ next.sort = rest;
+ }
+ }
+ if (next.frozen === from) next.frozen = to ?? null;
+ // Which column the footer counts the work on. Lost on a rename, it left the sheet with
+ // no progress reading and no sign of why.
+ if (next.progress === from) next.progress = to ?? null;
+ return next;
+}
+
+/** One table keyed by column name, with `from`'s entry moved to `to` or dropped. */
+function moveKey(table, from, to) {
+ const next = { ...(table ?? {}) };
+ if (!(from in next)) return next;
+ const held = next[from];
+ delete next[from];
+ if (to) next[to] = held;
+ return next;
+}
+
+/** A heading with its spelling taken out of it, for lining two sheets up. */
+function foldHeading(name) {
+ return String(name ?? '')
+ .normalize('NFD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]/g, '');
+}
+
+/**
+ * Which column of this sheet belongs in which column of that one.
+ *
+ * The opening proposal of a move, and every line of it is a select the analyst can
+ * overrule. The server used to match on the name alone and drop the rest, so a column
+ * written `local_time` at one end and `Local time` at the other was a silent loss the
+ * analyst read about in the toast, after the rows had left.
+ *
+ * An exact name is taken as an answer. A name that differs only in how it is written —
+ * case, accents, the space against the underscore — is proposed as a **guess** and says
+ * so, because a guess that looks like a match is worse than no proposal. Nothing further
+ * is attempted: `Time` onto `Local time` is right about as often as it is wrong, and that
+ * one is the analyst's to point. One target is taken once, since two columns poured into
+ * one would lose the second.
+ */
+export function suggestMapping(mine, theirs) {
+ const ours = (mine ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN);
+ const free = (theirs ?? []).filter((name) => String(name).toLowerCase() !== ID_COLUMN);
+ const taken = new Set();
+ const pairs = ours.map((name) => ({ name, to: '', guessed: false }));
+
+ for (const pair of pairs) {
+ const exact = free.find((name) => name === pair.name && !taken.has(name));
+ if (exact) {
+ pair.to = exact;
+ taken.add(exact);
+ }
+ }
+ // A second pass, so an exact match is never spent on a fold: `Address` and `Adresse`
+ // both fold to the same thing, and the one spelled the same way has first claim.
+ for (const pair of pairs) {
+ if (pair.to) continue;
+ const folded = foldHeading(pair.name);
+ if (!folded) continue;
+ const near = free.find((name) => !taken.has(name) && foldHeading(name) === folded);
+ if (!near) continue;
+ pair.to = near;
+ pair.guessed = true;
+ taken.add(near);
+ }
+ return pairs;
+}
+
+// -- the sidecar --------------------------------------------------------------
+
+export function setColour(meta, key, colour) {
+ const colours = { ...(meta?.colours ?? {}) };
+ if (colour && ROW_COLOURS.includes(colour)) colours[key] = colour;
+ else delete colours[key];
+ return { ...emptyMeta(), ...meta, colours };
+}
+
+/** Point a cell at an entity, or clear it. The cell keeps whatever text it holds:
+ * the link is what the case knows, the text is what the file says. */
+export function setLink(meta, key, column, entityId) {
+ const links = { ...(meta?.links ?? {}) };
+ const cells = { ...(links[key] ?? {}) };
+ if (entityId) cells[column] = entityId;
+ else delete cells[column];
+ if (Object.keys(cells).length) links[key] = cells;
+ else delete links[key];
+ return { ...emptyMeta(), ...meta, links };
+}
+
+export function linkAt(meta, key, column) {
+ return meta?.links?.[key]?.[column] ?? null;
+}
+
+/** Every entity this sidecar points at: the cells that link, the words a column means
+ * in the case, the files rows carry. Mirrors `engine/sheets.linked_entity_ids`. */
+export function linkedEntityIds(meta) {
+ const found = [];
+ for (const cells of Object.values(meta?.links ?? {})) found.push(...Object.values(cells ?? {}));
+ for (const words of Object.values(meta?.values ?? {})) found.push(...Object.values(words ?? {}));
+ for (const held of Object.values(meta?.attachments ?? {})) found.push(...(held ?? []));
+ return [...new Set(found.filter(Boolean).map(String))];
+}
+
+/**
+ * The sidecar with every pointer at one of `gone` removed, or the same object back when
+ * it held none.
+ *
+ * The delete already cleared the file (`engine/sheets.forget_entities`); this clears the
+ * copy on screen, which is the copy the next save would otherwise write the dead ids
+ * back from. Same three places, so a cell, a column's vocabulary and a row's files all
+ * stop pointing at material the case no longer holds.
+ */
+export function withoutEntities(meta, gone) {
+ if (!gone?.size) return meta;
+ const held = (value) => !gone.has(String(value));
+ let hit = false;
+
+ const links = {};
+ for (const [key, cells] of Object.entries(meta?.links ?? {})) {
+ const kept = Object.fromEntries(Object.entries(cells ?? {}).filter(([, id]) => held(id)));
+ if (Object.keys(kept).length !== Object.keys(cells ?? {}).length) hit = true;
+ if (Object.keys(kept).length) links[key] = kept;
+ }
+
+ const values = {};
+ for (const [name, words] of Object.entries(meta?.values ?? {})) {
+ const kept = Object.fromEntries(Object.entries(words ?? {}).filter(([, id]) => held(id)));
+ if (Object.keys(kept).length !== Object.keys(words ?? {}).length) hit = true;
+ if (Object.keys(kept).length) values[name] = kept;
+ }
+
+ const attachments = {};
+ for (const [key, list] of Object.entries(meta?.attachments ?? {})) {
+ const kept = (list ?? []).filter(held);
+ if (kept.length !== (list ?? []).length) hit = true;
+ if (kept.length) attachments[key] = kept;
+ }
+
+ return hit ? { ...emptyMeta(), ...meta, links, values, attachments } : meta;
+}
+
+/**
+ * What a colour means in this sheet.
+ *
+ * Six colours with nothing written against them is six colours whose meaning lives in one
+ * analyst's head — and a case is handed over. Kept in the sidecar rather than in the file
+ * because the colour is: losing both together costs presentation, which is the deal the
+ * sidecar is under.
+ */
+export function setLegend(meta, colour, label) {
+ const legend = { ...(meta?.legend ?? {}) };
+ const text = String(label ?? '').trim();
+ if (text && ROW_COLOURS.includes(colour)) legend[colour] = text;
+ else delete legend[colour];
+ return { ...emptyMeta(), ...meta, legend };
+}
+
+/**
+ * Keep one row under the heading while the rest scrolls, or let it go.
+ *
+ * The reference candidate a comparison grid is read *against*: the confirmed sighting the
+ * other eleven are being compared to, which otherwise scrolls away at row twelve and takes
+ * the point of the grid with it. Keyed like a colour, so a re-sort cannot move it onto
+ * somebody else's row.
+ */
+export function setPinned(meta, key) {
+ const wanted = key && meta?.pinned !== key ? String(key) : null;
+ return { ...emptyMeta(), ...meta, pinned: wanted };
+}
+
+/** One line per row, or the four a note needs. A grid of thirty-pixel rows is right for a
+ * worklist and wrong for the column the reasoning is written in. */
+export function setTall(meta, tall) {
+ return { ...emptyMeta(), ...meta, tall: Boolean(tall) };
+}
+
+export function setWidth(meta, column, width) {
+ return {
+ ...emptyMeta(),
+ ...meta,
+ widths: { ...(meta?.widths ?? {}), [column]: Math.max(60, Math.min(720, Math.round(width))) },
+ };
+}
+
+export function toggleHidden(meta, column) {
+ const hidden = new Set(meta?.hidden ?? []);
+ if (!hidden.delete(column)) hidden.add(column);
+ return { ...emptyMeta(), ...meta, hidden: [...hidden] };
+}
+
+/** Click a heading: sort ascending, then descending, then not at all. Three
+ * states on one control, so putting a sort back is the same gesture as setting
+ * it rather than a second one to find. A second key already in place survives the
+ * cycle and goes with the sort when it is turned off — it is a tiebreak, not a sort. */
+export function nextSort(sort, column) {
+ if (sort?.column !== column) return { column, desc: false, ...(sort?.then ? { then: sort.then } : {}) };
+ return sort.desc ? null : { ...sort, desc: true };
+}
+
+/**
+ * Break the first key's ties with a second column: ascending, then descending, then not
+ * at all.
+ *
+ * The same three states as a heading's own click, because it is the same question asked
+ * one level down — and it is a **menu row** rather than a fourth state on the heading,
+ * since "sort by this" and "sort by this too" one gesture apart would be a trap. Naming
+ * the column the sort is already on clears the second key: one column cannot break its
+ * own tie.
+ */
+export function nextSecondSort(sort, column) {
+ if (!sort?.column) return sort ?? null;
+ const drop = () => {
+ const { then: _dropped, ...rest } = sort;
+ return rest;
+ };
+ if (!column || column === sort.column) return drop();
+ if (sort.then?.column !== column) return { ...sort, then: { column, desc: false } };
+ return sort.then.desc ? drop() : { ...sort, then: { column, desc: true } };
+}
+
+/** Keep one column beside the key while the table scrolls sideways, or stop. The
+ * key column is not a candidate: it already sticks, being the row's handle, and
+ * offering to freeze it would offer a change that does nothing. */
+export function setFrozen(meta, column) {
+ const wanted = column && String(column).toLowerCase() !== ID_COLUMN ? String(column) : null;
+ return { ...emptyMeta(), ...meta, frozen: meta?.frozen === wanted ? null : wanted };
+}
+
+/**
+ * Where each column that stays put sits, in pixels from the left edge.
+ *
+ * The key column sticks because it is the row's handle: on a comparison grid forty
+ * columns wide, losing which row you are on is losing the grid. One more column may
+ * be frozen beside it — the subject, usually, which is the column that says what the
+ * row *is*. Offsets are accumulated in drawn order rather than declared, so a column
+ * moved by dragging cannot end up overlapping the one it now follows.
+ */
+export function stickyOffsets(drawn, meta) {
+ const frozen = meta?.frozen ?? null;
+ const offsets = {};
+ let left = GUTTER_WIDTH;
+ for (const column of drawn ?? []) {
+ const isKey = String(column.name).toLowerCase() === ID_COLUMN;
+ if (!isKey && column.name !== frozen) continue;
+ offsets[column.name] = left;
+ left += meta?.widths?.[column.name] ?? DEFAULT_WIDTH;
+ }
+ return offsets;
+}
+
+// -- what is selected ---------------------------------------------------------
+
+/**
+ * The rectangle between two cells, in table coordinates.
+ *
+ * Both ends are given as table row and column indices, but the rectangle is walked
+ * in **display** order: the analyst who shift-clicks two cells means everything
+ * between them on screen, and the file's own order may be nothing like it. Either
+ * end having scrolled out of the filter collapses the range to the cursor rather
+ * than selecting something nobody pointed at.
+ */
+export function cellRange(shown, drawn, anchor, cursor) {
+ const only = { rows: [cursor?.row].filter((row) => row >= 0), columns: [cursor?.column].filter((column) => column >= 0) };
+ if (!anchor || !cursor) return only;
+ const columnsOrder = (drawn ?? []).map((column) => column.index);
+ const top = shown.indexOf(anchor.row);
+ const bottom = shown.indexOf(cursor.row);
+ const left = columnsOrder.indexOf(anchor.column);
+ const right = columnsOrder.indexOf(cursor.column);
+ if (top === -1 || bottom === -1 || left === -1 || right === -1) return only;
+ return {
+ rows: shown.slice(Math.min(top, bottom), Math.max(top, bottom) + 1),
+ columns: columnsOrder.slice(Math.min(left, right), Math.max(left, right) + 1),
+ };
+}
+
+/** The cells of a range, as rows — what goes on the clipboard when a range is
+ * copied, in the order they are on screen. */
+export function rangeValues(table, range) {
+ return (range?.rows ?? []).map((row) =>
+ (range?.columns ?? []).map((column) => table.rows[row]?.[column] ?? ''),
+ );
+}
+
+/** The edits that copy a range's top row down over the rest of it. The gesture
+ * every grid has: state one answer, then say "and these too". */
+export function fillDownEdits(table, range) {
+ const [first, ...rest] = range?.rows ?? [];
+ if (first === undefined || !rest.length) return [];
+ return (range.columns ?? []).flatMap((column) =>
+ fillEdits(table, column, rest, table.rows[first]?.[column] ?? ''),
+ );
+}
+
+// -- what is ticked -----------------------------------------------------------
+
+/** The keys of the rows on screen, in the order they are drawn. What "tick
+ * everything shown" means, and the answer to "is everything shown ticked". */
+export function shownKeys(table, shown) {
+ return (shown ?? []).map((index) => rowKey(table.columns, table.rows[index]));
+}
+
+/**
+ * Every key from one row to another, in display order.
+ *
+ * Shift-click means "and everything between", and *between* is what the analyst can
+ * see — the order the grid draws, not the order the file holds. Handing back the two
+ * ends as well makes the gesture read the same whichever end was clicked first.
+ */
+export function keysBetween(table, shown, fromKey, toKey) {
+ const keys = shownKeys(table, shown);
+ const from = keys.indexOf(fromKey);
+ const to = keys.indexOf(toKey);
+ if (from === -1 || to === -1) return to === -1 ? [] : [toKey];
+ return keys.slice(Math.min(from, to), Math.max(from, to) + 1);
+}
+
+// -- the scrollbars -----------------------------------------------------------
+//
+// The grid draws its own rather than using the browser's. Two reasons, and the
+// second is the one that decided it: the app's chrome sets thin scrollbars
+// everywhere, which is right for a panel that hints there is more below and wrong
+// for a wide table where the bar *is* how you navigate; and on Linux — one of the
+// three platforms shipped — the native bars are overlays that fade out, so half
+// the time there is nothing on screen to grab.
+
+/** The smallest thumb still worth aiming at, in pixels. */
+const MIN_THUMB = 30;
+
+/**
+ * Where a scrollbar's thumb sits and how big it is, or null when nothing overflows.
+ *
+ * `travel` is how far the thumb may move, which is not the track length once the
+ * thumb has a minimum size — the two diverge on a very long sheet, and using the
+ * track length there makes the thumb run off the end.
+ */
+export function scrollThumb(track, content, offset, min = MIN_THUMB) {
+ if (!(track > 0) || !(content > track)) return null;
+ const size = Math.min(track, Math.max(min, Math.round((track * track) / content)));
+ const travel = track - size;
+ const maxScroll = content - track;
+ const clamped = Math.min(Math.max(offset, 0), maxScroll);
+ return {
+ size,
+ travel,
+ maxScroll,
+ position: travel > 0 ? Math.round((clamped / maxScroll) * travel) : 0,
+ };
+}
+
+/** The scroll offset a thumb dragged to `position` pixels along its track means. */
+export function scrollFromThumb(thumb, position) {
+ if (!thumb || thumb.travel <= 0) return 0;
+ const clamped = Math.min(Math.max(position, 0), thumb.travel);
+ return Math.round((clamped / thumb.travel) * thumb.maxScroll);
+}
diff --git a/frontend/src/lib/sheet.test.js b/frontend/src/lib/sheet.test.js
new file mode 100644
index 0000000..5a21199
--- /dev/null
+++ b/frontend/src/lib/sheet.test.js
@@ -0,0 +1,1150 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAX_COLUMNS,
+ MAX_ROWS,
+ tooBigBy,
+ DEFAULT_WIDTH,
+ GUTTER_WIDTH,
+ ID_COLUMN,
+ addColumn,
+ addRow,
+ applyEdits,
+ clearFilters,
+ columnValues,
+ compareCells,
+ dropChip,
+ duplicateColumn,
+ duplicateRows,
+ emptyMeta,
+ explodeRow,
+ fillEdits,
+ filterChips,
+ filterSummary,
+ freeColumnName,
+ highlightParts,
+ insertColumn,
+ insertRow,
+ isFilterActive,
+ keyIndex,
+ keysBetween,
+ linkAt,
+ linkedEntityIds,
+ linkLabel,
+ answersTerms,
+ searchTerms,
+ mergeRows,
+ moveColumn,
+ nextSecondSort,
+ nextSort,
+ onlyFilterValue,
+ readFilters,
+ removeColumn,
+ removeRows,
+ renameColumn,
+ renameFilterColumn,
+ rowHeight,
+ rowKey,
+ scrollFromThumb,
+ scrollThumb,
+ serializeFilters,
+ setCells,
+ setColour,
+ setFilterContains,
+ setFilterRange,
+ setFilterWithout,
+ setFrozen,
+ setLegend,
+ setLink,
+ setPinned,
+ setTall,
+ setWidth,
+ shownKeys,
+ stickyOffsets,
+ suggestMapping,
+ toggleFilterFill,
+ toggleFilterValue,
+ toggleHidden,
+ urlsIn,
+ visibleColumns,
+ visibleRows,
+ withoutEntities,
+} from './sheet.js';
+
+const table = () => ({
+ columns: ['id', 'Subject', 'Status', 'Score'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out', '10'],
+ ['r2', 'Pont nord', '', '9'],
+ ['r3', 'Gare est', 'to check', '100'],
+ ],
+});
+
+describe('the key column', () => {
+ it('is found wherever it sits', () => {
+ expect(keyIndex(['id', 'name'])).toBe(0);
+ expect(keyIndex(['name', 'ID'])).toBe(1);
+ });
+
+ it('falls back to the first column rather than losing the row', () => {
+ expect(keyIndex(['name', 'plate'])).toBe(0);
+ });
+
+ it('is what a row is addressed by', () => {
+ expect(rowKey(['id', 'name'], ['r7', 'Quai sud'])).toBe('r7');
+ });
+
+ it('is drawn even when hidden is asked for', () => {
+ const drawn = visibleColumns(table().columns, { hidden: [ID_COLUMN, 'Score'] });
+ expect(drawn.map((column) => column.name)).toEqual(['id', 'Subject', 'Status']);
+ });
+});
+
+describe('ordering', () => {
+ it('compares numbers as numbers', () => {
+ expect(compareCells('9', '10')).toBe(-1);
+ expect(compareCells('10', '9')).toBe(1);
+ });
+
+ it('compares text the way it reads', () => {
+ expect(compareCells('AB-2', 'AB-10')).toBe(-1);
+ });
+
+ it('sinks blank cells whichever way the arrow points', () => {
+ const rows = table().rows;
+ const up = visibleRows(table(), { sort: { column: 'Status', desc: false } });
+ const down = visibleRows(table(), { sort: { column: 'Status', desc: true } });
+ expect(rows[up.at(-1)][2]).toBe('');
+ expect(rows[down.at(-1)][2]).toBe('');
+ });
+
+ it('keeps equal cells in the order the file has them', () => {
+ const same = {
+ columns: ['id', 'Status'],
+ rows: [['r1', 'x'], ['r2', 'x'], ['r3', 'x']],
+ };
+ expect(visibleRows(same, { sort: { column: 'Status', desc: true } })).toEqual([0, 1, 2]);
+ });
+
+ it('cycles a heading through up, down and off', () => {
+ expect(nextSort(null, 'Status')).toEqual({ column: 'Status', desc: false });
+ expect(nextSort({ column: 'Status', desc: false }, 'Status')).toEqual({
+ column: 'Status',
+ desc: true,
+ });
+ expect(nextSort({ column: 'Status', desc: true }, 'Status')).toBeNull();
+ expect(nextSort({ column: 'Status', desc: true }, 'Score')).toEqual({
+ column: 'Score',
+ desc: false,
+ });
+ });
+});
+
+describe('the question asked of a sheet', () => {
+ it('needs every term to appear somewhere in the row', () => {
+ expect(answersTerms(['r1', 'Quai sud', 'ruled out'], searchTerms('quai out'))).toBe(true);
+ expect(answersTerms(['r1', 'Quai sud', 'ruled out'], searchTerms('quai nord'))).toBe(false);
+ });
+
+ it('matches everything when nothing is typed', () => {
+ expect(answersTerms(['r1', 'x'], searchTerms(' '))).toBe(true);
+ });
+
+ it('narrows to the chosen values of a column', () => {
+ const shown = visibleRows(table(), { filters: { Status: new Set(['to check']) } });
+ expect(shown).toEqual([2]);
+ });
+
+ it('combines the box and the chips', () => {
+ const shown = visibleRows(table(), {
+ query: 'gare',
+ filters: { Status: new Set(['to check']) },
+ });
+ expect(shown).toEqual([2]);
+ expect(visibleRows(table(), { query: 'quai', filters: { Status: new Set(['to check']) } }))
+ .toEqual([]);
+ });
+
+ it('counts a column values, commonest first', () => {
+ const counted = columnValues(
+ { columns: ['id', 'Status'], rows: [['r1', 'a'], ['r2', 'b'], ['r3', 'a']] },
+ 'Status',
+ );
+ expect(counted.values).toEqual([
+ { value: 'a', rows: 2 },
+ { value: 'b', rows: 1 },
+ ]);
+ expect(counted.total).toBe(2);
+ expect(counted.capped).toBe(false);
+ });
+
+ it('pages a column holding more values than a menu lists, rather than refusing it', () => {
+ const rows = Array.from({ length: 60 }, (_, index) => [`r${index}`, `value ${index}`]);
+ const counted = columnValues({ columns: ['id', 'Free'], rows }, 'Free', null, { limit: 40 });
+ expect(counted.values).toHaveLength(40);
+ expect(counted.total).toBe(60);
+ expect(counted.capped).toBe(true);
+ });
+
+ it('narrows the values against the whole column, not against the page', () => {
+ const rows = Array.from({ length: 60 }, (_, index) => [`r${index}`, `value ${index}`]);
+ const counted = columnValues({ columns: ['id', 'Free'], rows }, 'Free', null, {
+ term: 'value 5',
+ limit: 40,
+ });
+ // `value 5` and `value 50`..`value 59`: found past the fortieth entry of the list.
+ expect(counted.matching).toBe(11);
+ expect(counted.capped).toBe(false);
+ });
+});
+
+describe('edits', () => {
+
+ it('append a row already carrying a key', () => {
+ const next = addRow(table());
+ expect(next.rows).toHaveLength(4);
+ expect(rowKey(next.columns, next.rows[3])).toMatch(/^r[0-9a-f]{10}$/);
+ });
+
+ it('drop the rows asked for and leave the rest', () => {
+ const next = removeRows(table(), [0, 2]);
+ expect(next.rows.map((row) => row[0])).toEqual(['r2']);
+ });
+
+ it('never create two columns with one name', () => {
+ expect(freeColumnName(['Status'], 'Status')).toBe('Status 2');
+ expect(addColumn(table(), 'Status').columns.at(-1)).toBe('Status 2');
+ expect(addColumn(table(), 'Status').rows[0]).toHaveLength(5);
+ });
+});
+
+describe('renaming a column', () => {
+ it('carries its width, its sort and its links onto the new name', () => {
+ const meta = {
+ ...emptyMeta(),
+ widths: { Status: 200 },
+ hidden: ['Status'],
+ sort: { column: 'Status', desc: true },
+ links: { r1: { Status: 'e_1', Subject: 'e_2' } },
+ };
+ const { table: next, meta: moved } = renameColumn(table(), meta, 2, 'Verdict');
+
+ expect(next.columns).toEqual(['id', 'Subject', 'Verdict', 'Score']);
+ expect(moved.widths).toEqual({ Verdict: 200 });
+ expect(moved.hidden).toEqual(['Verdict']);
+ expect(moved.sort).toEqual({ column: 'Verdict', desc: true });
+ expect(moved.links.r1).toEqual({ Subject: 'e_2', Verdict: 'e_1' });
+ });
+
+ it('refuses to collide with another column and keeps the old name', () => {
+ const { table: next } = renameColumn(table(), emptyMeta(), 2, 'Subject');
+ expect(next.columns[2]).toBe('Subject 2');
+ });
+
+ it('keeps the old name when the new one is blank', () => {
+ const { table: next } = renameColumn(table(), emptyMeta(), 2, ' ');
+ expect(next.columns[2]).toBe('Status');
+ });
+});
+
+describe('removing a column', () => {
+ it('takes the cells and everything the sidecar hung on it', () => {
+ const meta = {
+ ...emptyMeta(),
+ widths: { Status: 200, Score: 90 },
+ sort: { column: 'Status', desc: false },
+ links: { r1: { Status: 'e_1' } },
+ };
+ const { table: next, meta: pruned } = removeColumn(table(), meta, 2);
+
+ expect(next.columns).toEqual(['id', 'Subject', 'Score']);
+ expect(next.rows[0]).toEqual(['r1', 'Quai sud', '10']);
+ expect(pruned.widths).toEqual({ Score: 90 });
+ expect(pruned.sort).toBeNull();
+ expect(pruned.links).toEqual({});
+ });
+});
+
+describe('asking a column something other than a value', () => {
+ // The three questions a worklist gets asked. `To be found`, `-`, `?` and an empty
+ // cell all mean "not done" to the person filtering, and no list of chosen values
+ // catches them.
+ const worklist = () => ({
+ columns: ['id', 'Coordinates', 'Note'],
+ rows: [
+ ['r1', '48.85, 2.29', 'confirmed by the author'],
+ ['r2', '', 'to be found'],
+ ['r3', ' ', 'no idea'],
+ ['r4', '50.10, 3.00', 'AI video, do not use'],
+ ],
+ });
+
+ it('finds the rows with nothing in a column yet', () => {
+ const filters = toggleFilterFill({}, 'Coordinates', 'blank');
+ expect(visibleRows(worklist(), { filters })).toEqual([1, 2]);
+ });
+
+ it('counts whitespace as nothing, the way the analyst reads it', () => {
+ const filters = toggleFilterFill({}, 'Coordinates', 'filled');
+ expect(visibleRows(worklist(), { filters })).toEqual([0, 3]);
+ });
+
+ it('excludes on a term without excluding the blanks', () => {
+ const filters = setFilterWithout({}, 'Note', 'AI video');
+ expect(visibleRows(worklist(), { filters })).toEqual([0, 1, 2]);
+ });
+
+ it('reads a term case-insensitively, like the search box', () => {
+ expect(visibleRows(worklist(), { filters: setFilterWithout({}, 'Note', 'ai VIDEO') })).toEqual([
+ 0, 1, 2,
+ ]);
+ });
+
+ it('keeps the rows holding a term, which is all a column of prose can offer', () => {
+ // The other half of `without`. Past the bound there is no list of values to tick,
+ // so a column of notes could be ruled out by a word and never kept by one.
+ const filters = setFilterContains({}, 'Note', 'found');
+ expect(visibleRows(worklist(), { filters })).toEqual([1]);
+ });
+
+ it('reads the two halves of that question together', () => {
+ let filters = setFilterContains({}, 'Note', 'o');
+ filters = setFilterWithout(filters, 'Note', 'AI');
+ expect(visibleRows(worklist(), { filters })).toEqual([0, 1, 2]);
+ });
+
+ it('ands the clauses of one column together', () => {
+ let filters = toggleFilterFill({}, 'Note', 'filled');
+ filters = setFilterWithout(filters, 'Note', 'idea');
+ expect(visibleRows(worklist(), { filters })).toEqual([0, 1, 3]);
+ });
+
+ it('still takes a bare set of values, which is the common case', () => {
+ const shown = visibleRows(worklist(), { filters: { Note: new Set(['no idea']) } });
+ expect(shown).toEqual([2]);
+ });
+
+ it('asking the same thing twice stops asking it', () => {
+ const once = toggleFilterFill({}, 'Coordinates', 'blank');
+ expect(isFilterActive(once.Coordinates)).toBe(true);
+ expect(toggleFilterFill(once, 'Coordinates', 'blank').Coordinates).toBeUndefined();
+ });
+
+ it('drops the column once nothing is left to ask of it', () => {
+ const filters = toggleFilterValue({}, 'Note', 'no idea');
+ expect(toggleFilterValue(filters, 'Note', 'no idea')).toEqual({});
+ });
+
+ it('shows one chip per clause, each removable on its own', () => {
+ let filters = toggleFilterValue({}, 'Note', 'no idea');
+ filters = toggleFilterFill(filters, 'Coordinates', 'blank');
+ filters = setFilterWithout(filters, 'Note', 'AI');
+
+ const chips = filterChips(filters);
+ expect(chips.map((chip) => chip.label)).toEqual(['no idea', 'without AI', 'empty']);
+
+ const left = dropChip(filters, chips.find((chip) => chip.part === 'without'));
+ expect(filterChips(left).map((chip) => chip.label)).toEqual(['no idea', 'empty']);
+ });
+
+ it('names the blank value in a chip rather than showing nothing', () => {
+ const chips = filterChips(toggleFilterValue({}, 'Note', ''));
+ expect(chips[0].label).toBe('(blank)');
+ });
+
+ it('takes back a term the same way a chip does', () => {
+ const filters = setFilterContains({}, 'Note', 'found');
+ const [chip] = filterChips(filters);
+ expect(chip.label).toBe('with found');
+ expect(dropChip(filters, chip)).toEqual({});
+ });
+
+ it('asking for one value drops what else was asked of that column', () => {
+ // What a cell offers: the answer under the pointer is the whole question, so a
+ // second value ticked in the menu is not carried along with it.
+ let filters = toggleFilterValue({}, 'Note', 'no idea');
+ filters = setFilterWithout(filters, 'Note', 'AI');
+ filters = toggleFilterFill(filters, 'Coordinates', 'blank');
+
+ const only = onlyFilterValue(filters, 'Note', 'to be found');
+ expect(filterSummary(only.Note)).toBe('to be found');
+ // And it leaves the other columns exactly as they were.
+ expect(filterSummary(only.Coordinates)).toBe('empty');
+ });
+
+ it('says what is asked of a column in one line, for the panel to state', () => {
+ let filters = toggleFilterValue({}, 'Note', 'no idea');
+ filters = setFilterContains(filters, 'Note', 'ide');
+ expect(filterSummary(filters.Note)).toBe('no idea · with ide');
+ expect(filterSummary(undefined)).toBe('');
+ });
+
+ it('finds a value inside a cell that holds several of them', () => {
+ // Comparing the whole cell found neither answer, so clicking a chip in the grid
+ // narrowed a list column to nothing at all.
+ const table = {
+ columns: ['id', 'Equipments'],
+ rows: [['r1', 'Buk-M2E, ZU23-2'], ['r2', 'S-125'], ['r3', '']],
+ };
+ const roles = { Equipments: { kind: 'choice', multi: ', ' } };
+ const filters = toggleFilterValue({}, 'Equipments', 'ZU23-2');
+ expect(visibleRows(table, { filters, roles })).toEqual([0]);
+ expect(
+ visibleRows(table, { filters: toggleFilterValue({}, 'Equipments', 'S-125'), roles }),
+ ).toEqual([1]);
+ // And an empty cell still answers the blank entry the menu offers.
+ expect(visibleRows(table, { filters: toggleFilterValue({}, 'Equipments', ''), roles })).toEqual([
+ 2,
+ ]);
+ });
+
+ it('asks a column for the cells its own type cannot read', () => {
+ const table = {
+ columns: ['id', 'Count'],
+ rows: [['r1', '3'], ['r2', 'about 12'], ['r3', '']],
+ };
+ const roles = { Count: { kind: 'number' } };
+ const filters = toggleFilterFill({}, 'Count', 'unreadable');
+ expect(visibleRows(table, { filters, roles })).toEqual([1]);
+ expect(filterChips(filters)[0].label).toBe('to check');
+ });
+
+ it('counts a list column value by value rather than cell by cell', () => {
+ const table = {
+ columns: ['id', 'Equipments'],
+ rows: [['r1', 'Buk-M2E, S-125'], ['r2', 'S-125']],
+ };
+ expect(columnValues(table, 'Equipments', { kind: 'choice', multi: ', ' }).values)
+ .toEqual([
+ { value: 'S-125', rows: 2 },
+ { value: 'Buk-M2E', rows: 1 },
+ ]);
+ });
+});
+
+describe('asking a column for a range', () => {
+ const distances = () => ({
+ columns: ['id', 'Distance'],
+ rows: [['r1', '2'], ['r2', '12'], ['r3', 'about 5'], ['r4', '']],
+ });
+
+ it('keeps the rows between the two bounds and drops what it cannot read', () => {
+ const filters = setFilterRange({}, 'Distance', { from: '1', to: '10' });
+ expect(visibleRows(distances(), { filters, roles: { Distance: { kind: 'number' } } }))
+ .toEqual([0]);
+ });
+
+ it('takes either bound on its own', () => {
+ const roles = { Distance: { kind: 'number' } };
+ expect(visibleRows(distances(), { filters: setFilterRange({}, 'Distance', { from: '3' }), roles }))
+ .toEqual([1]);
+ expect(visibleRows(distances(), { filters: setFilterRange({}, 'Distance', { to: '3' }), roles }))
+ .toEqual([0]);
+ });
+
+ it('reads a date column as moments rather than as words', () => {
+ const table = {
+ columns: ['id', 'When'],
+ rows: [['r1', '03/01/2026'], ['r2', '28/02/2026'], ['r3', 'unknown']],
+ };
+ const filters = setFilterRange({}, 'When', { from: '2026-02-01' });
+ expect(visibleRows(table, { filters, roles: { When: { kind: 'when' } } })).toEqual([1]);
+ });
+
+ it('says each bound as its own chip, and each one is removable alone', () => {
+ const filters = setFilterRange({}, 'Distance', { from: '1', to: '10' });
+ const chips = filterChips(filters);
+ expect(chips.map((chip) => chip.label)).toEqual(['from 1', 'to 10']);
+ expect(isFilterActive(dropChip(filters, chips[0]).Distance)).toBe(true);
+ expect(dropChip(dropChip(filters, chips[0]), chips[1]).Distance).toBeUndefined();
+ });
+});
+
+describe('marking what the search found', () => {
+ it('cuts a cell into the parts a term matched and the parts it did not', () => {
+ expect(highlightParts('Quai sud, Kherson', 'kherson')).toEqual([
+ { text: 'Quai sud, ', hit: false },
+ { text: 'Kherson', hit: true },
+ ]);
+ });
+
+ it('marks two overlapping terms once rather than twice', () => {
+ expect(highlightParts('Kherson', 'kher kherson')).toEqual([{ text: 'Kherson', hit: true }]);
+ });
+
+ it('leaves the cell whole when nothing is being searched for', () => {
+ expect(highlightParts('Quai sud', ' ')).toEqual([{ text: 'Quai sud', hit: false }]);
+ });
+});
+
+describe('growing a table where the work is', () => {
+ it('inserts a column at an index rather than at the end', () => {
+ const next = insertColumn(table(), 2, 'Verdict');
+ expect(next.columns).toEqual(['id', 'Subject', 'Verdict', 'Status', 'Score']);
+ expect(next.rows[0]).toEqual(['r1', 'Quai sud', '', 'ruled out', '10']);
+ });
+
+ it('names an inserted column around one already taken', () => {
+ expect(insertColumn(table(), 1, 'Status').columns[1]).toBe('Status 2');
+ });
+
+ it('copies a column beside itself with its cells and its lens', () => {
+ const meta = { ...emptyMeta(), widths: { Status: 220 }, roles: { Status: { kind: 'state' } },
+ notes: { Status: 'where it got to' }, links: { r1: { Status: 'e_7' } } };
+ const copied = duplicateColumn(table(), meta, 2);
+ expect(copied.table.columns).toEqual(['id', 'Subject', 'Status', 'Status copy', 'Score']);
+ expect(copied.table.rows[0][3]).toBe('ruled out');
+ expect(copied.meta.widths['Status copy']).toBe(220);
+ expect(copied.meta.roles['Status copy']).toEqual({ kind: 'state' });
+ expect(copied.meta.notes['Status copy']).toBe('where it got to');
+ // The link stays on the cell the case answered about, and is not claimed by a copy.
+ expect(copied.meta.links.r1['Status copy']).toBeUndefined();
+ });
+
+ it('inserts a blank row at an index, keyed', () => {
+ const next = insertRow(table(), 1);
+ expect(next.rows).toHaveLength(4);
+ expect(next.rows[1][0]).toMatch(/^r[0-9a-f]{10}$/);
+ expect(next.rows[1][1]).toBe('');
+ expect(next.rows[2][1]).toBe('Pont nord');
+ });
+
+ it('duplicates rows under themselves, each with a key of its own', () => {
+ const { table: next, keys } = duplicateRows(table(), [0, 2]);
+ expect(next.rows.map((row) => row[1])).toEqual([
+ 'Quai sud', 'Quai sud', 'Pont nord', 'Gare est', 'Gare est',
+ ]);
+ expect(keys).toHaveLength(2);
+ expect(new Set(next.rows.map((row) => row[0])).size).toBe(5);
+ });
+});
+
+describe('sorting a column that knows what it holds', () => {
+ // The most visible thing a role buys, and the reason the roles reach `visibleRows`.
+ const dated = () => ({
+ columns: ['id', 'Date'],
+ rows: [
+ ['r1', '01/02/2026'],
+ ['r2', '31/01/2026'],
+ ['r3', 'AFTER'],
+ ['r4', ''],
+ ],
+ });
+
+ it('reads a European date as a date instead of as text', () => {
+ const asText = visibleRows(dated(), { sort: { column: 'Date', desc: false } });
+ expect(asText.slice(0, 2)).toEqual([0, 1]); // 01/02 before 31/01: wrong, and expected
+
+ const byRole = visibleRows(dated(), {
+ sort: { column: 'Date', desc: false },
+ roles: { Date: { kind: 'when', dayFirst: true } },
+ });
+ expect(byRole.slice(0, 2)).toEqual([1, 0]); // 31 January before 1 February
+ });
+
+ it('keeps the blank at the bottom whichever way the arrow points', () => {
+ const roles = { Date: { kind: 'when', dayFirst: true } };
+ for (const desc of [false, true]) {
+ const shown = visibleRows(dated(), { sort: { column: 'Date', desc }, roles });
+ expect(shown.at(-1)).toBe(3);
+ }
+ });
+
+ it('puts a cell the role cannot read after the ones it can', () => {
+ const shown = visibleRows(dated(), {
+ sort: { column: 'Date', desc: false },
+ roles: { Date: { kind: 'when' } },
+ });
+ expect(shown).toEqual([1, 0, 2, 3]);
+ });
+
+ it('ranks a state column by its vocabulary, not its alphabet', () => {
+ const table = {
+ columns: ['id', 'Status'],
+ rows: [['r1', 'done'], ['r2', 'to do'], ['r3', 'in progress']],
+ };
+ const shown = visibleRows(table, {
+ sort: { column: 'Status', desc: false },
+ roles: { Status: { kind: 'state', values: ['to do', 'in progress', 'done'] } },
+ });
+ expect(shown.map((index) => table.rows[index][1])).toEqual(['to do', 'in progress', 'done']);
+ });
+
+ it('falls back to reading the words where the role says nothing', () => {
+ const table = { columns: ['id', 'Name'], rows: [['r1', 'AB-10'], ['r2', 'AB-2']] };
+ const shown = visibleRows(table, {
+ sort: { column: 'Name', desc: false },
+ roles: { Name: { kind: 'stamped' } },
+ });
+ expect(shown).toEqual([1, 0]);
+ });
+
+ it('sorts as before when no role is declared, so nothing regressed', () => {
+ const shown = visibleRows(table(), { sort: { column: 'Score', desc: false } });
+ expect(shown.map((index) => table().rows[index][3])).toEqual(['9', '10', '100']);
+ });
+});
+
+describe('writing many cells at once', () => {
+ it('fills a column for the rows asked for and leaves the rest', () => {
+ const edits = fillEdits(table(), 2, [0, 2], 'done');
+ const next = setCells(
+ table(),
+ edits.map((edit) => ({ ...edit, value: edit.after })),
+ );
+ expect(next.rows.map((row) => row[2])).toEqual(['done', '', 'done']);
+ });
+
+ it('records what each cell held, so the fill can be walked back', () => {
+ const edits = fillEdits(table(), 2, [0, 1], 'done');
+ expect(edits).toEqual([
+ { row: 0, column: 2, before: 'ruled out', after: 'done' },
+ { row: 1, column: 2, before: '', after: 'done' },
+ ]);
+ });
+
+ it('leaves out the cells that already said it', () => {
+ expect(fillEdits(table(), 2, [0], 'ruled out')).toEqual([]);
+ });
+
+ it('refuses to fill the key column, whatever is asked', () => {
+ expect(fillEdits(table(), 0, [0, 1], 'same')).toEqual([]);
+ });
+
+ it('walks a step backward and forward again', () => {
+ const start = table();
+ const edits = fillEdits(start, 2, [0, 1], 'done');
+ const done = applyEdits(start, edits, 'forward');
+ expect(done.rows.map((row) => row[2])).toEqual(['done', 'done', 'to check']);
+
+ const back = applyEdits(done, edits, 'backward');
+ expect(back.rows.map((row) => row[2])).toEqual(['ruled out', '', 'to check']);
+ });
+
+ it('never mutates the table it was handed', () => {
+ const before = table();
+ setCells(before, [{ row: 0, column: 1, value: 'changed' }]);
+ expect(before.rows[0][1]).toBe('Quai sud');
+ });
+
+ it('ignores a write outside the table', () => {
+ const next = setCells(table(), [{ row: 99, column: 1, value: 'x' }, { row: 0, column: 99, value: 'x' }]);
+ expect(next.rows).toEqual(table().rows);
+ });
+});
+
+describe('moving a column', () => {
+ it('takes its cells with it', () => {
+ const next = moveColumn(table(), 3, 1);
+ expect(next.columns).toEqual(['id', 'Score', 'Subject', 'Status']);
+ expect(next.rows[0]).toEqual(['r1', '10', 'Quai sud', 'ruled out']);
+ });
+
+ it('moves the other way just as well', () => {
+ const next = moveColumn(table(), 1, 3);
+ expect(next.columns).toEqual(['id', 'Status', 'Score', 'Subject']);
+ expect(next.rows[2]).toEqual(['r3', 'to check', '100', 'Gare est']);
+ });
+
+ it('leaves the table alone when the move is not one', () => {
+ expect(moveColumn(table(), 1, 1)).toEqual(table());
+ expect(moveColumn(table(), 9, 0)).toEqual(table());
+ expect(moveColumn(table(), 0, -1)).toEqual(table());
+ });
+
+ it('is recorded in the file, not in the sidecar', () => {
+ // A column order is something the collaborator opening the CSV sees, so it
+ // belongs in the file. Nothing in the sidecar is keyed on position.
+ const next = moveColumn(table(), 3, 1);
+ expect(Object.keys(emptyMeta())).not.toContain('order');
+ expect(next.columns.indexOf('Score')).toBe(1);
+ });
+});
+
+describe('the columns that stay put', () => {
+ it('sticks the key column past the gutter', () => {
+ const drawn = visibleColumns(table().columns, emptyMeta());
+ expect(stickyOffsets(drawn, emptyMeta())).toEqual({ id: GUTTER_WIDTH });
+ });
+
+ it('sticks one chosen column beside it, at the key column width', () => {
+ const meta = setFrozen(emptyMeta(), 'Subject');
+ const drawn = visibleColumns(table().columns, meta);
+ expect(stickyOffsets(drawn, meta)).toEqual({
+ id: GUTTER_WIDTH,
+ Subject: GUTTER_WIDTH + DEFAULT_WIDTH,
+ });
+ });
+
+ it('accumulates the real widths rather than assuming the default', () => {
+ const meta = { ...setFrozen(emptyMeta(), 'Subject'), widths: { id: 80 } };
+ const drawn = visibleColumns(table().columns, meta);
+ expect(stickyOffsets(drawn, meta).Subject).toBe(GUTTER_WIDTH + 80);
+ });
+
+ it('follows the drawn order, so a moved column cannot overlap what it now follows', () => {
+ const moved = moveColumn(table(), 1, 0); // Subject before id
+ const meta = setFrozen(emptyMeta(), 'Subject');
+ const drawn = visibleColumns(moved.columns, meta);
+ expect(stickyOffsets(drawn, meta)).toEqual({
+ Subject: GUTTER_WIDTH,
+ id: GUTTER_WIDTH + DEFAULT_WIDTH,
+ });
+ });
+
+ it('refuses to freeze the key column, which already stays put', () => {
+ expect(setFrozen(emptyMeta(), 'id').frozen).toBeNull();
+ });
+
+ it('unfreezes on being asked again', () => {
+ const frozen = setFrozen(emptyMeta(), 'Subject');
+ expect(setFrozen(frozen, 'Subject').frozen).toBeNull();
+ });
+
+ it('carries the freeze onto a renamed column and loses it with a deleted one', () => {
+ const meta = setFrozen(emptyMeta(), 'Status');
+ expect(renameColumn(table(), meta, 2, 'Verdict').meta.frozen).toBe('Verdict');
+ expect(removeColumn(table(), meta, 2).meta.frozen).toBeNull();
+ });
+
+ it('drops a column hidden out of sight from the sticky set', () => {
+ const meta = { ...setFrozen(emptyMeta(), 'Subject'), hidden: ['Subject'] };
+ const drawn = visibleColumns(table().columns, meta);
+ expect(stickyOffsets(drawn, meta)).toEqual({ id: GUTTER_WIDTH });
+ });
+});
+
+describe('ticking a range of rows', () => {
+ it('gives the keys on screen in the order they are drawn', () => {
+ const sorted = visibleRows(table(), { sort: { column: 'Score', desc: false } });
+ expect(shownKeys(table(), sorted)).toEqual(['r2', 'r1', 'r3']);
+ });
+
+ it('takes everything between two rows, in display order', () => {
+ const sorted = visibleRows(table(), { sort: { column: 'Score', desc: false } });
+ expect(keysBetween(table(), sorted, 'r2', 'r3')).toEqual(['r2', 'r1', 'r3']);
+ });
+
+ it('reads the same whichever end was clicked first', () => {
+ const shown = visibleRows(table(), {});
+ expect(keysBetween(table(), shown, 'r3', 'r1')).toEqual(['r1', 'r2', 'r3']);
+ });
+
+ it('falls back to the row clicked when the other end is no longer shown', () => {
+ const shown = visibleRows(table(), { query: 'gare' });
+ expect(keysBetween(table(), shown, 'r1', 'r3')).toEqual(['r3']);
+ });
+});
+
+describe('links in a cell', () => {
+ it('finds every link, not just the first', () => {
+ expect(urlsIn('source https://a.example/x and archive https://b.example/y')).toEqual([
+ 'https://a.example/x',
+ 'https://b.example/y',
+ ]);
+ });
+
+ it('leaves the punctuation that ended the sentence behind', () => {
+ expect(urlsIn('see https://a.example/x.')).toEqual(['https://a.example/x']);
+ });
+
+ it('finds nothing in a cell that holds no link', () => {
+ expect(urlsIn('AB-123')).toEqual([]);
+ expect(urlsIn(null)).toEqual([]);
+ });
+
+ it('shows a link as its host, because the query string says nothing in a grid', () => {
+ expect(linkLabel('https://www.example.com/')).toBe('example.com');
+ expect(linkLabel('https://t.me/channel/1234?single')).toBe('t.me/…');
+ expect(linkLabel('not a url')).toBe('not a url');
+ });
+});
+
+describe('the scrollbars the grid draws itself', () => {
+ it('draws nothing when everything fits', () => {
+ expect(scrollThumb(500, 500, 0)).toBeNull();
+ expect(scrollThumb(500, 200, 0)).toBeNull();
+ expect(scrollThumb(0, 900, 0)).toBeNull();
+ });
+
+ it('sizes the thumb by how much of the table is on screen', () => {
+ const thumb = scrollThumb(400, 800, 0);
+ expect(thumb.size).toBe(200);
+ expect(thumb.position).toBe(0);
+ });
+
+ it('puts the thumb at the end when the table is scrolled to the end', () => {
+ const thumb = scrollThumb(400, 800, 400);
+ expect(thumb.position).toBe(thumb.travel);
+ });
+
+ it('keeps the thumb grabbable on a very long sheet', () => {
+ const thumb = scrollThumb(400, 600_000, 0);
+ expect(thumb.size).toBe(30);
+ // Travel is the track less the thumb, not the track: using the track here is
+ // what makes a minimum-size thumb run off the end of its own bar.
+ expect(thumb.travel).toBe(370);
+ });
+
+ it('never reports a position outside the bar for an out-of-range offset', () => {
+ expect(scrollThumb(400, 800, -50).position).toBe(0);
+ expect(scrollThumb(400, 800, 9999).position).toBe(scrollThumb(400, 800, 400).travel);
+ });
+
+ it('turns a dragged thumb back into a scroll offset', () => {
+ const thumb = scrollThumb(400, 800, 0);
+ expect(scrollFromThumb(thumb, 0)).toBe(0);
+ expect(scrollFromThumb(thumb, thumb.travel)).toBe(400);
+ expect(scrollFromThumb(thumb, thumb.travel / 2)).toBe(200);
+ });
+
+ it('clamps a drag that runs past either end', () => {
+ const thumb = scrollThumb(400, 800, 0);
+ expect(scrollFromThumb(thumb, -200)).toBe(0);
+ expect(scrollFromThumb(thumb, 9999)).toBe(400);
+ expect(scrollFromThumb(null, 40)).toBe(0);
+ });
+});
+
+describe('the sidecar', () => {
+ it('paints and unpaints a row', () => {
+ const painted = setColour(emptyMeta(), 'r1', 'red');
+ expect(painted.colours).toEqual({ r1: 'red' });
+ expect(setColour(painted, 'r1', null).colours).toEqual({});
+ });
+
+ it('ignores a colour outside the palette', () => {
+ expect(setColour(emptyMeta(), 'r1', 'chartreuse').colours).toEqual({});
+ });
+
+ it('points a cell at an entity and clears it again', () => {
+ const linked = setLink(emptyMeta(), 'r1', 'Subject', 'e_7');
+ expect(linkAt(linked, 'r1', 'Subject')).toBe('e_7');
+ expect(setLink(linked, 'r1', 'Subject', null).links).toEqual({});
+ });
+
+ it('keeps a row other links when one of them goes', () => {
+ let meta = setLink(emptyMeta(), 'r1', 'Subject', 'e_7');
+ meta = setLink(meta, 'r1', 'Status', 'e_8');
+ expect(setLink(meta, 'r1', 'Subject', null).links).toEqual({ r1: { Status: 'e_8' } });
+ });
+
+ it('bounds a column width to something a grid can draw', () => {
+ expect(setWidth(emptyMeta(), 'Subject', 5).widths.Subject).toBe(60);
+ expect(setWidth(emptyMeta(), 'Subject', 5000).widths.Subject).toBe(720);
+ });
+
+ it('toggles a column out of sight and back', () => {
+ const hidden = toggleHidden(emptyMeta(), 'Score');
+ expect(hidden.hidden).toEqual(['Score']);
+ expect(toggleHidden(hidden, 'Score').hidden).toEqual([]);
+ });
+});
+
+// -- the question, written down -----------------------------------------------
+//
+// The sort and the hidden columns were always in the sidecar; the half that decides
+// which rows are on screen lived in the tab and died with it. The runtime holds the
+// chosen values as a Set and the file holds a list — JSON has no set — so these two
+// functions are the boundary and they have to agree.
+
+describe('the question a sheet was left on', () => {
+ it('writes the chosen values out as a list and reads them back as a set', () => {
+ const asked = toggleFilterValue({}, 'Status', 'to do');
+ const stored = serializeFilters(asked);
+ expect(Array.isArray(stored.Status.values)).toBe(true);
+ expect(stored.Status.values).toEqual(['to do']);
+
+ const back = readFilters(stored, ['id', 'Status']);
+ expect(back.Status.values).toBeInstanceOf(Set);
+ expect(isFilterActive(back.Status)).toBe(true);
+ });
+
+ it('does not write down a filter that asks nothing', () => {
+ const off = toggleFilterValue(toggleFilterValue({}, 'Status', 'to do'), 'Status', 'to do');
+ expect(serializeFilters(off)).toEqual({});
+ });
+
+ it('drops a stored filter whose column the file no longer has', () => {
+ const stored = serializeFilters(toggleFilterValue({}, 'Gone', 'anything'));
+ expect(readFilters(stored, ['id', 'Status'])).toEqual({});
+ // With no list of columns to check against, everything stored is taken.
+ expect(Object.keys(readFilters(stored))).toEqual(['Gone']);
+ });
+
+ it('moves what is asked of a column onto its new name, and drops it on a delete', () => {
+ // The rows on screen must not change because a heading was spelled again.
+ const asked = toggleFilterValue({}, 'Status', 'to do');
+ expect(Object.keys(renameFilterColumn(asked, 'Status', 'State'))).toEqual(['State']);
+ expect(renameFilterColumn(asked, 'Status', null)).toEqual({});
+ // A column nothing was asked of leaves the rest alone.
+ expect(renameFilterColumn(asked, 'Subject', 'Name')).toEqual(asked);
+ });
+
+ it('clears every column at once', () => {
+ expect(clearFilters()).toEqual({});
+ });
+});
+
+describe('a rename or a delete, and everything hanging off the column name', () => {
+ const table = {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [['r1', 'Quai sud', 'done']],
+ };
+ const meta = {
+ ...emptyMeta(),
+ widths: { Status: 200 },
+ hidden: ['Status'],
+ roles: { Status: { kind: 'state' } },
+ notes: { Status: 'where this row got to' },
+ filters: { Status: { values: ['done'] } },
+ promoted: { r1: { Status: 'done' } },
+ links: { r1: { Status: 'e_7' } },
+ progress: 'Status',
+ frozen: 'Status',
+ sort: { column: 'Subject', desc: false, then: { column: 'Status', desc: true } },
+ };
+
+ it('takes all of it with the new name', () => {
+ const moved = renameColumn(table, meta, 2, 'State');
+ expect(moved.table.columns).toEqual(['id', 'Subject', 'State']);
+ expect(moved.meta.widths).toEqual({ State: 200 });
+ expect(moved.meta.hidden).toEqual(['State']);
+ expect(moved.meta.roles.State.kind).toBe('state');
+ expect(moved.meta.notes).toEqual({ State: 'where this row got to' });
+ expect(moved.meta.filters).toEqual({ State: { values: ['done'] } });
+ expect(moved.meta.promoted).toEqual({ r1: { State: 'done' } });
+ expect(moved.meta.links).toEqual({ r1: { State: 'e_7' } });
+ expect(moved.meta.progress).toBe('State');
+ expect(moved.meta.frozen).toBe('State');
+ expect(moved.meta.sort.then).toEqual({ column: 'State', desc: true });
+ });
+
+ it('takes all of it away with the column', () => {
+ const gone = removeColumn(table, meta, 2);
+ expect(gone.table.columns).toEqual(['id', 'Subject']);
+ expect(gone.meta.widths).toEqual({});
+ expect(gone.meta.hidden).toEqual([]);
+ expect(gone.meta.roles).toEqual({});
+ expect(gone.meta.notes).toEqual({});
+ expect(gone.meta.filters).toEqual({});
+ expect(gone.meta.promoted).toEqual({});
+ expect(gone.meta.links).toEqual({});
+ expect(gone.meta.progress).toBeNull();
+ expect(gone.meta.frozen).toBeNull();
+ // The first key survives; only the tiebreak it no longer has is dropped.
+ expect(gone.meta.sort).toEqual({ column: 'Subject', desc: false });
+ });
+
+ it('drops the sort itself when the column it sorted on goes', () => {
+ const sorted = { ...emptyMeta(), sort: { column: 'Status', desc: true } };
+ expect(removeColumn(table, sorted, 2).meta.sort).toBeNull();
+ expect(renameColumn(table, sorted, 2, 'State').meta.sort).toEqual({
+ column: 'State',
+ desc: true,
+ });
+ });
+});
+
+describe('a second key, for when the first one ties', () => {
+ it('cycles ascending, descending, off', () => {
+ const sort = { column: 'Status', desc: false };
+ const up = nextSecondSort(sort, 'Subject');
+ expect(up.then).toEqual({ column: 'Subject', desc: false });
+ const down = nextSecondSort(up, 'Subject');
+ expect(down.then).toEqual({ column: 'Subject', desc: true });
+ expect(nextSecondSort(down, 'Subject').then).toBeUndefined();
+ });
+
+ it('refuses to break a column ties with itself, which is a loop', () => {
+ const sort = { column: 'Status', desc: false, then: { column: 'Subject', desc: false } };
+ expect(nextSecondSort(sort, 'Status').then).toBeUndefined();
+ });
+
+ it('is nothing at all without a first key', () => {
+ expect(nextSecondSort(null, 'Subject')).toBeNull();
+ });
+
+ it('orders the rows by the second key inside the first', () => {
+ const table = {
+ columns: ['id', 'Status', 'Subject'],
+ rows: [
+ ['r1', 'done', 'Quai sud'],
+ ['r2', 'to do', 'Aval'],
+ ['r3', 'done', 'Amont'],
+ ['r4', 'to do', 'Zone 5'],
+ ],
+ };
+ const sort = { column: 'Status', desc: false, then: { column: 'Subject', desc: false } };
+ const seen = visibleRows(table, { sort }).map((index) => table.rows[index][0]);
+ expect(seen).toEqual(['r3', 'r1', 'r2', 'r4']);
+ });
+});
+
+describe('folding rows together and pulling one apart', () => {
+ const table = {
+ columns: ['id', 'Subject', 'Notes'],
+ rows: [
+ ['r1', 'Quai sud', ''],
+ ['r2', 'Quai sud, harbour side', 'seen on the 4th'],
+ ['r3', 'Pont nord', ''],
+ ],
+ };
+
+ it('keeps the fullest answer per column, and the first row own key', () => {
+ // The surviving row keeps its key, so its colour, its links and its promotion
+ // record survive with it.
+ const merged = mergeRows(table, [0, 1]);
+ expect(merged.folded).toBe(1);
+ expect(merged.key).toBe('r1');
+ expect(merged.table.rows).toEqual([
+ ['r1', 'Quai sud, harbour side', 'seen on the 4th'],
+ ['r3', 'Pont nord', ''],
+ ]);
+ });
+
+ it('does nothing to one row on its own', () => {
+ expect(mergeRows(table, [1]).table).toBe(table);
+ expect(mergeRows(table, []).folded).toBe(0);
+ });
+
+ it('turns one cell of values into a row each, the rest of the row copied down', () => {
+ const inbox = {
+ columns: ['id', 'Systems', 'Source'],
+ rows: [['r1', 'Buk-M2E, ZU23-2, S-300', 'https://a.org/1']],
+ };
+ const grown = explodeRow(inbox, 0, 1, ',');
+ expect(grown.keys).toHaveLength(2);
+ expect(grown.table.rows.map((row) => row[1])).toEqual(['Buk-M2E', 'ZU23-2', 'S-300']);
+ expect(grown.table.rows.every((row) => row[2] === 'https://a.org/1')).toBe(true);
+ // Every new row is its own row, so nothing hangs on somebody else's key.
+ expect(new Set(grown.table.rows.map((row) => row[0])).size).toBe(3);
+ });
+
+ it('leaves a cell holding one value alone, and never splits the handle', () => {
+ expect(explodeRow(table, 0, 1, ',').keys).toEqual([]);
+ expect(explodeRow(table, 0, 0, ',').table).toBe(table);
+ });
+});
+
+describe('what the grid remembers about how it is drawn', () => {
+ it('answers one of two row heights, because a note cannot live in one line', () => {
+ expect(rowHeight(emptyMeta())).toBe(30);
+ expect(rowHeight(setTall(emptyMeta(), true))).toBe(78);
+ expect(setTall(setTall(emptyMeta(), true), false).tall).toBe(false);
+ });
+
+ it('names a colour, and forgets it when the name is taken away', () => {
+ const named = setLegend(emptyMeta(), 'red', ' ruled out ');
+ expect(named.legend).toEqual({ red: 'ruled out' });
+ expect(setLegend(named, 'red', '').legend).toEqual({});
+ // A colour the palette does not hold is not a colour this sheet paints with.
+ expect(setLegend(emptyMeta(), 'chartreuse', 'invented').legend).toEqual({});
+ });
+
+ it('keeps one row under the heading, and lets it go when it is pinned again', () => {
+ const pinned = setPinned(emptyMeta(), 'r1');
+ expect(pinned.pinned).toBe('r1');
+ expect(setPinned(pinned, 'r1').pinned).toBeNull();
+ expect(setPinned(pinned, 'r2').pinned).toBe('r2');
+ });
+});
+
+
+describe('the bounds the file actually has', () => {
+ const table = (rows, columns = 3) => ({
+ columns: Array.from({ length: columns }, (_, at) => `c${at}`),
+ rows: Array.from({ length: rows }, () => []),
+ });
+
+ it('lets an ordinary sheet grow', () => {
+ expect(tooBigBy(table(10), { rows: 400 })).toBeNull();
+ expect(tooBigBy(table(10), { columns: 6 })).toBeNull();
+ });
+
+ it('says how much room is left rather than only refusing', () => {
+ const said = tooBigBy(table(MAX_ROWS - 12), { rows: 400 });
+ expect(said).toContain('12');
+ });
+
+ it('refuses the column that would not fit', () => {
+ expect(tooBigBy(table(1, MAX_COLUMNS), { columns: 1 })).toContain(String(MAX_COLUMNS));
+ expect(tooBigBy(table(1, MAX_COLUMNS - 1), { columns: 1 })).toBeNull();
+ });
+
+ it('answers for a table that is already over, which is how a pass is checked', () => {
+ // `cleanTable` asks about the table a pass produced, not about a growth it planned.
+ expect(tooBigBy(table(1, MAX_COLUMNS + 2))).not.toBeNull();
+ expect(tooBigBy(table(MAX_ROWS + 1))).toContain('full');
+ });
+});
+
+describe('a sidecar and what the case still holds', () => {
+ const meta = {
+ ...emptyMeta(),
+ links: { r1: { Subject: 'e_gone', Note: 'e_kept' }, r2: { Subject: 'e_gone' } },
+ values: { Unit: { 'Buk-M2E': 'e_gone', 'ZU23-2': 'e_kept' } },
+ attachments: { r1: ['e_file', 'e_gone'] },
+ colours: { r1: 'grey' },
+ };
+
+ it('names every entity the sidecar points at, once each', () => {
+ expect(linkedEntityIds(meta).sort()).toEqual(['e_file', 'e_gone', 'e_kept']);
+ expect(linkedEntityIds(emptyMeta())).toEqual([]);
+ });
+
+ it('drops the pointers at what was deleted, in all three places', () => {
+ const next = withoutEntities(meta, new Set(['e_gone']));
+
+ expect(next.links).toEqual({ r1: { Note: 'e_kept' } });
+ expect(next.values).toEqual({ Unit: { 'ZU23-2': 'e_kept' } });
+ expect(next.attachments).toEqual({ r1: ['e_file'] });
+ });
+
+ it('leaves the reading built around them alone', () => {
+ // a colour is the analyst's, not a pointer at the case
+ expect(withoutEntities(meta, new Set(['e_gone'])).colours).toEqual({ r1: 'grey' });
+ });
+
+ it('hands back the same sidecar when nothing it points at has gone', () => {
+ expect(withoutEntities(meta, new Set(['e_elsewhere']))).toBe(meta);
+ expect(withoutEntities(meta, new Set())).toBe(meta);
+ });
+});
+
+describe('lining two sheets up before a row is moved', () => {
+ it('takes an identical name as the answer, and says nothing about it', () => {
+ expect(suggestMapping(['Subject', 'Status'], ['id', 'Subject', 'Status'])).toEqual([
+ { name: 'Subject', to: 'Subject', guessed: false },
+ { name: 'Status', to: 'Status', guessed: false },
+ ]);
+ });
+
+ it('proposes a name that differs only in how it is written, and calls it a guess', () => {
+ // Case, accents and the space against the underscore: the same column, twice.
+ expect(suggestMapping(['Local time', 'Vérifié'], ['id', 'local_time', 'verifie'])).toEqual([
+ { name: 'Local time', to: 'local_time', guessed: true },
+ { name: 'Vérifié', to: 'verifie', guessed: true },
+ ]);
+ });
+
+ it('leaves a column the other sheet has nothing for pointed at nothing', () => {
+ expect(suggestMapping(['Scratch'], ['id', 'Subject'])).toEqual([
+ { name: 'Scratch', to: '', guessed: false },
+ ]);
+ });
+
+ it('spends a target once, and the exact spelling has first claim on it', () => {
+ const pairs = suggestMapping(['adresse', 'Adresse'], ['id', 'Adresse']);
+
+ expect(pairs).toEqual([
+ { name: 'adresse', to: '', guessed: false },
+ { name: 'Adresse', to: 'Adresse', guessed: false },
+ ]);
+ });
+
+ it('leaves the key column out of it, on both sides', () => {
+ const pairs = suggestMapping(['id', 'Subject'], ['id', 'Subject']);
+
+ expect(pairs).toEqual([{ name: 'Subject', to: 'Subject', guessed: false }]);
+ });
+});
diff --git a/frontend/src/lib/sheetAppend.js b/frontend/src/lib/sheetAppend.js
new file mode 100644
index 0000000..cfb3e57
--- /dev/null
+++ b/frontend/src/lib/sheetAppend.js
@@ -0,0 +1,92 @@
+/**
+ * Adding a batch of rows to the sheet that is already open.
+ *
+ * Import filed a **new sheet**, always. That is right the first time and wrong every time
+ * after it: the daily batch of links, the second export from the same tool, the forty rows
+ * a colleague sent — all of them belong in the worklist that already carries the statuses,
+ * the roles and the colours. The only ways out were to paste into a selection, which needs
+ * the columns to already line up, or to keep twelve sheets nobody compares.
+ *
+ * So an incoming table is **mapped** onto this sheet's columns and appended. The mapping is
+ * proposed by name and then the analyst's; a column left unmapped is dropped, and it says
+ * how many. Nothing here parses CSV — `POST /sheets/parse` does, because there is one CSV
+ * parser in this app and it is in Python.
+ *
+ * Pure: tables in, a table out. The append is an ordinary structural edit, so it undoes
+ * like anything else and the ordinary save writes it.
+ */
+
+import { ID_COLUMN, keyIndex, newKey } from './sheet.js';
+
+function fold(name) {
+ return String(name ?? '').trim().toLowerCase();
+}
+
+/**
+ * A first mapping of incoming columns onto the ones this sheet has.
+ *
+ * Exact name first, then the same name in another casing — `Source` and `source` are the
+ * same column in every export anybody actually sends. Nothing is guessed beyond that: a
+ * `Place` mapped onto `City` because both look geographic is a silent mistake in a column
+ * of evidence.
+ *
+ * The key column is never a target: rows arriving from elsewhere are keyed here, and
+ * writing somebody else's identifier into it would hang this sheet's colours on a stranger.
+ */
+export function guessMapping(incoming, columns) {
+ const byFold = new Map(
+ (columns ?? [])
+ .filter((name) => fold(name) !== ID_COLUMN)
+ .map((name) => [fold(name), name]),
+ );
+ const mapping = {};
+ for (const name of incoming ?? []) {
+ if (fold(name) === ID_COLUMN) continue;
+ mapping[name] = byFold.get(fold(name)) ?? '';
+ }
+ return mapping;
+}
+
+/** How much of the incoming table the mapping actually carries. What the dialog says
+ * before the press, because "40 rows added" over silently dropped columns is the kind of
+ * import an analyst finds out about a week later. */
+export function mappingSummary(incoming, mapping) {
+ const taken = (incoming ?? []).filter((name) => mapping?.[name]);
+ return {
+ taken: taken.length,
+ dropped: (incoming ?? []).filter((name) => fold(name) !== ID_COLUMN && !mapping?.[name]),
+ };
+}
+
+/**
+ * The sheet with the incoming rows appended, each keyed anew.
+ *
+ * A row that arrives blank in every mapped column is left out: an export's trailing empty
+ * line should not become a row somebody has to notice and delete.
+ */
+export function appendRows(table, incoming, mapping) {
+ const columns = table?.columns ?? [];
+ const at = keyIndex(columns);
+ // Where each incoming column lands, resolved once: an import of four hundred rows must
+ // not look its columns up four hundred times.
+ const lands = (incoming?.columns ?? [])
+ .map((name, from) => ({ from, to: columns.indexOf(mapping?.[name] ?? '') }))
+ .filter((pair) => pair.to !== -1 && pair.to !== at);
+ if (!lands.length) return { table, added: 0 };
+
+ const made = [];
+ for (const row of incoming?.rows ?? []) {
+ const cells = columns.map(() => '');
+ let anything = false;
+ for (const pair of lands) {
+ const value = String(row?.[pair.from] ?? '');
+ cells[pair.to] = value;
+ if (value.trim()) anything = true;
+ }
+ if (!anything) continue;
+ cells[at] = newKey();
+ made.push(cells);
+ }
+ if (!made.length) return { table, added: 0 };
+ return { table: { ...table, rows: [...(table.rows ?? []), ...made] }, added: made.length };
+}
diff --git a/frontend/src/lib/sheetAppend.test.js b/frontend/src/lib/sheetAppend.test.js
new file mode 100644
index 0000000..f6cdfa8
--- /dev/null
+++ b/frontend/src/lib/sheetAppend.test.js
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { appendRows, guessMapping, mappingSummary } from './sheetAppend.js';
+
+const SHEET = {
+ columns: ['id', 'Subject', 'Status', 'Source'],
+ rows: [['r1', 'Quai sud', 'done', 'https://a.org/1']],
+};
+
+describe('proposing where the incoming columns land', () => {
+ it('matches on the name, and on the same name in another casing', () => {
+ // `Source` and `source` are the same column in every export anybody actually sends.
+ const mapping = guessMapping(['Subject', 'source', 'Comment'], SHEET.columns);
+ expect(mapping).toEqual({ Subject: 'Subject', source: 'Source', Comment: '' });
+ });
+
+ it('guesses nothing beyond the name', () => {
+ // A `Place` landing in `City` because both look geographic is a silent mistake in a
+ // column of evidence.
+ expect(guessMapping(['Place'], ['id', 'City'])).toEqual({ Place: '' });
+ });
+
+ it('never offers the row handle, in either direction', () => {
+ // Rows arriving from elsewhere are keyed here; writing somebody else's identifier in
+ // would hang this sheet's colours on a stranger.
+ expect(guessMapping(['id', 'Subject'], SHEET.columns)).toEqual({ Subject: 'Subject' });
+ expect(guessMapping(['Subject'], ['id', 'Subject'])).toEqual({ Subject: 'Subject' });
+ });
+
+ it('says what would be dropped, before the press', () => {
+ const mapping = guessMapping(['id', 'Subject', 'Comment', 'Rank'], SHEET.columns);
+ expect(mappingSummary(['id', 'Subject', 'Comment', 'Rank'], mapping)).toEqual({
+ taken: 1,
+ dropped: ['Comment', 'Rank'],
+ });
+ });
+});
+
+describe('the rows appended', () => {
+ const incoming = {
+ columns: ['Subject', 'Source'],
+ rows: [
+ ['Pont nord', 'https://a.org/2'],
+ ['Zone 5', 'https://a.org/3'],
+ ],
+ };
+
+ it('lands each row in the columns it was mapped to, keyed anew', () => {
+ const grown = appendRows(SHEET, incoming, { Subject: 'Subject', Source: 'Source' });
+ expect(grown.added).toBe(2);
+ expect(grown.table.rows).toHaveLength(3);
+ expect(grown.table.rows[1].slice(1)).toEqual(['Pont nord', '', 'https://a.org/2']);
+ expect(grown.table.rows[1][0]).toMatch(/^r[0-9a-f]{10}$/);
+ expect(new Set(grown.table.rows.map((row) => row[0])).size).toBe(3);
+ // The sheet it was given is untouched, because an append is one undoable step.
+ expect(SHEET.rows).toHaveLength(1);
+ });
+
+ it('writes only the columns the mapping names', () => {
+ const grown = appendRows(SHEET, incoming, { Subject: 'Status' });
+ expect(grown.table.rows[1].slice(1)).toEqual(['', 'Pont nord', '']);
+ });
+
+ it('leaves out a row that arrives blank in every mapped column', () => {
+ // An export's trailing empty line should not become a row somebody has to delete.
+ const trailing = { columns: ['Subject'], rows: [['Pont nord'], [' '], ['']] };
+ expect(appendRows(SHEET, trailing, { Subject: 'Subject' }).added).toBe(1);
+ });
+
+ it('adds nothing when the mapping carries no column of this sheet', () => {
+ const grown = appendRows(SHEET, incoming, { Subject: '', Source: '' });
+ expect(grown.added).toBe(0);
+ expect(grown.table).toBe(SHEET);
+ });
+
+ it('refuses to write into the row handle even when told to', () => {
+ expect(appendRows(SHEET, incoming, { Subject: 'id' }).added).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/sheetBuild.js b/frontend/src/lib/sheetBuild.js
new file mode 100644
index 0000000..909b3d2
--- /dev/null
+++ b/frontend/src/lib/sheetBuild.js
@@ -0,0 +1,81 @@
+/**
+ * Reading a sheet as a geolocation index, and proposing which column is which.
+ *
+ * The build is the one road out of a sheet that fetches bytes, so it is offered on a
+ * sheet that can actually feed it and hidden everywhere else: **two columns of addresses
+ * and one of coordinates**. That is what a geolocation index is — what was filmed, what
+ * was published about it, and where it turns out to be.
+ *
+ * What a column holds is read the same way the pass reads it: the declared role wins, and
+ * a sheet imported five minutes ago has none, so the cells are read instead. A column of
+ * links is decided here rather than by `detectRole`, which deliberately never answers
+ * `url` — it suggests roles for display, and a column of sources turned into a wall of
+ * thumbnails would fetch pages nobody asked for.
+ */
+import { ID_COLUMN } from './sheet.js';
+import { detectRole } from './sheetRoles.js';
+
+/** The same two thirds `detectRole` reads a column on: a binder's column is half-finished
+ * by definition, and one blank in three does not change what it holds. */
+const ENOUGH = 0.66;
+
+export function columnKinds(table, meta) {
+ const columns = (table?.columns ?? []).filter(
+ (name) => String(name).toLowerCase() !== ID_COLUMN,
+ );
+ const found = {};
+ for (const name of columns) {
+ const declared = meta?.roles?.[name]?.kind ?? '';
+ if (declared) {
+ found[name] = declared;
+ continue;
+ }
+ const at = (table?.columns ?? []).indexOf(name);
+ const cells = (table?.rows ?? [])
+ .map((row) => String(row[at] ?? '').trim())
+ .filter(Boolean);
+ const share = cells.length
+ ? cells.filter((cell) => /^https?:\/\//i.test(cell)).length / cells.length
+ : 0;
+ found[name] = share >= ENOUGH ? 'url' : (detectRole(cells) ?? '');
+ }
+ return found;
+}
+
+/** Whether this sheet can feed a build at all. Two addresses and a point: one address is
+ * a media library import, and no point is not a geolocation. */
+export function canBuild(kinds) {
+ const held = Object.values(kinds ?? {});
+ return held.filter((kind) => kind === 'url').length >= 2 && held.includes('latlon');
+}
+
+/** Which column is which, proposed rather than decided: every one of these is a select the
+ * analyst can change, and a sheet whose columns are named anything at all still opens
+ * filled in.
+ *
+ * The two addresses are told apart by their names when they say so — a column called
+ * *Geolocation proof* is the published picture — and by their order when they do not,
+ * because a binder writes the footage before what was made of it. */
+export function proposal(table, meta) {
+ const kinds = columnKinds(table, meta);
+ const columns = Object.keys(kinds);
+ const named = (test) => columns.find((name) => test.test(name)) ?? '';
+ const urls = columns.filter((name) => kinds[name] === 'url');
+ const published =
+ urls.find((name) => /proof|geoloc|published|picture|image/i.test(name)) ?? urls[1] ?? '';
+ const source = urls.find((name) => name !== published) ?? '';
+ return {
+ title: named(/^title$/i) || named(/title|subject|name|event/i) || firstPlain(columns, kinds),
+ source,
+ proof: published,
+ point: columns.find((name) => kinds[name] === 'latlon') ?? '',
+ note: named(/^notes?$/i) || named(/note|comment|remark/i),
+ status: columns.find((name) => kinds[name] === 'state') ?? '',
+ };
+}
+
+/** The first column carrying nothing the app already reads, which is where a name lives
+ * when nobody called it one. */
+function firstPlain(columns, kinds) {
+ return columns.find((name) => !kinds[name]) ?? '';
+}
diff --git a/frontend/src/lib/sheetBuild.test.js b/frontend/src/lib/sheetBuild.test.js
new file mode 100644
index 0000000..0d9da5e
--- /dev/null
+++ b/frontend/src/lib/sheetBuild.test.js
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import { canBuild, columnKinds, proposal } from './sheetBuild.js';
+
+const TEMPLATE = {
+ columns: ['_key', 'Title', 'Source media', 'Geolocation proof', 'Coordinates', 'Status', 'Notes'],
+ rows: [],
+};
+const ROLES = {
+ roles: {
+ 'Source media': { kind: 'url' },
+ 'Geolocation proof': { kind: 'url' },
+ Coordinates: { kind: 'latlon' },
+ Status: { kind: 'state' },
+ },
+};
+
+describe('a sheet read as a geolocation index', () => {
+ it('takes the declared role over anything the cells look like', () => {
+ const kinds = columnKinds(TEMPLATE, ROLES);
+ expect(kinds['Source media']).toBe('url');
+ expect(kinds.Coordinates).toBe('latlon');
+ expect(kinds.Title).toBe('');
+ });
+
+ it('reads a sheet nobody has declared roles on yet', () => {
+ const table = {
+ columns: ['_key', 'What', 'Clip', 'Picture', 'Where'],
+ rows: [
+ ['r1', 'Bridge', 'https://ex.org/a', 'https://ex.org/b', '48.85, 2.35'],
+ ['r2', 'Depot', 'https://ex.org/c', 'https://ex.org/d', '50.45, 30.52'],
+ ],
+ };
+ const kinds = columnKinds(table, {});
+ expect(kinds.Clip).toBe('url');
+ expect(kinds.Picture).toBe('url');
+ expect(kinds.Where).toBe('latlon');
+ expect(canBuild(kinds)).toBe(true);
+ });
+
+ // The button is the whole of the offer: a sheet that cannot feed a build must not show
+ // one, or the analyst presses it to be told what they should have been shown.
+ it('is not buildable with one address, or with no point', () => {
+ expect(canBuild({ A: 'url', B: 'latlon' })).toBe(false);
+ expect(canBuild({ A: 'url', B: 'url' })).toBe(false);
+ expect(canBuild({})).toBe(false);
+ });
+
+ it('proposes the template s own columns without being told', () => {
+ expect(proposal(TEMPLATE, ROLES)).toEqual({
+ title: 'Title',
+ source: 'Source media',
+ proof: 'Geolocation proof',
+ point: 'Coordinates',
+ note: 'Notes',
+ status: 'Status',
+ });
+ });
+
+ it('tells the two addresses apart by order when their names do not say', () => {
+ const table = { columns: ['_key', 'Event', 'First link', 'Second link', 'Point'], rows: [] };
+ const meta = {
+ roles: {
+ 'First link': { kind: 'url' },
+ 'Second link': { kind: 'url' },
+ Point: { kind: 'latlon' },
+ },
+ };
+ const picked = proposal(table, meta);
+ expect(picked.source).toBe('First link');
+ expect(picked.proof).toBe('Second link');
+ expect(picked.title).toBe('Event');
+ });
+});
diff --git a/frontend/src/lib/sheetClean.js b/frontend/src/lib/sheetClean.js
new file mode 100644
index 0000000..c83f7b4
--- /dev/null
+++ b/frontend/src/lib/sheetClean.js
@@ -0,0 +1,280 @@
+/**
+ * The rewrites a sheet needs because its rows came from somewhere else.
+ *
+ * A binder that arrives by import is never in the shape the work wants: the city and the
+ * country are in one cell, the coordinates are pasted with the label still attached, half
+ * the names carry a trailing space that makes two values out of one, and the word the
+ * analyst has decided to stop using is in four hundred cells. None of that is a filter,
+ * a role or an edit — it is a **pass over the column**, and doing it by hand is how an
+ * afternoon disappears.
+ *
+ * Six passes, and they are all the same shape underneath: given a table and which cells
+ * to touch, hand back either a list of cell edits or a whole table. Which of the two says
+ * everything about the pass — replacing a word changes cells, splitting a column changes
+ * the table — and it is also what decides how the undo stack records it, so the caller
+ * never has to guess.
+ *
+ * Nothing here reads a role and nothing here writes the file. A pass is the analyst
+ * asking for an edit by name, which is the one thing that separates it from a lens: a
+ * role never improves the file, and every one of these does.
+ */
+
+import { freeColumnName, insertColumn, keyIndex, linkLabel, removeColumn, urlsIn } from './sheet.js';
+
+/** How many columns one split may produce. A cell that breaks into more parts than this
+ * is prose with punctuation in it, not a record with fields. */
+export const MAX_PARTS = 8;
+
+/**
+ * One cell cut on a separator, into at most `MAX_PARTS` pieces.
+ *
+ * The last piece keeps whatever is left, separators and all, the way every maxsplit in
+ * every language does it. Dropping the tail instead is what a split of a twelve-segment
+ * cell used to do: four segments went nowhere, and with "keep this column too" unticked the
+ * original was deleted after them, so the words were gone from the file with nothing said.
+ * Nothing is lost now, and the preview's samples show the fat last cell.
+ */
+function pieces(cell, cut) {
+ const parts = String(cell ?? '').split(cut);
+ const held =
+ parts.length <= MAX_PARTS
+ ? parts
+ : [...parts.slice(0, MAX_PARTS - 1), parts.slice(MAX_PARTS - 1).join(cut)];
+ return held.map((piece) => piece.trim());
+}
+
+/** The ways a column's words can be recased. `title` is the one an imported binder wants
+ * most: a column of SHOUTED place names is unreadable beside the analyst's own. */
+export const CASINGS = ['upper', 'lower', 'title'];
+
+/** The cells a pass may write: everything but the row's handle, which is the case's. */
+function writableColumns(table, columns) {
+ const key = keyIndex(table.columns);
+ return [...new Set(columns ?? [])].filter(
+ (index) => index !== key && index >= 0 && index < table.columns.length,
+ );
+}
+
+/** One edit per cell that actually changes, which is what keeps an undo step honest:
+ * a pass over four hundred rows that rewrote two of them undoes those two. */
+function edits(table, columns, rows, rewrite) {
+ const made = [];
+ for (const column of writableColumns(table, columns)) {
+ for (const row of rows ?? []) {
+ const before = table.rows[row]?.[column];
+ if (before === undefined) continue;
+ const after = rewrite(String(before), row, column);
+ if (after !== undefined && after !== before) made.push({ row, column, before, after });
+ }
+ }
+ return made;
+}
+
+/**
+ * Find a word and write another in its place.
+ *
+ * Plain text rather than a pattern, deliberately: a regular expression in a box with no
+ * preview is how a sheet loses a column, and the analyst reaching for one is reaching past
+ * what this is for — `OK en cours` becoming `in progress` on the four hundred rows an
+ * import arrived with.
+ *
+ * `wholeCell` is the difference between renaming a value and rewriting a substring:
+ * `done` inside `undone` is not the value `done`, and a status column has to be able to
+ * say so.
+ */
+export function replaceEdits(table, { columns, rows, find, replace = '', matchCase = false, wholeCell = false }) {
+ const needle = String(find ?? '');
+ if (!needle) return [];
+ const written = String(replace ?? '');
+ const compare = matchCase ? (text) => text : (text) => text.toLowerCase();
+ const wanted = compare(needle);
+ return edits(table, columns, rows, (before) => {
+ if (wholeCell) return compare(before.trim()) === wanted ? written : before;
+ const body = compare(before);
+ if (!body.includes(wanted)) return before;
+ let out = '';
+ let at = 0;
+ for (;;) {
+ const found = body.indexOf(wanted, at);
+ if (found === -1) break;
+ out += before.slice(at, found) + written;
+ at = found + needle.length;
+ }
+ return out + before.slice(at);
+ });
+}
+
+/**
+ * Take the spacing out.
+ *
+ * The pass that fixes the bug nobody sees: `Kherson ` and `Kherson` are two values in
+ * every menu, two chips in every cell and two rows in every count, and the difference is
+ * a character the grid cannot draw. Line breaks inside a cell survive — a note column is
+ * why a cell may hold sentences.
+ */
+export function tidyEdits(table, columns, rows) {
+ return edits(table, columns, rows, (before) =>
+ before
+ .split('\n')
+ .map((line) => line.replace(/[^\S\n]+/g, ' ').trim())
+ .join('\n')
+ .trim(),
+ );
+}
+
+/** A word with its first letter up and the rest down, applied per word. Hyphens and
+ * apostrophes start a word too, so `saint-jean` and `o'brien` come back right. */
+function titleCase(text) {
+ return text
+ .toLowerCase()
+ .replace(/(^|[\s\-–—'’(/.])(\p{L})/gu, (whole, lead, letter) => lead + letter.toUpperCase());
+}
+
+export function caseEdits(table, columns, rows, casing) {
+ if (!CASINGS.includes(casing)) return [];
+ return edits(table, columns, rows, (before) => {
+ if (casing === 'upper') return before.toUpperCase();
+ if (casing === 'lower') return before.toLowerCase();
+ return titleCase(before);
+ });
+}
+
+/**
+ * What a split would produce, without producing it.
+ *
+ * Read before it is done, because a separator chosen wrong is a column turned into
+ * confetti: the preview says how many parts the widest cell breaks into and shows the
+ * first few, which is the difference between `Kherson, Ukraine` splitting on `,` and a
+ * column of prose doing the same.
+ *
+ * `over` is how many cells hold more than `MAX_PARTS` segments, so the screen can say that
+ * their tail lands in the last column instead of in one of its own.
+ */
+export function splitPreview(table, index, separator) {
+ const cut = String(separator ?? '');
+ if (!cut) return { parts: 0, rows: 0, samples: [], over: 0 };
+ let parts = 0;
+ let touched = 0;
+ let over = 0;
+ const samples = [];
+ for (const row of table.rows ?? []) {
+ const cell = String(row[index] ?? '');
+ if (!cell.trim()) continue;
+ const held = pieces(cell, cut);
+ if (held.length > 1) {
+ touched += 1;
+ parts = Math.max(parts, held.length);
+ if (cell.split(cut).length > MAX_PARTS) over += 1;
+ if (samples.length < 3) samples.push(held);
+ }
+ }
+ return { parts, rows: touched, samples, over };
+}
+
+/**
+ * One column broken into several on a separator.
+ *
+ * The original is kept unless the analyst says otherwise, and that default is the whole
+ * safety of the pass: the file is the artifact, a split is a guess about how it was
+ * written, and a guess that deletes what it was reading is not one the analyst can check
+ * afterwards.
+ */
+export function splitTable(table, meta, index, { separator, keep = true } = {}) {
+ const name = table.columns[index];
+ const cut = String(separator ?? '');
+ if (name === undefined || !cut) return { table, meta, names: [] };
+ const { parts } = splitPreview(table, index, cut);
+ if (parts < 2) return { table, meta, names: [] };
+
+ const cells = (table.rows ?? []).map((row) => pieces(row[index], cut));
+ let grown = table;
+ const names = [];
+ for (let part = 0; part < parts; part += 1) {
+ const at = index + 1 + part;
+ grown = insertColumn(
+ grown,
+ at,
+ `${name} ${part + 1}`,
+ cells.map((row) => row[part] ?? ''),
+ );
+ names.push(grown.columns[at]);
+ }
+ if (keep) return { table: grown, meta, names };
+ // Dropping the original is a delete like any other, so it goes through the grid's own
+ // one: it moves the sidecar with it, and a second implementation here is a second
+ // answer to what a deleted column takes with it.
+ const dropped = removeColumn(grown, meta, index);
+ return { table: dropped.table, meta: dropped.meta, names };
+}
+
+/**
+ * Several columns written into one.
+ *
+ * The other half of the import chore: a file that arrives with `Street`, `Number` and
+ * `City` in three columns is one address the analyst has to read three cells to know. The
+ * empties are left out rather than joined, so `Kherson` does not come back as `, Kherson,`
+ * because two of the three cells were blank.
+ */
+export function mergeTable(table, meta, indices, { joiner = ' ', name = '', keep = true } = {}) {
+ const wanted = [...new Set(indices ?? [])]
+ .filter((index) => table.columns[index] !== undefined)
+ .sort((a, b) => a - b);
+ if (wanted.length < 2) return { table, meta, name: null };
+ const heading = String(name ?? '').trim() || wanted.map((index) => table.columns[index]).join(' + ');
+ const at = wanted[wanted.length - 1] + 1;
+ const values = table.rows.map((row) =>
+ wanted
+ .map((index) => String(row[index] ?? '').trim())
+ .filter(Boolean)
+ .join(String(joiner ?? '')),
+ );
+ let grown = insertColumn(table, at, heading, values);
+ const made = grown.columns[at];
+ let next = meta;
+ if (!keep) {
+ // Right to left, so an index still points at the column it named after the one
+ // before it has gone.
+ for (const index of [...wanted].reverse()) {
+ const dropped = removeColumn(grown, next, index);
+ grown = dropped.table;
+ next = dropped.meta;
+ }
+ }
+ return { table: grown, meta: next, name: made };
+}
+
+/**
+ * The links a column holds, lifted into a column of their own.
+ *
+ * A source column in a real binder is a sentence with a URL in it, sometimes three. What
+ * an analyst wants out of it is either the addresses — to promote them into bookmarks —
+ * or just the hosts, which is a reading of the case: eleven rows sourced to one Telegram
+ * channel is a finding, and it is invisible while the hosts are buried in prose.
+ */
+export function extractTable(table, meta, index, { what = 'url', name = '', separator = ', ' } = {}) {
+ const from = table.columns[index];
+ if (from === undefined) return { table, meta, name: null, filled: 0 };
+ const heading = String(name ?? '').trim() || `${from} ${what === 'host' ? 'hosts' : 'links'}`;
+ let filled = 0;
+ const values = table.rows.map((row) => {
+ const found = urlsIn(row[index]);
+ if (!found.length) return '';
+ const written = what === 'host' ? [...new Set(found.map((url) => host(url)))] : found;
+ filled += 1;
+ return written.join(separator);
+ });
+ if (!filled) return { table, meta, name: null, filled: 0 };
+ const at = index + 1;
+ const grown = insertColumn(table, at, freeColumnName(table.columns, heading), values);
+ return { table: grown, meta, name: grown.columns[at], filled };
+}
+
+/** A URL's host, without the `www.` — `linkLabel` says the same thing but adds a mark
+ * when the path carries more, and a cell of hosts is a value to be counted. */
+function host(url) {
+ try {
+ return new URL(url).hostname.replace(/^www\./, '');
+ } catch {
+ return linkLabel(url);
+ }
+}
diff --git a/frontend/src/lib/sheetClean.test.js b/frontend/src/lib/sheetClean.test.js
new file mode 100644
index 0000000..24c9ef9
--- /dev/null
+++ b/frontend/src/lib/sheetClean.test.js
@@ -0,0 +1,196 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAX_PARTS,
+ caseEdits,
+ extractTable,
+ mergeTable,
+ replaceEdits,
+ splitPreview,
+ splitTable,
+ tidyEdits,
+} from './sheetClean.js';
+import { emptyMeta } from './sheet.js';
+
+const table = () => ({
+ columns: ['id', 'Place', 'Status', 'Source'],
+ rows: [
+ ['r1', 'Kherson, Ukraine', 'OK en cours', 'seen at https://t.me/chan/12 today'],
+ ['r2', ' Mykolaiv , Ukraine ', 'done', 'no source'],
+ ['r3', 'Odesa', 'OK en cours', 'https://example.org/a and https://t.me/chan/13'],
+ ],
+});
+
+const everyRow = [0, 1, 2];
+
+describe('replacing a word', () => {
+ it('rewrites only the cells that change', () => {
+ const edits = replaceEdits(table(), {
+ columns: [2],
+ rows: everyRow,
+ find: 'OK en cours',
+ replace: 'in progress',
+ });
+ expect(edits.map((edit) => edit.row)).toEqual([0, 2]);
+ expect(edits[0].after).toBe('in progress');
+ });
+
+ it('replaces every occurrence in a cell, not just the first', () => {
+ const one = { columns: ['id', 'Note'], rows: [['r1', 'a-a-a']] };
+ expect(replaceEdits(one, { columns: [1], rows: [0], find: 'a', replace: 'b' })[0].after)
+ .toBe('b-b-b');
+ });
+
+ it('is case-insensitive unless told otherwise', () => {
+ const one = { columns: ['id', 'Note'], rows: [['r1', 'Done']] };
+ expect(replaceEdits(one, { columns: [1], rows: [0], find: 'done', replace: 'x' })[0].after)
+ .toBe('x');
+ expect(replaceEdits(one, { columns: [1], rows: [0], find: 'done', replace: 'x', matchCase: true }))
+ .toEqual([]);
+ });
+
+ it('tells a value from a substring when the whole cell is asked for', () => {
+ const one = { columns: ['id', 'Note'], rows: [['r1', 'undone'], ['r2', 'done']] };
+ const edits = replaceEdits(one, {
+ columns: [1], rows: [0, 1], find: 'done', replace: 'ruled out', wholeCell: true,
+ });
+ expect(edits.map((edit) => edit.row)).toEqual([1]);
+ });
+
+ it('never writes the row handle, whatever it is asked', () => {
+ expect(replaceEdits(table(), { columns: [0], rows: everyRow, find: 'r', replace: 'x' }))
+ .toEqual([]);
+ });
+
+ it('finds nothing to do when nothing is asked for', () => {
+ expect(replaceEdits(table(), { columns: [2], rows: everyRow, find: '' })).toEqual([]);
+ });
+});
+
+describe('taking the spacing out', () => {
+ it('trims the ends and collapses what is inside', () => {
+ const edits = tidyEdits(table(), [1], everyRow);
+ expect(edits).toHaveLength(1);
+ expect(edits[0].after).toBe('Mykolaiv , Ukraine');
+ });
+
+ it('keeps the line breaks a note column holds', () => {
+ const one = { columns: ['id', 'Note'], rows: [['r1', ' two\n lines ']] };
+ expect(tidyEdits(one, [1], [0])[0].after).toBe('two\nlines');
+ });
+});
+
+describe('recasing a column', () => {
+ it('upper, lower and one that reads like a name', () => {
+ const one = { columns: ['id', 'Place'], rows: [['r1', 'saint-jean de LUZ']] };
+ expect(caseEdits(one, [1], [0], 'upper')[0].after).toBe('SAINT-JEAN DE LUZ');
+ expect(caseEdits(one, [1], [0], 'lower')[0].after).toBe('saint-jean de luz');
+ expect(caseEdits(one, [1], [0], 'title')[0].after).toBe('Saint-Jean De Luz');
+ });
+
+ it('refuses a casing it does not know rather than guessing one', () => {
+ expect(caseEdits(table(), [1], everyRow, 'sentence')).toEqual([]);
+ });
+});
+
+describe('splitting a column', () => {
+ it('says what it would do before doing it', () => {
+ const read = splitPreview(table(), 1, ',');
+ expect(read.parts).toBe(2);
+ expect(read.rows).toBe(2);
+ expect(read.samples[0]).toEqual(['Kherson', 'Ukraine']);
+ });
+
+ it('makes one column per part, beside the original, and keeps it', () => {
+ const { table: next, names } = splitTable(table(), emptyMeta(), 1, { separator: ',' });
+ expect(names).toEqual(['Place 1', 'Place 2']);
+ expect(next.columns).toEqual(['id', 'Place', 'Place 1', 'Place 2', 'Status', 'Source']);
+ expect(next.rows[0].slice(1, 4)).toEqual(['Kherson, Ukraine', 'Kherson', 'Ukraine']);
+ expect(next.rows[2].slice(2, 4)).toEqual(['Odesa', '']);
+ });
+
+ it('drops the original on request, and what the sidecar knew about it', () => {
+ const meta = { ...emptyMeta(), widths: { Place: 200 }, frozen: 'Place' };
+ const { table: next, meta: moved } = splitTable(table(), meta, 1, {
+ separator: ',', keep: false,
+ });
+ expect(next.columns).toEqual(['id', 'Place 1', 'Place 2', 'Status', 'Source']);
+ expect(moved.widths.Place).toBeUndefined();
+ expect(moved.frozen).toBeNull();
+ });
+
+ it('does nothing where the separator is nowhere in the column', () => {
+ const { table: next, names } = splitTable(table(), emptyMeta(), 1, { separator: '|' });
+ expect(names).toEqual([]);
+ expect(next.columns).toHaveLength(4);
+ });
+
+ it('keeps the tail of a cell that breaks into more parts than there are columns', () => {
+ // Twelve segments used to become eight columns and four segments written nowhere — and
+ // with the original dropped after them, the words were gone from the file. The last
+ // column keeps the rest, the way every maxsplit does.
+ const wide = {
+ columns: ['id', 'Prose'],
+ rows: [['r1', 'a,b,c,d,e,f,g,h,i,j,k,l']],
+ };
+ const read = splitPreview(wide, 1, ',');
+ expect(read.parts).toBe(MAX_PARTS);
+ expect(read.over).toBe(1);
+ expect(read.samples[0].at(-1)).toBe('h,i,j,k,l');
+
+ const { table: next } = splitTable(wide, emptyMeta(), 1, { separator: ',', keep: false });
+ expect(next.columns).toEqual([
+ 'id', 'Prose 1', 'Prose 2', 'Prose 3', 'Prose 4', 'Prose 5', 'Prose 6', 'Prose 7', 'Prose 8',
+ ]);
+ // Nothing dropped: every segment is still readable in the row.
+ expect(next.rows[0].slice(1).join(',')).toBe('a,b,c,d,e,f,g,h,i,j,k,l');
+ });
+
+ it('says nothing about a tail when every cell fits', () => {
+ expect(splitPreview(table(), 1, ',').over).toBe(0);
+ });
+});
+
+describe('merging columns', () => {
+ it('writes one column after the last of them and leaves the empties out', () => {
+ const { table: next, name } = mergeTable(table(), emptyMeta(), [1, 2], { joiner: ' — ' });
+ expect(name).toBe('Place + Status');
+ expect(next.columns[3]).toBe('Place + Status');
+ expect(next.rows[0][3]).toBe('Kherson, Ukraine — OK en cours');
+ });
+
+ it('joins nothing onto nothing rather than leaving a bare separator', () => {
+ const one = { columns: ['id', 'A', 'B'], rows: [['r1', '', 'only']] };
+ expect(mergeTable(one, emptyMeta(), [1, 2], { joiner: ', ' }).table.rows[0][3]).toBe('only');
+ });
+
+ it('refuses to merge one column with itself', () => {
+ expect(mergeTable(table(), emptyMeta(), [1], {}).name).toBeNull();
+ });
+
+ it('drops the originals on request', () => {
+ const { table: next } = mergeTable(table(), emptyMeta(), [1, 2], { keep: false });
+ expect(next.columns).toEqual(['id', 'Place + Status', 'Source']);
+ });
+});
+
+describe('lifting the links out of a column', () => {
+ it('makes a column of the addresses it found', () => {
+ const { table: next, name, filled } = extractTable(table(), emptyMeta(), 3, { what: 'url' });
+ expect(name).toBe('Source links');
+ expect(filled).toBe(2);
+ expect(next.rows[0][4]).toBe('https://t.me/chan/12');
+ expect(next.rows[2][4]).toBe('https://example.org/a, https://t.me/chan/13');
+ expect(next.rows[1][4]).toBe('');
+ });
+
+ it('makes a column of hosts, deduplicated, which is what counts as a reading', () => {
+ const { table: next } = extractTable(table(), emptyMeta(), 3, { what: 'host' });
+ expect(next.rows[2][4]).toBe('example.org, t.me');
+ });
+
+ it('adds no column where the column holds no link at all', () => {
+ const { table: next, name } = extractTable(table(), emptyMeta(), 1, { what: 'url' });
+ expect(name).toBeNull();
+ expect(next.columns).toHaveLength(4);
+ });
+});
diff --git a/frontend/src/lib/sheetClipboard.js b/frontend/src/lib/sheetClipboard.js
new file mode 100644
index 0000000..e7c0fef
--- /dev/null
+++ b/frontend/src/lib/sheetClipboard.js
@@ -0,0 +1,164 @@
+/**
+ * The clipboard, as a table operation.
+ *
+ * There is exactly one CSV parser and one CSV writer in the app and both are in
+ * Python (`engine/sheets.py`). That invariant is about **files**: delimiter
+ * sniffing, quoting rules, the bytes on disk. A clipboard block is not that case.
+ * It is TSV — what every spreadsheet and every browser table puts on the clipboard
+ * — and a paste into a selection is not a table, it is a **patch**: where it lands,
+ * how far it reaches, whether it makes the sheet longer. That is selection
+ * geometry, which only the side holding the selection knows, so it lives here and
+ * a paste costs no round trip.
+ *
+ * Pure on purpose: text in, table out. No DOM, no fetch, no clipboard API — the
+ * component reads the event and hands the string over.
+ */
+
+import { keyIndex, newKey, urlsIn } from './sheet.js';
+
+/** How many rows one paste may add. The same order as the sheet's own bound: past
+ * this it is an import, and `sheets/import` is the route that exists for it. */
+export const MAX_PASTE_ROWS = 20_000;
+
+/**
+ * A clipboard block, as rows of cells.
+ *
+ * Tab splits cells and newline splits rows, except inside a quoted cell — which is
+ * how a spreadsheet ships a note holding a line break or a tab, and dropping that
+ * rule turns one row of prose into nine rows of fragments. `""` inside a quoted
+ * cell is one quote, as in CSV.
+ *
+ * A quote that opens and never closes is read to the end of the block rather than
+ * refused: half the blocks on a clipboard come from somewhere that quotes badly,
+ * and the analyst would rather see the text than an error.
+ */
+export function parseBlock(text) {
+ const body = String(text ?? '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+ if (!body) return [];
+ const rows = [];
+ let cells = [];
+ let cell = '';
+ let quoted = false;
+ for (let at = 0; at < body.length; at += 1) {
+ const char = body[at];
+ if (quoted) {
+ if (char !== '"') cell += char;
+ else if (body[at + 1] === '"') {
+ cell += '"';
+ at += 1;
+ } else quoted = false;
+ continue;
+ }
+ if (char === '"' && cell === '') quoted = true;
+ else if (char === '\t') {
+ cells.push(cell);
+ cell = '';
+ } else if (char === '\n') {
+ cells.push(cell);
+ rows.push(cells);
+ cells = [];
+ cell = '';
+ } else cell += char;
+ }
+ cells.push(cell);
+ rows.push(cells);
+ // A block copied out of a spreadsheet ends with a line break; that is a
+ // terminator, not an empty row, and pasting it would append a blank line.
+ if (rows.length > 1 && rows.at(-1).length === 1 && rows.at(-1)[0] === '') rows.pop();
+ return rows;
+}
+
+/** A range of cells as a clipboard block, quoted where a reader would otherwise
+ * read one cell as several. Tab-separated because that is what a spreadsheet
+ * expects to receive, whatever delimiter its own files use. */
+export function toBlock(rows) {
+ return (rows ?? [])
+ .map((row) =>
+ (row ?? [])
+ .map((cell) => {
+ const value = String(cell ?? '');
+ return /[\t\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
+ })
+ .join('\t'),
+ )
+ .join('\n');
+}
+
+/**
+ * Whether a block reads as a list of links rather than as a table.
+ *
+ * Two links and no tab: a table has tabs, and one link is a cell someone pasted
+ * into a cell. This is the inbox the field binders keep as a "to be sorted" tab —
+ * a wall of links dropped out of a chat — and turning it into a row per link is the
+ * gesture that replaces an afternoon.
+ */
+export function looksLikeLinks(text) {
+ const body = String(text ?? '');
+ return !body.includes('\t') && urlsIn(body).length > 1;
+}
+
+/** A block of links as one row per link, for the column it is pasted into. */
+export function linkRows(text) {
+ return urlsIn(text).map((url) => [url]);
+}
+
+/**
+ * Paste *block* into *table* with its top-left cell at (row, column).
+ *
+ * Four rules, and each one is a decision:
+ *
+ * - **It lands where it looks like it lands.** `view` is the rows and the columns as
+ * they are drawn, and the block walks that order rather than the file's: a sheet
+ * that is filtered, sorted, or has had a column dragged elsewhere would otherwise
+ * copy the three rows on screen and write them into three the analyst cannot see.
+ * Without a view the file's own order is the order.
+ * - **Rows grow.** A block longer than what is left below gets the rows it needs,
+ * each with its own key. That is the whole point of pasting a worklist in.
+ * - **Columns do not.** A block wider than what is drawn to the right is clipped, and
+ * `clipped` says by how much. Inventing columns would change the file's schema from
+ * a keystroke, and a heading the analyst never chose is worse than a cell lost.
+ * - **The key column is never written.** It is the row's handle; a pasted value
+ * landing on it would move every colour and every link to another row.
+ *
+ * Returns the new table plus what happened, so the grid can say it out loud.
+ */
+export function pasteBlock(table, block, at = { row: 0, column: 0 }, view = null) {
+ const columns = table?.columns ?? [];
+ const key = keyIndex(columns);
+ const everyRow = table.rows.map((_, index) => index);
+ const everyColumn = columns.map((_, index) => index);
+ const atRow = Math.max(0, at?.row ?? 0);
+ const atColumn = Math.max(0, at?.column ?? 0);
+ // A cell the view does not hold — the pinned row, drawn outside the list — is pasted
+ // on in the file's order, since there is no place for it in the drawn one.
+ let rowOrder = view?.rows?.length ? view.rows : everyRow;
+ let columnOrder = view?.columns?.length ? view.columns : everyColumn;
+ if (!rowOrder.includes(atRow)) rowOrder = everyRow;
+ if (!columnOrder.includes(atColumn)) columnOrder = everyColumn;
+ const startRow = Math.max(0, rowOrder.indexOf(atRow));
+ const startColumn = Math.max(0, columnOrder.indexOf(atColumn));
+ const width = Math.max(0, ...(block ?? []).map((row) => row.length));
+ const clipped = Math.max(0, startColumn + width - columnOrder.length);
+ const wanted = startRow + (block?.length ?? 0);
+ const added = Math.min(Math.max(0, wanted - rowOrder.length), MAX_PASTE_ROWS);
+
+ const rows = table.rows.map((row) => [...row]);
+ const order = [...rowOrder];
+ for (let index = 0; index < added; index += 1) {
+ order.push(rows.length);
+ rows.push(columns.map((_, column) => (column === key ? newKey() : '')));
+ }
+
+ let written = 0;
+ (block ?? []).forEach((cells, down) => {
+ const target = rows[order[startRow + down]];
+ if (!target) return;
+ cells.forEach((value, across) => {
+ const column = columnOrder[startColumn + across];
+ if (column === undefined || column === key) return;
+ target[column] = String(value ?? '');
+ written += 1;
+ });
+ });
+ return { table: { ...table, rows }, added, clipped, written };
+}
diff --git a/frontend/src/lib/sheetClipboard.test.js b/frontend/src/lib/sheetClipboard.test.js
new file mode 100644
index 0000000..3f79536
--- /dev/null
+++ b/frontend/src/lib/sheetClipboard.test.js
@@ -0,0 +1,219 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAX_PASTE_ROWS,
+ linkRows,
+ looksLikeLinks,
+ parseBlock,
+ pasteBlock,
+ toBlock,
+} from './sheetClipboard.js';
+import { keyIndex } from './sheet.js';
+
+const table = () => ({
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out'],
+ ['r2', 'Pont nord', ''],
+ ],
+});
+
+describe('reading a clipboard block', () => {
+ it('splits cells on tabs and rows on newlines', () => {
+ expect(parseBlock('a\tb\nc\td')).toEqual([
+ ['a', 'b'],
+ ['c', 'd'],
+ ]);
+ });
+
+ it('keeps a quoted note whole, line breaks and tabs and all', () => {
+ // What a spreadsheet actually puts on the clipboard for a cell holding
+ // sentences. Reading it naively turns one row of prose into three rows.
+ const block = parseBlock('AB-123\t"two\nlines\there"\nAB-124\tplain');
+ expect(block).toEqual([
+ ['AB-123', 'two\nlines\there'],
+ ['AB-124', 'plain'],
+ ]);
+ });
+
+ it('reads a doubled quote as one quote', () => {
+ expect(parseBlock('"he said ""no"""')).toEqual([['he said "no"']]);
+ });
+
+ it('reads an unclosed quote to the end rather than refusing the paste', () => {
+ expect(parseBlock('"never closed\tstill mine')).toEqual([['never closed\tstill mine']]);
+ });
+
+ it('normalises the line endings every platform sends', () => {
+ expect(parseBlock('a\r\nb\rc')).toEqual([['a'], ['b'], ['c']]);
+ });
+
+ it('treats the trailing line break as a terminator, not an empty row', () => {
+ expect(parseBlock('a\tb\n')).toEqual([['a', 'b']]);
+ });
+
+ it('keeps a genuinely blank row in the middle', () => {
+ expect(parseBlock('a\n\nb')).toEqual([['a'], [''], ['b']]);
+ });
+
+ it('reads nothing out of nothing', () => {
+ expect(parseBlock('')).toEqual([]);
+ expect(parseBlock(null)).toEqual([]);
+ });
+});
+
+describe('writing a range to the clipboard', () => {
+ it('separates with tabs, which is what a spreadsheet expects to receive', () => {
+ expect(toBlock([['a', 'b'], ['c', 'd']])).toBe('a\tb\nc\td');
+ });
+
+ it('quotes a cell a reader would otherwise read as several', () => {
+ expect(toBlock([['two\nlines']])).toBe('"two\nlines"');
+ expect(toBlock([['with\ttab']])).toBe('"with\ttab"');
+ expect(toBlock([['he said "no"']])).toBe('"he said ""no"""');
+ });
+
+ it('round-trips whatever it wrote', () => {
+ const range = [['plain', 'two\nlines'], ['he said "no"', 'with\ttab']];
+ expect(parseBlock(toBlock(range))).toEqual(range);
+ });
+});
+
+describe('a block of links', () => {
+ it('is recognised by having links and no tabs', () => {
+ expect(looksLikeLinks('https://a.example/x\nhttps://b.example/y')).toBe(true);
+ // One link is a cell someone pasted into a cell, not an inbox.
+ expect(looksLikeLinks('https://a.example/x')).toBe(false);
+ // A table has tabs, whatever its cells hold.
+ expect(looksLikeLinks('https://a.example\tnote\nhttps://b.example\tnote')).toBe(false);
+ });
+
+ it('becomes one row per link, even when prose surrounds them', () => {
+ const text = 'look at https://a.example/one\nand also https://b.example/two, later';
+ expect(linkRows(text)).toEqual([['https://a.example/one'], ['https://b.example/two']]);
+ });
+
+ it('keeps a repeated link rather than deciding it was a mistake', () => {
+ expect(linkRows('https://a.example\nhttps://a.example')).toHaveLength(2);
+ });
+});
+
+describe('pasting into a table', () => {
+ it('writes the block where the cursor is', () => {
+ const { table: next } = pasteBlock(table(), [['A', 'B']], { row: 0, column: 1 });
+ expect(next.rows[0]).toEqual(['r1', 'A', 'B']);
+ expect(next.rows[1]).toEqual(['r2', 'Pont nord', '']);
+ });
+
+ it('never mutates the table it was handed', () => {
+ const before = table();
+ pasteBlock(before, [['A']], { row: 0, column: 1 });
+ expect(before.rows[0][1]).toBe('Quai sud');
+ });
+
+ it('grows the sheet by as many rows as the block needs, each with its own key', () => {
+ const { table: next, added } = pasteBlock(
+ table(),
+ [['A'], ['B'], ['C']],
+ { row: 1, column: 1 },
+ );
+ expect(added).toBe(2);
+ expect(next.rows).toHaveLength(4);
+ expect(next.rows.map((row) => row[1])).toEqual(['Quai sud', 'A', 'B', 'C']);
+ const keys = next.rows.map((row) => row[keyIndex(next.columns)]);
+ expect(new Set(keys).size).toBe(4);
+ expect(keys[3]).toMatch(/^r[0-9a-f]{10}$/);
+ });
+
+ it('clips a block wider than the table and says by how much', () => {
+ // Inventing a column would change the file's schema from a keystroke, and a
+ // heading nobody chose is worse than a cell that did not fit.
+ const { table: next, clipped } = pasteBlock(table(), [['A', 'B', 'C']], { row: 0, column: 1 });
+ expect(clipped).toBe(1);
+ expect(next.columns).toEqual(['id', 'Subject', 'Status']);
+ expect(next.rows[0]).toEqual(['r1', 'A', 'B']);
+ });
+
+ it('never writes the key column, whatever lands on it', () => {
+ const { table: next } = pasteBlock(table(), [['stolen', 'A']], { row: 0, column: 0 });
+ expect(next.rows[0][0]).toBe('r1');
+ expect(next.rows[0][1]).toBe('A');
+ });
+
+ it('skips the key column when it is not the first, rather than shifting the block', () => {
+ const moved = {
+ columns: ['Subject', 'id', 'Status'],
+ rows: [['Quai sud', 'r1', 'ruled out']],
+ };
+ const { table: next } = pasteBlock(moved, [['A', 'B', 'C']], { row: 0, column: 0 });
+ expect(next.rows[0]).toEqual(['A', 'r1', 'C']);
+ });
+
+ it('lands on the rows that are on screen, not on the ones under them in the file', () => {
+ // Three rows of a filtered sheet were copied off the screen; they have to come back
+ // to the screen. Writing rows 1..3 of the file would fill rows nobody can see.
+ const filtered = {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out'],
+ ['r2', 'hidden', ''],
+ ['r3', 'Pont nord', ''],
+ ['r4', 'hidden', ''],
+ ],
+ };
+ const { table: next } = pasteBlock(filtered, [['A'], ['B']], { row: 0, column: 1 }, {
+ rows: [0, 2],
+ columns: [0, 1, 2],
+ });
+ expect(next.rows.map((row) => row[1])).toEqual(['A', 'hidden', 'B', 'hidden']);
+ });
+
+ it('walks the columns in the order they are drawn', () => {
+ const { table: next } = pasteBlock(table(), [['A', 'B']], { row: 0, column: 2 }, {
+ rows: [0, 1],
+ columns: [0, 2, 1],
+ });
+ expect(next.rows[0]).toEqual(['r1', 'B', 'A']);
+ });
+
+ it('counts a column that is not drawn as one the block did not fit in', () => {
+ const { table: next, clipped } = pasteBlock(table(), [['A', 'B']], { row: 0, column: 1 }, {
+ rows: [0, 1],
+ columns: [0, 1],
+ });
+ expect(clipped).toBe(1);
+ expect(next.rows[0]).toEqual(['r1', 'A', 'ruled out']);
+ });
+
+ it('grows past the last row on screen rather than past the last row of the file', () => {
+ const filtered = {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', ''],
+ ['r2', 'hidden', ''],
+ ],
+ };
+ const { table: next, added } = pasteBlock(filtered, [['A'], ['B']], { row: 0, column: 1 }, {
+ rows: [0],
+ columns: [0, 1, 2],
+ });
+ expect(added).toBe(1);
+ expect(next.rows.map((row) => row[1])).toEqual(['A', 'hidden', 'B']);
+ });
+
+ it('falls back to the file\'s order for a cell the view does not hold', () => {
+ // The pinned row is drawn above the list, so it is in no view; a paste on it still
+ // has to land on it.
+ const { table: next } = pasteBlock(table(), [['A']], { row: 1, column: 1 }, {
+ rows: [0],
+ columns: [0, 1, 2],
+ });
+ expect(next.rows[1][1]).toBe('A');
+ });
+
+ it('bounds how far one paste may grow the sheet', () => {
+ expect(MAX_PASTE_ROWS).toBe(20_000);
+ const huge = Array.from({ length: MAX_PASTE_ROWS + 10 }, (_, index) => [`v${index}`]);
+ const { added } = pasteBlock(table(), huge, { row: 0, column: 1 });
+ expect(added).toBe(MAX_PASTE_ROWS);
+ });
+});
diff --git a/frontend/src/lib/sheetDiff.js b/frontend/src/lib/sheetDiff.js
new file mode 100644
index 0000000..a894ef4
--- /dev/null
+++ b/frontend/src/lib/sheetDiff.js
@@ -0,0 +1,98 @@
+/**
+ * What changed between the table the grid holds and the table on disk.
+ *
+ * The conflict banner used to offer two buttons — reload, or overwrite — over one
+ * sentence saying the file had moved on. Both are irreversible in the direction that
+ * matters and the analyst had nothing to decide *with*: overwriting three rows somebody
+ * added in a spreadsheet and overwriting a stray cell they fixed are the same press.
+ *
+ * So the two tables are compared and the answer is counted before anything is pressed.
+ * Rows are matched **by key**, never by position, for the same reason everything else in
+ * a sheet is: the file may well have been sorted in the spreadsheet that touched it, and a
+ * positional diff would report four hundred changed rows where somebody re-ordered them.
+ *
+ * Pure: two tables in, a reading out. No fetch, no DOM.
+ */
+
+import { keyIndex } from './sheet.js';
+
+/** How many differing cells are listed. The count is the answer; the list is the sample
+ * that makes it believable, and a wall of two hundred rows is neither. */
+const SAMPLE = 12;
+
+function byKey(table) {
+ const at = keyIndex(table?.columns ?? []);
+ const rows = new Map();
+ for (const row of table?.rows ?? []) rows.set(String(row?.[at] ?? ''), row);
+ return rows;
+}
+
+/**
+ * The two tables compared, as counts plus a sample.
+ *
+ * `mine` is what the grid is showing and `theirs` is what the file says. The words are
+ * deliberate: every count is phrased from the grid's side, so `rowsAdded` is rows the file
+ * has that the grid never saw — the ones an overwrite would delete.
+ */
+export function diffTables(mine, theirs) {
+ const ours = byKey(mine);
+ const disk = byKey(theirs);
+ const columnsMine = mine?.columns ?? [];
+ const columnsDisk = theirs?.columns ?? [];
+ const shared = columnsMine.filter((name) => columnsDisk.includes(name));
+
+ const changed = [];
+ let cellsChanged = 0;
+ for (const [key, row] of ours) {
+ const other = disk.get(key);
+ if (!other) continue;
+ for (const name of shared) {
+ const left = String(row[columnsMine.indexOf(name)] ?? '');
+ const right = String(other[columnsDisk.indexOf(name)] ?? '');
+ if (left === right) continue;
+ cellsChanged += 1;
+ if (changed.length < SAMPLE) changed.push({ key, column: name, mine: left, theirs: right });
+ }
+ }
+
+ return {
+ rowsAdded: [...disk.keys()].filter((key) => !ours.has(key)).length,
+ rowsGone: [...ours.keys()].filter((key) => !disk.has(key)).length,
+ cellsChanged,
+ columnsAdded: columnsDisk.filter((name) => !columnsMine.includes(name)),
+ columnsGone: columnsMine.filter((name) => !columnsDisk.includes(name)),
+ changed,
+ };
+}
+
+/** Whether the two tables say the same thing. A stamp can move without the table moving:
+ * a spreadsheet that opened the file and saved it unchanged rewrote every byte of it. */
+export function sameTable(diff) {
+ return (
+ !diff.rowsAdded &&
+ !diff.rowsGone &&
+ !diff.cellsChanged &&
+ !diff.columnsAdded.length &&
+ !diff.columnsGone.length
+ );
+}
+
+/**
+ * The diff in one line, from the file's side.
+ *
+ * Written as what the *file* holds rather than as a verdict, because that is what the
+ * analyst is choosing between: "3 rows and 2 cells this grid has not got" is a reason to
+ * reload, and it is the same sentence whether they typed those rows in LibreOffice or a
+ * colleague did.
+ */
+export function describeDiff(diff) {
+ if (sameTable(diff)) return 'The file holds the same table, written again.';
+ const parts = [];
+ const rows = (count, word) => `${count} ${count === 1 ? word : `${word}s`}`;
+ if (diff.rowsAdded) parts.push(`${rows(diff.rowsAdded, 'row')} not in this grid`);
+ if (diff.rowsGone) parts.push(`${rows(diff.rowsGone, 'row')} gone from the file`);
+ if (diff.cellsChanged) parts.push(`${rows(diff.cellsChanged, 'cell')} written differently`);
+ if (diff.columnsAdded.length) parts.push(`a new column (${diff.columnsAdded.join(', ')})`);
+ if (diff.columnsGone.length) parts.push(`no ${diff.columnsGone.join(', ')} column`);
+ return `On disk: ${parts.join(', ')}.`;
+}
diff --git a/frontend/src/lib/sheetDiff.test.js b/frontend/src/lib/sheetDiff.test.js
new file mode 100644
index 0000000..1286a9c
--- /dev/null
+++ b/frontend/src/lib/sheetDiff.test.js
@@ -0,0 +1,85 @@
+import { describe, expect, it } from 'vitest';
+import { describeDiff, diffTables, sameTable } from './sheetDiff.js';
+
+const MINE = {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'done'],
+ ['r2', 'Pont nord', ''],
+ ],
+};
+
+describe('what the grid holds against what the file says', () => {
+ it('counts the rows the file has that the grid never saw, and the other way', () => {
+ // Phrased from the grid's side, because that is what the analyst is choosing between:
+ // `rowsAdded` are the rows an overwrite would delete.
+ const diff = diffTables(MINE, {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'done'],
+ ['r3', 'Zone 5', 'to do'],
+ ],
+ });
+ expect(diff.rowsAdded).toBe(1);
+ expect(diff.rowsGone).toBe(1);
+ expect(diff.cellsChanged).toBe(0);
+ });
+
+ it('matches rows by key, so a file somebody sorted is not four hundred changes', () => {
+ const sorted = { columns: MINE.columns, rows: [...MINE.rows].reverse() };
+ expect(sameTable(diffTables(MINE, sorted))).toBe(true);
+ });
+
+ it('lists the differing cells, with both readings', () => {
+ const diff = diffTables(MINE, {
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out'],
+ ['r2', 'Pont nord', ''],
+ ],
+ });
+ expect(diff.cellsChanged).toBe(1);
+ expect(diff.changed).toEqual([
+ { key: 'r1', column: 'Status', mine: 'done', theirs: 'ruled out' },
+ ]);
+ });
+
+ it('cuts the list at a sample, because a wall of rows is not evidence', () => {
+ const many = (status) => ({
+ columns: ['id', 'Status'],
+ rows: Array.from({ length: 40 }, (_, index) => [`r${index}`, status]),
+ });
+ const diff = diffTables(many('done'), many('to do'));
+ expect(diff.cellsChanged).toBe(40);
+ expect(diff.changed).toHaveLength(12);
+ });
+
+ it('names the columns each side has that the other has not', () => {
+ const diff = diffTables(MINE, {
+ columns: ['id', 'Subject', 'Verdict'],
+ rows: [['r1', 'Quai sud', 'yes']],
+ });
+ expect(diff.columnsAdded).toEqual(['Verdict']);
+ expect(diff.columnsGone).toEqual(['Status']);
+ });
+
+ it('says the table is the same when a spreadsheet only rewrote every byte of it', () => {
+ // A stamp moves whenever the file is written, and opening a CSV and saving it
+ // unchanged is exactly that. Saying so is the answer that ends the banner.
+ const diff = diffTables(MINE, structuredClone(MINE));
+ expect(sameTable(diff)).toBe(true);
+ expect(describeDiff(diff)).toBe('The file holds the same table, written again.');
+ });
+
+ it('says the difference in one line, from the file side', () => {
+ const said = describeDiff({
+ rowsAdded: 3,
+ rowsGone: 0,
+ cellsChanged: 1,
+ columnsAdded: ['Verdict'],
+ columnsGone: [],
+ changed: [],
+ });
+ expect(said).toBe('On disk: 3 rows not in this grid, 1 cell written differently, a new column (Verdict).');
+ });
+});
diff --git a/frontend/src/lib/sheetExport.js b/frontend/src/lib/sheetExport.js
new file mode 100644
index 0000000..626a2cd
--- /dev/null
+++ b/frontend/src/lib/sheetExport.js
@@ -0,0 +1,102 @@
+/**
+ * Getting a sheet out of the case, as the CSV somebody else opens.
+ *
+ * What travels is **what is on screen**: the columns that are drawn, in the order they
+ * are drawn, and the rows the filter and the sort left. The case folder already holds
+ * `sheets/<name>.csv`, so a button that copied that file byte for byte would hand the
+ * analyst something they already have. What they do not have is this reading of it.
+ *
+ * The file is written **by the server, into the folder saved for sheet exports** — the
+ * case's own `exports/` until the analyst picks another. That is what every other finished
+ * thing in this app does, and a table that landed in the browser's downloads instead was
+ * the one export nobody could find twice. It also keeps the single CSV writer in Python
+ * (`engine/sheets.py`): a second one here would be a second answer to how a quoted newline
+ * is written, on the one artifact whose whole promise is that any spreadsheet opens it.
+ */
+
+import { api } from './api.js';
+
+/** The drawn columns and the shown rows, as a plain table. Indices are translated
+ * here because the grid draws in one order and stores in another. */
+export function viewTable(table, drawn, shown) {
+ return {
+ columns: (drawn ?? []).map((column) => column.name),
+ rows: (shown ?? []).map((index) =>
+ (drawn ?? []).map((column) => table?.rows?.[index]?.[column.index] ?? ''),
+ ),
+ };
+}
+
+/**
+ * Where a copied table came from, as the two lines that make it citable.
+ *
+ * This is what the app kept from the idea of a sheet **plate** and the only part of it
+ * worth keeping. A picture of a grid is worse than the CSV *and* worse than the Markdown
+ * — not selectable, not sortable, not diffable — but a plate carried one thing a bare
+ * table does not: its provenance on the page. Twelve rows pasted into a ticket with no
+ * case, no filter and no timestamp are twelve rows nobody can check a week later, and
+ * "which sheet was this, and what was hidden when you copied it" is the first question
+ * anybody asks.
+ *
+ * The filter is stated because it is the line that changes what the rows *mean*: `12 of
+ * 468` is a reading, and a reader who cannot see that `Coordinates is empty` was on has
+ * been handed a sample presented as a set.
+ */
+export function provenance({ caseName, sheet, filter, sort, shown, total, at } = {}) {
+ const said = [];
+ const title = [caseName, sheet].filter(Boolean).join(' · ');
+ const count =
+ Number.isFinite(shown) && Number.isFinite(total)
+ ? `${shown} of ${total} ${total === 1 ? 'row' : 'rows'}`
+ : '';
+ if (title || count) said.push([title, count].filter(Boolean).join(' — '));
+ if (filter) said.push(`Showing ${filter}`);
+ if (sort) said.push(`Sorted by ${sort}`);
+ if (at) said.push(String(at).replace('T', ' ').slice(0, 16));
+ return said;
+}
+
+/**
+ * The same reading as a Markdown table, for the report rather than for the spreadsheet.
+ *
+ * A CSV is what a collaborator opens; a Markdown table is what goes in the Notebook, a
+ * ticket or a message, and re-typing twelve rows into a note is exactly the step that
+ * makes an analyst stop citing the sheet. Pipes inside a cell are escaped and newlines
+ * become `<br>`, because a table that breaks its own rows is a table nobody can read.
+ *
+ * The header is a blockquote above it rather than a caption below, because what is
+ * quoted has to be read before the numbers are: it is the difference between a table
+ * pasted into a ticket and a table somebody can cite.
+ */
+export function toMarkdown(view, said = []) {
+ const columns = view?.columns ?? [];
+ if (!columns.length) return '';
+ const cell = (value) =>
+ String(value ?? '')
+ .replace(/\|/g, '\\|')
+ .replace(/\n+/g, '<br>')
+ .trim();
+ const lines = [
+ ...(said.length ? [...said.map((line) => `> ${line}`), ''] : []),
+ `| ${columns.map(cell).join(' | ')} |`,
+ `| ${columns.map(() => '---').join(' | ')} |`,
+ ...(view?.rows ?? []).map((row) => `| ${columns.map((_, at) => cell(row[at])).join(' | ')} |`),
+ ];
+ return `${lines.join('\n')}\n`;
+}
+
+/**
+ * Write the view out, into the folder this case files sheet CSVs in.
+ *
+ * Answers the file and the folder, so the caller can say where it went and how much of the
+ * sheet that was — an export of twelve rows out of four hundred is worth hearing before it
+ * is mailed.
+ */
+export async function exportCsv(caseId, sheetId, view) {
+ return api.post(`/api/cases/${caseId}/sheets/${sheetId}/csv`, view);
+}
+
+/** Open that folder. The same gesture the note PDFs and the analysis plates offer, since
+ * a file written somewhere the analyst cannot see is a file they will export twice. */
+export const revealSheetExports = (caseId) =>
+ api.post(`/api/cases/${caseId}/sheets/csv/reveal`);
diff --git a/frontend/src/lib/sheetExport.test.js b/frontend/src/lib/sheetExport.test.js
new file mode 100644
index 0000000..7f78a3e
--- /dev/null
+++ b/frontend/src/lib/sheetExport.test.js
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const post = vi.fn(async () => ({ file: 'Candidates.csv', path: '/cases/harbour/exports' }));
+vi.mock('./api.js', () => ({ api: { post } }));
+
+const { exportCsv, provenance, revealSheetExports, toMarkdown, viewTable } = await import(
+ './sheetExport.js'
+);
+
+const table = {
+ columns: ['id', 'Subject', 'Status', 'Notes'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out', 'seen'],
+ ['r2', 'Pont nord', '', ''],
+ ['r3', 'Gare est', 'to check', 'asked'],
+ ],
+};
+
+/** The grid's own shape: the columns drawn, each carrying the index it reads from. */
+const drawn = (...names) =>
+ names.map((name) => ({ name, index: table.columns.indexOf(name) }));
+
+describe('what an export carries', () => {
+ it('takes the columns drawn, in the order they are drawn', () => {
+ // A column moved or hidden in the grid is a decision about how the table reads, and
+ // the file handed over is that reading rather than the one on disk.
+ const view = viewTable(table, drawn('id', 'Status', 'Subject'), [0, 1, 2]);
+ expect(view.columns).toEqual(['id', 'Status', 'Subject']);
+ expect(view.rows[0]).toEqual(['r1', 'ruled out', 'Quai sud']);
+ });
+
+ it('takes the rows on screen, in the order they are on screen', () => {
+ // Filtered to the rows left to check and sorted: exporting all four hundred would
+ // hand over a file the analyst did not ask for and did not read.
+ const view = viewTable(table, drawn('id', 'Subject'), [2, 1]);
+ expect(view.rows).toEqual([
+ ['r3', 'Gare est'],
+ ['r2', 'Pont nord'],
+ ]);
+ });
+
+ it('reads a short row as empty cells rather than as undefined', () => {
+ const ragged = { columns: ['id', 'Subject'], rows: [['r1']] };
+ expect(viewTable(ragged, drawn('id', 'Subject'), [0]).rows).toEqual([['r1', '']]);
+ });
+});
+
+describe('handing the file over', () => {
+ beforeEach(() => post.mockClear());
+
+ it('asks the server to write it, and says where it landed', async () => {
+ // The CSV is written on the Python side, into the folder this case files sheets in:
+ // one CSV writer in the app, and one place finished work goes.
+ const answer = await exportCsv('case-a', 'e_sheet', { columns: ['id'], rows: [['r1']] });
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/sheets/e_sheet/csv', {
+ columns: ['id'],
+ rows: [['r1']],
+ });
+ expect(answer.file).toBe('Candidates.csv');
+ expect(answer.path).toBe('/cases/harbour/exports');
+ });
+
+ it('opens that folder without being told where it is', async () => {
+ await revealSheetExports('case-a');
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/sheets/csv/reveal');
+ });
+});
+
+describe('the same reading as a Markdown table', () => {
+ it('writes a header, a rule and the rows', () => {
+ const view = viewTable(table, drawn('Subject', 'Status'), [0, 1]);
+ expect(toMarkdown(view)).toBe(
+ '| Subject | Status |\n| --- | --- |\n| Quai sud | ruled out |\n| Pont nord | |\n',
+ );
+ });
+
+ it('keeps a cell from breaking the table it sits in', () => {
+ const view = { columns: ['Note'], rows: [['a | b\ntwo lines']] };
+ expect(toMarkdown(view)).toContain('| a \\| b<br>two lines |');
+ });
+
+ it('writes nothing for a view with no column', () => {
+ expect(toMarkdown({ columns: [], rows: [] })).toBe('');
+ });
+});
+
+describe('where a copied table came from', () => {
+ it('states the case, the sheet, how much of it and when', () => {
+ // What the retired sheet plate was actually for. Twelve rows pasted into a ticket
+ // with no case and no filter are twelve rows nobody can check a week later.
+ expect(
+ provenance({
+ caseName: 'Harbour',
+ sheet: 'Geolocation index',
+ filter: 'Coordinates is empty',
+ sort: 'Date, newest first',
+ shown: 12,
+ total: 468,
+ at: '2026-08-17T14:32:07.000Z',
+ }),
+ ).toEqual([
+ 'Harbour · Geolocation index — 12 of 468 rows',
+ 'Showing Coordinates is empty',
+ 'Sorted by Date, newest first',
+ '2026-08-17 14:32',
+ ]);
+ });
+
+ it('says nothing about a filter or a sort that is not on', () => {
+ expect(provenance({ caseName: 'Harbour', sheet: 'Leads', shown: 3, total: 3 })).toEqual([
+ 'Harbour · Leads — 3 of 3 rows',
+ ]);
+ expect(provenance()).toEqual([]);
+ });
+
+ it('quotes those lines above the table, so they are read before the numbers', () => {
+ const view = viewTable(table, drawn('Subject'), [0]);
+ expect(toMarkdown(view, ['Harbour · Leads — 1 of 3 rows'])).toBe(
+ '> Harbour · Leads — 1 of 3 rows\n\n| Subject |\n| --- |\n| Quai sud |\n',
+ );
+ // And a table copied without them is the table it always was.
+ expect(toMarkdown(view)).toBe('| Subject |\n| --- |\n| Quai sud |\n');
+ });
+});
diff --git a/frontend/src/lib/sheetFromProofs.test.js b/frontend/src/lib/sheetFromProofs.test.js
new file mode 100644
index 0000000..76374ac
--- /dev/null
+++ b/frontend/src/lib/sheetFromProofs.test.js
@@ -0,0 +1,85 @@
+/**
+ * The outgoing shape, as the two rules that keep it honest on the browser's side.
+ *
+ * A `locked` column is the one role that is written by the app **and** carries a link:
+ * the whole point of those cells is that they open the entity the case filled them from.
+ * Every other written role points at nothing, so offering the `@` on one would offer a
+ * link to nowhere.
+ *
+ * And the sheet this shape builds must not offer the proofs build. That road downloads
+ * what a column of addresses points at; here the proofs already exist, so a button
+ * saying "build them" would be a button with nothing to do.
+ */
+import { describe, expect, it } from 'vitest';
+import { canBuild, columnKinds } from './sheetBuild.js';
+import { COMPUTED_NATURES, ROLE_KINDS, normalizeRole } from './sheetRoles.js';
+
+/** The shape as the server builds it. Mirrors `engine/sheetfromcase.proof_columns`. */
+const TABLE = {
+ columns: ['id', 'Title', 'Source media', 'Place', 'Coordinates', 'In case', 'Status', 'Notes'],
+ rows: [['r1', 'Rooftop shot', 'GX010234', 'Rooftop', '47.10000, 37.50000', 'YES', 'done', '']],
+};
+const META = {
+ roles: {
+ Title: { kind: 'locked' },
+ 'Source media': { kind: 'locked' },
+ Place: { kind: 'locked' },
+ Coordinates: { kind: 'computed', of: 'point', from: 'Place' },
+ 'In case': { kind: 'computed', of: 'in_case' },
+ Status: { kind: 'state', values: ['to do', 'in progress', 'done', 'ruled out'] },
+ },
+ links: { r1: { Title: 'e1', 'Source media': 'e2', Place: 'e3' } },
+ built: { r1: 'e1' },
+};
+
+describe('the roles the outgoing shape declares', () => {
+ it('knows the locked kind and the in_case nature', () => {
+ expect(ROLE_KINDS).toContain('locked');
+ expect(COMPUTED_NATURES).toContain('in_case');
+ });
+
+ it('keeps a locked role down to its kind, since it has nothing else to say', () => {
+ expect(normalizeRole({ kind: 'locked' })).toEqual({ kind: 'locked' });
+ // Fields a kind does not use are dropped rather than carried.
+ expect(normalizeRole({ kind: 'locked', values: ['a'], of: 'point' })).toEqual({
+ kind: 'locked',
+ });
+ });
+
+ it('accepts in_case as a computed nature and asks it for no column', () => {
+ const clean = normalizeRole({ kind: 'computed', of: 'in_case' });
+ expect(clean.of).toBe('in_case');
+ // It reads `built`, not a named column: nothing to follow and nothing to count.
+ expect(clean.from).toBeUndefined();
+ expect(clean.columns).toBeUndefined();
+ });
+
+ it('falls back rather than storing a nature nobody implements', () => {
+ expect(normalizeRole({ kind: 'computed', of: 'invented' }).of).toBe('has_point');
+ });
+});
+
+describe('what this sheet is not', () => {
+ it('does not offer the proofs build, because there is nothing left to fetch', () => {
+ expect(canBuild(columnKinds(TABLE, META))).toBe(false);
+ });
+
+ it('holds no address column at all, which is what makes that true', () => {
+ expect(Object.values(columnKinds(TABLE, META))).not.toContain('url');
+ });
+
+ it('still offers it on the incoming template, which is the other direction', () => {
+ const incoming = {
+ columns: ['id', 'Title', 'Source media', 'Geolocation proof', 'Coordinates'],
+ rows: [],
+ };
+ const roles = {
+ roles: {
+ 'Source media': { kind: 'url' },
+ 'Geolocation proof': { kind: 'url' },
+ Coordinates: { kind: 'latlon' },
+ },
+ };
+ expect(canBuild(columnKinds(incoming, roles))).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/sheetGeo.js b/frontend/src/lib/sheetGeo.js
new file mode 100644
index 0000000..e16cf6d
--- /dev/null
+++ b/frontend/src/lib/sheetGeo.js
@@ -0,0 +1,175 @@
+/**
+ * Reading a column of place names into coordinates, and a column of coordinates back into
+ * place names.
+ *
+ * Both directions already existed in this app — the map's own search and the country
+ * backfill go through `/api/geo/geocode` and `/api/geo/reverse` — and the sheet, which is
+ * where a geolocation index is actually worked, could reach neither. So an analyst holding
+ * four hundred rows of `Kherson, Ukraine` typed the coordinates in by hand, or gave up on
+ * the column.
+ *
+ * Two rules, and they are the same rule twice:
+ *
+ * - **Nothing is applied on its own.** The pass proposes a cell per row and the analyst
+ * presses to write them, because a geocoder's first hit is a guess and a guess written
+ * into a column of evidence is indistinguishable from a fact somebody established.
+ * - **Only where the answer is missing.** A row that already holds a point is never asked
+ * about: overwriting a coordinate somebody read off a photograph with one Nominatim
+ * guessed from a name is the worst thing this could do.
+ *
+ * Distinct values rather than rows, because a column of four hundred rows holds forty
+ * places. Nominatim is paced server-side at one request per 1.1 s, so forty values is
+ * three quarters of a minute — which is why the caller walks them one at a time and can
+ * stop.
+ *
+ * **And the case is asked before the internet is.** A forward pass used to send every row
+ * to Nominatim, including the ones whose cell already points at an entity the case has
+ * placed — a second of somebody else's server spent guessing a name the case could have
+ * answered exactly, and no answer at all when the cell says `3rd Bde` rather than a
+ * toponym. So the pass has two halves: what the graph knows, written straight, and the
+ * words left over, looked up.
+ */
+
+import { api } from './api.js';
+import { linkAt, rowKey } from './sheet.js';
+import { formatLatLon, parseLatLon } from './sheetRoles.js';
+
+/** How many distinct values one pass will look up. Past this it is a batch job, and a
+ * browser tab waiting four minutes on a paced geocoder is a tab that looks broken. */
+export const MAX_LOOKUPS = 60;
+
+/** How many entities one pass asks the place of. Mirrors `api/sheets.MAX_POINTS`: this
+ * half is answered off the case's own graph, so it is bounded by the sheet's working
+ * size and not by a stranger's rate limit. */
+export const MAX_CASE_POINTS = 2000;
+
+/**
+ * The rows a forward pass can answer without leaving the machine: their cell in the source
+ * column points at an entity, and their target cell is empty.
+ *
+ * Rows and not values, because the link is on the cell. Two rows saying `Kherson` may point
+ * at two different entities, and a pass that grouped them would put one row's place on the
+ * other's ground — the same reason the reverse pass is row by row.
+ */
+export function linkedRows(table, meta, sourceIndex, targetIndex, rows) {
+ const column = table?.columns?.[sourceIndex];
+ if (column === undefined) return [];
+ const wanted = [];
+ for (const index of rows ?? []) {
+ const row = table?.rows?.[index];
+ if (!row) continue;
+ // An empty cell is not a place to read, the same rule the lookup half is under. It
+ // also covers a link left behind by a cell somebody blanked.
+ if (!String(row[sourceIndex] ?? '').trim()) continue;
+ if (targetIndex !== -1 && String(row[targetIndex] ?? '').trim()) continue;
+ const id = linkAt(meta, rowKey(table.columns, row), column);
+ if (id) wanted.push({ row: index, id: String(id) });
+ }
+ return wanted.slice(0, MAX_CASE_POINTS);
+}
+
+/**
+ * Where the case puts these entities, as `{ id: { lat, lon } }`.
+ *
+ * Never throws: a case that cannot answer leaves every row to the geocoder, which is the
+ * behaviour this pass had before it learned to ask.
+ */
+export async function casePoints(caseId, sheetId, ids) {
+ if (!caseId || !sheetId || !ids?.length) return {};
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${sheetId}/points`, {
+ ids: [...new Set(ids)].slice(0, MAX_CASE_POINTS),
+ });
+ return answer?.points ?? {};
+ } catch {
+ return {};
+ }
+}
+
+/** One place name, as the geocoder's best answer or null. Never throws: a value nothing
+ * answers for is a row left alone, not a pass that stops. */
+export async function geocodeValue(value) {
+ try {
+ return await api.get(`/api/geo/geocode?q=${encodeURIComponent(value)}`);
+ } catch {
+ return null;
+ }
+}
+
+/** One point, as what is around it, or null. */
+export async function reverseValue(lat, lon) {
+ try {
+ return await api.get(`/api/geo/reverse?lat=${lat}&lon=${lon}`);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The distinct words a forward pass would look up: filled in the source column, missing in
+ * the target one.
+ *
+ * Every value carries the rows holding it, so one lookup fills all of them — and so the
+ * dialog can say `Kherson · 34 rows` before anything is written.
+ */
+export function namesToRead(table, sourceIndex, targetIndex, rows) {
+ const found = new Map();
+ for (const index of rows ?? []) {
+ const row = table?.rows?.[index];
+ if (!row) continue;
+ const value = String(row[sourceIndex] ?? '').trim();
+ if (!value) continue;
+ if (targetIndex !== -1 && String(row[targetIndex] ?? '').trim()) continue;
+ if (!found.has(value)) found.set(value, { value, rows: [] });
+ found.get(value).rows.push(index);
+ }
+ return [...found.values()].sort((a, b) => b.rows.length - a.rows.length);
+}
+
+/**
+ * The rows a reverse pass would ask about: a readable point in the source column, nothing
+ * in the target one.
+ *
+ * Rows rather than values, because two rows are never the same point: five decimals is a
+ * metre, and rounding them together to save a lookup would put one row's answer on
+ * another row's ground.
+ */
+export function pointsToRead(table, sourceIndex, targetIndex, rows) {
+ const wanted = [];
+ for (const index of rows ?? []) {
+ const row = table?.rows?.[index];
+ if (!row) continue;
+ if (targetIndex !== -1 && String(row[targetIndex] ?? '').trim()) continue;
+ const point = parseLatLon(row[sourceIndex]);
+ if (point && !point.outOfBounds) wanted.push({ row: index, point });
+ }
+ return wanted;
+}
+
+/** A geocoder answer as the cell a point column holds: the app's one spelling, five
+ * decimals, which is about a metre — and no more, because the answer is a guess about a
+ * name and a sixth decimal would dress it up as a survey. */
+export function pointCell(answer) {
+ if (!answer || !Number.isFinite(answer.lat) || !Number.isFinite(answer.lon)) return '';
+ return formatLatLon({ lat: Number(answer.lat), lon: Number(answer.lon) });
+}
+
+/** Which parts of a reverse answer make a place name a person would write. Ordered from
+ * the closest thing to a street up to the country, and cut to the two that fit a cell. */
+const PLACE_KEYS = ['city', 'town', 'village', 'municipality', 'county', 'state', 'country'];
+
+/**
+ * A reverse answer as a short place name — `Kherson, Ukraine` — or the empty string.
+ *
+ * The full `display_name` is a postal address seven parts long, which is a cell nobody can
+ * read in a grid thirty pixels tall. The town and the country are what a worklist means by
+ * "where is this".
+ */
+export function placeCell(answer) {
+ const address = answer?.address ?? {};
+ const local = PLACE_KEYS.map((key) => String(address[key] ?? '').trim()).filter(Boolean);
+ const country = String(address.country ?? '').trim();
+ const near = local.find((name) => name !== country) ?? '';
+ if (near && country && near !== country) return `${near}, ${country}`;
+ return near || country || String(answer?.display_name ?? '').split(',')[0].trim();
+}
diff --git a/frontend/src/lib/sheetGeo.test.js b/frontend/src/lib/sheetGeo.test.js
new file mode 100644
index 0000000..46b5a2b
--- /dev/null
+++ b/frontend/src/lib/sheetGeo.test.js
@@ -0,0 +1,189 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const get = vi.fn();
+const post = vi.fn();
+vi.mock('./api.js', () => ({ api: { get, post } }));
+
+const {
+ MAX_CASE_POINTS,
+ MAX_LOOKUPS,
+ casePoints,
+ geocodeValue,
+ linkedRows,
+ namesToRead,
+ placeCell,
+ pointCell,
+ pointsToRead,
+ reverseValue,
+} = await import('./sheetGeo.js');
+
+const TABLE = {
+ columns: ['id', 'Place', 'Coordinates'],
+ rows: [
+ ['r1', 'Kherson, Ukraine', ''],
+ ['r2', 'Kherson, Ukraine', ''],
+ ['r3', 'Mykolaiv', ''],
+ ['r4', 'Kherson, Ukraine', '46.63500, 32.61690'],
+ ['r5', '', ''],
+ ],
+};
+const ALL = [0, 1, 2, 3, 4];
+
+describe('which values a forward pass would look up', () => {
+ it('groups the rows by the value, so one lookup fills all of them', () => {
+ // A column of four hundred rows holds forty places, and Nominatim is paced at about
+ // one request a second: asking per row would be forty minutes for forty facts.
+ const work = namesToRead(TABLE, 1, 2, ALL);
+ expect(work.map((entry) => entry.value)).toEqual(['Kherson, Ukraine', 'Mykolaiv']);
+ expect(work[0].rows).toEqual([0, 1]);
+ });
+
+ it('never asks about a row that already holds an answer', () => {
+ // Overwriting a coordinate somebody read off a photograph with one a geocoder guessed
+ // from a name is the worst thing this could do.
+ expect(namesToRead(TABLE, 1, 2, ALL).flatMap((entry) => entry.rows)).not.toContain(3);
+ });
+
+ it('skips an empty cell, because a blank is not a place to look up', () => {
+ expect(namesToRead(TABLE, 1, 2, ALL).flatMap((entry) => entry.rows)).not.toContain(4);
+ });
+
+ it('reads only the rows it was given, which are the ones on screen', () => {
+ expect(namesToRead(TABLE, 1, 2, [2]).map((entry) => entry.value)).toEqual(['Mykolaiv']);
+ });
+
+ it('takes every row when no target column is chosen yet', () => {
+ expect(namesToRead(TABLE, 1, -1, ALL).flatMap((entry) => entry.rows)).toContain(3);
+ });
+});
+
+describe('which rows the case can answer without a geocoder', () => {
+ const meta = {
+ links: {
+ r1: { Place: 'e_kherson' },
+ r2: { Place: 'e_other' },
+ r4: { Place: 'e_kherson' },
+ r5: { Place: 'e_kherson' },
+ },
+ };
+
+ it('takes the linked rows whose target cell is still empty', () => {
+ const work = linkedRows(TABLE, meta, 1, 2, ALL);
+ expect(work).toEqual([
+ { row: 0, id: 'e_kherson' },
+ { row: 1, id: 'e_other' },
+ ]);
+ });
+
+ it('is rows and not values, because the link is on the cell', () => {
+ // Two rows saying `Kherson` may point at two different entities, and grouping them
+ // would put one row's place on the other's ground.
+ const work = linkedRows(TABLE, meta, 1, -1, ALL);
+ expect(work.map((entry) => entry.id)).toEqual(['e_kherson', 'e_other', 'e_kherson']);
+ });
+
+ it('skips a blank cell, even one a link was left on', () => {
+ expect(linkedRows(TABLE, meta, 1, -1, ALL).map((entry) => entry.row)).not.toContain(4);
+ });
+
+ it('leaves an unlinked row to the geocoder', () => {
+ expect(linkedRows(TABLE, { links: {} }, 1, 2, ALL)).toEqual([]);
+ expect(linkedRows(TABLE, undefined, 1, 2, ALL)).toEqual([]);
+ });
+
+ it('asks the case for the points, deduplicated, and never throws', async () => {
+ post.mockResolvedValueOnce({ points: { e_kherson: { lat: 46.635, lon: 32.6169 } } });
+ const answer = await casePoints('c1', 's1', ['e_kherson', 'e_kherson', 'e_other']);
+ expect(answer).toEqual({ e_kherson: { lat: 46.635, lon: 32.6169 } });
+ expect(post).toHaveBeenCalledWith('/api/cases/c1/sheets/s1/points', {
+ ids: ['e_kherson', 'e_other'],
+ });
+
+ // A case that cannot answer leaves every row to the geocoder, which is what this
+ // pass did before it learned to ask.
+ post.mockRejectedValueOnce(new Error('offline'));
+ expect(await casePoints('c1', 's1', ['e_kherson'])).toEqual({});
+ expect(await casePoints('c1', 's1', [])).toEqual({});
+ });
+
+ it('is bounded by the sheet working size, not by a stranger rate limit', () => {
+ expect(MAX_CASE_POINTS).toBe(2000);
+ });
+});
+
+describe('which rows a reverse pass would ask about', () => {
+ const points = {
+ columns: ['id', 'Coordinates', 'Place'],
+ rows: [
+ ['r1', '46.63500, 32.61690', ''],
+ ['r2', '46.63500, 32.61690', 'Kherson'],
+ ['r3', 'to be found', ''],
+ ['r4', '91, 200', ''],
+ ],
+ };
+
+ it('is rows and not values, because two rows are never the same point', () => {
+ // Five decimals is a metre. Rounding two readings together to save a lookup would put
+ // one row's answer on another row's ground.
+ const work = pointsToRead(points, 1, 2, [0, 1, 2, 3]);
+ expect(work.map((entry) => entry.row)).toEqual([0]);
+ expect(work[0].point.lat).toBeCloseTo(46.635);
+ });
+
+ it('leaves a cell nothing can be read out of, and one off the globe', () => {
+ expect(pointsToRead(points, 1, 2, [2, 3])).toEqual([]);
+ });
+});
+
+describe('an answer as the cell a column holds', () => {
+ it('writes a point in the app own spelling, to about a metre', () => {
+ // No further: the answer is a guess about a name, and a sixth decimal would dress it
+ // up as a survey.
+ expect(pointCell({ lat: 46.6350086, lon: 32.6169 })).toBe('46.63501, 32.61690');
+ expect(pointCell({ lat: 'nowhere' })).toBe('');
+ expect(pointCell(null)).toBe('');
+ });
+
+ it('writes the town and the country, not a seven-part postal address', () => {
+ expect(placeCell({ address: { city: 'Kherson', country: 'Ukraine' } })).toBe(
+ 'Kherson, Ukraine',
+ );
+ expect(placeCell({ address: { village: 'Posad-Pokrovske', country: 'Ukraine' } })).toBe(
+ 'Posad-Pokrovske, Ukraine',
+ );
+ });
+
+ it('says the country alone rather than saying it twice', () => {
+ expect(placeCell({ address: { country: 'Ukraine' } })).toBe('Ukraine');
+ });
+
+ it('falls back to the first part of the display name when there is no address', () => {
+ expect(placeCell({ display_name: 'Kherson, Kherson Oblast, Ukraine' })).toBe('Kherson');
+ expect(placeCell(null)).toBe('');
+ });
+});
+
+describe('asking the geocoder', () => {
+ it('goes through the routes the map already uses', async () => {
+ get.mockResolvedValueOnce({ lat: 46.635, lon: 32.6169 });
+ expect(await geocodeValue('Kherson, Ukraine')).toEqual({ lat: 46.635, lon: 32.6169 });
+ expect(get).toHaveBeenCalledWith('/api/geo/geocode?q=Kherson%2C%20Ukraine');
+
+ get.mockResolvedValueOnce({ address: { city: 'Kherson' } });
+ await reverseValue(46.635, 32.6169);
+ expect(get).toHaveBeenLastCalledWith('/api/geo/reverse?lat=46.635&lon=32.6169');
+ });
+
+ it('answers nothing rather than throwing, so one dead value does not stop the pass', async () => {
+ get.mockRejectedValueOnce(new Error('offline'));
+ expect(await geocodeValue('Kherson')).toBeNull();
+ get.mockRejectedValueOnce(new Error('offline'));
+ expect(await reverseValue(1, 2)).toBeNull();
+ });
+
+ it('caps a pass at something a browser tab can wait for', () => {
+ // Past this it is a batch job, and a tab waiting four minutes on a paced geocoder is
+ // a tab that looks broken.
+ expect(MAX_LOOKUPS).toBe(60);
+ });
+});
diff --git a/frontend/src/lib/sheetHistory.js b/frontend/src/lib/sheetHistory.js
new file mode 100644
index 0000000..d57461b
--- /dev/null
+++ b/frontend/src/lib/sheetHistory.js
@@ -0,0 +1,117 @@
+/**
+ * Undo for a table, sized for the table's real weight.
+ *
+ * `lib/history.js` keeps whole serialised snapshots, which is right for the tools
+ * that use it — a collage, a graph layout, a proof — where a step *is* the document.
+ * A sheet is different: it holds up to twenty thousand rows of sixty-four columns,
+ * so one snapshot per keystroke is megabytes of JSON per edit, and bounding that
+ * stack by size leaves an undo three steps deep on exactly the sheet where undo
+ * matters most.
+ *
+ * So a cell edit records **what changed** — the cells, their before and their after
+ * — and only a structural edit, where the shape moves and no list of cells could
+ * describe it, records the table on both sides. A hundred typed cells cost a hundred
+ * small entries; adding a column costs one big one.
+ *
+ * Every entry carries both sides, which is what makes the stack a stack of reversible
+ * steps rather than a stack of states: undo walks one step back, redo walks it
+ * forward, and the oldest entries can be dropped without the floor drifting into a
+ * state the sheet was never in.
+ *
+ * Pure: entries are plain data and this module never applies them. The caller owns
+ * the applying, because the caller owns the table.
+ */
+
+/** What the stack may hold, in characters of recorded state. Generous enough for a
+ * long afternoon of cell edits, small enough that a sheet reworked all day does
+ * not keep every version of itself in memory. */
+export const DEFAULT_BUDGET = 4_000_000;
+
+/** Roughly what one recorded cell costs. A fixed figure rather than a measurement:
+ * this only has to rank entries against one budget, not report memory. */
+const CELL_COST = 64;
+
+/** One or more cell edits, each `{ row, column, before, after }`. */
+export function cellsEntry(edits) {
+ return { kind: 'cells', edits: edits ?? [] };
+}
+
+/** A whole-table entry, for a change no list of cells describes: a column added,
+ * removed, renamed or moved, rows deleted, a paste that grew the sheet. Both sides
+ * are kept, so the step reverses like any other. */
+export function snapshotEntry(before, after) {
+ return { kind: 'snapshot', before: String(before ?? ''), after: String(after ?? '') };
+}
+
+/** Roughly what an entry costs to keep. */
+export function weigh(entry) {
+ if (entry?.kind === 'snapshot') return entry.before.length + entry.after.length;
+ return (entry?.edits?.length ?? 0) * CELL_COST;
+}
+
+/**
+ * A bounded undo/redo stack of reversible entries.
+ *
+ * `undo()` and `redo()` hand back `{ entry, direction }`. Backward means the sheet
+ * goes to each edit's `before`; forward means it goes to its `after`. What that does
+ * to the table is the caller's business.
+ */
+export function createSheetHistory({ budget = DEFAULT_BUDGET } = {}) {
+ /** @type {{ entry: object, weight: number }[]} */
+ let stack = [];
+ let index = -1;
+ let spent = 0;
+
+ /** Drop the oldest steps until the stack is inside its budget. What is dropped is
+ * undo depth, never correctness: the steps that remain still reverse exactly. */
+ function trim() {
+ while (stack.length > 1 && spent > budget) {
+ spent -= stack.shift().weight;
+ index -= 1;
+ }
+ if (index < -1) index = -1;
+ }
+
+ return {
+ get canUndo() {
+ return index >= 0;
+ },
+ get canRedo() {
+ return index < stack.length - 1;
+ },
+ /** How many steps are kept, for a test that wants the bound to be real. */
+ get size() {
+ return stack.length;
+ },
+ /** Forget everything: a different sheet, or the same one reloaded from disk. */
+ reset() {
+ stack = [];
+ index = -1;
+ spent = 0;
+ },
+ /** Record one step, dropping any redone tail: a new edit forks the timeline. */
+ record(entry) {
+ if (entry?.kind === 'cells' && !entry.edits.length) return false;
+ if (entry?.kind === 'snapshot' && entry.before === entry.after) return false;
+ for (const dropped of stack.slice(index + 1)) spent -= dropped.weight;
+ stack = stack.slice(0, index + 1);
+ const weight = weigh(entry);
+ stack.push({ entry, weight });
+ spent += weight;
+ index = stack.length - 1;
+ trim();
+ return true;
+ },
+ undo() {
+ if (index < 0) return null;
+ const { entry } = stack[index];
+ index -= 1;
+ return { entry, direction: 'backward' };
+ },
+ redo() {
+ if (index >= stack.length - 1) return null;
+ index += 1;
+ return { entry: stack[index].entry, direction: 'forward' };
+ },
+ };
+}
diff --git a/frontend/src/lib/sheetHistory.test.js b/frontend/src/lib/sheetHistory.test.js
new file mode 100644
index 0000000..e8d6642
--- /dev/null
+++ b/frontend/src/lib/sheetHistory.test.js
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+import { cellsEntry, createSheetHistory, snapshotEntry, weigh } from './sheetHistory.js';
+
+const edit = (row) => ({ row, column: 1, before: '', after: 'x' });
+
+describe('recording steps', () => {
+ it('starts with nothing to undo', () => {
+ const history = createSheetHistory();
+ expect(history.canUndo).toBe(false);
+ expect(history.canRedo).toBe(false);
+ });
+
+ it('walks back and forward through cell edits', () => {
+ const history = createSheetHistory();
+ history.record(cellsEntry([edit(0)]));
+ history.record(cellsEntry([edit(1)]));
+
+ const back = history.undo();
+ expect(back.direction).toBe('backward');
+ expect(back.entry.edits[0].row).toBe(1);
+ expect(history.canRedo).toBe(true);
+
+ const forward = history.redo();
+ expect(forward.direction).toBe('forward');
+ expect(forward.entry.edits[0].row).toBe(1);
+ expect(history.canRedo).toBe(false);
+ });
+
+ it('undoes all the way back to the table as it was opened', () => {
+ const history = createSheetHistory();
+ history.record(cellsEntry([edit(0)]));
+ expect(history.undo()).not.toBeNull();
+ expect(history.canUndo).toBe(false);
+ expect(history.undo()).toBeNull();
+ });
+
+ it('drops the redone tail when a new edit forks the timeline', () => {
+ const history = createSheetHistory();
+ history.record(cellsEntry([edit(0)]));
+ history.record(cellsEntry([edit(1)]));
+ history.undo();
+ history.record(cellsEntry([edit(2)]));
+
+ expect(history.canRedo).toBe(false);
+ expect(history.undo().entry.edits[0].row).toBe(2);
+ });
+
+ it('records nothing for an edit that changed nothing', () => {
+ const history = createSheetHistory();
+ expect(history.record(cellsEntry([]))).toBe(false);
+ expect(history.record(snapshotEntry('{"a":1}', '{"a":1}'))).toBe(false);
+ expect(history.canUndo).toBe(false);
+ });
+});
+
+describe('a structural step', () => {
+ it('reverses like any other, because it keeps both sides', () => {
+ // The reason a snapshot carries `before` as well as `after`: undoing an added
+ // column has to land on a table, and the entry is the only thing that holds it.
+ const history = createSheetHistory();
+ history.record(snapshotEntry('{"columns":["id"]}', '{"columns":["id","New"]}'));
+
+ const back = history.undo();
+ expect(back.entry.before).toBe('{"columns":["id"]}');
+ expect(history.redo().entry.after).toBe('{"columns":["id","New"]}');
+ });
+
+ it('interleaves with cell edits in one stack', () => {
+ const history = createSheetHistory();
+ history.record(cellsEntry([edit(0)]));
+ history.record(snapshotEntry('a', 'b'));
+ history.record(cellsEntry([edit(1)]));
+
+ expect(history.undo().entry.kind).toBe('cells');
+ expect(history.undo().entry.kind).toBe('snapshot');
+ expect(history.undo().entry.kind).toBe('cells');
+ expect(history.canUndo).toBe(false);
+ });
+});
+
+describe('the bound', () => {
+ it('weighs a cell edit at a fraction of a whole table', () => {
+ expect(weigh(cellsEntry([edit(0)]))).toBeLessThan(weigh(snapshotEntry('x'.repeat(400), '')));
+ });
+
+ it('lets hundreds of typed cells stay undoable where snapshots would not', () => {
+ // The whole reason this module exists. A twenty-thousand-row sheet serialises to
+ // megabytes, so a snapshot per keystroke buys a three-step undo; a patch per
+ // keystroke buys the afternoon.
+ const history = createSheetHistory({ budget: 20_000 });
+ for (let index = 0; index < 300; index += 1) history.record(cellsEntry([edit(index)]));
+ expect(history.size).toBe(300);
+
+ const snapshots = createSheetHistory({ budget: 20_000 });
+ for (let index = 0; index < 300; index += 1) {
+ snapshots.record(snapshotEntry('x'.repeat(10_000), 'y'.repeat(10_000)));
+ }
+ expect(snapshots.size).toBe(1);
+ });
+
+ it('drops the oldest steps and keeps the newest reversible', () => {
+ const history = createSheetHistory({ budget: 128 });
+ for (let index = 0; index < 10; index += 1) history.record(cellsEntry([edit(index)]));
+ expect(history.size).toBeLessThan(10);
+ // Whatever survived still steps back exactly, which is the guarantee: what a
+ // trim costs is depth, never a wrong state.
+ expect(history.undo().entry.edits[0].row).toBe(9);
+ });
+
+ it('reclaims what a dropped redo tail was holding', () => {
+ // Two 300-character steps fit in 640; a third would not. Forking away the second
+ // has to give its weight back, or the small step replacing it evicts the first —
+ // an undo stack that shrinks every time someone changes their mind.
+ const history = createSheetHistory({ budget: 640 });
+ history.record(snapshotEntry('x'.repeat(150), 'y'.repeat(150)));
+ history.record(snapshotEntry('a'.repeat(150), 'b'.repeat(150)));
+ expect(history.size).toBe(2);
+
+ history.undo();
+ history.record(cellsEntry([edit(0)]));
+ expect(history.size).toBe(2);
+ });
+
+ it('forgets everything when the sheet is reloaded from disk', () => {
+ const history = createSheetHistory();
+ history.record(cellsEntry([edit(0)]));
+ history.reset();
+ expect(history.canUndo).toBe(false);
+ expect(history.canRedo).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/sheetLinks.js b/frontend/src/lib/sheetLinks.js
new file mode 100644
index 0000000..438d4cb
--- /dev/null
+++ b/frontend/src/lib/sheetLinks.js
@@ -0,0 +1,94 @@
+/**
+ * Whether a column of sources still answers.
+ *
+ * Most of a worklist is links: the post a claim rests on, the channel it came from, the
+ * archive copy somebody made. They rot, and nothing in the grid said which ones already
+ * had — so a finding could be published on a source that had been gone for a month, and
+ * the only way to know was to open four hundred tabs.
+ *
+ * Distinct addresses rather than rows, because eleven rows sourced to one channel hold one
+ * address eleven times, and asking that host eleven times would be the rudest way to learn
+ * one fact. The answers come back per address and are spread over the rows holding it.
+ *
+ * The request is the only part of a sheet that leaves the machine, and it goes on a press:
+ * `engine/sheetlinks.py` is where the verdict is made and what the five states mean.
+ */
+
+import { api } from './api.js';
+import { urlsIn } from './sheet.js';
+
+/** How many addresses travel in one request. Mirrors `engine/sheetlinks.MAX_LINKS`: the
+ * column is walked in chunks so the pass can show progress and be stopped half way. */
+export const CHUNK = 25;
+
+/**
+ * The distinct addresses one column holds, each with the rows holding it.
+ *
+ * Read over the rows given — the ones on screen — for the same reason the cleaning passes
+ * and the number footers are: a filter narrowed to the twelve rows left to check is the
+ * question being asked, and checking all four hundred answers a different one.
+ */
+export function urlsInColumn(table, columnIndex, rows) {
+ const found = new Map();
+ for (const index of rows ?? []) {
+ const row = table?.rows?.[index];
+ if (!row) continue;
+ for (const url of urlsIn(row[columnIndex])) {
+ if (!found.has(url)) found.set(url, { url, rows: [] });
+ const entry = found.get(url);
+ if (entry.rows.at(-1) !== index) entry.rows.push(index);
+ }
+ }
+ return [...found.values()];
+}
+
+/** A list cut into the batches the route takes. */
+export function chunk(list, size = CHUNK) {
+ const out = [];
+ for (let at = 0; at < (list?.length ?? 0); at += size) out.push(list.slice(at, at + size));
+ return out;
+}
+
+/** Ask about one batch. The answer is keyed by address, exactly as it was sent. */
+export async function checkLinks(caseId, sheetId, urls) {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${sheetId}/links/check`, { urls });
+ return answer.links ?? {};
+}
+
+/** The states worth acting on, in the order a reading lists them. `refused` is deliberately
+ * not among them: a 403 behind a login says nothing about whether the page is there. */
+const BAD = ['gone', 'unreachable'];
+
+/**
+ * What a sweep found, as the reading the grid draws: how many answered, which addresses
+ * did not, and the rows holding them.
+ *
+ * Rows rather than a bare count, because the answer has to land in the table — the point of
+ * knowing eleven sources are dead is painting those eleven rows.
+ */
+export function readVerdicts(entries, verdicts) {
+ const bad = [];
+ let ok = 0;
+ let refused = 0;
+ let skipped = 0;
+ for (const entry of entries ?? []) {
+ const verdict = verdicts?.[entry.url];
+ if (!verdict) continue;
+ if (verdict.state === 'ok') ok += 1;
+ else if (verdict.state === 'refused') refused += 1;
+ // Counted rather than folded into the bad ones: the batch ran out of its budget and
+ // never asked, which says nothing about the page. A sweep that quietly reported them
+ // as answered would be the worst of the five states.
+ else if (verdict.state === 'skipped') skipped += 1;
+ if (BAD.includes(verdict.state)) {
+ bad.push({ url: entry.url, rows: entry.rows, state: verdict.state, code: verdict.code ?? null });
+ }
+ }
+ return {
+ ok,
+ refused,
+ skipped,
+ bad: bad.sort((a, b) => b.rows.length - a.rows.length),
+ rows: [...new Set(bad.flatMap((entry) => entry.rows))],
+ };
+}
diff --git a/frontend/src/lib/sheetLinks.test.js b/frontend/src/lib/sheetLinks.test.js
new file mode 100644
index 0000000..8eb30b1
--- /dev/null
+++ b/frontend/src/lib/sheetLinks.test.js
@@ -0,0 +1,112 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const post = vi.fn();
+vi.mock('./api.js', () => ({ api: { post } }));
+
+const { CHUNK, checkLinks, chunk, readVerdicts, urlsInColumn } = await import('./sheetLinks.js');
+
+const TABLE = {
+ columns: ['id', 'Source'],
+ rows: [
+ ['r1', 'https://a.org/one'],
+ ['r2', 'seen on https://a.org/one and https://a.org/two'],
+ ['r3', 'nothing here'],
+ ['r4', 'https://a.org/two'],
+ ],
+};
+
+describe('the addresses one column holds', () => {
+ it('is distinct addresses, each carrying the rows holding it', () => {
+ // Eleven rows sourced to one channel hold one address eleven times, and asking that
+ // host eleven times would be the rudest way to learn one fact.
+ const found = urlsInColumn(TABLE, 1, [0, 1, 2, 3]);
+ expect(found.map((entry) => entry.url)).toEqual(['https://a.org/one', 'https://a.org/two']);
+ expect(found[0].rows).toEqual([0, 1]);
+ expect(found[1].rows).toEqual([1, 3]);
+ });
+
+ it('reads the rows it was given, which are the ones on screen', () => {
+ // A filter narrowed to the twelve rows left to check is the question being asked;
+ // checking all four hundred answers a different one.
+ expect(urlsInColumn(TABLE, 1, [3]).map((entry) => entry.url)).toEqual(['https://a.org/two']);
+ expect(urlsInColumn(TABLE, 1, [])).toEqual([]);
+ });
+});
+
+describe('walking a long column in batches', () => {
+ it('cuts the list the size the route takes', () => {
+ expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
+ expect(chunk([])).toEqual([]);
+ expect(chunk(null)).toEqual([]);
+ });
+
+ it('mirrors the cap the server holds, so a batch is never refused at the door', () => {
+ expect(CHUNK).toBe(25);
+ expect(chunk(Array.from({ length: 26 }, (_, n) => n))[0]).toHaveLength(25);
+ });
+
+ it('asks the sheet own route, and takes an empty answer as an empty answer', async () => {
+ post.mockResolvedValueOnce({ links: { 'https://a.org/one': { state: 'ok' } } });
+ expect(await checkLinks('case-a', 'e_sheet', ['https://a.org/one'])).toEqual({
+ 'https://a.org/one': { state: 'ok' },
+ });
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/sheets/e_sheet/links/check', {
+ urls: ['https://a.org/one'],
+ });
+
+ post.mockResolvedValueOnce({});
+ expect(await checkLinks('case-a', 'e_sheet', [])).toEqual({});
+ });
+});
+
+describe('what a sweep found', () => {
+ const entries = [
+ { url: 'https://a.org/live', rows: [0] },
+ { url: 'https://a.org/deleted', rows: [1, 2, 3] },
+ { url: 'https://a.org/behind-a-login', rows: [4] },
+ { url: 'https://a.org/nowhere', rows: [5] },
+ { url: 'https://a.org/unanswered', rows: [6] },
+ ];
+ const verdicts = {
+ 'https://a.org/live': { state: 'ok', code: 200 },
+ 'https://a.org/deleted': { state: 'gone', code: 404 },
+ 'https://a.org/behind-a-login': { state: 'refused', code: 403 },
+ 'https://a.org/nowhere': { state: 'unreachable', code: null },
+ };
+
+ it('counts what answered apart from what refused to say', () => {
+ // A 403 behind a login says nothing about whether the page is there, so folding it
+ // into "dead" is how a source gets thrown away for having a paywall.
+ const read = readVerdicts(entries, verdicts);
+ expect(read.ok).toBe(1);
+ expect(read.refused).toBe(1);
+ expect(read.bad.map((entry) => entry.state)).toEqual(['gone', 'unreachable']);
+ });
+
+ it('puts the address the most rows rest on first', () => {
+ expect(readVerdicts(entries, verdicts).bad[0].url).toBe('https://a.org/deleted');
+ });
+
+ it('hands back the rows to paint, deduplicated', () => {
+ // The point of knowing eleven sources are dead is painting those eleven rows.
+ expect(readVerdicts(entries, verdicts).rows).toEqual([1, 2, 3, 5]);
+ });
+
+ it('says nothing about an address the batch never got an answer for', () => {
+ const read = readVerdicts(entries, verdicts);
+ expect(read.bad.map((entry) => entry.url)).not.toContain('https://a.org/unanswered');
+ expect(readVerdicts([], {})).toEqual({ ok: 0, refused: 0, skipped: 0, bad: [], rows: [] });
+ });
+
+ it('counts the addresses the batch ran out of time for apart from the dead ones', () => {
+ // "We did not ask" is not a fact about the page, and a sweep that folded it into
+ // "answered" would report a column as checked when a third of it was not.
+ const read = readVerdicts(
+ [...entries, { url: 'https://a.org/late', rows: [7] }],
+ { ...verdicts, 'https://a.org/late': { state: 'skipped', code: null } },
+ );
+ expect(read.skipped).toBe(1);
+ expect(read.ok).toBe(1);
+ expect(read.bad.map((entry) => entry.url)).not.toContain('https://a.org/late');
+ });
+});
diff --git a/frontend/src/lib/sheetReading.fixture.json b/frontend/src/lib/sheetReading.fixture.json
new file mode 100644
index 0000000..5324c93
--- /dev/null
+++ b/frontend/src/lib/sheetReading.fixture.json
@@ -0,0 +1,52 @@
+{
+ "why": [
+ "One list of cells, read by both readers, with the one answer they must agree on.",
+ "The browser sorts and picks off a cell; the server dates a Claim off the same cell.",
+ "Two copies of a reader that only claim to mirror each other are two readers, and the",
+ "cell they disagree about is the one an analyst is promoting at that moment. The role",
+ "vocabularies were already gated this way; the readings were not, and they had drifted:",
+ "the server took 99:00 for an hour and the browser took 12:30:75 for a time.",
+ "Read by tests/test_sheets.py and by lib/sheetRoles.test.js. Compared on the fields both",
+ "sides answer: a when's shape and canonical text, a point's numbers and its decimals."
+ ],
+ "when": [
+ { "cell": "01:57", "reads": { "shape": "time", "text": "01:57" } },
+ { "cell": "23:59:59", "reads": { "shape": "time", "text": "23:59" } },
+ { "cell": "12:30:75", "reads": null },
+ { "cell": "24:00", "reads": null },
+ { "cell": "31/01/2026", "reads": { "shape": "moment", "text": "2026-01-31" } },
+ {
+ "cell": "01/02/2026",
+ "role": { "dayFirst": false },
+ "reads": { "shape": "moment", "text": "2026-01-02" }
+ },
+ { "cell": "29/02/2025", "reads": null },
+ { "cell": "03/01/26 06:42", "reads": { "shape": "moment", "text": "2026-01-03T06:42" } },
+ { "cell": "2026-01-03 01:57", "reads": { "shape": "moment", "text": "2026-01-03T01:57" } },
+ { "cell": "03/01/2026 99:00", "reads": null },
+ { "cell": "03/01/2026 12:30:75", "reads": null },
+ {
+ "cell": "Sat, 03 Jan 2026 06:42:02 GMT",
+ "reads": { "shape": "moment", "text": "2026-01-03T06:42" }
+ },
+ { "cell": "?", "reads": null },
+ { "cell": "", "reads": null }
+ ],
+ "point": [
+ { "cell": "48.8566, 2.3522", "reads": { "lat": 48.8566, "lon": 2.3522, "decimals": 4 } },
+ { "cell": "48.8566,2.3522", "reads": { "lat": 48.8566, "lon": 2.3522, "decimals": 4 } },
+ { "cell": "48,8566; 2,3522", "reads": { "lat": 48.8566, "lon": 2.3522, "decimals": 4 } },
+ { "cell": "48,8566 2,3522", "reads": { "lat": 48.8566, "lon": 2.3522, "decimals": 4 } },
+ { "cell": "48.8566N 2.3522E", "reads": { "lat": 48.8566, "lon": 2.3522, "decimals": 4 } },
+ { "cell": "48.8566S 2.3522W", "reads": { "lat": -48.8566, "lon": -2.3522, "decimals": 4 } },
+ {
+ "cell": "48°51'24\"N 2°21'08\"E",
+ "reads": { "lat": 48.8566667, "lon": 2.3522222, "decimals": 4 }
+ },
+ { "cell": "48,8", "reads": null },
+ { "cell": "-1,5", "reads": null },
+ { "cell": "48,8566", "reads": null },
+ { "cell": "not a point", "reads": null },
+ { "cell": "", "reads": null }
+ ]
+}
diff --git a/frontend/src/lib/sheetRoles.js b/frontend/src/lib/sheetRoles.js
new file mode 100644
index 0000000..527bde2
--- /dev/null
+++ b/frontend/src/lib/sheetRoles.js
@@ -0,0 +1,1186 @@
+/**
+ * What a sheet's column can know about itself.
+ *
+ * The rule this module exists to serve, and never to break:
+ *
+ * > The CSV keeps **the words**. A status, a list of values, a quantity, a lat/lon are
+ * > text a spreadsheet shows as it found them. The sidecar keeps **what the app knows
+ * > about the column** — its role, its vocabulary, its separator, its unit. Losing the
+ * > sidecar costs chips and colours, never a finding.
+ *
+ * So nothing here rewrites a cell. Everything here *reads* one, and every reader is
+ * allowed to fail: `To be found` in a coordinates column, `?` in a date column and
+ * `OK en cours` outside a status vocabulary are what the real binders hold on every
+ * page. A role that refused them would refuse the work, so a role is a lens, never a
+ * validator — the value stays, it is shown as it is, and the filter can still find it.
+ *
+ * Pure: text in, readings out. No DOM, no case, no fetch, and no import from
+ * `lib/sheet.js` — that one imports this, and the arrow points one way.
+ */
+
+/** Every role a column may hold. Mirrors `engine/sheetroles.ROLE_KINDS`. `url` is the
+ * column a promotion files as sources, `row` points at another row of the same sheet,
+ * `offset` carries a time relative to a named anchor.
+ *
+ * `locked` is the odd one: a column whose text the **app** owns and the analyst reads. It
+ * exists because a sheet built out of the case is a view of the case, and a view somebody
+ * can type over is a view that starts lying the first time they do. Unlike `stamped` and
+ * `computed` it carries a link — the point of those columns is that the cell opens the
+ * entity — so `linkable()` admits it where it refuses every other role. */
+export const ROLE_KINDS = [
+ 'state',
+ 'choice',
+ 'boolean',
+ 'number',
+ 'latlon',
+ 'when',
+ 'picture',
+ 'url',
+ 'row',
+ 'offset',
+ 'stamped',
+ 'computed',
+ 'locked',
+];
+
+/** What a cell of a `picture` column has to hold before anything is drawn from it: an
+ * address, not somebody's filename. A path off another disk is a picture nobody but them
+ * can see, and drawing a broken frame for it would say the cell was wrong when it is
+ * merely elsewhere. */
+const PICTURE_URL = /\bhttps?:\/\/[^\s<>"'()[\]]+/i;
+
+/** Addresses that end in something a browser draws. Used to *suggest* the role — a URL
+ * with no extension is an image often enough that a declared column does not consult
+ * this — and to recognise a file **inside the case**, where there is no host to ask. */
+const IMAGE_PATH = /\.(?:jpe?g|png|gif|webp|avif|bmp|svg)(?:[?#].*)?$/i;
+
+/** The picture one cell points at, or null. The first address it holds: a cell carrying
+ * a photo and its archive copy is one row of work, and a strip of two thumbnails in a
+ * cell thirty pixels tall would be neither. */
+export function pictureUrl(cell) {
+ const found = String(cell ?? '').match(PICTURE_URL);
+ return found ? found[0].replace(/[.,;:!?]+$/, '') : null;
+}
+
+/**
+ * A cell of a picture column read as **a file of this case**, or null.
+ *
+ * The gap this closes was the plainest one in the tool: a geolocation index is worked on
+ * the images the case already holds, and a picture column that only understood `http`
+ * could draw a stranger's photo and not the case's own. The Notebook could already cite
+ * case media; the grid could not.
+ *
+ * A case-relative path and nothing else — no scheme, no leading slash, no `..` — because
+ * the cell is text a collaborator will read in a spreadsheet and `media/quai-sud.jpg` is
+ * the only spelling that means the same thing to them as to the app. Anything absolute is
+ * refused rather than drawn: it names a disk this case does not travel with.
+ */
+export function picturePath(cell) {
+ const body = String(cell ?? '').trim();
+ if (!body || /^[a-z]+:/i.test(body) || body.startsWith('/') || body.startsWith('\\')) return null;
+ if (body.includes('..') || /[\r\n\t]/.test(body)) return null;
+ const path = body.replace(/\\/g, '/');
+ return IMAGE_PATH.test(path) ? path : null;
+}
+
+/**
+ * How a picture cell is drawn: an address to fetch, or a file to read out of the case.
+ *
+ * One answer for both, so the grid asks once and the two cannot drift into two rules about
+ * what a picture is. `kind` is what decides whether anything leaves the machine.
+ */
+export function pictureRef(cell) {
+ const url = pictureUrl(cell);
+ if (url) return { kind: 'url', value: url };
+ const path = picturePath(cell);
+ return path ? { kind: 'case', value: path } : null;
+}
+
+/** The state vocabulary a column starts with. Ordered, least done first: that order
+ * *is* the ranking the sort reads, so reordering the list reorders the column. */
+export const STATE_DEFAULTS = ['to do', 'in progress', 'done', 'ruled out'];
+
+/** And the colour each of those four is painted, because a worklist is read at a glance
+ * before it is read row by row: nothing started grey, work in flight blue, settled
+ * green, eliminated red. Seeded when a state column is born and the analyst's from then
+ * on — the defaults sit *under* what the role declares, so clearing the green off `done`
+ * clears it for good. Mirrors `engine/sheetroles.STATE_COLOURS`. */
+export const STATE_COLOURS = {
+ 'to do': 'grey',
+ 'in progress': 'blue',
+ 'done': 'green',
+ 'ruled out': 'red',
+};
+
+/** The two words a boolean column starts with, in that order: yes first, so the sort puts
+ * what is true above what is not. Capitals because that is how the binders write them, and
+ * because `computed` writes the same pair — one column of `YES`/`NO` in the file, whether
+ * the app filled it or the analyst did. */
+export const BOOLEAN_DEFAULTS = ['YES', 'NO'];
+
+/** The colours the grid offers, for a row and for a chip alike. Mirrors
+ * `engine/sheets.ROW_COLOURS`, and `lib/sheet.js` re-exports it so there is one list on
+ * this side. Drawn from the annotation palette, never the amber accent: that one means
+ * selection, and a value painted with it would read as a selected value. */
+export const ROW_COLOURS = ['red', 'orange', 'yellow', 'green', 'blue', 'grey'];
+
+/** What a multi-value column is split on unless the analyst says otherwise. The
+ * binders' own separator, comma-space, which is also what a spreadsheet's own
+ * concatenations produce. */
+export const DEFAULT_SEPARATOR = ', ';
+
+/** The three things a `when` column can hold, which are the three the binders write: a
+ * date, a bare time of day whose date lives in the sheet's title, or both together. */
+export const WHEN_SHAPES = ['date', 'time', 'datetime'];
+
+/** The one answer a number column's footer gives. Asked rather than assumed: a total is
+ * what a column of counts wants and nonsense on a column of percentages, and a column
+ * of years wants neither. Mirrors `engine/sheetroles.NUMBER_SUMMARIES`. */
+export const NUMBER_SUMMARIES = ['none', 'count', 'sum', 'mean', 'range'];
+
+/** How long a unit may be. `%`, `€`, `km`, `rounds` — a label, not a sentence. */
+const MAX_UNIT = 8;
+
+/** How long a synchronisation anchor may be named. `IGLA launch`, `second impact` — read
+ * in a heading and in a Claim's reasoning, so a phrase and not a note. Mirrors
+ * `engine/sheetroles.MAX_ANCHOR_NAME`. */
+export const MAX_ANCHOR_NAME = 60;
+
+/** How many anchors one sheet may declare. An event has a handful of moments several
+ * videos can be lined up on; past that the sheet is a transcript. */
+export const MAX_ANCHORS = 12;
+
+/**
+ * What a computed column may be. Mirrors `engine/sheetroles.COMPUTED_NATURES`.
+ *
+ * `has_point` is the one the binders' `On map: YES/NO` actually meant: not "this row
+ * points at something" but "the thing it points at has a place". A brigade points at an
+ * entity and is not on a map.
+ *
+ * The other two are the number a **comparison grid** needs and had no way to get. This
+ * app has no formulas on purpose — a spreadsheet's second copy of the case is exactly what
+ * a sheet is not — but eleven candidates against six criteria asks one arithmetic question
+ * and asks it constantly: how far is this row done (`filled_of`), and how many of its
+ * criteria are met (`yes_of`). They are computed on the **server** like the other one,
+ * because a computed column is written into the CSV and the collaborator opening the file
+ * is owed the number rather than an empty column.
+ *
+ * `point` and `relations` are what `has_point` is not. It answers *whether* the case knows
+ * the row's subject; those two answer **what it knows** — the coordinates, and the entities
+ * at the far end of its edges. Without them a column pointed at the case said nothing about
+ * the case, so the coordinates and the parent unit went on being copied by hand into the
+ * column alongside, which is the retyping the whole bridge exists to end.
+ *
+ * `in_case` is the only one that reads `built` rather than `links`, because it is the only
+ * one asking about an entity that may be **gone**: a link naming something deleted is swept
+ * on the next read, so by the time anyone asks, the cell that would have answered is blank.
+ * The row that lost its proof is exactly the row worth finding.
+ */
+export const COMPUTED_NATURES = [
+ 'has_point',
+ 'filled_of',
+ 'yes_of',
+ 'point',
+ 'relations',
+ 'in_case',
+];
+
+/** The natures that count over a chosen set of columns rather than asking the graph. */
+export const COUNTING_NATURES = ['filled_of', 'yes_of'];
+
+/** The natures that follow **one named column's** link and restate what the case holds
+ * at the end of it. Named rather than swept, because a sheet may point at the case from
+ * a subject column and a place column both, and "whatever this row points at" would
+ * answer about whichever the walk reached first. */
+export const LINKED_NATURES = ['point', 'relations'];
+
+/** How many columns one of those may read. Mirrors `engine/sheetroles.MAX_COUNTED_COLUMNS`:
+ * a score over sixty columns is not a score. */
+export const MAX_COUNTED_COLUMNS = 24;
+
+/** How many distinct values a column may hold and still read as a set of answers.
+ * Mirrors `lib/sheet.js`'s own bound on the values a filter menu offers. */
+const MAX_CHOICE_VALUES = 40;
+
+function blank(value) {
+ return !String(value ?? '').trim();
+}
+
+/** What a yes and a no look like across the spellings the binders use. Read by detection —
+ * once a column is a boolean, its own two words are the ones that count — and by a
+ * `yes_of` score, for the columns nobody declared. Mirrors `engine/sheetroles.YES_WORDS`. */
+export const YES_WORDS = new Set(['yes', 'y', 'true', 'oui', 'x', '1', 'ok', 'done']);
+const NO_WORDS = new Set(['no', 'n', 'false', 'non', '-', '0', 'ko']);
+
+// -- the role record ----------------------------------------------------------
+
+/**
+ * One column's role, reduced to the fields its kind actually uses.
+ *
+ * Fields a kind does not use are dropped rather than carried: a column that was a
+ * `choice` and became a `when` would otherwise keep a vocabulary nobody reads, and the
+ * next reader would wonder which of the two the column is.
+ */
+export function normalizeRole(role) {
+ const kind = ROLE_KINDS.includes(role?.kind) ? role.kind : null;
+ if (!kind) return null;
+ const clean = { kind };
+ if (kind === 'state' || kind === 'choice' || kind === 'boolean') {
+ const values = Array.isArray(role.values)
+ ? [...new Set(role.values.map((value) => String(value)).filter((value) => value !== ''))]
+ : [];
+ clean.values = values.slice(0, MAX_CHOICE_VALUES);
+ // A state column nobody has said anything about is born with the four words and the
+ // four colours together: the words alone would be a status column that reads as grey
+ // text, and painting four chips by hand is the kind of setup a default is for.
+ const born = kind === 'state' && !clean.values.length;
+ if (born) clean.values = [...STATE_DEFAULTS];
+ // Exactly two, because that is what makes one click a toggle rather than a menu. A
+ // third word would leave the cell with nowhere to go next.
+ if (kind === 'boolean') {
+ clean.values = clean.values.slice(0, 2);
+ while (clean.values.length < 2) clean.values.push(BOOLEAN_DEFAULTS[clean.values.length]);
+ // How the cell is drawn, and nothing more. A tick column is a yes/no column: the
+ // file still holds the two words, the sort still reads them, the filter still
+ // finds them. Its own kind would have been a second copy of all of that for a
+ // difference of one glyph — and a column whose file said nothing readable.
+ clean.tick = Boolean(role.tick);
+ }
+ // A colour per value, kept apart from the values themselves: the value is what a cell
+ // is matched against, so it must stay exactly the word the file holds. What the role
+ // says wins over the birth colours, value by value, so a colour can be changed and a
+ // colour can be removed.
+ clean.colours = Object.fromEntries(
+ Object.entries({ ...(born ? STATE_COLOURS : {}), ...(role.colours ?? {}) }).filter(
+ ([value, colour]) => clean.values.includes(value) && ROW_COLOURS.includes(colour),
+ ),
+ );
+ }
+ if (kind === 'choice') {
+ // Whether one cell may hold several values, and what they are written between. A
+ // separator or nothing: reading a quantity out of `2x S-125` used to live here too,
+ // and it was a count kept in a column of values — a count belongs in a number column
+ // beside a column saying what is being counted.
+ clean.multi = typeof role.multi === 'string' && role.multi ? role.multi : null;
+ }
+ if (kind === 'number') {
+ // What follows the number when it is written out — `%`, `€`, `km`. A unit rather
+ // than a list of formats: a percentage and a currency differ by the sign after the
+ // digits, and an enum of five would have had to grow a sixth the first time a
+ // column held tonnes.
+ clean.unit = typeof role.unit === 'string' ? role.unit.trim().slice(0, MAX_UNIT) : '';
+ // Where it is written. Beside the heading always, since that is where a spreadsheet
+ // puts it and the file holds the digits alone; after every cell only when the column
+ // says so, because `40 %` reads as the value where four hundred repeated `km` read
+ // as noise.
+ clean.unitInCells = Boolean(role.unitInCells);
+ // Which one answer the footer gives. `sum` is what a count column wants and the
+ // wrong answer for a column of percentages, which is exactly why it is asked.
+ clean.summary = NUMBER_SUMMARIES.includes(role.summary) ? role.summary : 'sum';
+ }
+ if (kind === 'when') {
+ // Which of the three the column holds. Declared rather than inferred on every read:
+ // the analyst can say "these are times" about a column that is still empty, and an
+ // inferred shape would flip under them as the first rows are filled.
+ clean.shape = WHEN_SHAPES.includes(role.shape) ? role.shape : 'date';
+ // Which number a slash date leads with. Guessing silently reverses twelve days a
+ // month, and the binders read `dd/MM/yyyy`, so that is the default and it is
+ // stated rather than inferred.
+ clean.dayFirst = role.dayFirst === undefined ? true : Boolean(role.dayFirst);
+ }
+ if (kind === 'row') {
+ // Which column's words name the other row. The binders' `Links with others` held
+ // unit names, and that is kept: a file whose links read `r7f3a` is a file the
+ // collaborator opening it cannot follow. Null means the first column that is not
+ // the key, resolved where the table is known.
+ clean.of = typeof role.of === 'string' && role.of ? role.of : null;
+ // A brigade lists several companies, so a cell holds several names.
+ clean.multi = typeof role.multi === 'string' && role.multi ? role.multi : null;
+ }
+ if (kind === 'offset') {
+ // Which anchor the cell is counted from. One column per anchor and no syntax in the
+ // cell: the binders held `start synchro` *and* `end synchro`, so a single anchor per
+ // sheet would not have survived the first real event.
+ clean.anchor = typeof role.anchor === 'string' ? role.anchor.trim().slice(0, MAX_ANCHOR_NAME) : '';
+ }
+ if (kind === 'computed') {
+ clean.of = COMPUTED_NATURES.includes(role.of) ? role.of : COMPUTED_NATURES[0];
+ if (COUNTING_NATURES.includes(clean.of)) {
+ // Which columns it counts, in the order they were chosen: the number does not
+ // depend on it, but the panel lists them back and a list that reshuffles itself
+ // reads as a different answer.
+ clean.columns = [...new Set((Array.isArray(role.columns) ? role.columns : []).map(String))]
+ .filter(Boolean)
+ .slice(0, MAX_COUNTED_COLUMNS);
+ }
+ if (LINKED_NATURES.includes(clean.of)) {
+ clean.from = typeof role.from === 'string' && role.from ? role.from : null;
+ }
+ if (clean.of === 'relations') {
+ clean.multi = typeof role.multi === 'string' && role.multi ? role.multi : DEFAULT_SEPARATOR;
+ }
+ }
+ return clean;
+}
+
+/** How a counting column reads in a heading or a footer: `3 of 6`, or nothing when it has
+ * been told to read no columns. Said once here, because the number in the cell is bare —
+ * the denominator repeated down four hundred rows would be four hundred copies of one
+ * fact. */
+export function countedOf(role) {
+ return COUNTING_NATURES.includes(role?.of) ? (role.columns?.length ?? 0) : 0;
+}
+
+/** The colour a value's chip is painted, or null for the neutral one. */
+export function valueColour(role, value) {
+ return role?.colours?.[value] ?? null;
+}
+
+/**
+ * A vocabulary with one value moved, added, renamed, painted or dropped.
+ *
+ * One function rather than five, because every one of them is the same edit — a list and
+ * a colour map, out the other side — and because the **order is the ranking** the sort
+ * reads. That is why nothing here sorts on its own: `to do → in progress → done` is the
+ * order of the work, and an editor that alphabetised it would have put `done` first.
+ *
+ * `at` is where the value is now; `to` is where it goes, or -1 to drop it. A value that
+ * is not in the list yet is appended.
+ */
+export function editVocabulary(role, { value, at = -1, to = null, colour = undefined }) {
+ const values = [...(role?.values ?? [])];
+ const colours = { ...(role?.colours ?? {}) };
+ const name = String(value ?? '').trim();
+ const from = at >= 0 ? at : values.indexOf(name);
+
+ if (to === -1) {
+ if (from === -1) return { values, colours };
+ delete colours[values[from]];
+ values.splice(from, 1);
+ return { values, colours };
+ }
+ if (from === -1) {
+ if (!name || values.includes(name)) return { values, colours };
+ values.push(name);
+ } else if (name && values[from] !== name) {
+ // A rename carries the colour with it: the colour belongs to the answer, not to the
+ // characters, and a value fixed for a typo that lost its paint reads as a new one.
+ if (values.includes(name)) return { values, colours };
+ const painted = colours[values[from]];
+ delete colours[values[from]];
+ values[from] = name;
+ if (painted) colours[name] = painted;
+ }
+ if (to !== null && to !== -1 && from !== -1) {
+ const moved = values.splice(from, 1);
+ values.splice(Math.max(0, Math.min(values.length, to)), 0, ...moved);
+ }
+ if (colour !== undefined) {
+ const target = name || values[from];
+ if (colour && ROW_COLOURS.includes(colour)) colours[target] = colour;
+ else delete colours[target];
+ }
+ return { values, colours };
+}
+
+/** The same values, ordered by their words. Asked for by name and never applied on its
+ * own: a state column's order is the order of the work, not the alphabet. */
+export function sortVocabulary(role, { desc = false } = {}) {
+ const values = [...(role?.values ?? [])].sort((a, b) =>
+ a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }),
+ );
+ return { values: desc ? values.reverse() : values, colours: { ...(role?.colours ?? {}) } };
+}
+
+/**
+ * A column's vocabulary against what its cells actually say.
+ *
+ * Three answers a worklist needs and the textarea could not give: how many rows hold each
+ * declared value, which declared values nothing uses, and which values the cells hold
+ * that the vocabulary has never heard of. The third is the one that matters on an
+ * imported binder — `OK en cours` sitting outside a list of four that were never in this
+ * file — and it is offered rather than corrected, because the file keeps the words.
+ */
+export function vocabularyUse(table, columnIndex, role) {
+ const totals = valueTotals(table, columnIndex, role) ?? [];
+ const held = new Map(totals.map((entry) => [entry.value, entry]));
+ const declared = role?.values ?? [];
+ const known = new Set(declared);
+ return {
+ counts: Object.fromEntries(declared.map((value) => [value, held.get(value)?.rows ?? 0])),
+ unused: declared.filter((value) => !(held.get(value)?.rows ?? 0)),
+ outside: totals.filter((entry) => entry.value && !known.has(entry.value)),
+ };
+}
+
+/**
+ * What a column looks like it holds, as a suggestion.
+ *
+ * Offered, never applied: the menu shows it and the analyst confirms, because a role
+ * imposed by a guess is a role that has to be undone before the work can start. Only
+ * the three readings a machine can be sure of are guessed — a point, a moment, a small
+ * closed set. A **state** is never guessed: whether `pass` means done or means skipped
+ * is a judgement about the investigation, not about the characters in the cell.
+ */
+export function detectRole(values) {
+ const filled = (values ?? []).map((value) => String(value ?? '').trim()).filter(Boolean);
+ if (filled.length < 2) return null;
+ const share = (test) => filled.filter(test).length / filled.length;
+ // Two thirds rather than all of them: the binders' columns are half-finished by
+ // definition, and a column of coordinates with `To be found` in a third of its rows is
+ // still a column of coordinates.
+ if (share((value) => parseLatLon(value)) >= 0.66) return 'latlon';
+ if (share((value) => parseWhen(value)) >= 0.66) return 'when';
+ // Suggested off the extension alone, and never off "it is a URL": a column of sources
+ // is URLs too, and turning one into a wall of thumbnails would fetch forty pages the
+ // analyst never asked for.
+ if (share((value) => IMAGE_PATH.test(String(value))) >= 0.66) return 'picture';
+ const distinct = new Set(filled);
+ // Two words and both of them a yes or a no: `YES/NO`, `true/false`, `oui/non`, `x/-`.
+ // Two arbitrary words are a set of values, not a question with two answers.
+ if (
+ distinct.size === 2 &&
+ [...distinct].every((value) => YES_WORDS.has(value.toLowerCase()) || NO_WORDS.has(value.toLowerCase()))
+ ) {
+ return 'boolean';
+ }
+ if (distinct.size <= Math.min(MAX_CHOICE_VALUES, filled.length / 2)) return 'choice';
+ return null;
+}
+
+// -- numbers ------------------------------------------------------------------
+
+const NUMBER_CELL = /^[~≈<>±]?\s*([+-]?[\d\u00a0 ']*\d(?:[.,]\d+)?)\s*%?$/;
+
+/**
+ * A cell read as a number, or null.
+ *
+ * Strict on purpose. `1 234` and `12,5` are read, because a European export writes both,
+ * and a leading `~` or `>` is read because an estimate is still a number. `Only 9 in
+ * service?` is **not**: extracting a digit out of prose would also turn `AB-123` into 123,
+ * and a total built on that is a total nobody can check. What the role cannot read it
+ * reports, which is the honest half of the deal.
+ */
+export function parseNumber(text) {
+ const match = String(text ?? '').trim().match(NUMBER_CELL);
+ if (!match) return null;
+ const digits = match[1].replace(/[\u00a0 ']/g, '').replace(',', '.');
+ const value = Number(digits);
+ return Number.isFinite(value) ? value : null;
+}
+
+/**
+ * What a number column adds up to over the rows given, and what it could not read.
+ *
+ * Given **row indices**, not the table, and that is the whole point: the answer is about
+ * what is on screen. A sheet filtered to the twelve rows left to check should total those
+ * twelve, because the question being asked is about them.
+ *
+ * `unreadable` is the honest half of a role that lets a cell say `unknown`. A footer
+ * reading `20 over 2` on a column of fifteen rows was arithmetic nobody could check: the
+ * total is right, and it is right about two cells out of fifteen. The count is what says
+ * so, and the grid offers it as a filter.
+ */
+export function numberTotals(table, columnIndex, rowIndices) {
+ let count = 0;
+ let sum = 0;
+ let min = null;
+ let max = null;
+ let unreadable = 0;
+ for (const index of rowIndices ?? []) {
+ const cell = table.rows[index]?.[columnIndex];
+ const value = parseNumber(cell);
+ if (value === null) {
+ if (!blank(cell)) unreadable += 1;
+ continue;
+ }
+ count += 1;
+ sum += value;
+ min = min === null ? value : Math.min(min, value);
+ max = max === null ? value : Math.max(max, value);
+ }
+ // Floating point: `0.1 + 0.2` must not read as `0.30000000000000004` in a footer.
+ const tidy = (value) => (value === null ? null : Math.round(value * 1e6) / 1e6);
+ return {
+ count,
+ unreadable,
+ sum: tidy(sum),
+ mean: count ? tidy(sum / count) : null,
+ min: tidy(min),
+ max: tidy(max),
+ };
+}
+
+/**
+ * Whether the column's own lens can read this cell.
+ *
+ * The rule a role exists under is that it never refuses a cell — `To be found` in a
+ * coordinates column is what the real binders hold on every page. The cost of that is
+ * silence: a number column summing two cells out of fifteen looks exactly like one
+ * summing fifteen. This is the other half of the deal, and the grid spends it on a badge
+ * and a filter rather than on a refusal.
+ *
+ * An empty cell reads: blank is *unknown*, which is an answer, not a mistake.
+ */
+export function readsCell(role, cell) {
+ const body = String(cell ?? '').trim();
+ if (!body) return true;
+ const kind = role?.kind;
+ if (kind === 'number') return parseNumber(body) !== null;
+ if (kind === 'latlon') {
+ const point = parseLatLon(body);
+ return Boolean(point) && !point.outOfBounds;
+ }
+ if (kind === 'when') return parseWhen(body, role) !== null;
+ if (kind === 'picture') return pictureRef(body) !== null;
+ if (kind === 'offset') return parseOffset(body) !== null;
+ // Whether a row name finds its row is a question about the whole table, so it is
+ // answered where the table is (`lib/sheetRows.js`) and not here. Every cell reads.
+ if (kind === 'row') return true;
+ // A value outside the column's own words is readable in the sense that it is shown,
+ // and unreadable in the sense the analyst cares about: it is not one of the answers
+ // this column takes, so it is what "to check" means here.
+ if (isChipped(role)) return cellChips(body, role).every((chip) => chip.known);
+ return true;
+}
+
+/** How many of a column's filled cells its lens cannot read, over how many there are. */
+export function readable(table, columnIndex, role) {
+ let total = 0;
+ let read = 0;
+ for (const row of table?.rows ?? []) {
+ const cell = row[columnIndex];
+ if (blank(cell)) continue;
+ total += 1;
+ if (readsCell(role, cell)) read += 1;
+ }
+ return { total, read, unreadable: total - read };
+}
+
+// -- lat/lon ------------------------------------------------------------------
+
+const DECIMAL_PAIR =
+ /^\s*([+-]?\d{1,3}(?:[.,]\d+)?)\s*°?\s*([NnSs])?(\s*[,;/]\s*|\s+)([+-]?\d{1,3}(?:[.,]\d+)?)\s*°?\s*([EeWw])?\s*$/;
+const DMS =
+ /(\d{1,3})\s*°\s*(\d{1,2})?\s*['′]?\s*([\d.]+)?\s*["″]?\s*([NnSsEeWw])/g;
+
+function decimals(text) {
+ const at = String(text).replace(',', '.').indexOf('.');
+ return at === -1 ? 0 : String(text).length - at - 1;
+}
+
+function signed(value, hemisphere, negatives) {
+ const number = Number(String(value).replace(',', '.'));
+ return negatives.includes(String(hemisphere ?? '').toUpperCase()) ? -Math.abs(number) : number;
+}
+
+/**
+ * A cell read as a point, or null.
+ *
+ * Three shapes, because one binder column held all three: a decimal pair
+ * (`48.8566, 2.3522`), a decimal pair with hemispheres (`48.8566N 2.3522E`), and
+ * degrees-minutes-seconds (`48°51'24"N 2°21'08"E`).
+ *
+ * `decimals` is how precisely the cell was written, which is a claim about the ground:
+ * two decimals is about a kilometre, and a worklist full of two-decimal coordinates is
+ * a worklist of neighbourhoods presented as addresses. `outOfBounds` is reported rather
+ * than refused — a transposed pair is a finding about the file, not a parse failure.
+ *
+ * A comma is a decimal mark, so `48,8` is one number rather than two coordinates. It
+ * separates a pair only where it cannot be decimal: a space after it, a hemisphere letter,
+ * or a full stop already doing the job. Mirrors `engine/sheetroles.parse_latlon`.
+ */
+export function parseLatLon(text) {
+ const body = String(text ?? '').trim();
+ if (!body) return null;
+
+ const pair = body.match(DECIMAL_PAIR);
+ if (pair) {
+ const [, rawLat, latHem, separator, rawLon, lonHem] = pair;
+ if (separator === ',' && !body.includes('.') && !latHem && !lonHem) return null;
+ const lat = signed(rawLat, latHem, ['S']);
+ const lon = signed(rawLon, lonHem, ['W']);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ return {
+ lat,
+ lon,
+ decimals: Math.min(decimals(rawLat), decimals(rawLon)),
+ outOfBounds: Math.abs(lat) > 90 || Math.abs(lon) > 180,
+ };
+ }
+
+ const parts = [...body.matchAll(DMS)];
+ if (parts.length === 2) {
+ const read = parts.map(([, deg, min, sec, hem]) => {
+ const value = Number(deg) + Number(min ?? 0) / 60 + Number(sec ?? 0) / 3600;
+ return { value: signed(value, hem, ['S', 'W']), hem: String(hem).toUpperCase() };
+ });
+ const lat = read.find((entry) => 'NS'.includes(entry.hem));
+ const lon = read.find((entry) => 'EW'.includes(entry.hem));
+ if (!lat || !lon) return null;
+ // Seconds resolve to about thirty metres, which is five decimal places of
+ // confidence the writer did not claim; four is the honest reading.
+ return {
+ lat: lat.value,
+ lon: lon.value,
+ decimals: 4,
+ outOfBounds: Math.abs(lat.value) > 90 || Math.abs(lon.value) > 180,
+ };
+ }
+ return null;
+}
+
+/** About how far apart two points written to this many decimals could be, in metres.
+ * One degree of latitude is 111 320 m, so the last digit written is the uncertainty. */
+export function precisionMetres(places) {
+ return Math.round(111_320 * 10 ** -Math.max(0, places));
+}
+
+/** A point as one canonical string. The only function here that produces a cell rather
+ * than reading one, and it is never called on a save: normalising is an edit the
+ * analyst asks for, and it lands in the undo stack like any other. */
+export function formatLatLon(point, places = 5) {
+ if (!point) return '';
+ return `${point.lat.toFixed(places)}, ${point.lon.toFixed(places)}`;
+}
+
+const EARTH_M = 6_371_000;
+
+/** Metres between two points, on a sphere. Close enough at worklist distances, and it
+ * needs no projection to be right about "these two rows are the same place". */
+export function distanceMetres(a, b) {
+ const toRad = Math.PI / 180;
+ const dLat = (b.lat - a.lat) * toRad;
+ const dLon = (b.lon - a.lon) * toRad;
+ const lat1 = a.lat * toRad;
+ const lat2 = b.lat * toRad;
+ const h =
+ Math.sin(dLat / 2) ** 2 + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
+ return Math.round(2 * EARTH_M * Math.asin(Math.min(1, Math.sqrt(h))));
+}
+
+// -- offsets, and the anchor they are counted from ----------------------------
+
+const OFFSET = /^([+-]?)(?:(\d+):)?(\d{1,3}):(\d{2})(?:[.,](\d{1,3}))?$/;
+const BARE_SECONDS = /^([+-]?)(\d{1,5})(?:[.,](\d{1,3}))?\s*s?$/i;
+
+/**
+ * A cell read as seconds away from an anchor, or null. Mirrors
+ * `engine/sheetroles.parse_offset`.
+ *
+ * `-00:01:50`, `00:04:04`, `1:05` and a bare `-110` — the four spellings a video player
+ * and a spreadsheet between them produce. Negative means *before* the anchor, which is
+ * what the binders' leading minus already meant.
+ */
+export function parseOffset(text) {
+ const body = String(text ?? '').trim();
+ if (!body) return null;
+ const found = body.match(OFFSET);
+ if (found) {
+ const [, sign, hours, minutes, seconds, fraction] = found;
+ if (Number(seconds) > 59 || (hours !== undefined && Number(minutes) > 59)) return null;
+ const total =
+ Number(hours ?? 0) * 3600 + Number(minutes) * 60 + Number(seconds) + Number(`0.${fraction ?? 0}`);
+ return sign === '-' ? -total : total;
+ }
+ const bare = body.match(BARE_SECONDS);
+ if (!bare) return null;
+ const value = Number(bare[2]) + Number(`0.${bare[3] ?? 0}`);
+ return bare[1] === '-' ? -value : value;
+}
+
+/** Seconds written the way the binders write them, `-00:01:50`. One spelling out,
+ * several in: what the analyst typed stays in the cell. */
+export function formatOffset(seconds) {
+ const sign = seconds < 0 ? '-' : '';
+ const whole = Math.trunc(Math.abs(seconds));
+ const pad = (value) => String(value).padStart(2, '0');
+ return `${sign}${pad(Math.floor(whole / 3600))}:${pad(Math.floor(whole / 60) % 60)}:${pad(whole % 60)}`;
+}
+
+/**
+ * The absolute instant an offset lands on, as an ISO timestamp, or null.
+ *
+ * Drawn beside the cell so the relative column reads as an absolute time the moment the
+ * anchor is dated — and it stays a *reading*, never written into the cell: an inferred
+ * moment is a Claim, and `engine/sheetclaims.py` is the only thing that files one.
+ */
+export function offsetMoment(anchorAt, seconds) {
+ const at = Date.parse(String(anchorAt ?? ''));
+ if (!Number.isFinite(at) || seconds === null || seconds === undefined) return null;
+ return `${new Date(at + Math.round(seconds) * 1000).toISOString().slice(0, 19)}Z`;
+}
+
+// -- dates and times ----------------------------------------------------------
+
+const SLASH = /^(\d{1,4})[/.-](\d{1,2})[/.-](\d{2,4})(?:[ T]+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
+const CLOCK = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/;
+const MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
+const RFC = /^(?:\w{3},\s*)?(\d{1,2})\s+(\w{3})\w*\s+(\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?/i;
+
+/**
+ * A moment as milliseconds, or NaN when the calendar has no such day.
+ *
+ * `Date.UTC` rolls a bad day forward — `29/02/2025` comes back as 1 March — so a column
+ * holding an impossible date sorted as though it were the day after, silently. Checked
+ * rather than rolled, and it is also what keeps this reader and
+ * `engine/sheetroles.parse_when` answering the same thing about the same cell, which is
+ * what a Claim dated off a column depends on.
+ */
+/**
+ * Whether this is a time of day rather than one that rolls over into the next.
+ *
+ * `Date.UTC` takes 99:00 and moves the day instead of refusing, and 12:30:75 keeps the day
+ * it was given — so a cell the server refuses used to sort here without a word. Asked before
+ * the moment is built, exactly as `engine/sheetroles._holds` asks it.
+ */
+function clockHolds(hour, minute, second) {
+ return !(hour > 23 || minute > 59 || second > 59);
+}
+
+function utc(year, month, day, hour = 0, minute = 0, second = 0) {
+ const key = Date.UTC(year, month - 1, day, hour, minute, second);
+ const back = new Date(key);
+ const same =
+ back.getUTCFullYear() === year && back.getUTCMonth() === month - 1 && back.getUTCDate() === day;
+ return same ? key : NaN;
+}
+
+/**
+ * A cell read as a moment, or null.
+ *
+ * Everything the three binders wrote: `dd/MM/yyyy`, `yyyy-MM-dd`, a bare `hh:mm`,
+ * either with a time appended, and the full RFC form an email header carries
+ * (`Sat, 03 Jan 2026 06:42:02 GMT`).
+ *
+ * A bare clock is kept as a **time of day** rather than pinned to some arbitrary date:
+ * the binder's `Local time` column holds `01:57` for an event whose date lives in the
+ * sheet's title, and inventing a date for it would be inventing evidence. `shape` says
+ * which of the two a reading is, and `key` sorts within its own shape.
+ */
+export function parseWhen(text, role = {}) {
+ const body = String(text ?? '').trim();
+ if (!body) return null;
+ const dayFirst = role.dayFirst === undefined ? true : Boolean(role.dayFirst);
+
+ const clock = body.match(CLOCK);
+ if (clock) {
+ const [, hour, minute, second] = clock.map(Number);
+ if (!clockHolds(hour, minute, second)) return null;
+ return {
+ shape: 'time',
+ key: hour * 3600 + minute * 60 + (second || 0),
+ text: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
+ };
+ }
+
+ const rfc = body.match(RFC);
+ if (rfc) {
+ const month = MONTHS.indexOf(rfc[2].slice(0, 3).toLowerCase()) + 1;
+ if (month) {
+ if (!clockHolds(Number(rfc[4] ?? 0), Number(rfc[5] ?? 0), Number(rfc[6] ?? 0))) return null;
+ const key = utc(Number(rfc[3]), month, Number(rfc[1]), Number(rfc[4] ?? 0), Number(rfc[5] ?? 0), Number(rfc[6] ?? 0));
+ if (!Number.isFinite(key)) return null;
+ return { shape: 'moment', key, text: new Date(key).toISOString().slice(0, rfc[4] ? 16 : 10) };
+ }
+ }
+
+ const slash = body.match(SLASH);
+ if (slash) {
+ const [, one, two, three, hour, minute, second] = slash;
+ // A four-digit leading group can only be a year, whatever the column's convention.
+ const isoish = one.length === 4;
+ const year = Number(isoish ? one : three.length === 2 ? `20${three}` : three);
+ const day = Number(isoish ? three : dayFirst ? one : two);
+ const month = Number(isoish ? two : dayFirst ? two : one);
+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;
+ if (!clockHolds(Number(hour ?? 0), Number(minute ?? 0), Number(second ?? 0))) return null;
+ const key = utc(year, month, day, Number(hour ?? 0), Number(minute ?? 0), Number(second ?? 0));
+ if (!Number.isFinite(key)) return null;
+ return {
+ shape: 'moment',
+ key,
+ text: new Date(key).toISOString().slice(0, hour ? 16 : 10),
+ };
+ }
+ return null;
+}
+
+/**
+ * Which way round a column already writes its dates.
+ *
+ * Read from the column rather than declared, and that is the point: a picker that wrote
+ * `2026-01-31` into a column of `31/01/2026` would restyle the file from a click, and the
+ * file keeps the words. Ties go to the slash form, which is what the binders use.
+ */
+export function dateSpelling(values) {
+ let iso = 0;
+ let slash = 0;
+ for (const value of values ?? []) {
+ const body = String(value ?? '').trim();
+ if (/^\d{4}[/.-]\d{1,2}[/.-]\d{1,2}/.test(body)) iso += 1;
+ else if (/^\d{1,2}[/.-]\d{1,2}[/.-]\d{2,4}/.test(body)) slash += 1;
+ }
+ return iso > slash ? 'iso' : 'slash';
+}
+
+/**
+ * Which of the three shapes a `when` column actually holds.
+ *
+ * The role is called *a date or a time* because the binders write all three: a column of
+ * `dd/MM/yyyy`, a column of bare `01:57` local times whose date lives in the sheet's
+ * title, and a column of both together. Read from the column rather than declared, so the
+ * picker a cell offers is the one the column is written in — offering a calendar for a
+ * column of clocks would be offering to put a date where the analyst deliberately did not.
+ */
+export function whenShape(values) {
+ let times = 0;
+ let dated = 0;
+ let withHour = 0;
+ for (const value of values ?? []) {
+ const read = parseWhen(value);
+ if (!read) continue;
+ if (read.shape === 'time') times += 1;
+ else {
+ dated += 1;
+ if (read.text.includes('T')) withHour += 1;
+ }
+ }
+ if (times > dated) return 'time';
+ return withHour * 2 >= dated && withHour > 0 ? 'datetime' : 'date';
+}
+
+/** The input type a shape is picked with. One place, so the editor and any test agree. */
+export function pickerType(shape) {
+ return shape === 'time' ? 'time' : shape === 'datetime' ? 'datetime-local' : 'date';
+}
+
+/**
+ * A moment chosen from a picker, spelled the way this column spells moments.
+ *
+ * The picker hands over `HH:MM`, `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` whatever the locale;
+ * what lands in the cell is the column's own form, so picking in a `dd/MM/yyyy` column
+ * leaves it a `dd/MM/yyyy` column. On a date-only column an hour already in the cell is
+ * kept: `03/01/2026 06:42` is a moment somebody established, and a date picker has no
+ * business dropping the hour from it.
+ */
+export function spellWhen(picked, { shape = 'date', spelling = 'slash', keep = '' } = {}) {
+ const body = String(picked ?? '').trim();
+ if (!body) return '';
+ if (shape === 'time') return body.slice(0, 5);
+
+ const [datePart, timePart] = body.split('T');
+ const [year, month, day] = datePart.split('-');
+ if (!year || !month || !day) return '';
+ const date = spelling === 'iso' ? `${year}-${month}-${day}` : `${day}/${month}/${year}`;
+ if (shape === 'datetime') return timePart ? `${date} ${timePart.slice(0, 5)}` : date;
+ const clock = String(keep ?? '').match(/\b(\d{1,2}:\d{2}(?::\d{2})?)\b/);
+ return clock ? `${date} ${clock[1]}` : date;
+}
+
+// -- values, and how many of each ---------------------------------------------
+
+/** A cell as the values it holds. One value unless the column says it is a list.
+ * Mirrors `engine/sheetroles.split_values`. Two kinds hold lists and for the same
+ * reason: a `choice` cell holds three pieces of equipment, a `row` cell holds the three
+ * companies of a brigade. */
+export function splitValues(cell, role) {
+ const body = String(cell ?? '');
+ const separator = role?.kind === 'choice' || role?.kind === 'row' ? role.multi : null;
+ if (!separator) return blank(body) ? [] : [body.trim()];
+ return body
+ .split(separator)
+ .map((part) => part.trim())
+ .filter(Boolean);
+}
+
+/** A cell as chips: the value, how many of it, and whether the vocabulary knows it.
+ * An unknown value is a chip like any other — the binders write outside their own
+ * vocabulary constantly, and a lens that hid those would hide the work. */
+/** Whether a column draws its cells as chips: a closed set of answers, of any size —
+ * plus a `row` column, whose answers are the other rows of this sheet and read the same
+ * way, one name per chip. */
+export function isChipped(role) {
+ return ['state', 'choice', 'boolean', 'row'].includes(role?.kind);
+}
+
+/** The other of a boolean column's two words, for a cell that is clicked rather than
+ * edited. Anything outside the pair goes to the first: a cell holding `maybe` in a
+ * yes/no column is answered by clicking it, not by being left alone. */
+export function flipBoolean(role, value) {
+ const [yes, no] = role?.values ?? [];
+ return String(value ?? '').trim() === yes ? no : yes;
+}
+
+/**
+ * What a tick box holds after it is clicked: nothing → yes → no → nothing.
+ *
+ * Three states rather than two, and for the reason the sort control has three: a box
+ * is drawn on an **empty** cell as well as a filled one, so a two-state toggle would
+ * make *not answered yet* and *no* look identical and leave no way back to the first.
+ * On a worklist that is the difference between four hundred rows checked and four
+ * hundred rows nobody has opened.
+ *
+ * A word outside the pair answers yes, the way `flipBoolean` does: a cell holding
+ * `maybe` is settled by clicking it.
+ */
+export function cycleTick(role, value) {
+ const [yes, no] = role?.values ?? BOOLEAN_DEFAULTS;
+ const held = String(value ?? '').trim();
+ if (!held) return yes;
+ if (held === yes) return no;
+ if (held === no) return '';
+ return yes;
+}
+
+/** Whether a cell reads as this column's yes, its no, or neither. What the tick box
+ * draws, so the three states are decided in one place. */
+export function tickState(role, value) {
+ const [yes, no] = role?.values ?? BOOLEAN_DEFAULTS;
+ const held = String(value ?? '').trim();
+ if (!held) return 'blank';
+ if (held === yes) return 'yes';
+ if (held === no) return 'no';
+ return 'other';
+}
+
+export function cellChips(cell, role) {
+ const known = new Set(role?.values ?? []);
+ return splitValues(cell, role).map((value) => ({
+ value,
+ known: known.has(value),
+ colour: valueColour(role, value),
+ raw: value,
+ }));
+}
+
+/**
+ * Every value of a column, with how many rows hold it.
+ *
+ * One number, and it is the one a filter is about: *how many rows say `S-125`*. A cell
+ * holding the same value twice counts once, because the row is what the filter hands
+ * back. Nothing is cut here — `columnValues` pages the list, since how much of it fits a
+ * menu is the menu's question.
+ */
+export function valueTotals(table, columnIndex, role) {
+ const totals = new Map();
+ for (const row of table?.rows ?? []) {
+ for (const value of new Set(cellChips(row[columnIndex], role).map((chip) => chip.value))) {
+ const entry = totals.get(value) ?? { value, rows: 0 };
+ entry.rows += 1;
+ totals.set(value, entry);
+ }
+ }
+ return [...totals.values()].sort(
+ (a, b) => b.rows - a.rows || a.value.localeCompare(b.value),
+ );
+}
+
+// -- sorting ------------------------------------------------------------------
+
+/**
+ * What one cell is worth to a sort, computed once for the whole column.
+ *
+ * The comparator used to do this work itself, which meant `parseWhen` ran twice per
+ * comparison — a hundred and twelve thousand times on twenty thousand rows, and again on
+ * every keystroke, because the sorted view is derived from the table. Measured on a full
+ * sheet that was eight hundred milliseconds of blocked main thread per cell typed.
+ *
+ * So a key is read **once per row** and the comparator only orders keys. It is the same
+ * move the filters already make one function up ("compiled once per column rather than
+ * once per cell"); the sort had been left out of it.
+ *
+ * Three answers, and they are not the same:
+ *
+ * - an array of numbers — what the role read, most significant component first;
+ * - `null` — the role can read this column but not this cell, which sorts **after**
+ * the ones it can, so a date column puts `?` at the end rather than in mid-January;
+ * - `undefined` — this role does not order anything, and the caller compares words.
+ */
+export function sortKey(role, value) {
+ const kind = role?.kind;
+ if (kind === 'state' || kind === 'boolean') {
+ // The vocabulary's own order is the ranking: `to do` before `done` because that is
+ // how the analyst wrote the list, not because of how the words spell.
+ const at = (role.values ?? []).indexOf(String(value ?? '').trim());
+ return [at === -1 ? Number.MAX_SAFE_INTEGER : at];
+ }
+ if (kind === 'when') {
+ const read = parseWhen(value, role);
+ // A column holding both a date and a bare clock cannot interleave them: they are
+ // different scales. Dates first, clocks after, each ordered among its own.
+ return read ? [read.shape === 'moment' ? 0 : 1, read.key] : null;
+ }
+ if (kind === 'latlon') {
+ const read = parseLatLon(value);
+ // North to south, then west to east: the reading order of a map, and the one that
+ // puts the rows of one area together. The latitude is negated so that both
+ // components read the same way — smaller is earlier.
+ return read ? [-read.lat, read.lon] : null;
+ }
+ if (kind === 'number' || kind === 'offset') {
+ // An offset sorts by its seconds and that is the point of it: `-00:01:50` before
+ // `00:04:04` is the order the videos actually run in, and it is usable long before
+ // anybody has worked out what time the anchor happened.
+ const read = kind === 'offset' ? parseOffset(value) : parseNumber(value);
+ return read === null ? null : [read];
+ }
+ return undefined;
+}
+
+/** Whether a role orders a column at all, so a caller can skip reading keys it
+ * would then ignore. */
+export function sortsByRole(role) {
+ return sortKey(role, '') !== undefined;
+}
+
+/**
+ * Two keys ordered, or null when they do not settle it.
+ *
+ * Null is the whole design: the caller falls back to its own text comparison, so a
+ * column whose role reads half its cells still sorts, and this module never has to
+ * know how `lib/sheet.js` compares words.
+ */
+export function compareSortKeys(a, b) {
+ if (a === undefined || b === undefined) return null;
+ if (a === null && b === null) return null;
+ if (a === null || b === null) return a === null ? 1 : -1;
+ for (let at = 0; at < a.length; at += 1) {
+ if (a[at] !== b[at]) return a[at] < b[at] ? -1 : 1;
+ }
+ return null;
+}
+
+// -- how far along the work is ------------------------------------------------
+
+/**
+ * What a column says about how much is left.
+ *
+ * Two readings, and the first needs no role at all — which is the point. The binder
+ * this tool most has to replace, a 468-row geolocation index, has no status column:
+ * its columns are a date, a title, a country, coordinates and a link. Its question,
+ * *how many are left to geolocate*, is the fill rate of one column. A progress reading
+ * defined only on a status vocabulary would show nothing on the sheet that needs it
+ * most.
+ */
+export function columnProgress(table, columnIndex, role) {
+ const rows = table?.rows ?? [];
+ const total = rows.length;
+ if (columnIndex === -1) return null;
+ const empty = rows.filter((row) => blank(row[columnIndex])).length;
+ if (role?.kind !== 'state') {
+ return { kind: 'fill', total, filled: total - empty, empty };
+ }
+ const counts = new Map((role.values ?? []).map((value) => [value, 0]));
+ let other = 0;
+ for (const row of rows) {
+ const value = String(row[columnIndex] ?? '').trim();
+ if (!value) continue;
+ if (counts.has(value)) counts.set(value, counts.get(value) + 1);
+ else other += 1;
+ }
+ return {
+ kind: 'state',
+ total,
+ empty,
+ other,
+ buckets: [...counts.entries()].map(([value, count]) => ({ value, count })),
+ };
+}
+
+/**
+ * Which column a sheet's progress should be read off, when nobody has said.
+ *
+ * A suggestion, never a setting: a status column if one has been declared, otherwise
+ * the emptiest column that is not the row's handle, because the column with the most
+ * gaps in it is the one being worked through. Returns null rather than guess when
+ * every column is full — a sheet with nothing left to fill has no progress to show.
+ */
+export function suggestProgressColumn(table, roles, keyName) {
+ const columns = table?.columns ?? [];
+ const declared = columns.find((name) => roles?.[name]?.kind === 'state');
+ if (declared) return declared;
+ let best = null;
+ columns.forEach((name, index) => {
+ if (name === keyName) return;
+ const empty = (table.rows ?? []).filter((row) => blank(row[index])).length;
+ if (empty > 0 && (!best || empty > best.empty)) best = { name, empty };
+ });
+ return best?.name ?? null;
+}
+
+// -- what the column says twice, and what sits too close ----------------------
+
+/** The values a column repeats, with the rows holding them. Blank is not a duplicate:
+ * four hundred rows with nothing in a column are a worklist, not a mistake. */
+export function duplicateGroups(table, columnIndex, role) {
+ const seen = new Map();
+ (table?.rows ?? []).forEach((row, index) => {
+ for (const chip of cellChips(row[columnIndex], role)) {
+ if (!chip.value) continue;
+ const key = chip.value.toLowerCase();
+ if (!seen.has(key)) seen.set(key, { value: chip.value, rows: [] });
+ const group = seen.get(key);
+ if (group.rows.at(-1) !== index) group.rows.push(index);
+ }
+ });
+ return [...seen.values()]
+ .filter((group) => group.rows.length > 1)
+ .sort((a, b) => b.rows.length - a.rows.length || a.value.localeCompare(b.value));
+}
+
+/** How many buckets a sweep may hold before it is refused. A sheet at the row bound
+ * with every row placed is 20 000 points, which buckets to far fewer than this. */
+const MAX_BUCKETS = 200_000;
+
+/**
+ * Rows whose points sit within *metres* of each other.
+ *
+ * Bucketed rather than compared pair by pair, and that is not an optimisation: at the
+ * sheet's own bound of twenty thousand rows a naive sweep is two hundred million
+ * pairs, which is a frozen tab. Each point falls in a cell of the given size and is
+ * compared against its own cell and the eight around it, so the work is linear in the
+ * rows and the answer is exact for the distance asked.
+ *
+ * `capped` says the list was cut, because a silent cut reads as "there are no more".
+ */
+export function nearbyPairs(table, columnIndex, metres = 200, { cap = 200 } = {}) {
+ const points = [];
+ (table?.rows ?? []).forEach((row, index) => {
+ const point = parseLatLon(row[columnIndex]);
+ if (point && !point.outOfBounds) points.push({ index, ...point });
+ });
+ const size = Math.max(1, metres);
+ const latStep = size / 111_320;
+ const buckets = new Map();
+ for (const point of points) {
+ // Longitude degrees shrink towards the poles; using the latitude step for both
+ // would make the cells too narrow near the equator and miss pairs near the poles.
+ const lonStep = latStep / Math.max(0.01, Math.cos((point.lat * Math.PI) / 180));
+ point.cell = [Math.floor(point.lat / latStep), Math.floor(point.lon / lonStep)];
+ point.lonStep = lonStep;
+ const key = point.cell.join(':');
+ if (!buckets.has(key)) buckets.set(key, []);
+ buckets.get(key).push(point);
+ if (buckets.size > MAX_BUCKETS) return { pairs: [], capped: true };
+ }
+
+ const pairs = [];
+ const done = new Set();
+ for (const point of points) {
+ for (let dLat = -1; dLat <= 1; dLat += 1) {
+ for (let dLon = -1; dLon <= 1; dLon += 1) {
+ for (const other of buckets.get(`${point.cell[0] + dLat}:${point.cell[1] + dLon}`) ?? []) {
+ if (other.index <= point.index) continue;
+ const seen = `${point.index}:${other.index}`;
+ if (done.has(seen)) continue;
+ done.add(seen);
+ const apart = distanceMetres(point, other);
+ if (apart <= metres) pairs.push({ rows: [point.index, other.index], metres: apart });
+ }
+ }
+ }
+ if (pairs.length >= cap) return { pairs: pairs.slice(0, cap), capped: true };
+ }
+ return { pairs: pairs.sort((a, b) => a.metres - b.metres), capped: false };
+}
diff --git a/frontend/src/lib/sheetRoles.test.js b/frontend/src/lib/sheetRoles.test.js
new file mode 100644
index 0000000..9bfbebb
--- /dev/null
+++ b/frontend/src/lib/sheetRoles.test.js
@@ -0,0 +1,1035 @@
+import { describe, expect, it } from 'vitest';
+import {
+ compareSortKeys,
+ sortKey,
+ sortsByRole,
+ BOOLEAN_DEFAULTS,
+ COMPUTED_NATURES,
+ COUNTING_NATURES,
+ LINKED_NATURES,
+ ROW_COLOURS,
+ DEFAULT_SEPARATOR,
+ ROLE_KINDS,
+ STATE_COLOURS,
+ STATE_DEFAULTS,
+ cellChips,
+ countedOf,
+ columnProgress,
+ cycleTick,
+ dateSpelling,
+ detectRole,
+ distanceMetres,
+ duplicateGroups,
+ editVocabulary,
+ flipBoolean,
+ formatLatLon,
+ formatOffset,
+ nearbyPairs,
+ normalizeRole,
+ numberTotals,
+ offsetMoment,
+ parseLatLon,
+ parseNumber,
+ parseOffset,
+ picturePath,
+ pictureRef,
+ pictureUrl,
+ parseWhen,
+ precisionMetres,
+ readable,
+ readsCell,
+ pickerType,
+ sortVocabulary,
+ spellWhen,
+ splitValues,
+ suggestProgressColumn,
+ tickState,
+ valueTotals,
+ vocabularyUse,
+ whenShape,
+} from './sheetRoles.js';
+import shared from './sheetReading.fixture.json';
+
+/** Two cells ordered by what the column knows, the way `visibleRows` ends up ordering
+ * them once it has read a key per row. Written here rather than shipped: the grid never
+ * compares two raw cells, so a module-level version of this would be code the app does
+ * not call. */
+const compareByRole = (role, a, b) => compareSortKeys(sortKey(role, a), sortKey(role, b));
+
+describe('the role record', () => {
+ it('refuses a kind it does not implement rather than storing it', () => {
+ expect(normalizeRole({ kind: 'invented' })).toBeNull();
+ expect(normalizeRole(null)).toBeNull();
+ expect(ROLE_KINDS).toEqual([
+ 'state',
+ 'choice',
+ 'boolean',
+ 'number',
+ 'latlon',
+ 'when',
+ 'picture',
+ 'url',
+ 'row',
+ 'offset',
+ 'stamped',
+ 'computed',
+ 'locked',
+ ]);
+ });
+
+ it('reads a row column as the words that name the other rows', () => {
+ // Names and not keys: a file whose links read `r7f3a` is a file the collaborator
+ // opening it cannot follow, and names are what the binders actually wrote.
+ expect(normalizeRole({ kind: 'row' })).toEqual({ kind: 'row', of: null, multi: null });
+ const role = normalizeRole({ kind: 'row', of: 'Unit', multi: ', ' });
+ expect(splitValues('1st Coy, 2nd Coy', role)).toEqual(['1st Coy', '2nd Coy']);
+ // Whether a name finds its row is a question about the whole table, so this reader
+ // never calls a cell unreadable on its own.
+ expect(readsCell(role, 'a unit nobody listed')).toBe(true);
+ });
+
+ it('reads an offset as seconds either side of its anchor', () => {
+ const role = normalizeRole({ kind: 'offset', anchor: ' IGLA launch ' });
+ expect(role).toEqual({ kind: 'offset', anchor: 'IGLA launch' });
+ expect(parseOffset('-00:01:50')).toBe(-110);
+ expect(parseOffset('00:04:04')).toBe(244);
+ expect(parseOffset('1:05')).toBe(65);
+ expect(parseOffset('-110')).toBe(-110);
+ expect(parseOffset('1:05:00')).toBe(3900);
+ // Sixty-one seconds is not a time somebody meant to write.
+ expect(parseOffset('00:00:61')).toBeNull();
+ expect(parseOffset('then')).toBeNull();
+ expect(formatOffset(-110)).toBe('-00:01:50');
+ // The relative order is usable before anybody has dated the shot, which is the whole
+ // reason the column exists.
+ expect(compareByRole(role, '-00:01:50', '00:04:04')).toBe(-1);
+ expect(offsetMoment('2026-01-03T01:57:00Z', -110)).toBe('2026-01-03T01:55:10Z');
+ expect(offsetMoment('', -110)).toBeNull();
+ });
+
+ it('reads a picture column as the address its cells hold', () => {
+ const role = normalizeRole({ kind: 'picture' });
+ expect(role).toEqual({ kind: 'picture' });
+ expect(pictureUrl('https://example.org/a.jpg')).toBe('https://example.org/a.jpg');
+ expect(pictureUrl('shot at https://example.org/a.jpg.')).toBe('https://example.org/a.jpg');
+ // A path off somebody else's disk is elsewhere, not wrong: nothing is drawn for it.
+ expect(pictureUrl('C:\\photos\\a.jpg')).toBeNull();
+ expect(readsCell(role, 'to be found')).toBe(false);
+ expect(readsCell(role, '')).toBe(true);
+ });
+
+ it('reads a picture column as a file this case holds, as well as an address', () => {
+ // A geolocation index is worked on the images the case already holds, and a column
+ // that only understood `http` could draw a stranger's photo and not the case's own.
+ expect(picturePath('media/quai-sud.jpg')).toBe('media/quai-sud.jpg');
+ expect(pictureRef('media/quai-sud.jpg')).toEqual({ kind: 'case', value: 'media/quai-sud.jpg' });
+ expect(pictureRef('https://a.org/1.jpg')).toEqual({
+ kind: 'url',
+ value: 'https://a.org/1.jpg',
+ });
+ expect(pictureRef('to be found')).toBeNull();
+ });
+
+ it('refuses a path that names a disk this case does not travel with', () => {
+ // The cell is text a collaborator reads in a spreadsheet, and `media/quai-sud.jpg` is
+ // the only spelling that means the same thing to them as to the app.
+ expect(picturePath('/home/someone/a.jpg')).toBeNull();
+ expect(picturePath('C:\\photos\\a.jpg')).toBeNull();
+ expect(picturePath('media/../../etc/passwd.jpg')).toBeNull();
+ expect(picturePath('media/notes.txt')).toBeNull();
+ expect(picturePath('')).toBeNull();
+ });
+
+ it('says how many columns a counting column counts, for the heading to state once', () => {
+ // The denominator is said in the heading and the panel; the cells hold the bare
+ // number, because repeating it down four hundred rows is four hundred copies of one
+ // fact in cells thirty pixels tall.
+ expect(countedOf({ kind: 'computed', of: 'filled_of', columns: ['a', 'b'] })).toBe(2);
+ expect(countedOf({ kind: 'computed', of: 'has_point' })).toBe(0);
+ expect(countedOf(null)).toBe(0);
+ });
+
+ it('suggests a picture off the extension, never off "it is a link"', () => {
+ expect(detectRole(['https://a.org/1.jpg', 'https://a.org/2.png'])).toBe('picture');
+ expect(detectRole(['https://t.me/c/1', 'https://t.me/c/2'])).not.toBe('picture');
+ });
+
+ it('gives a state column the default vocabulary when it has none', () => {
+ expect(normalizeRole({ kind: 'state' }).values).toEqual(STATE_DEFAULTS);
+ });
+
+ it('paints those four defaults, because a worklist is read at a glance', () => {
+ const role = normalizeRole({ kind: 'state' });
+ expect(role.colours).toEqual({
+ 'to do': 'grey',
+ 'in progress': 'blue',
+ 'done': 'green',
+ 'ruled out': 'red',
+ });
+ expect(STATE_COLOURS).toEqual(role.colours);
+ // Every one of them from the palette a row is painted with, so a chip and a row read
+ // in the same six colours.
+ for (const colour of Object.values(STATE_COLOURS)) expect(ROW_COLOURS).toContain(colour);
+ });
+
+ it('lets the column change one of those colours and remove another', () => {
+ // The defaults sit under what the role says, value by value. Removing a `#colour`
+ // from a line has to stick, or the analyst could never un-paint a value.
+ const role = normalizeRole({
+ kind: 'state',
+ values: [...STATE_DEFAULTS],
+ colours: { 'to do': 'orange', 'in progress': 'blue' },
+ });
+ expect(role.colours).toEqual({ 'to do': 'orange', 'in progress': 'blue' });
+ });
+
+ it('does not paint a vocabulary the column brought itself', () => {
+ // An imported binder's own words are the vocabulary. `done` among them means what the
+ // binder meant, and a colour the app chose for it would be the app reading the case.
+ const role = normalizeRole({ kind: 'state', values: ['pass', 'done', 'OK en cours'] });
+ expect(role.colours).toEqual({});
+ });
+
+ it('keeps a state vocabulary in the order it was given, because that is the ranking', () => {
+ const role = normalizeRole({ kind: 'state', values: ['seen', 'geolocated', 'ruled out'] });
+ expect(role.values).toEqual(['seen', 'geolocated', 'ruled out']);
+ });
+
+ it('drops the fields a kind does not use', () => {
+ // A column that was a choice and became a when would otherwise keep a vocabulary
+ // nobody reads, and the next reader could not tell which of the two it is.
+ const role = normalizeRole({ kind: 'when', values: ['a', 'b'], multi: ', ' });
+ expect(role).toEqual({ kind: 'when', shape: 'date', dayFirst: true });
+ });
+
+ it('defaults a slash date to day first, because guessing reverses twelve days a month', () => {
+ expect(normalizeRole({ kind: 'when' }).dayFirst).toBe(true);
+ expect(normalizeRole({ kind: 'when', dayFirst: false }).dayFirst).toBe(false);
+ });
+
+ it('pins a computed column to a nature it knows', () => {
+ expect(normalizeRole({ kind: 'computed' }).of).toBe('has_point');
+ expect(normalizeRole({ kind: 'computed', of: 'invented' }).of).toBe('has_point');
+ // The order is the contract: the server falls back to the first of them.
+ expect(COMPUTED_NATURES).toEqual([
+ 'has_point',
+ 'filled_of',
+ 'yes_of',
+ 'point',
+ 'relations',
+ 'in_case',
+ ]);
+ expect(COUNTING_NATURES).toEqual(['filled_of', 'yes_of']);
+ expect(LINKED_NATURES).toEqual(['point', 'relations']);
+ });
+
+ it('makes a linked nature name the column whose link it follows', () => {
+ // A sheet can point at the case from a subject column and a place column both, so
+ // "whatever this row points at" would answer about whichever came first.
+ expect(normalizeRole({ kind: 'computed', of: 'point', from: 'Subject' })).toEqual({
+ kind: 'computed',
+ of: 'point',
+ from: 'Subject',
+ });
+ expect(normalizeRole({ kind: 'computed', of: 'point' }).from).toBeNull();
+ // A list of relations is written with a separator, so the column reads as chips the
+ // way any other multi-valued column does.
+ expect(normalizeRole({ kind: 'computed', of: 'relations', from: 'Unit' }).multi).toBe(', ');
+ // And a counting nature keeps none of that: the fields a kind does not use go.
+ expect(normalizeRole({ kind: 'computed', of: 'yes_of', from: 'Unit' }).from).toBeUndefined();
+ });
+
+ it('keeps only the columns a counting nature actually counts', () => {
+ // The columns are named in the role, so a column dropped in a spreadsheet must not
+ // leave the score counting something that is not there.
+ const role = normalizeRole({ kind: 'computed', of: 'filled_of', columns: ['a', 'a', 'b', ''] });
+ expect(role.columns).toEqual(['a', 'b']);
+ // And a nature that counts nothing is not a nature that counts every column.
+ expect(normalizeRole({ kind: 'computed', of: 'yes_of' }).columns).toEqual([]);
+ // The one that walks the graph has no columns to name.
+ expect(normalizeRole({ kind: 'computed', of: 'has_point' }).columns).toBeUndefined();
+ });
+
+ it('deduplicates a vocabulary rather than showing one value twice', () => {
+ expect(normalizeRole({ kind: 'choice', values: ['a', 'a', 'b'] }).values).toEqual(['a', 'b']);
+ });
+
+});
+
+describe('a column with two answers', () => {
+ it('starts on the words the binders write, yes first', () => {
+ // Yes first because that order is the ranking the sort reads, and because `computed`
+ // writes the same pair — one column of YES/NO in the file either way.
+ expect(normalizeRole({ kind: 'boolean' }).values).toEqual(BOOLEAN_DEFAULTS);
+ expect(BOOLEAN_DEFAULTS).toEqual(['YES', 'NO']);
+ });
+
+ it('takes the column own two words', () => {
+ expect(normalizeRole({ kind: 'boolean', values: ['oui', 'non'] }).values).toEqual([
+ 'oui',
+ 'non',
+ ]);
+ });
+
+ it('holds exactly two, because one click has to be a toggle', () => {
+ const three = normalizeRole({ kind: 'boolean', values: ['a', 'b', 'c'] });
+ expect(three.values).toEqual(['a', 'b']);
+ expect(normalizeRole({ kind: 'boolean', values: ['only'] }).values).toEqual(['only', 'NO']);
+ });
+
+ it('flips to the other word, and answers anything else with the first', () => {
+ const role = normalizeRole({ kind: 'boolean' });
+ expect(flipBoolean(role, 'YES')).toBe('NO');
+ expect(flipBoolean(role, 'NO')).toBe('YES');
+ expect(flipBoolean(role, '')).toBe('YES');
+ expect(flipBoolean(role, 'maybe')).toBe('YES');
+ });
+
+ it('sorts what is true above what is not', () => {
+ const role = normalizeRole({ kind: 'boolean' });
+ expect(compareByRole(role, 'YES', 'NO')).toBe(-1);
+ });
+
+ it('can be drawn as a tick box without becoming another kind of column', () => {
+ // A drawing choice and nothing more: the file holds the same two words, so the CSV
+ // a collaborator opens reads the same whether the grid drew chips or boxes.
+ const role = normalizeRole({ kind: 'boolean', values: ['oui', 'non'], tick: true });
+ expect(role.kind).toBe('boolean');
+ expect(role.tick).toBe(true);
+ expect(role.values).toEqual(['oui', 'non']);
+ expect(normalizeRole({ kind: 'boolean' }).tick).toBe(false);
+ });
+
+ it('cycles a box through three states, because it is drawn on an empty cell too', () => {
+ // Two states would make "nobody has been through this row" and "no" identical, and
+ // leave no way back to the first.
+ const role = normalizeRole({ kind: 'boolean', tick: true });
+ expect(cycleTick(role, '')).toBe('YES');
+ expect(cycleTick(role, 'YES')).toBe('NO');
+ expect(cycleTick(role, 'NO')).toBe('');
+ // A word the pair does not hold is settled by clicking it, as a flip is.
+ expect(cycleTick(role, 'maybe')).toBe('YES');
+ });
+
+ it('names the three states a box draws, plus the word it cannot read', () => {
+ const role = normalizeRole({ kind: 'boolean', values: ['oui', 'non'], tick: true });
+ expect(tickState(role, 'oui')).toBe('yes');
+ expect(tickState(role, 'non')).toBe('no');
+ expect(tickState(role, ' ')).toBe('blank');
+ expect(tickState(role, 'peut-être')).toBe('other');
+ });
+
+ it('is guessed only when both words are a yes or a no', () => {
+ expect(detectRole(['YES', 'NO', 'YES', 'NO'])).toBe('boolean');
+ expect(detectRole(['true', 'false', 'true', 'false'])).toBe('boolean');
+ expect(detectRole(['oui', 'non', 'oui', 'non'])).toBe('boolean');
+ // Two arbitrary words are a set of values, not a question with two answers.
+ expect(detectRole(['VID', 'PIC', 'VID', 'PIC'])).toBe('choice');
+ });
+});
+
+describe('a column of numbers', () => {
+ it('reads what a European export writes', () => {
+ expect(parseNumber('1 200')).toBe(1200);
+ expect(parseNumber("1'200")).toBe(1200);
+ expect(parseNumber('12,5')).toBe(12.5);
+ expect(parseNumber('-3')).toBe(-3);
+ expect(parseNumber('42%')).toBe(42);
+ });
+
+ it('reads an estimate, because an estimate is still a number', () => {
+ expect(parseNumber('~9')).toBe(9);
+ expect(parseNumber('>100')).toBe(100);
+ });
+
+ it('refuses a digit buried in prose', () => {
+ // `Only 9 in service?` is a real cell. Extracting the 9 would also turn `AB-123` into
+ // 123, and a total built on that is a total nobody can check.
+ expect(parseNumber('Only 9 in service?')).toBeNull();
+ expect(parseNumber('AB-123')).toBeNull();
+ expect(parseNumber('')).toBeNull();
+ expect(parseNumber('-')).toBeNull();
+ });
+
+ it('totals the rows it is given, which is what is on screen', () => {
+ const table = {
+ columns: ['id', 'Count'],
+ rows: [['r1', '3'], ['r2', '1 200'], ['r3', 'Only 9 in service?'], ['r4', '-5']],
+ };
+ expect(numberTotals(table, 1, [0, 1, 2, 3])).toEqual({
+ count: 3,
+ // `Only 9 in service?` is filled and unread, which is what the badge and the
+ // "to check" filter are made of: a total over three of four cells says so.
+ unreadable: 1,
+ sum: 1198,
+ mean: 399.333333,
+ min: -5,
+ max: 1200,
+ });
+ // Filtered to one row, the answer is about that row.
+ expect(numberTotals(table, 1, [0])).toEqual({
+ count: 1, unreadable: 0, sum: 3, mean: 3, min: 3, max: 3,
+ });
+ expect(numberTotals(table, 1, [2])).toEqual({
+ count: 0, unreadable: 1, sum: 0, mean: null, min: null, max: null,
+ });
+ });
+
+ it('keeps a footer free of floating-point noise', () => {
+ const table = { columns: ['id', 'n'], rows: [['r1', '0.1'], ['r2', '0.2']] };
+ expect(numberTotals(table, 1, [0, 1]).sum).toBe(0.3);
+ });
+
+ it('sorts by the number, and sends what it cannot read to the end', () => {
+ const role = normalizeRole({ kind: 'number' });
+ expect(compareByRole(role, '9', '10')).toBe(-1);
+ expect(compareByRole(role, '1 200', '9')).toBe(1);
+ expect(compareByRole(role, '9', 'Only 9 in service?')).toBe(-1);
+ expect(compareByRole(role, 'a', 'b')).toBeNull();
+ });
+});
+
+describe('a colour on a value', () => {
+ it('keeps a value that merely contains a hash', () => {
+ // `#REF!` is what a binder's own broken formula leaves behind, and it is in this
+ // repo's fixtures. The colour is picked from a palette rather than typed at the end
+ // of the word, so nothing has to guess where the value stops.
+ const role = normalizeRole({ kind: 'choice', values: ['#REF!'], colours: { '#REF!': 'grey' } });
+ expect(role.values).toEqual(['#REF!']);
+ expect(role.colours).toEqual({ '#REF!': 'grey' });
+ });
+
+ it('drops a colour whose value or name it does not know', () => {
+ const role = normalizeRole({
+ kind: 'state',
+ values: ['done'],
+ colours: { done: 'green', gone: 'red', gone2: 'chartreuse' },
+ });
+ expect(role.colours).toEqual({ done: 'green' });
+ });
+
+ it('hands a chip the colour of its value', () => {
+ const role = normalizeRole({ kind: 'state', values: ['done'], colours: { done: 'green' } });
+ expect(cellChips('done', role)[0].colour).toBe('green');
+ expect(cellChips('pass', role)[0].colour).toBeNull();
+ });
+
+ it('paints the same palette a row is painted with', () => {
+ // One colour language in the app: a third list would be the one that goes wrong.
+ expect(ROW_COLOURS).toEqual(['red', 'orange', 'yellow', 'green', 'blue', 'grey']);
+ });
+});
+
+describe('guessing what a column holds', () => {
+ it('recognises a column of points', () => {
+ expect(detectRole(['48.85, 2.35', '50.10, 3.00', '-33.87, 151.21'])).toBe('latlon');
+ });
+
+ it('recognises one through the gaps, because a binder is half-finished', () => {
+ // A coordinates column with `To be found` in a third of its rows is still a
+ // coordinates column, and refusing to see that is refusing the real file.
+ expect(detectRole(['48.85, 2.35', '50.10, 3.00', 'To be found'])).toBe('latlon');
+ });
+
+ it('recognises a column of dates', () => {
+ expect(detectRole(['03/01/2026', '14/02/2026', '?'])).toBe('when');
+ });
+
+ it('recognises a small closed set of answers', () => {
+ expect(detectRole(['VID', 'PIC', 'VID', 'SAT', 'VID', 'PIC'])).toBe('choice');
+ });
+
+ it('never guesses a state, because that is a judgement and not a shape', () => {
+ // Whether `pass` means done or means skipped is a fact about the investigation.
+ expect(detectRole(['to do', 'done', 'pass', 'to do', 'done', 'pass'])).toBe('choice');
+ });
+
+ it('guesses nothing about prose, or about one cell', () => {
+ expect(detectRole(['a note about the quay', 'another, longer note', 'a third one'])).toBeNull();
+ expect(detectRole(['48.85, 2.35'])).toBeNull();
+ expect(detectRole([])).toBeNull();
+ });
+});
+
+describe('reading a point', () => {
+ it('reads the decimal pair the binders write four hundred times', () => {
+ expect(parseLatLon('48.8566, 2.3522')).toMatchObject({ lat: 48.8566, lon: 2.3522 });
+ expect(parseLatLon('48.8566,2.3522')).toMatchObject({ lat: 48.8566, lon: 2.3522 });
+ expect(parseLatLon(' 48.8566 2.3522 ')).toMatchObject({ lat: 48.8566, lon: 2.3522 });
+ expect(parseLatLon('-33.87, 151.21')).toMatchObject({ lat: -33.87, lon: 151.21 });
+ });
+
+ it('reads hemispheres as signs', () => {
+ expect(parseLatLon('33.87S, 151.21E')).toMatchObject({ lat: -33.87, lon: 151.21 });
+ expect(parseLatLon('40.71N, 74.01W')).toMatchObject({ lat: 40.71, lon: -74.01 });
+ });
+
+ it('reads degrees, minutes and seconds', () => {
+ const point = parseLatLon(`48°51'24"N 2°21'08"E`);
+ expect(point.lat).toBeCloseTo(48.8567, 3);
+ expect(point.lon).toBeCloseTo(2.3522, 3);
+ });
+
+ it('reads a comma decimal, which a European export writes', () => {
+ expect(parseLatLon('48,8566; 2,3522')).toMatchObject({ lat: 48.8566, lon: 2.3522 });
+ expect(parseLatLon('48,8566 2,3522')).toMatchObject({ lat: 48.8566, lon: 2.3522 });
+ });
+
+ it('reads a bare comma as the decimal mark rather than as a pair', () => {
+ // `48,8` is one number in the convention the whole app reads, so it is not a point.
+ // The comma separates two coordinates only where it cannot be decimal: a space after
+ // it, a hemisphere letter, or a full stop already doing the job.
+ expect(parseLatLon('48,8')).toBeNull();
+ expect(parseLatLon('-1,5')).toBeNull();
+ expect(parseLatLon('48, 8')).toMatchObject({ lat: 48, lon: 8 });
+ expect(parseLatLon('48.5,2.3')).toMatchObject({ lat: 48.5, lon: 2.3 });
+ expect(parseLatLon('48,8N 2,3E')).toMatchObject({ lat: 48.8, lon: 2.3 });
+ });
+
+ it('refuses what is not a point, without complaining', () => {
+ // `To be found` is on every page of the real binders. A role that threw here would
+ // refuse the work.
+ expect(parseLatLon('To be found')).toBeNull();
+ expect(parseLatLon('-')).toBeNull();
+ expect(parseLatLon('')).toBeNull();
+ expect(parseLatLon('48.8566')).toBeNull();
+ });
+
+ it('reports how precisely the cell was written', () => {
+ expect(parseLatLon('48.85, 2.35').decimals).toBe(2);
+ expect(parseLatLon('48.8566, 2.3').decimals).toBe(1);
+ expect(precisionMetres(2)).toBe(1113); // about a kilometre
+ expect(precisionMetres(5)).toBe(1);
+ });
+
+ it('reports a transposed pair rather than refusing it', () => {
+ // Latitude 151 is a finding about the file, not a parse failure.
+ expect(parseLatLon('151.21, 33.87').outOfBounds).toBe(true);
+ expect(parseLatLon('48.85, 2.35').outOfBounds).toBe(false);
+ });
+
+ it('writes a point back as one canonical form', () => {
+ expect(formatLatLon(parseLatLon(`48°51'24"N 2°21'08"E`))).toBe('48.85667, 2.35222');
+ expect(formatLatLon(null)).toBe('');
+ });
+
+ it('measures the ground between two points', () => {
+ // A hundred metres north, near the equator.
+ expect(distanceMetres({ lat: 0, lon: 0 }, { lat: 0.0008993, lon: 0 })).toBe(100);
+ expect(distanceMetres({ lat: 48.8566, lon: 2.3522 }, { lat: 48.8566, lon: 2.3522 })).toBe(0);
+ });
+});
+
+describe('reading a moment', () => {
+ it('reads the European slash date the binders use', () => {
+ expect(parseWhen('03/01/2026').text).toBe('2026-01-03');
+ expect(parseWhen('3/1/26').text).toBe('2026-01-03');
+ });
+
+ it('reads a month-first column when the column says so', () => {
+ expect(parseWhen('03/01/2026', { dayFirst: false }).text).toBe('2026-03-01');
+ });
+
+ it('reads a four-digit lead as a year whatever the convention', () => {
+ expect(parseWhen('2026-01-03', { dayFirst: true }).text).toBe('2026-01-03');
+ });
+
+ it('keeps a bare clock as a time of day rather than inventing a date', () => {
+ // The binder's `Local time` holds `01:57` for an event whose date is in the sheet's
+ // title. Pinning it to a date would be inventing evidence.
+ const read = parseWhen('01:57');
+ expect(read.shape).toBe('time');
+ expect(read.key).toBe(1 * 3600 + 57 * 60);
+ expect(read.text).toBe('01:57');
+ });
+
+ it('reads the full form an email header carries', () => {
+ expect(parseWhen('Sat, 03 Jan 2026 06:42:02 GMT').text).toBe('2026-01-03T06:42');
+ });
+
+ it('reads a date with a time appended', () => {
+ expect(parseWhen('03/01/2026 06:42').text).toBe('2026-01-03T06:42');
+ });
+
+ it('refuses what the binders write when they do not know', () => {
+ expect(parseWhen('AFTER')).toBeNull();
+ expect(parseWhen('?')).toBeNull();
+ expect(parseWhen('between 2:00 and 2:10')).toBeNull();
+ expect(parseWhen('32/01/2026')).toBeNull();
+ expect(parseWhen('03/13/2026')).toBeNull();
+ expect(parseWhen('25:00')).toBeNull();
+ });
+
+ it('refuses an hour that would roll over into the next day', () => {
+ // `Date.UTC` takes 12:30:75 and keeps the day, and it takes 99:00 and moves it — so
+ // both used to pass here while the server refused them, and the analyst read a message
+ // about a value they never typed.
+ expect(parseWhen('12:30:75')).toBeNull();
+ expect(parseWhen('03/01/2026 12:30:75')).toBeNull();
+ expect(parseWhen('03/01/2026 99:00')).toBeNull();
+ expect(parseWhen('Sat, 03 Jan 2026 06:42:99 GMT')).toBeNull();
+ expect(parseWhen('23:59:59').text).toBe('23:59');
+ });
+});
+
+describe('the same cell, read by both readers', () => {
+ // The parity gate the role vocabularies had and the readings did not. The other half is
+ // `tests/test_sheets.py::test_both_readers_answer_the_same_thing_about_a_shared_list_of_cells`,
+ // over this same file: one list of cells, one expected answer, two readers held to it.
+ it('answers what the shared fixture says, cell by cell', () => {
+ expect(shared.when.length && shared.point.length).toBeTruthy();
+ for (const entry of shared.when) {
+ const read = parseWhen(entry.cell, entry.role ?? {});
+ if (entry.reads === null) {
+ expect(read, entry.cell).toBeNull();
+ continue;
+ }
+ expect(read, entry.cell).not.toBeNull();
+ expect(read.shape, entry.cell).toBe(entry.reads.shape);
+ expect(read.text, entry.cell).toBe(entry.reads.text);
+ }
+ for (const entry of shared.point) {
+ const point = parseLatLon(entry.cell);
+ if (entry.reads === null) {
+ expect(point, entry.cell).toBeNull();
+ continue;
+ }
+ expect(point, entry.cell).not.toBeNull();
+ expect(point.lat).toBeCloseTo(entry.reads.lat, 6);
+ expect(point.lon).toBeCloseTo(entry.reads.lon, 6);
+ expect(point.decimals, entry.cell).toBe(entry.reads.decimals);
+ }
+ });
+});
+
+describe('a moment chosen from a picker', () => {
+ it('reads which way round the column already writes them', () => {
+ // Read from the column and not declared: a picker that wrote `2026-01-31` into a
+ // column of `31/01/2026` would restyle the file from a click.
+ expect(dateSpelling(['31/01/2026', '14/02/2026'])).toBe('slash');
+ expect(dateSpelling(['2026-01-31', '2026-02-14'])).toBe('iso');
+ expect(dateSpelling(['AFTER', '?'])).toBe('slash', 'ties go to what the binders use');
+ });
+
+ it('reads which of the three shapes the column holds', () => {
+ // The role is called "a date or a time" because the binders write all three. Offering
+ // a calendar on a column of bare clocks would offer to put a date where the analyst
+ // deliberately did not.
+ expect(whenShape(['31/01/2026', '14/02/2026'])).toBe('date');
+ expect(whenShape(['01:57', '02:10'])).toBe('time');
+ expect(whenShape(['03/01/2026 06:42', '04/01/2026 07:15'])).toBe('datetime');
+ expect(whenShape(['AFTER', '?'])).toBe('date');
+ });
+
+ it('picks each shape with the input made for it', () => {
+ expect(pickerType('date')).toBe('date');
+ expect(pickerType('time')).toBe('time');
+ expect(pickerType('datetime')).toBe('datetime-local');
+ });
+
+ it('spells the picked moment the way the column does', () => {
+ expect(spellWhen('2026-03-04', { spelling: 'slash' })).toBe('04/03/2026');
+ expect(spellWhen('2026-03-04', { spelling: 'iso' })).toBe('2026-03-04');
+ expect(spellWhen('', {})).toBe('');
+ });
+
+ it('spells a time on its own, and a moment with its hour', () => {
+ expect(spellWhen('01:57', { shape: 'time' })).toBe('01:57');
+ expect(spellWhen('2026-03-04T06:42', { shape: 'datetime', spelling: 'slash' }))
+ .toBe('04/03/2026 06:42');
+ });
+
+ it('keeps an hour the cell already established on a date-only column', () => {
+ // `03/01/2026 06:42` is a moment somebody worked out; a date picker has no business
+ // dropping the hour from it.
+ expect(spellWhen('2026-03-04', { spelling: 'slash', keep: '03/01/2026 06:42' }))
+ .toBe('04/03/2026 06:42');
+ expect(spellWhen('2026-03-04', { spelling: 'slash', keep: '03/01/2026' })).toBe('04/03/2026');
+ });
+});
+
+describe('a cell holding several values', () => {
+ const role = normalizeRole({ kind: 'choice', multi: DEFAULT_SEPARATOR, values: ['Buk-M2E'] });
+
+ it('splits on the separator the column declares, and only then', () => {
+ expect(splitValues('Buk-M2E, ZU23-2', role)).toEqual(['Buk-M2E', 'ZU23-2']);
+ expect(splitValues('Buk-M2E, ZU23-2', normalizeRole({ kind: 'choice' }))).toEqual([
+ 'Buk-M2E, ZU23-2',
+ ]);
+ });
+
+ it('reads a list as its values and nothing else', () => {
+ // A quantity used to be read out of `2x S-125` here. It is gone: a count kept in a
+ // column of values is a count nothing can total, and the answer is a number column
+ // beside a column naming what is counted.
+ const list = normalizeRole({ kind: 'choice', multi: ', ' });
+ expect(cellChips('Buk-M2E, 2x S-125', list)).toEqual([
+ { value: 'Buk-M2E', known: false, colour: null, raw: 'Buk-M2E' },
+ { value: '2x S-125', known: false, colour: null, raw: '2x S-125' },
+ ]);
+ });
+
+ it('marks a value the vocabulary does not know without hiding it', () => {
+ const chips = cellChips('Buk-M2E, Mi-17V-5', role);
+ expect(chips.map((chip) => chip.known)).toEqual([true, false]);
+ });
+
+ it('totals by value, one row counted once however often it says it', () => {
+ const list = normalizeRole({ kind: 'choice', multi: ', ' });
+ const table = {
+ columns: ['id', 'Equipments'],
+ rows: [
+ ['r1', 'S-125, S-125'],
+ ['r2', 'S-125, Buk-M2E'],
+ ],
+ };
+ // How many rows hold it, which is what the filter hands back.
+ expect(valueTotals(table, 1, list)).toEqual([
+ { value: 'S-125', rows: 2 },
+ { value: 'Buk-M2E', rows: 1 },
+ ]);
+ });
+});
+
+describe('sorting by what the column knows', () => {
+ it('orders a state column by its vocabulary, not its alphabet', () => {
+ const role = normalizeRole({ kind: 'state' });
+ // 'in progress' before 'ruled out' by rank; alphabetically it would be the reverse
+ // of nothing useful at all.
+ expect(compareByRole(role, 'in progress', 'ruled out')).toBe(-1);
+ expect(compareByRole(role, 'done', 'to do')).toBe(1);
+ expect(compareByRole(role, 'done', 'done')).toBeNull();
+ });
+
+ it('puts a word outside the vocabulary after the ones inside it', () => {
+ const role = normalizeRole({ kind: 'state' });
+ expect(compareByRole(role, 'OK en cours', 'ruled out')).toBe(1);
+ });
+
+ it('orders a date column by the date, which is the whole point of the role', () => {
+ // Without the role this is text: `01/02/2026` sorts before `31/01/2026`.
+ const role = normalizeRole({ kind: 'when' });
+ expect(compareByRole(role, '31/01/2026', '01/02/2026')).toBe(-1);
+ });
+
+ it('sends the cells a date column cannot read to the end', () => {
+ const role = normalizeRole({ kind: 'when' });
+ expect(compareByRole(role, '31/01/2026', 'AFTER')).toBe(-1);
+ expect(compareByRole(role, 'AFTER', '31/01/2026')).toBe(1);
+ expect(compareByRole(role, 'AFTER', '?')).toBeNull();
+ });
+
+ it('keeps dates and bare clocks apart, because they are different scales', () => {
+ const role = normalizeRole({ kind: 'when' });
+ expect(compareByRole(role, '03/01/2026', '01:57')).toBe(-1);
+ expect(compareByRole(role, '01:57', '02:10')).toBe(-1);
+ });
+
+ it('orders points north to south, so one area reads together', () => {
+ const role = normalizeRole({ kind: 'latlon' });
+ expect(compareByRole(role, '50.1, 3.0', '48.8, 2.3')).toBe(-1);
+ expect(compareByRole(role, '48.8, 2.3', '48.8, 4.0')).toBe(-1);
+ });
+
+ it('says nothing about a column of values, which sorts as the words it holds', () => {
+ expect(compareByRole(normalizeRole({ kind: 'choice', multi: ', ' }), 'A, B', 'C')).toBeNull();
+ });
+
+ it('says nothing when it has nothing to say, so the caller falls back to words', () => {
+ expect(compareByRole(null, 'a', 'b')).toBeNull();
+ expect(compareByRole({ kind: 'stamped' }, 'a', 'b')).toBeNull();
+ expect(compareByRole(normalizeRole({ kind: 'choice' }), 'a', 'b')).toBeNull();
+ });
+});
+
+describe('how much is left', () => {
+ // The 468-row geolocation index: a date, a title, a country, coordinates, a link.
+ // No status column anywhere, and its question is how many are left to geolocate.
+ const index = () => ({
+ columns: ['id', 'Title', 'Coordinates'],
+ rows: [
+ ['r1', 'Quai sud', '48.85, 2.35'],
+ ['r2', 'Pont nord', ''],
+ ['r3', 'Gare est', ' '],
+ ['r4', 'Dépôt', '50.10, 3.00'],
+ ],
+ });
+
+ it('reads a fill rate off any column, with no role at all', () => {
+ expect(columnProgress(index(), 2, null)).toEqual({
+ kind: 'fill',
+ total: 4,
+ filled: 2,
+ empty: 2,
+ });
+ });
+
+ it('counts whitespace as empty, the way the analyst reads it', () => {
+ expect(columnProgress(index(), 2, null).empty).toBe(2);
+ });
+
+ it('reads a state column as its buckets, in vocabulary order', () => {
+ const table = {
+ columns: ['id', 'Status'],
+ rows: [['r1', 'done'], ['r2', 'done'], ['r3', 'to do'], ['r4', ''], ['r5', 'pass']],
+ };
+ expect(columnProgress(table, 1, normalizeRole({ kind: 'state' }))).toEqual({
+ kind: 'state',
+ total: 5,
+ empty: 1,
+ other: 1,
+ buckets: [
+ { value: 'to do', count: 1 },
+ { value: 'in progress', count: 0 },
+ { value: 'done', count: 2 },
+ { value: 'ruled out', count: 0 },
+ ],
+ });
+ });
+
+ it('suggests the declared status column when there is one', () => {
+ const table = { columns: ['id', 'Status', 'Notes'], rows: [['r1', '', '']] };
+ expect(suggestProgressColumn(table, { Status: { kind: 'state' } }, 'id')).toBe('Status');
+ });
+
+ it('otherwise suggests the emptiest column, which is the one being worked through', () => {
+ expect(suggestProgressColumn(index(), {}, 'id')).toBe('Coordinates');
+ });
+
+ it('suggests nothing when there is nothing left to fill', () => {
+ const full = { columns: ['id', 'Title'], rows: [['r1', 'Quai sud']] };
+ expect(suggestProgressColumn(full, {}, 'id')).toBeNull();
+ });
+
+ it('never suggests the row handle', () => {
+ const table = { columns: ['id', 'Title'], rows: [['', ''], ['', '']] };
+ expect(suggestProgressColumn(table, {}, 'id')).toBe('Title');
+ });
+});
+
+describe('what a column says twice', () => {
+ const table = () => ({
+ columns: ['id', 'Plate'],
+ rows: [['r1', 'AB-123'], ['r2', 'ab-123'], ['r3', ''], ['r4', 'CD-456'], ['r5', 'AB-123']],
+ });
+
+ it('groups the repeats and leaves the singles out', () => {
+ const groups = duplicateGroups(table(), 1, null);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].rows).toEqual([0, 1, 4]);
+ });
+
+ it('reads a difference of case as the same value', () => {
+ expect(duplicateGroups(table(), 1, null)[0].value).toBe('AB-123');
+ });
+
+ it('does not call four hundred empty cells a duplicate', () => {
+ const empty = { columns: ['id', 'Coordinates'], rows: [['r1', ''], ['r2', ''], ['r3', '']] };
+ expect(duplicateGroups(empty, 1, null)).toEqual([]);
+ });
+
+ it('finds a value repeated inside a multi-value column', () => {
+ const role = normalizeRole({ kind: 'choice', multi: ', ' });
+ const lists = {
+ columns: ['id', 'Equipments'],
+ rows: [['r1', 'Buk-M2E, ZU23-2'], ['r2', 'S-125, Buk-M2E']],
+ };
+ expect(duplicateGroups(lists, 1, role)[0]).toMatchObject({ value: 'Buk-M2E', rows: [0, 1] });
+ });
+});
+
+describe('points that sit too close to be two places', () => {
+ it('finds the pair and says how far apart it is', () => {
+ const table = {
+ columns: ['id', 'Coordinates'],
+ rows: [
+ ['r1', '48.85660, 2.35220'],
+ ['r2', '48.85670, 2.35230'],
+ ['r3', '50.10000, 3.00000'],
+ ],
+ };
+ const { pairs, capped } = nearbyPairs(table, 1, 200);
+ expect(capped).toBe(false);
+ expect(pairs).toHaveLength(1);
+ expect(pairs[0].rows).toEqual([0, 1]);
+ expect(pairs[0].metres).toBeLessThan(20);
+ });
+
+ it('finds a pair that straddles a bucket edge', () => {
+ // The reason the sweep looks at the eight neighbouring cells: two points ten metres
+ // apart can fall either side of a boundary, and a single-cell sweep would miss them.
+ const table = {
+ columns: ['id', 'Coordinates'],
+ rows: [['r1', '48.8500000, 2.3500000'], ['r2', '48.8500899, 2.3500000']],
+ };
+ expect(nearbyPairs(table, 1, 20).pairs).toHaveLength(1);
+ });
+
+ it('ignores what it cannot read and what cannot be true', () => {
+ const table = {
+ columns: ['id', 'Coordinates'],
+ rows: [['r1', 'To be found'], ['r2', '151.2, 33.8'], ['r3', '48.85, 2.35']],
+ };
+ expect(nearbyPairs(table, 1, 500).pairs).toEqual([]);
+ });
+
+ it('stays linear on a sheet at the row bound instead of freezing the tab', () => {
+ // Twenty thousand rows compared pair by pair is two hundred million comparisons.
+ // Bucketed, this is one pass, and the assertion is that it returns at all.
+ const rows = Array.from({ length: 20_000 }, (_, index) => [
+ `r${index}`,
+ `${(index % 900) / 10 + 1}, ${(index % 700) / 10 + 1}`,
+ ]);
+ const { pairs, capped } = nearbyPairs({ columns: ['id', 'Coordinates'], rows }, 1, 50);
+ expect(capped).toBe(true);
+ expect(pairs.length).toBeGreaterThan(0);
+ });
+
+ it('says when the list was cut rather than reading as complete', () => {
+ const rows = Array.from({ length: 60 }, (_, index) => [`r${index}`, '48.85000, 2.35000']);
+ const { pairs, capped } = nearbyPairs({ columns: ['id', 'Coordinates'], rows }, 1, 100, {
+ cap: 10,
+ });
+ expect(pairs).toHaveLength(10);
+ expect(capped).toBe(true);
+ });
+});
+
+describe('a column vocabulary the analyst edits', () => {
+ const role = normalizeRole({
+ kind: 'state',
+ values: ['to do', 'in progress', 'done'],
+ colours: { done: 'green' },
+ });
+
+ it('moves a value, because the order is the ranking the sort reads', () => {
+ const moved = editVocabulary(role, { value: 'done', at: 2, to: 0 });
+ expect(moved.values).toEqual(['done', 'to do', 'in progress']);
+ expect(moved.colours).toEqual({ done: 'green' });
+ });
+
+ it('adds a value it has never heard of, and refuses one it has', () => {
+ expect(editVocabulary(role, { value: 'ruled out' }).values).toContain('ruled out');
+ expect(editVocabulary(role, { value: 'done' }).values).toHaveLength(3);
+ });
+
+ it('carries a colour through a rename, because the colour belongs to the answer', () => {
+ const renamed = editVocabulary(role, { value: 'settled', at: 2 });
+ expect(renamed.values).toEqual(['to do', 'in progress', 'settled']);
+ expect(renamed.colours).toEqual({ settled: 'green' });
+ });
+
+ it('drops a value and the colour hanging on it', () => {
+ const dropped = editVocabulary(role, { value: 'done', at: 2, to: -1 });
+ expect(dropped.values).toEqual(['to do', 'in progress']);
+ expect(dropped.colours).toEqual({});
+ });
+
+ it('paints and unpaints one value, refusing a colour off the palette', () => {
+ expect(editVocabulary(role, { value: 'to do', at: 0, colour: 'red' }).colours['to do']).toBe('red');
+ expect(editVocabulary(role, { value: 'done', at: 2, colour: null }).colours).toEqual({});
+ expect(editVocabulary(role, { value: 'to do', at: 0, colour: 'chartreuse' }).colours['to do'])
+ .toBeUndefined();
+ });
+
+ it('sorts only when asked, in both directions', () => {
+ // Never on its own: `to do → in progress → done` is the order of the work, and an
+ // editor that alphabetised it would have put `done` first.
+ expect(sortVocabulary(role).values).toEqual(['done', 'in progress', 'to do']);
+ expect(sortVocabulary(role, { desc: true }).values).toEqual(['to do', 'in progress', 'done']);
+ });
+
+ it('says which values are used, which are not, and which words sit outside', () => {
+ const table = {
+ columns: ['id', 'Status'],
+ rows: [['r1', 'done'], ['r2', 'done'], ['r3', 'OK en cours'], ['r4', '']],
+ };
+ const use = vocabularyUse(table, 1, role);
+ expect(use.counts).toEqual({ 'to do': 0, 'in progress': 0, done: 2 });
+ expect(use.unused).toEqual(['to do', 'in progress']);
+ expect(use.outside.map((entry) => entry.value)).toEqual(['OK en cours']);
+ });
+});
+
+describe('the cells a lens cannot read', () => {
+ it('reads an empty cell, because blank is unknown rather than wrong', () => {
+ expect(readsCell({ kind: 'number' }, '')).toBe(true);
+ expect(readsCell({ kind: 'number' }, ' ')).toBe(true);
+ });
+
+ it('answers per kind, and calls a point off the globe unreadable', () => {
+ expect(readsCell({ kind: 'number' }, '1 200')).toBe(true);
+ expect(readsCell({ kind: 'number' }, 'about 12')).toBe(false);
+ expect(readsCell({ kind: 'latlon' }, '48.85, 2.35')).toBe(true);
+ expect(readsCell({ kind: 'latlon' }, '148.85, 2.35')).toBe(false);
+ expect(readsCell({ kind: 'when', dayFirst: true }, '31/01/2026')).toBe(true);
+ expect(readsCell({ kind: 'when', dayFirst: true }, 'AFTER')).toBe(false);
+ });
+
+ it('calls a value outside a vocabulary unreadable, which is what "to check" means', () => {
+ const role = normalizeRole({ kind: 'choice', multi: ', ', values: ['a', 'b'] });
+ expect(readsCell(role, 'a, b')).toBe(true);
+ expect(readsCell(role, 'a, zzz')).toBe(false);
+ });
+
+ it('counts what a column reads against what it holds', () => {
+ const table = {
+ columns: ['id', 'Count'],
+ rows: [['r1', '3'], ['r2', 'about 12'], ['r3', '']],
+ };
+ expect(readable(table, 1, { kind: 'number' })).toEqual({ total: 2, read: 1, unreadable: 1 });
+ });
+});
+
+describe('a number column that says how it is written', () => {
+ it('keeps a unit, where it is written and which answer the footer gives', () => {
+ const role = normalizeRole({ kind: 'number', unit: ' % ', summary: 'mean', unitInCells: 1 });
+ expect(role).toEqual({ kind: 'number', unit: '%', unitInCells: true, summary: 'mean' });
+ });
+
+ it('leaves the unit to the heading unless the column asked for it in the cells', () => {
+ expect(normalizeRole({ kind: 'number', unit: 'km' }).unitInCells).toBe(false);
+ });
+
+ it('falls back to a total, which is what a column of counts wants', () => {
+ expect(normalizeRole({ kind: 'number' }).summary).toBe('sum');
+ expect(normalizeRole({ kind: 'number', summary: 'invented' }).summary).toBe('sum');
+ });
+});
+
+
+describe('what a cell is worth to a sort, read once', () => {
+ it('says nothing for a role that does not order anything', () => {
+ expect(sortsByRole(normalizeRole({ kind: 'choice', multi: ', ' }))).toBe(false);
+ expect(sortsByRole(null)).toBe(false);
+ expect(sortsByRole(normalizeRole({ kind: 'when' }))).toBe(true);
+ expect(sortsByRole(normalizeRole({ kind: 'state', values: ['a'] }))).toBe(true);
+ });
+
+ it('orders by the key alone, the way the comparator then does', () => {
+ const role = normalizeRole({ kind: 'when' });
+ const keys = ['31/01/2026', '01/02/2026', 'AFTER'].map((cell) => sortKey(role, cell));
+
+ expect(compareSortKeys(keys[0], keys[1])).toBe(-1);
+ // A cell the role cannot read sorts after the ones it can.
+ expect(compareSortKeys(keys[0], keys[2])).toBe(-1);
+ expect(compareSortKeys(keys[2], keys[0])).toBe(1);
+ // Two it cannot read do not settle it, so the caller compares the words.
+ expect(compareSortKeys(keys[2], sortKey(role, '?'))).toBeNull();
+ });
+
+ it('reads a cell once where the comparator read it on every comparison', () => {
+ // The point of the whole shape: n reads rather than 2·n·log n of them.
+ const role = normalizeRole({ kind: 'when' });
+ let reads = 0;
+ const cells = Array.from({ length: 64 }, (_, at) => `0${(at % 9) + 1}/01/2026`);
+ const keys = cells.map((cell) => {
+ reads += 1;
+ return sortKey(role, cell);
+ });
+ const order = keys.map((_, at) => at).sort((a, b) => compareSortKeys(keys[a], keys[b]) ?? a - b);
+
+ expect(reads).toBe(cells.length);
+ expect(order.length).toBe(cells.length);
+ });
+});
diff --git a/frontend/src/lib/sheetRows.js b/frontend/src/lib/sheetRows.js
new file mode 100644
index 0000000..1496e46
--- /dev/null
+++ b/frontend/src/lib/sheetRows.js
@@ -0,0 +1,117 @@
+/**
+ * One row of a sheet pointing at another row of the same sheet.
+ *
+ * The binders wrote an order of battle in a column called `Links with others`: a brigade
+ * listing its companies, each company naming its brigade back, held together by a
+ * spreadsheet validation. That validation cannot survive a row being moved, and in the
+ * real file it had **already** decayed — half the cells read `#REF!`.
+ *
+ * So nothing here stores a pointer. The cell keeps the **words** it always held, exactly
+ * like every other cell in this app, and the link is re-read from those words every time:
+ * a name points at a row when exactly one other row spells it that way in the naming
+ * column. A word that names no row, or names two, is *reported* rather than guessed —
+ * which turns the same decay the binders suffered into a list of what to fix.
+ *
+ * The other half is the reading the binders could not have at all: **who points at me**.
+ * A brigade's row shows its companies without anybody having to keep two columns in step.
+ *
+ * Pure: a table and a role in, readings out. Mirrors `engine/sheetroles.row_targets`,
+ * which is the copy promotion reads before it draws `part-of` edges into the graph.
+ */
+
+import { ID_COLUMN } from './sheet.js';
+import { splitValues } from './sheetRoles.js';
+
+/** Which column's words name a row, for a given `row` role: the one it declares, else
+ * the first column that is not the key — which is the subject column on every sheet
+ * anyone builds, and the one a reader would have used. */
+export function namingColumn(columns, role) {
+ const declared = role?.of;
+ if (declared && (columns ?? []).includes(declared)) return declared;
+ return (columns ?? []).find((name) => String(name).toLowerCase() !== ID_COLUMN) ?? null;
+}
+
+function keyAt(columns) {
+ const at = (columns ?? []).findIndex((name) => String(name).toLowerCase() === ID_COLUMN);
+ return at === -1 ? 0 : at;
+}
+
+/**
+ * What each row's `row` column points at, by row key.
+ *
+ * `{ keys, missing }` per row: the rows it reached, and the words that reached none or
+ * reached more than one. Both are wanted — `missing` is what the column's badge counts,
+ * and a column where it is high is a column somebody renamed a row out from under.
+ */
+export function rowTargets(table, columnIndex, role) {
+ const columns = table?.columns ?? [];
+ const named = namingColumn(columns, role);
+ if (named === null || columnIndex === -1) return new Map();
+ const nameAt = columns.indexOf(named);
+ const at = keyAt(columns);
+ const rows = table?.rows ?? [];
+
+ // Every word the naming column holds, and the rows holding it. A word two rows share
+ // names neither of them: that is a finding about the file, not a coin toss.
+ const holders = new Map();
+ for (const row of rows) {
+ const word = String(row[nameAt] ?? '').trim().toLowerCase();
+ if (!word) continue;
+ if (!holders.has(word)) holders.set(word, []);
+ holders.get(word).push(String(row[at] ?? ''));
+ }
+
+ const found = new Map();
+ for (const row of rows) {
+ const key = String(row[at] ?? '');
+ const keys = [];
+ const missing = [];
+ for (const word of splitValues(row[columnIndex], role)) {
+ const held = (holders.get(word.toLowerCase()) ?? []).filter((other) => other !== key);
+ if (held.length === 1) {
+ if (!keys.includes(held[0])) keys.push(held[0]);
+ } else {
+ missing.push(word);
+ }
+ }
+ if (keys.length || missing.length) found.set(key, { keys, missing });
+ }
+ return found;
+}
+
+/**
+ * The other direction: for each row, the rows whose column points **at it**.
+ *
+ * The reading the binders kept by hand in a second column and could not keep in step. It
+ * is derived rather than stored for the same reason the forward direction is: one truth,
+ * re-read, so it cannot disagree with itself.
+ */
+export function backLinks(targets) {
+ const back = new Map();
+ for (const [key, found] of targets ?? []) {
+ for (const other of found.keys) {
+ if (!back.has(other)) back.set(other, []);
+ if (!back.get(other).includes(key)) back.get(other).push(key);
+ }
+ }
+ return back;
+}
+
+/** How a row reads when it is named somewhere else: its own naming cell, or its key when
+ * that cell is empty. A blank chip would be a pointer nobody could follow back. */
+export function rowLabel(table, key, role) {
+ const columns = table?.columns ?? [];
+ const named = namingColumn(columns, role);
+ const at = keyAt(columns);
+ const row = (table?.rows ?? []).find((entry) => String(entry[at] ?? '') === key);
+ if (!row) return key;
+ return String(row[columns.indexOf(named)] ?? '').trim() || key;
+}
+
+/** How many of a column's words reach no single row. What the heading badge says, and
+ * the number that goes up the moment somebody renames a row in a spreadsheet. */
+export function unresolved(targets) {
+ let count = 0;
+ for (const found of (targets ?? new Map()).values()) count += found.missing.length;
+ return count;
+}
diff --git a/frontend/src/lib/sheetRows.test.js b/frontend/src/lib/sheetRows.test.js
new file mode 100644
index 0000000..6815695
--- /dev/null
+++ b/frontend/src/lib/sheetRows.test.js
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+import { normalizeRole } from './sheetRoles.js';
+import { backLinks, namingColumn, rowLabel, rowTargets, unresolved } from './sheetRows.js';
+
+/** An order of battle as the binders wrote one: a brigade listing its companies, each
+ * company naming its brigade back, and one name that no longer matches anything. */
+const orbat = {
+ columns: ['id', 'Unit', 'Links with others'],
+ rows: [
+ ['r1', '3rd Brigade', '1st Coy, 2nd Coy'],
+ ['r2', '1st Coy', '3rd Brigade'],
+ ['r3', '2nd Coy', '3rd Brigade'],
+ ['r4', 'Recon Coy', '3rd Bde'],
+ ],
+};
+
+const role = normalizeRole({ kind: 'row', of: 'Unit', multi: ', ' });
+const at = orbat.columns.indexOf('Links with others');
+
+describe('one row pointing at another', () => {
+ it('follows the words, because the words are what the file holds', () => {
+ // Not keys: a file whose links read `r7f3a` is a file the collaborator opening it
+ // in a spreadsheet cannot follow.
+ const found = rowTargets(orbat, at, role);
+ expect(found.get('r1').keys).toEqual(['r2', 'r3']);
+ expect(found.get('r2').keys).toEqual(['r1']);
+ });
+
+ it('reports a name that reaches no row rather than guessing which one it meant', () => {
+ // The binders' own column had decayed to `#REF!` for exactly this reason. Here the
+ // same decay is a list of what to fix instead of a cell that says nothing.
+ const found = rowTargets(orbat, at, role);
+ expect(found.get('r4').keys).toEqual([]);
+ expect(found.get('r4').missing).toEqual(['3rd Bde']);
+ expect(unresolved(found)).toBe(1);
+ });
+
+ it('reports a name two rows share rather than picking one of them', () => {
+ const twins = {
+ columns: ['id', 'Unit', 'Parent'],
+ rows: [
+ ['r1', '1st Coy', 'HQ'],
+ ['r2', 'HQ', ''],
+ ['r3', 'HQ', ''],
+ ],
+ };
+ const found = rowTargets(twins, 2, normalizeRole({ kind: 'row', of: 'Unit' }));
+ expect(found.get('r1')).toEqual({ keys: [], missing: ['HQ'] });
+ });
+
+ it('never lets a row point at itself', () => {
+ const alone = { columns: ['id', 'Unit', 'Parent'], rows: [['r1', 'HQ', 'HQ']] };
+ const found = rowTargets(alone, 2, normalizeRole({ kind: 'row', of: 'Unit' }));
+ expect(found.get('r1')).toEqual({ keys: [], missing: ['HQ'] });
+ });
+
+ it('shows the other side without a second column being kept in step', () => {
+ // The reading the binders kept by hand and could not keep true: who points at me.
+ const back = backLinks(rowTargets(orbat, at, role));
+ expect(back.get('r1')).toEqual(['r2', 'r3']);
+ expect(back.get('r2')).toEqual(['r1']);
+ expect(back.has('r4')).toBe(false);
+ });
+
+ it('names a row by its own subject cell, and by its key when that cell is empty', () => {
+ expect(rowLabel(orbat, 'r2', role)).toBe('1st Coy');
+ const blank = { columns: ['id', 'Unit'], rows: [['r9', '']] };
+ expect(rowLabel(blank, 'r9', role)).toBe('r9');
+ });
+
+ it('falls back to the first column that is not the key', () => {
+ // Which is the subject column on every sheet anyone builds, and the one a reader
+ // would have used anyway.
+ expect(namingColumn(orbat.columns, { kind: 'row' })).toBe('Unit');
+ expect(namingColumn(orbat.columns, { kind: 'row', of: 'Gone' })).toBe('Unit');
+ expect(namingColumn(['id'], { kind: 'row' })).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/sheetTemplates.js b/frontend/src/lib/sheetTemplates.js
new file mode 100644
index 0000000..cae1b78
--- /dev/null
+++ b/frontend/src/lib/sheetTemplates.js
@@ -0,0 +1,117 @@
+/**
+ * The sheets an investigation starts over and over.
+ *
+ * A new sheet used to be born as *Subject · Status · Notes* — the right answer when there
+ * is nothing better to say, and the wrong one for the four tables an analyst builds by
+ * hand every case: a verification worklist, a geolocation index, a list of accounts, a
+ * run of events. Each of those is ten minutes of naming columns and declaring roles
+ * before any work happens, and every analyst builds a slightly different one, which is
+ * why two of their sheets never compare.
+ *
+ * So a template is columns **and** what the app should know about them: the status column
+ * arrives as a state with its four words painted, the coordinates arrive as a point, the
+ * dates arrive as dates. Nothing here is a schema — the columns are renamed, dropped and
+ * added like any others the moment the sheet exists. It is a starting point, not a shape
+ * the sheet has to keep.
+ *
+ * `progress` is which column the footer counts, so a fresh worklist can already say how
+ * many rows are left.
+ */
+
+/** The blank one, which is what `POST /sheets` makes on its own. Listed rather than
+ * implied: a template picker whose plainest answer is missing reads as a picker with no
+ * way out of it. */
+export const BLANK = {
+ id: 'blank',
+ label: 'Plain',
+ hint: 'Subject, Status, Notes',
+ columns: ['Subject', 'Status', 'Notes'],
+ roles: {},
+ progress: null,
+};
+
+export const SHEET_TEMPLATES = [
+ BLANK,
+ {
+ id: 'verify',
+ label: 'Verification worklist',
+ hint: 'A claim per row, checked and ruled on',
+ columns: ['Subject', 'Claim', 'Source', 'Status', 'Verdict', 'Checked on', 'Notes'],
+ roles: {
+ Status: { kind: 'state' },
+ Verdict: { kind: 'choice', values: ['confirmed', 'contradicted', 'unresolved'] },
+ 'Checked on': { kind: 'stamped' },
+ },
+ progress: 'Status',
+ },
+ {
+ // Named for what each column becomes rather than for what it looks like: this is the
+ // one sheet the app can build proofs out of, and it can only do that when it knows
+ // which address is the footage and which is the published picture. `Place` is gone —
+ // that is what a build *writes*, not something an analyst types.
+ id: 'geoloc',
+ label: 'Geolocation index',
+ hint: 'A picture per row, and where it turns out to be',
+ columns: [
+ 'Title',
+ 'Source media',
+ 'Geolocation proof',
+ 'Coordinates',
+ 'Status',
+ 'Notes',
+ ],
+ roles: {
+ 'Source media': { kind: 'url' },
+ 'Geolocation proof': { kind: 'url' },
+ Coordinates: { kind: 'latlon' },
+ Status: { kind: 'state' },
+ },
+ progress: 'Coordinates',
+ },
+ {
+ id: 'accounts',
+ label: 'Accounts',
+ hint: 'Handles, where they post, when they were last seen',
+ columns: ['Handle', 'Platform', 'Profile', 'Behind it', 'Last seen', 'Status', 'Notes'],
+ roles: {
+ Platform: { kind: 'choice' },
+ 'Last seen': { kind: 'when', shape: 'date' },
+ Status: { kind: 'state' },
+ },
+ progress: 'Status',
+ },
+ {
+ id: 'events',
+ label: 'Events',
+ hint: 'When, what, where, and what it rests on',
+ columns: ['When', 'What', 'Where', 'Coordinates', 'Source', 'Confidence', 'Notes'],
+ roles: {
+ When: { kind: 'when', shape: 'datetime' },
+ Coordinates: { kind: 'latlon' },
+ Confidence: { kind: 'choice', values: ['high', 'medium', 'low'] },
+ },
+ progress: 'Coordinates',
+ },
+];
+
+export function sheetTemplate(id) {
+ return SHEET_TEMPLATES.find((entry) => entry.id === id) ?? BLANK;
+}
+
+/**
+ * The sidecar a template asks for, over whatever the new sheet came back with.
+ *
+ * Applied as an ordinary save rather than at creation: the roles are the browser's to
+ * declare — it owns reading them — and a create route that also took a sidecar would be a
+ * second way to write one.
+ */
+export function templateMeta(meta, template) {
+ const chosen = template ?? BLANK;
+ const roles = { ...(meta?.roles ?? {}) };
+ for (const [column, role] of Object.entries(chosen.roles ?? {})) roles[column] = { ...role };
+ return {
+ ...meta,
+ roles,
+ progress: chosen.progress ?? meta?.progress ?? null,
+ };
+}
diff --git a/frontend/src/lib/sheetTemplates.test.js b/frontend/src/lib/sheetTemplates.test.js
new file mode 100644
index 0000000..d5ab1d4
--- /dev/null
+++ b/frontend/src/lib/sheetTemplates.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import { BLANK, SHEET_TEMPLATES, sheetTemplate, templateMeta } from './sheetTemplates.js';
+import { emptyMeta } from './sheet.js';
+import { normalizeRole } from './sheetRoles.js';
+
+describe('the sheets a case starts from', () => {
+ it('offers the plain one first, which is what the create route makes on its own', () => {
+ expect(SHEET_TEMPLATES[0]).toBe(BLANK);
+ expect(BLANK.columns).toEqual(['Subject', 'Status', 'Notes']);
+ });
+
+ it('names every column it declares a role for', () => {
+ for (const template of SHEET_TEMPLATES) {
+ for (const column of Object.keys(template.roles ?? {})) {
+ expect(template.columns).toContain(column);
+ }
+ if (template.progress) expect(template.columns).toContain(template.progress);
+ }
+ });
+
+ it('declares roles the app can actually read', () => {
+ for (const template of SHEET_TEMPLATES) {
+ for (const role of Object.values(template.roles ?? {})) {
+ expect(normalizeRole(role)).not.toBeNull();
+ }
+ }
+ });
+
+ it('falls back to the plain one for a name nobody knows', () => {
+ expect(sheetTemplate('nope')).toBe(BLANK);
+ expect(sheetTemplate('geoloc').id).toBe('geoloc');
+ });
+
+ it('lays its roles over the sidecar the new sheet came back with', () => {
+ const meta = templateMeta({ ...emptyMeta(), widths: { Subject: 200 } }, sheetTemplate('geoloc'));
+ expect(meta.widths).toEqual({ Subject: 200 });
+ expect(meta.roles.Coordinates).toEqual({ kind: 'latlon' });
+ expect(meta.roles.Status.kind).toBe('state');
+ expect(meta.progress).toBe('Coordinates');
+ });
+
+ // The build reads a sheet by its roles, not by its column names, so what a geolocation
+ // index is born with is what decides whether `Build proofs` is offered on it at all.
+ it('gives the geolocation index the two addresses and the point a build needs', () => {
+ const template = sheetTemplate('geoloc');
+ expect(template.columns).toEqual([
+ 'Title',
+ 'Source media',
+ 'Geolocation proof',
+ 'Coordinates',
+ 'Status',
+ 'Notes',
+ ]);
+ const kinds = Object.values(template.roles).map((role) => role.kind);
+ expect(kinds.filter((kind) => kind === 'url')).toHaveLength(2);
+ expect(kinds).toContain('latlon');
+ expect(template.columns).not.toContain('Place');
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 0dce05d..d25eca0 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -21,7 +21,7 @@ import { loadRelationTypes } from './relations.svelte.js';
export const prefs = $state({
coordFormat: 'dd', // 'dd' | 'dms' | 'mgrs'
units: 'metric', // 'metric' | 'imperial'
- homeView: { lat: 48.8584, lon: 2.2945, zoom: 16 }, // where Satellite opens
+ homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
postTarget: 'x', // social composer a fresh post draft starts with
signatureHandle: '', // account handle stamped onto proofs that opt into it
@@ -214,6 +214,15 @@ export const uiState = $state({
timelineRange: null, // { from, to }
/** A fact-time range handed to the Satellite map as a temporary event layer. */
mapTimelineRange: null, // { from, to }
+ /**
+ * A sheet's column of coordinates, handed to the map as a temporary layer.
+ *
+ * The **points travel**, not a query — which is the opposite of `drawInGraph` and for
+ * a reason: a sheet's coordinates are text in a file, not entities the case can be
+ * asked about, so there is no question the map could re-ask. Session-only, consumed
+ * and cleared by Satellite, and never part of a capture or a proof.
+ */
+ mapSheetPoints: null, // { points: [{ lat, lon, label, decimals }], sheet, column }
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
// A point, a date and a time handed over by Coords & Sky: the Satellite tab
// opens its Sun & moon mode there. Session-only, and never part of a capture
@@ -333,18 +342,9 @@ export async function openCase(id) {
!(await prepareCaseChange(currentId, id))
) return;
if (run !== openingCase) return;
- // reference viewers point at the previous case's media — drop them
- if (caseState.current?.id !== id) {
- uiState.refViewers = [];
- uiState.openNotebook = null;
- uiState.focusCapture = null;
- uiState.drawInGraph = null;
- uiState.openBoardEntity = null;
- uiState.openGraphEntity = null;
- uiState.timelineFocus = null;
- uiState.timelineRange = null;
- uiState.mapTimelineRange = null;
- }
+ // Everything queued names something in the case being left behind —
+ // reference viewers point at its media, `openProof` at one of its files.
+ if (caseState.current?.id !== id) clearCaseHandoffs();
const opened = await api.get(`/api/cases/${id}`);
// Case reads can finish out of order. Only the latest choice may become current,
// or a slow first click can put its case back after a faster second one opened.
@@ -443,22 +443,27 @@ export async function promoteCase(name) {
}
/**
- * Close the open case (dropping back to one-shot mode). Also clears every
- * cross-tool handoff — otherwise a queued handoff meant for the closed case
- * (e.g. "open this proof") could get consumed against whatever case comes
- * next, since the consuming effects only check that *some* case is open.
+ * Drop every queued cross-tool handoff.
+ *
+ * A handoff names something in the case that queued it — a proof, a draft, a
+ * media path, a point on the map — and the effects that consume one only check
+ * that *some* case is open. So anything still queued when the open case changes
+ * would be spent against the case that replaced it.
+ *
+ * One list, called from both `closeCase` and `openCase`. Written out twice they
+ * drifted, and switching between two cases went on carrying `openProof`,
+ * `openDraft`, `openInspect`, `composeQueue`, `inspectPath`, `focusMedia`,
+ * `postProof`, `gotoCoords` and `skyAt` across the boundary.
*/
-export function closeCase() {
- // Invalidate an open or refresh still in flight before dropping the current case.
- openingCase++;
- caseState.current = null;
- rememberCase(null);
+function clearCaseHandoffs() {
uiState.composeQueue = [];
uiState.postProof = null;
uiState.openProof = null;
uiState.openDraft = null;
+ uiState.openNotebook = null;
uiState.inspectPath = null;
uiState.focusMedia = null;
+ uiState.focusCapture = null;
uiState.openInspect = null;
uiState.drawInGraph = null;
uiState.openBoardEntity = null;
@@ -471,6 +476,18 @@ export function closeCase() {
uiState.refViewers = [];
}
+/**
+ * Close the open case (dropping back to one-shot mode). Also clears every
+ * cross-tool handoff — see `clearCaseHandoffs`.
+ */
+export function closeCase() {
+ // Invalidate an open or refresh still in flight before dropping the current case.
+ openingCase++;
+ caseState.current = null;
+ rememberCase(null);
+ clearCaseHandoffs();
+}
+
/**
* Permanently delete a case and everything it contains (the whole folder on
* disk — media, satellite, proofs, exports). Irreversible; the caller is
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 324bb6d..479a0f0 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -70,6 +70,10 @@ describe('closeCase', () => {
expect(uiState.timelineRange).toBeNull();
expect(uiState.mapTimelineRange).toBeNull();
expect(uiState.gotoCoords).toBeNull();
+ expect(uiState.openNotebook).toBeNull();
+ expect(uiState.focusCapture).toBeNull();
+ expect(uiState.skyAt).toBeNull();
+ expect(uiState.refViewers).toEqual([]);
});
});
@@ -123,7 +127,7 @@ describe('prefsReady — tools must not race the settings fetch', () => {
await loadPrefs().catch(() => {});
await expect(prefsReady).resolves.toBeUndefined(); // never hangs a tool
- expect(prefs.homeView).toEqual({ lat: 48.8584, lon: 2.2945, zoom: 16 });
+ expect(prefs.homeView).toEqual({ lat: 43, lon: 25, zoom: 3 });
});
});
@@ -279,6 +283,43 @@ describe('case request ownership', () => {
expect(state.caseState.loading).toBe(false);
});
+ it('drops every handoff meant for the case being left behind', async () => {
+ // Switching cases and closing one share this list. Written out twice they
+ // drifted, and an `openProof` queued in case A was spent against case B.
+ state.caseState.current = { id: 'case-a', name: 'Case A' };
+ api.get.mockResolvedValue({ id: 'case-b', name: 'Case B' });
+ const queued = {
+ composeQueue: ['media/a.jpg'],
+ postProof: { title: 'x' },
+ openProof: 'proof-a',
+ openDraft: 'draft-a',
+ openNotebook: { noteId: 'note-a' },
+ inspectPath: 'media/a.jpg',
+ focusMedia: 'media/a.jpg',
+ focusCapture: 'media/crop.png',
+ openInspect: 'session-a',
+ drawInGraph: { label: 'A question' },
+ openBoardEntity: 'entity-a',
+ openGraphEntity: 'entity-a',
+ timelineFocus: { itemId: 'event-a' },
+ timelineRange: { from: '2026-01-01', to: '2026-02-01' },
+ mapTimelineRange: { from: '2026-01-01', to: '2026-02-01' },
+ gotoCoords: { lat: 1, lon: 2 },
+ skyAt: { lat: 1, lon: 2, date: '2026-01-01', time: '12:00' },
+ refViewers: [{ id: 'v1' }],
+ };
+ Object.assign(state.uiState, queued);
+
+ await state.openCase('case-b');
+
+ for (const key of Object.keys(queued)) {
+ const left = state.uiState[key];
+ expect(Array.isArray(left) ? left : left ?? null, `uiState.${key}`).toEqual(
+ Array.isArray(queued[key]) ? [] : null
+ );
+ }
+ });
+
it('waits for case-owned work and cancels the switch when it cannot be saved', async () => {
const guard = vi.fn().mockResolvedValue(false);
const unregister = state.registerCaseChangeGuard(guard);
diff --git a/frontend/src/lib/statedSource.js b/frontend/src/lib/statedSource.js
new file mode 100644
index 0000000..99a559a
--- /dev/null
+++ b/frontend/src/lib/statedSource.js
@@ -0,0 +1,36 @@
+/**
+ * What "source" means wherever one is stated by hand.
+ *
+ * A paste, an import and a later correction write the same field, and the server
+ * validates the three through one function (`stated_source`, api/media.py). This
+ * is that rule on the near side, so a bad address is refused in the dialog rather
+ * than coming back as a 422 — and so the three surfaces cannot drift into three
+ * ideas of what an origin is.
+ *
+ * Links only. The field feeds the entity's `source_url`, the proof plate's source
+ * line and the lineage a lost file leaves behind, all of which are addresses. An
+ * origin that is not one — a hand-off, a disk — is a note.
+ */
+const HTTP_URL = /^https?:\/\/\S+$/i;
+
+/** Whether a hand-typed origin is one the case can keep. */
+export function isSourceUrl(url) {
+ return HTTP_URL.test((url ?? '').trim());
+}
+
+/** What is wrong with a typed source, or '' when nothing is. */
+export function sourceProblem(url) {
+ const value = (url ?? '').trim();
+ return value && !isSourceUrl(value) ? 'The source must be an http(s) address.' : '';
+}
+
+/** The files whose origin only the analyst can state: brought in off a disk, out
+ * of the clipboard, or adopted from the case folder. Mirrors
+ * `STATED_SOURCE_TYPES` (engine/media.py), which is what refuses the write. */
+const STATED_SOURCE_TYPES = new Set(['upload', 'clipboard', 'manual']);
+
+/** Whether this file's origin is the analyst's to state. A download's address is
+ * what the app fetched, and a derivative's origin is the file it came out of. */
+export function canStateSource(item) {
+ return STATED_SOURCE_TYPES.has(item?.source?.type);
+}
diff --git a/frontend/src/lib/statedSource.test.js b/frontend/src/lib/statedSource.test.js
new file mode 100644
index 0000000..101df9b
--- /dev/null
+++ b/frontend/src/lib/statedSource.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { canStateSource, isSourceUrl, sourceProblem } from './statedSource.js';
+
+describe('a stated source', () => {
+ it('is an http(s) address or nothing', () => {
+ expect(isSourceUrl('https://t.me/channel/42')).toBe(true);
+ expect(isSourceUrl(' http://example.org/a ')).toBe(true);
+ expect(isSourceUrl('ftp://host/file')).toBe(false);
+ expect(isSourceUrl('a friend sent it')).toBe(false);
+ expect(isSourceUrl('')).toBe(false);
+ });
+
+ it('says nothing about an empty field: stating no origin is a real answer', () => {
+ expect(sourceProblem('')).toBe('');
+ expect(sourceProblem(' ')).toBe('');
+ expect(sourceProblem(null)).toBe('');
+ });
+
+ it('names what is wrong with an address that is not one', () => {
+ expect(sourceProblem('sent on Signal')).toBe('The source must be an http(s) address.');
+ });
+});
+
+describe('whose origin the analyst gets to state', () => {
+ it('is the material they brought in themselves', () => {
+ expect(canStateSource({ source: { type: 'upload' } })).toBe(true);
+ expect(canStateSource({ source: { type: 'clipboard' } })).toBe(true);
+ expect(canStateSource({ source: { type: 'manual' } })).toBe(true);
+ });
+
+ it('is never what a tool fetched or made', () => {
+ // a download's address is what was actually pulled, and a frame's origin is
+ // the video it came out of — neither is a later edit's to rewrite
+ expect(canStateSource({ source: { type: 'download', url: 'https://x.com/a/1' } })).toBe(false);
+ expect(canStateSource({ source: { type: 'inspect', from: 'media/clip.mp4' } })).toBe(false);
+ expect(canStateSource({ source: { type: 'satellite' } })).toBe(false);
+ expect(canStateSource(null)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/thisBrowser.js b/frontend/src/lib/thisBrowser.js
new file mode 100644
index 0000000..911f62c
--- /dev/null
+++ b/frontend/src/lib/thisBrowser.js
@@ -0,0 +1,35 @@
+/**
+ * Which browser is showing this page.
+ *
+ * The app is a local server and a browser tab, so the tab *is* the analyst's browser —
+ * and the session Azimut is being asked to read is almost always the one they are looking
+ * at it in. Defaulting the cookie prompt to Firefox meant a Chrome user answered a
+ * question whose answer was on screen the whole time.
+ *
+ * Read off the user agent, which is a guess and is treated as one: it fills a select the
+ * analyst can change, never a setting written behind them. The order matters — every
+ * Chromium browser claims to be Chrome, and most claim to be Safari too — so the
+ * particular ones are tested before the general.
+ */
+const SIGNATURES = [
+ [/\bEdg[A-Z]?\//, 'edge'],
+ [/\bOPR\/|\bOpera\//, 'opera'],
+ [/\bVivaldi\//, 'vivaldi'],
+ [/\bBrave\//, 'brave'],
+ [/\bFirefox\/|\bFxiOS\//, 'firefox'],
+ [/\bChromium\//, 'chromium'],
+ [/\bChrome\/|\bCriOS\//, 'chrome'],
+ [/\bSafari\//, 'safari'],
+];
+
+/** The browser this page is in, or `fallback` when nothing in the agent says.
+ *
+ * Brave hides itself from the agent on purpose and answers `navigator.brave` instead, so
+ * it is asked directly — a Brave user offered "chrome" is offered a cookie store that
+ * does not exist on their machine. */
+export function thisBrowser(fallback = 'firefox', agent = null, nav = null) {
+ const runtime = nav ?? (typeof navigator === 'undefined' ? null : navigator);
+ if (runtime?.brave) return 'brave';
+ const said = agent ?? runtime?.userAgent ?? '';
+ return SIGNATURES.find(([pattern]) => pattern.test(said))?.[1] ?? fallback;
+}
diff --git a/frontend/src/lib/thisBrowser.test.js b/frontend/src/lib/thisBrowser.test.js
new file mode 100644
index 0000000..301f664
--- /dev/null
+++ b/frontend/src/lib/thisBrowser.test.js
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { thisBrowser } from './thisBrowser.js';
+
+const AGENTS = {
+ firefox: 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0',
+ chrome:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
+ edge:
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36 Edg/126.0',
+ opera:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36 OPR/112.0',
+ vivaldi:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36 Vivaldi/6.8',
+ chromium:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chromium/126.0 Chrome/126.0 Safari/537.36',
+ safari:
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15',
+};
+
+describe('which browser is showing this page', () => {
+ // Every Chromium browser claims to be Chrome and most claim to be Safari, so the
+ // particular ones have to be tested before the general or they all read as Chrome.
+ it('reads each browser off its own agent', () => {
+ for (const [expected, agent] of Object.entries(AGENTS)) {
+ expect(thisBrowser('firefox', agent, {})).toBe(expected);
+ }
+ });
+
+ it('asks Brave directly, since it hides itself from the agent on purpose', () => {
+ expect(thisBrowser('firefox', AGENTS.chrome, { brave: {} })).toBe('brave');
+ });
+
+ it('falls back rather than guessing at an agent it does not know', () => {
+ expect(thisBrowser('firefox', 'SomeKiosk/1.0', {})).toBe('firefox');
+ expect(thisBrowser('chrome', '', {})).toBe('chrome');
+ });
+});
diff --git a/frontend/src/lib/timelinePlate.js b/frontend/src/lib/timelinePlate.js
new file mode 100644
index 0000000..06b954f
--- /dev/null
+++ b/frontend/src/lib/timelinePlate.js
@@ -0,0 +1,314 @@
+/**
+ * The Timeline, serialised as SVG.
+ *
+ * The axis is HTML on screen — lanes of absolutely placed entries, every position a
+ * percentage of the window — so there is nothing to rasterise and nothing to copy. What
+ * there is, is the layout: `layoutTimelineItems` answers where every entry sits, in
+ * percentages, and a percentage lands on a plate as easily as in a stylesheet. This
+ * module multiplies out and draws, and decides nothing about time.
+ *
+ * It is handed a layout computed at `PLATE_PLOT`, not the one on screen. Lanes are packed
+ * by the pixels a label takes, so a layout made for the browser's width and replayed here
+ * would reserve the wrong gaps — the plate has to be the same page whatever window it was
+ * exported from.
+ *
+ * Two deliberate differences from the screen:
+ *
+ * - **The window is the reading.** A Timeline plate is its saved window, never a
+ * viewport: the axis is what the analyst chose to look at.
+ * - **An entry carries its name, not its date.** On screen the date is written beside
+ * the label because a pixel cannot be read precisely. A plate has a ruler above every
+ * lane and draws the precision it holds — a point, a bar, a dashed edge for an
+ * approximation, a hairline for the span a reduced date covers — so the words would be
+ * the one thing on the page repeating what the drawing already says.
+ */
+
+import {
+ PLATE_COLOURS,
+ fitText,
+ plateDocument,
+ round,
+ svgCircle,
+ svgLine,
+ svgRect,
+ svgText,
+} from './plate.js';
+import { TRACK_COLORS } from './timelineTracks.js';
+
+/** The plate's own axis geometry, in SVG user units. */
+export const TIMELINE_PLATE = {
+ width: 1180,
+ names: 150,
+ right: 16,
+ ruler: 38,
+ trackHead: 17,
+ lane: 24,
+ trackGap: 12,
+ marker: 4,
+ /** Roughly what one character of the 10px label face costs. Fixed rather than
+ * measured: a plate has to come out the same under a test. */
+ charWidth: 5.4,
+ labelSize: 10,
+};
+
+/**
+ * How wide the plate's axis is, in pixels.
+ *
+ * The number a caller has to lay its entries out against. `layoutTimelineItems` packs
+ * lanes by the room a label takes **in pixels**, so a layout computed for the screen and
+ * replayed here would reserve the wrong gaps: two entries the browser kept apart at
+ * 1900px land on top of each other at 1014, and a narrow window clusters entries this
+ * page had the room to draw. The Timeline hands over a layout made at this width.
+ */
+export const PLATE_PLOT = TIMELINE_PLATE.width - TIMELINE_PLATE.names - TIMELINE_PLATE.right;
+
+/**
+ * A track's colour on paper.
+ *
+ * The screen's own palette is `--anno-*`, which is tuned to sit on satellite imagery
+ * and is the same in both themes: its yellow disappears on white. So the six keep their
+ * order and their meaning, stepped down for paper — the way the graph families are.
+ * A track with no colour of its own inherits its category's, as on screen.
+ */
+export const PLATE_TRACKS = {
+ red: '#c0392b',
+ blue: '#2c6fb5',
+ amber: '#a8791a',
+ green: '#2f8f5b',
+ magenta: '#a03a9e',
+ orange: '#b4661c',
+};
+
+/** Mirrors `--timeline-*` in `app.css`'s light theme; `timelinePlate.test.js` fails on
+ * a drift. */
+export const PLATE_CATEGORIES = {
+ statement: '#1f7669',
+ media: '#4264b5',
+ case_activity: '#76539d',
+};
+
+export function trackColour(track = {}) {
+ if (TRACK_COLORS.includes(track.color)) return PLATE_TRACKS[track.color];
+ return PLATE_CATEGORIES[track.categories?.[0]] ?? PLATE_CATEGORIES.statement;
+}
+
+/** Cut a label to what the space beside it can hold, at the lane face's own metric. */
+export function fitLabel(text, room) {
+ return fitText(text, room, TIMELINE_PLATE.charWidth);
+}
+
+/**
+ * The axis and its lanes, sized to the tracks it holds.
+ *
+ * `tracks` are the grouped tracks the tool draws — each with its `layout` from
+ * `layoutTimelineItems` — and `ticks`, `bands` and `nowLeft` are the axis readings it
+ * already computed for the same window.
+ */
+export function timelineDrawing({
+ tracks = [],
+ ticks = [],
+ minorTicks = [],
+ bands = [],
+ nowLeft = null,
+ scaleWord = '',
+ clock = '',
+} = {}) {
+ const geometry = TIMELINE_PLATE;
+ const width = geometry.width;
+ const plotLeft = geometry.names;
+ const plotWidth = PLATE_PLOT;
+ const plotRight = plotLeft + plotWidth;
+ const atPercent = (percent) => plotLeft + (Number(percent) || 0) * plotWidth / 100;
+
+ // Every track's height first, so the gridlines can run the whole way down.
+ const rows = tracks.map((track) => (track.collapsed ? 0 : Math.max(1, track.layout?.rows ?? 1)));
+ const height = tracks.reduce(
+ (total, _track, index) =>
+ total + geometry.trackHead + rows[index] * geometry.lane + geometry.trackGap,
+ geometry.ruler,
+ );
+
+ const parts = [];
+
+ // -- the ruler ------------------------------------------------------------
+ parts.push(svgLine({
+ x1: plotLeft, y1: geometry.ruler, x2: width - geometry.right, y2: geometry.ruler,
+ stroke: PLATE_COLOURS.hint,
+ }));
+ for (const band of bands) {
+ parts.push(svgText(band.label, {
+ x: atPercent(band.left) + 3, y: 12, size: 10, fill: PLATE_COLOURS.hint,
+ }));
+ }
+ for (const tick of ticks) {
+ const x = atPercent(tick.left);
+ parts.push(svgLine({ x1: x, y1: geometry.ruler - 6, x2: x, y2: geometry.ruler }));
+ parts.push(svgText(tick.label, {
+ x, y: geometry.ruler - 9, size: 10, anchor: 'middle', fill: PLATE_COLOURS.label,
+ }));
+ }
+ const scale = [scaleWord, clock].filter(Boolean).join(' · ');
+ if (scale) {
+ parts.push(svgText(scale, {
+ x: plotLeft - 8, y: geometry.ruler - 9, size: 10, anchor: 'end', fill: PLATE_COLOURS.hint,
+ }));
+ }
+
+ // -- the gridlines, down every lane ---------------------------------------
+ for (const tick of minorTicks) {
+ const x = atPercent(tick.left);
+ parts.push(svgLine({ x1: x, y1: geometry.ruler, x2: x, y2: height, stroke: PLATE_COLOURS.rule, dash: '2 4' }));
+ }
+ for (const tick of ticks) {
+ const x = atPercent(tick.left);
+ parts.push(svgLine({ x1: x, y1: geometry.ruler, x2: x, y2: height, stroke: PLATE_COLOURS.rule }));
+ }
+ if (nowLeft !== null && nowLeft !== undefined) {
+ const x = atPercent(nowLeft);
+ parts.push(svgLine({ x1: x, y1: geometry.ruler, x2: x, y2: height, stroke: PLATE_COLOURS.accent, dash: '5 4' }));
+ parts.push(svgText('Now', { x: x + 3, y: geometry.ruler + 11, size: 9, fill: PLATE_COLOURS.accent }));
+ }
+
+ // -- the tracks -----------------------------------------------------------
+ let top = geometry.ruler;
+ let entries = 0;
+ tracks.forEach((track, index) => {
+ const colour = trackColour(track);
+ const head = top + geometry.trackHead;
+ const drawn = track.layout?.items ?? [];
+ const clusters = track.layout?.clusters ?? [];
+ const held = drawn.length + clusters.reduce((sum, cluster) => sum + (cluster.count ?? 0), 0);
+ entries += held;
+ parts.push(svgCircle({ x: 8, y: head - 8, r: 4, fill: colour }));
+ parts.push(svgText(fitLabel(track.label, geometry.names - 46), {
+ x: 18, y: head - 4, size: 11, weight: '600', fill: PLATE_COLOURS.ink,
+ }));
+ parts.push(svgText(track.collapsed ? 'folded' : String(held), {
+ x: geometry.names - 10, y: head - 4, size: 10, anchor: 'end', fill: PLATE_COLOURS.hint,
+ }));
+ if (track.groupLabel) {
+ parts.push(svgText(fitLabel(track.groupLabel, geometry.names - 28), {
+ x: 18, y: head + 8, size: 9, fill: PLATE_COLOURS.hint,
+ }));
+ }
+
+ if (!track.collapsed) {
+ for (const item of drawn) {
+ const laneTop = head + item.lane * geometry.lane;
+ const middle = laneTop + geometry.lane / 2;
+ const x = atPercent(item.left);
+ const interval = item.shape === 'interval';
+ // Held inside the axis: a bar carries a minimum width of its own, so one that
+ // starts at the very end of the window would otherwise cross the ruler it is
+ // being read against.
+ const span = Math.max(1.5, Math.min((Number(item.width) || 0) * plotWidth / 100, plotRight - x));
+ // The span a reduced date covers, drawn as the hairline it is on screen: the
+ // entry is somewhere in here, and the plate must not claim a point instead.
+ if (!interval && item.haloWidth > 0) {
+ const haloLeft = atPercent(item.haloLeft);
+ parts.push(svgRect({
+ x: haloLeft,
+ y: middle + 7,
+ width: Math.max(1, Math.min((Number(item.haloWidth) || 0) * plotWidth / 100, plotRight - haloLeft)),
+ height: 3,
+ fill: colour,
+ opacity: 0.35,
+ }));
+ }
+ if (interval) {
+ parts.push(svgRect({
+ x, y: middle - 6, width: span, height: 12, radius: 3,
+ fill: colour, opacity: 0.22, stroke: colour, strokeWidth: 1,
+ dash: item.approximate ? '4 3' : undefined,
+ }));
+ } else {
+ parts.push(svgCircle({
+ x, y: middle, r: geometry.marker,
+ fill: item.status === 'suggested' ? PLATE_COLOURS.paper : colour,
+ stroke: colour,
+ strokeWidth: 1.4,
+ dash: item.approximate ? '2 2' : undefined,
+ }));
+ }
+ // The lane packing reserved this entry a box, in these same units, and that box
+ // is why the lane below it is empty. A label is cut to it rather than to the far
+ // edge of the page, since the room out there is where the next entry stands.
+ const reserved = interval || !Number.isFinite(item.displayWidth)
+ ? Infinity
+ : Math.max(0, item.displayWidth - geometry.marker - 6);
+ // An entry the packing pushed against the right edge is labelled leftwards, the
+ // way the screen labels it, so its name has somewhere to go.
+ const anchor = !interval && item.endAligned ? 'end' : undefined;
+ const edge = anchor
+ ? x - geometry.marker - 5
+ : (interval ? x + span + 6 : x + geometry.marker + 5);
+ const label = fitLabel(
+ item.label,
+ Math.min(anchor ? edge - plotLeft : plotRight - edge, reserved),
+ );
+ if (label) {
+ parts.push(svgText(label, {
+ x: edge, y: middle + 3.5, size: geometry.labelSize, anchor,
+ fill: item.confidence === 'refuted' ? PLATE_COLOURS.hint : PLATE_COLOURS.ink,
+ }));
+ }
+ }
+ // What the lane could not hold, counted rather than dropped silently.
+ for (const cluster of clusters) {
+ const laneTop = head + cluster.lane * geometry.lane;
+ parts.push(svgText(`+${cluster.count}`, {
+ x: atPercent(cluster.left), y: laneTop + geometry.lane / 2 + 3.5,
+ size: 10, anchor: 'middle', fill: PLATE_COLOURS.hint,
+ }));
+ }
+ if (!drawn.length && !clusters.length) {
+ parts.push(svgText('No entries in this window', {
+ x: plotLeft + 6, y: head + geometry.lane / 2 + 3.5, size: 10, fill: PLATE_COLOURS.hint,
+ }));
+ }
+ }
+
+ top += geometry.trackHead + rows[index] * geometry.lane + geometry.trackGap;
+ });
+
+ parts.push(svgLine({ x1: plotLeft, y1: round(height), x2: width - geometry.right, y2: round(height), stroke: PLATE_COLOURS.hint }));
+
+ return {
+ body: parts.filter(Boolean).join('\n'),
+ width,
+ height: Math.round(height + 4),
+ tracks: tracks.length,
+ entries,
+ };
+}
+
+/**
+ * The legend a timeline plate needs: what each track's colour stands for, and the
+ * conventions the drawing uses to stay honest about precision.
+ */
+export function timelineLegend(tracks = []) {
+ const families = tracks.map((track) => ({
+ family: track.groupLabel ? `${track.groupLabel} · ${track.label}` : track.label,
+ colour: trackColour(track),
+ }));
+ const strokes = [
+ { label: 'an instant', shape: 'dot' },
+ { label: 'a period', dash: [], width: 8 },
+ { label: 'approximate', dash: [4, 3], width: 1.4 },
+ { label: 'the span a reduced date covers', dash: [], width: 2 },
+ ];
+ return { families, strokes };
+}
+
+export function timelinePlate({ meta = {}, ...scene } = {}) {
+ const drawing = timelineDrawing(scene);
+ const { families, strokes } = timelineLegend(scene.tracks ?? []);
+ const tally = [
+ `${drawing.tracks} track${drawing.tracks === 1 ? '' : 's'}`,
+ `${drawing.entries} entr${drawing.entries === 1 ? 'y' : 'ies'} in this window`,
+ ].join(' · ');
+ return {
+ ...plateDocument({ meta: { ...meta, tally }, families, strokes, drawing }),
+ drawing,
+ };
+}
diff --git a/frontend/src/lib/timelinePlate.test.js b/frontend/src/lib/timelinePlate.test.js
new file mode 100644
index 0000000..f46f2c4
--- /dev/null
+++ b/frontend/src/lib/timelinePlate.test.js
@@ -0,0 +1,258 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { axisTicks, layoutTimelineItems } from './timeline.js';
+import { TRACK_COLORS } from './timelineTracks.js';
+import { PLATE_COLOURS } from './plate.js';
+import {
+ PLATE_CATEGORIES,
+ PLATE_PLOT,
+ PLATE_TRACKS,
+ TIMELINE_PLATE,
+ fitLabel,
+ timelineDrawing,
+ timelineLegend,
+ timelinePlate,
+ trackColour,
+} from './timelinePlate.js';
+
+const css = readFileSync(new URL('../app.css', import.meta.url), 'utf8');
+
+const FROM = Date.parse('2026-03-01T00:00:00Z');
+const TO = Date.parse('2026-03-31T00:00:00Z');
+
+const ITEMS = [
+ {
+ id: 't1', label: 'Convoy seen at the roundabout', category: 'statement',
+ earliest: '2026-03-04T09:00:00Z', latest: '2026-03-04T09:00:00Z',
+ shape: 'point', sortable: true, raw: '2026-03-04T09:00:00Z',
+ },
+ {
+ id: 't2', label: 'Checkpoint standing', category: 'statement',
+ earliest: '2026-03-10T00:00:00Z', latest: '2026-03-18T00:00:00Z',
+ shape: 'interval', approximate: true, sortable: true, raw: '2026-03-10/2026-03-18',
+ },
+ {
+ id: 't3', label: 'IMG_2291.jpg', category: 'media',
+ earliest: '2026-03-22T00:00:00Z', latest: '2026-03-22T23:59:59Z',
+ shape: 'point', zone: 'date-only', precision: 'day', sortable: true, raw: '2026-03-22',
+ },
+];
+
+function track(extra = {}) {
+ const items = extra.items ?? ITEMS;
+ return {
+ id: 'events',
+ label: 'Events',
+ categories: ['statement'],
+ total: items.length,
+ items,
+ layout: layoutTimelineItems(items, FROM, TO, PLATE_PLOT),
+ ...extra,
+ };
+}
+
+function scene(extra = {}) {
+ return {
+ tracks: [track()],
+ ticks: axisTicks(FROM, TO, PLATE_PLOT),
+ minorTicks: [],
+ bands: [{ left: 0, width: 100, label: 'March 2026' }],
+ nowLeft: null,
+ scaleWord: 'Days',
+ clock: 'UTC',
+ ...extra,
+ };
+}
+
+describe('the timeline palette on paper', () => {
+ it('keeps the category hues the light theme states', () => {
+ const plain = css.replace(/\/\*[\s\S]*?\*\//g, '');
+ const light = plain.slice(plain.indexOf(":root[data-theme='light']"));
+ for (const [category, hue] of Object.entries(PLATE_CATEGORIES)) {
+ const token = category === 'case_activity' ? 'activity' : category;
+ expect(light).toContain(`--timeline-${token}: ${hue}`);
+ }
+ });
+
+ it('steps the six track colours down for white paper', () => {
+ expect(Object.keys(PLATE_TRACKS)).toEqual(TRACK_COLORS);
+ for (const hue of Object.values(PLATE_TRACKS)) {
+ expect(hue).toMatch(/^#[0-9a-f]{6}$/);
+ // Readable as a mark on white: the screen's own annotation yellow is not.
+ const [r, g, b] = [1, 3, 5].map((at) => parseInt(hue.slice(at, at + 2), 16) / 255);
+ expect(0.2126 * r + 0.7152 * g + 0.0722 * b).toBeLessThan(0.55);
+ }
+ });
+
+ it('gives a coloured track its colour and an unset one its category', () => {
+ expect(trackColour({ color: 'blue', categories: ['statement'] })).toBe(PLATE_TRACKS.blue);
+ expect(trackColour({ categories: ['media'] })).toBe(PLATE_CATEGORIES.media);
+ expect(trackColour({})).toBe(PLATE_CATEGORIES.statement);
+ });
+});
+
+describe('serialising the timeline', () => {
+ it('draws the ruler, its scale and one lane block per track', () => {
+ const drawing = timelineDrawing(scene());
+
+ expect(drawing.tracks).toBe(1);
+ expect(drawing.body).toContain('March 2026');
+ expect(drawing.body).toContain('Days · UTC');
+ expect(drawing.body).toContain('>Events<');
+ expect(drawing.width).toBe(TIMELINE_PLATE.width);
+ expect(drawing.height).toBeGreaterThan(TIMELINE_PLATE.ruler);
+ });
+
+ it('turns a percentage into a place on the axis, never a viewport', () => {
+ const { body } = timelineDrawing(scene());
+ const plot = TIMELINE_PLATE.width - TIMELINE_PLATE.names - TIMELINE_PLATE.right;
+ const item = track().layout.items.find((entry) => entry.id === 't1');
+ const expected = Math.round((TIMELINE_PLATE.names + item.left * plot / 100) * 100) / 100;
+
+ expect(body).toContain(`cx="${expected}"`);
+ });
+
+ it('draws an instant, a period and the span a reduced date covers apart', () => {
+ const { body } = timelineDrawing(scene());
+
+ expect(body).toContain('Convoy seen at the roundabout'); // a point, with its name
+ expect(body).toContain('Checkpoint standing');
+ // the approximate period is a dashed bar, the day-only media its own hairline
+ expect(body).toMatch(/<rect[^>]*stroke-dasharray="4 3"/);
+ expect(body).toMatch(/<rect[^>]*fill-opacity="0.35"/);
+ });
+
+ it('marks a proposal hollow, the way every surface draws one', () => {
+ const suggested = [{ ...ITEMS[0], status: 'suggested' }];
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: suggested })] }));
+
+ expect(body).toContain(`fill="${PLATE_COLOURS.paper}"`);
+ });
+
+ it('says a track is folded instead of drawing lanes it is hiding', () => {
+ const { body, height } = timelineDrawing(scene({ tracks: [track({ collapsed: true })] }));
+ const open = timelineDrawing(scene());
+
+ expect(body).toContain('>folded<');
+ expect(body).not.toContain('Checkpoint standing');
+ expect(height).toBeLessThan(open.height);
+ });
+
+ it('counts what a lane could not hold rather than dropping it quietly', () => {
+ // Seven entries at one instant: the layout keeps six lanes and clusters the rest.
+ const crowded = Array.from({ length: 7 }, (_, index) => ({
+ ...ITEMS[0], id: `c${index}`, label: `Entry ${index}`,
+ }));
+ const laid = layoutTimelineItems(crowded, FROM, TO, PLATE_PLOT);
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: crowded, layout: laid })] }));
+
+ expect(laid.clusters.length).toBeGreaterThan(0);
+ expect(body).toContain(`+${laid.clusters[0].count}`);
+ });
+
+ it('says so when the window holds nothing', () => {
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: [], layout: layoutTimelineItems([], FROM, TO, PLATE_PLOT) })] }));
+ expect(body).toContain('No entries in this window');
+ });
+
+ it('draws the present as a line only when it falls inside the window', () => {
+ expect(timelineDrawing(scene({ nowLeft: 40 })).body).toContain('>Now<');
+ expect(timelineDrawing(scene()).body).not.toContain('>Now<');
+ });
+
+ it('is laid out at its own width, which is the axis it draws', () => {
+ expect(PLATE_PLOT).toBe(TIMELINE_PLATE.width - TIMELINE_PLATE.names - TIMELINE_PLATE.right);
+ });
+
+ it('holds a label inside the room its lane reserved, not the room to the page edge', () => {
+ // The lane packing gives every entry a box, in pixels, and that box is why the next
+ // entry sits where it sits. A label written past it runs under its neighbour.
+ const long = [{ ...ITEMS[0], label: 'A convoy of eleven trucks leaving the depot at dawn' }];
+ const laid = layoutTimelineItems(long, FROM, TO, PLATE_PLOT);
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: long, layout: laid })] }));
+ const written = body.match(/>(A convoy[^<]*)</)[1];
+
+ expect(written).not.toBe(long[0].label);
+ expect([...written].length * TIMELINE_PLATE.charWidth)
+ .toBeLessThanOrEqual(laid.items[0].displayWidth);
+ });
+
+ it('labels an entry at the far right leftwards, the way the screen does', () => {
+ const late = [{
+ ...ITEMS[0], id: 'late', label: 'Last convoy',
+ earliest: '2026-03-29T00:00:00Z', latest: '2026-03-29T00:00:00Z',
+ raw: '2026-03-29T00:00:00Z',
+ }];
+ const laid = layoutTimelineItems(late, FROM, TO, PLATE_PLOT);
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: late, layout: laid })] }));
+
+ expect(laid.items[0].endAligned).toBe(true);
+ expect(body).toMatch(/<text[^>]*text-anchor="end"[^>]*>Last convoy</);
+ });
+
+ it('keeps a bar that ends with the window inside the axis', () => {
+ // A short period carries a minimum width of its own, so one closing on the last hour
+ // of the window would cross the ruler it is being read against.
+ const tail = [{
+ id: 'tail', label: 'Standing watch', category: 'statement',
+ earliest: '2026-03-30T20:00:00Z', latest: '2026-03-31T00:00:00Z',
+ shape: 'interval', sortable: true, raw: '2026-03-30T20:00:00Z/2026-03-31T00:00:00Z',
+ }];
+ const laid = layoutTimelineItems(tail, FROM, TO, PLATE_PLOT);
+ const { body } = timelineDrawing(scene({ tracks: [track({ items: tail, layout: laid })] }));
+ const bar = body.match(/<rect[^>]*fill-opacity="0.22"[^>]*>/)[0];
+ const at = Number(bar.match(/ x="([\d.]+)"/)[1]);
+ const wide = Number(bar.match(/ width="([\d.]+)"/)[1]);
+
+ expect(wide).toBeGreaterThan(0);
+ expect(at + wide).toBeLessThanOrEqual(TIMELINE_PLATE.width - TIMELINE_PLATE.right);
+ });
+});
+
+describe('the timeline legend', () => {
+ it('names every track and the conventions the drawing uses', () => {
+ const { families, strokes } = timelineLegend([
+ track({ color: 'blue' }),
+ track({ id: 'media', label: 'Photos', groupLabel: 'Media', categories: ['media'] }),
+ ]);
+
+ expect(families[0]).toEqual({ family: 'Events', colour: PLATE_TRACKS.blue });
+ expect(families[1].family).toBe('Media · Photos');
+ expect(strokes.map((entry) => entry.label)).toContain('approximate');
+ // A point is drawn as a mark, not as a stroke: the legend says what it shows.
+ expect(strokes[0]).toEqual({ label: 'an instant', shape: 'dot' });
+ });
+});
+
+describe('the timeline plate', () => {
+ it('states the window and the clock it was read on', () => {
+ const { svg } = timelinePlate({
+ meta: {
+ caseName: 'Bakhmut convoy', surface: 'Timeline', view: 'March window',
+ window: '1 – 31 Mar 2026', clock: 'Asia/Tokyo', at: '2026-08-13T20:10:00Z',
+ },
+ ...scene(),
+ });
+
+ expect(svg).toContain('March window');
+ expect(svg).toContain('Fact time 1 – 31 Mar 2026 · Clock Asia/Tokyo');
+ expect(svg).toContain('an instant');
+ expect(svg).not.toMatch(/var\(--/);
+ });
+
+ it('counts what the window holds, since the page is one reading of it', () => {
+ const { svg } = timelinePlate({ meta: { view: 'March window' }, ...scene() });
+ expect(svg).toContain('1 track · 3 entries in this window');
+ });
+});
+
+describe('fitting a label', () => {
+ it('cuts to the room beside the marker, and gives up when there is none', () => {
+ expect(fitLabel('Checkpoint standing', 1000)).toBe('Checkpoint standing');
+ expect(fitLabel('Checkpoint standing', 30)).toBe('Chec…');
+ expect(fitLabel('Checkpoint standing', 3)).toBe('');
+ // Never through a surrogate pair: a plate holding half of one cannot be written.
+ expect(fitLabel('🏴🏴🏴🏴', 18)).toBe('🏴🏴…');
+ expect(fitLabel(null, 100)).toBe('');
+ });
+});
diff --git a/frontend/src/lib/timelineTracks.js b/frontend/src/lib/timelineTracks.js
index 610170b..da8934c 100644
--- a/frontend/src/lib/timelineTracks.js
+++ b/frontend/src/lib/timelineTracks.js
@@ -66,8 +66,11 @@ export function normalizeTimelineTracks(value) {
const tracks = raw.length ? raw.map(timelineTrack) : defaultTimelineTracks();
const seen = new Set();
return tracks.map((track, index) => {
+ // The suffix counts up. A fixed one is loop-invariant, so a saved view whose
+ // ids already hold the deduped spelling (['t-3', 't', 't']) spun here
+ // forever and froze the tab.
let id = track.id;
- while (seen.has(id)) id = `${track.id}-${index + 1}`;
+ for (let n = index + 1; seen.has(id); n += 1) id = `${track.id}-${n}`;
seen.add(id);
return { ...track, id };
});
diff --git a/frontend/src/lib/timelineTracks.test.js b/frontend/src/lib/timelineTracks.test.js
index 9a374ea..18906f2 100644
--- a/frontend/src/lib/timelineTracks.test.js
+++ b/frontend/src/lib/timelineTracks.test.js
@@ -37,6 +37,29 @@ describe('Timeline tracks', () => {
expect(tracks[1].categories).toEqual(['statement']);
});
+ it('settles when the deduped spelling is itself already taken', () => {
+ // A saved or imported view can hold ids that already look deduped. The
+ // suffix used to be fixed per row, so this collided with itself forever and
+ // froze the tab on open. Vitest cannot fail a hang, so the test is the fact
+ // that this call returns at all.
+ const tracks = normalizeTimelineTracks([
+ { id: 't-3', label: 'One' },
+ { id: 't', label: 'Two' },
+ { id: 't', label: 'Three' },
+ ]);
+ const ids = tracks.map((track) => track.id);
+ expect(ids).toHaveLength(3);
+ expect(new Set(ids).size).toBe(3);
+ expect(ids).toContain('t-3');
+ });
+
+ it('keeps ids unique however many rows collide', () => {
+ const ids = normalizeTimelineTracks(
+ Array.from({ length: 6 }, () => ({ id: 'x', label: 'X' }))
+ ).map((track) => track.id);
+ expect(new Set(ids).size).toBe(6);
+ });
+
it('reorders and duplicates presentation without sharing arrays', () => {
const tracks = defaultTimelineTracks();
expect(moveTimelineTrack(tracks, 0, 1).map((track) => track.label)).toEqual(['Media', 'Events']);
diff --git a/frontend/src/lib/trash.js b/frontend/src/lib/trash.js
index c913363..9823502 100644
--- a/frontend/src/lib/trash.js
+++ b/frontend/src/lib/trash.js
@@ -16,6 +16,68 @@ import { reloadCase, toast } from './state.svelte.js';
/** What a delete dialog promises when the artifact goes to the trash. */
export const RESTORABLE = 'You can restore it from Trash until you empty it.';
+/** Entity types backed by a file on disk — deleting them drops the file too.
+ * Mirrors `engine/artifacts.KINDS`, and `test_sheets.py` fails when the two lists
+ * disagree: a sheet gained a file and this promised the analyst it had none. */
+export const FILE_BACKED = new Set([
+ 'media',
+ 'capture',
+ 'proof',
+ 'post',
+ 'inspect-session',
+ 'note',
+ 'sheet',
+]);
+
+/**
+ * What a delete asks before it runs, for one row or for a whole selection.
+ *
+ * One dialog for one gesture wherever the click came from, so the board's ticked
+ * rows and the organizer's selected tiles cannot drift into two promises about
+ * the same act. A single target previews the plan the backend will enforce over
+ * the dependents endpoint; a selection does not, since that is one request per
+ * row for a list nobody would read.
+ */
+export async function entityDeletePrompt(caseId, entities, { get = api.get } = {}) {
+ const many = entities.length > 1;
+ let consequences = null;
+ if (!many && entities.length) {
+ try {
+ consequences = await get(`/api/cases/${caseId}/entities/${entities[0].id}/dependents`);
+ } catch {
+ /* no preview — the delete still enforces the plan server-side */
+ }
+ }
+ const files = entities.some((entity) => FILE_BACKED.has(entity.type));
+ return {
+ title: many ? `Delete ${entities.length} items?` : 'Delete everywhere?',
+ message: many
+ ? `${entities.length} items will be removed from the case and their tools.`
+ : `“${entities[0]?.label}” will be removed from the case and its tool.`,
+ detail: files
+ ? `Moves ${many ? 'the items and their files' : 'the item and its files'} to the case trash.`
+ : `Moves ${many ? 'the items' : 'the item'} to the case trash.`,
+ consequences,
+ restorable: RESTORABLE,
+ confirmLabel: many ? 'Delete all' : 'Delete everywhere',
+ tone: 'default',
+ icon: 'trash',
+ };
+}
+
+/**
+ * Run that delete, and answer with what the case did.
+ *
+ * A selection goes over the bulk route so the whole act lands in the trash as
+ * **one** group: undoing a mis-click row by row would take as long as the
+ * mis-click did, which is the same as having no way back.
+ */
+export function deleteEntities(caseId, ids) {
+ return ids.length > 1
+ ? api.post(`/api/cases/${caseId}/entities/delete`, { ids })
+ : api.del(`/api/cases/${caseId}/entities/${ids[0]}`);
+}
+
export function trashUrl(caseId) {
return `/api/cases/${caseId}/trash`;
}
diff --git a/frontend/src/lib/trash.test.js b/frontend/src/lib/trash.test.js
index 3aa628b..8f1097e 100644
--- a/frontend/src/lib/trash.test.js
+++ b/frontend/src/lib/trash.test.js
@@ -3,11 +3,14 @@ import { api } from './api.js';
import { reloadCase, toast } from './state.svelte.js';
import {
deletedToast,
+ deleteEntities,
emptyTrash,
+ entityDeletePrompt,
formatSize,
purgeGroup,
readTrash,
restoreGroup,
+ RESTORABLE,
trashUrl,
undoAction,
} from './trash.js';
@@ -78,3 +81,72 @@ describe('trash size labels', () => {
expect(formatSize(bytes)).toBe(label);
});
});
+
+describe('deleting a selection', () => {
+ const rows = [
+ { id: 'e1', label: 'Quai sud', type: 'place' },
+ { id: 'e2', label: 'Clip', type: 'media' },
+ ];
+
+ it('sends a selection over the bulk route, so the whole act is one trash group', async () => {
+ await deleteEntities('case-1', ['e1', 'e2']);
+
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/entities/delete', {
+ ids: ['e1', 'e2'],
+ });
+ expect(api.del).not.toHaveBeenCalled();
+ });
+
+ it('sends one row over its own route', async () => {
+ await deleteEntities('case-1', ['e1']);
+
+ expect(api.del).toHaveBeenCalledWith('/api/cases/case-1/entities/e1');
+ expect(api.post).not.toHaveBeenCalled();
+ });
+
+ it('counts the selection in the dialog, and promises the way back', async () => {
+ const prompt = await entityDeletePrompt('case-1', rows, { get: vi.fn() });
+
+ expect(prompt.title).toBe('Delete 2 items?');
+ expect(prompt.confirmLabel).toBe('Delete all');
+ expect(prompt.restorable).toBe(RESTORABLE);
+ // one of the two is backed by a file, so the dialog says the files go too
+ expect(prompt.detail).toBe('Moves the items and their files to the case trash.');
+ });
+
+ it('says only what a selection of pure graph rows really touches', async () => {
+ const prompt = await entityDeletePrompt('case-1', [rows[0], { id: 'e3', type: 'person' }], {
+ get: vi.fn(),
+ });
+
+ expect(prompt.detail).toBe('Moves the items to the case trash.');
+ });
+
+ it('names the row when there is one, and previews what goes with it', async () => {
+ const get = vi.fn(async () => ({ cascade: [{ label: 'Inspect session' }], tombstone: [] }));
+ const prompt = await entityDeletePrompt('case-1', [rows[1]], { get });
+
+ expect(get).toHaveBeenCalledWith('/api/cases/case-1/entities/e2/dependents');
+ expect(prompt.title).toBe('Delete everywhere?');
+ expect(prompt.message).toContain('Clip');
+ expect(prompt.consequences.cascade).toHaveLength(1);
+ });
+
+ it('asks for no preview per row of a selection, and still asks the dialog', async () => {
+ const get = vi.fn();
+ const prompt = await entityDeletePrompt('case-1', rows, { get });
+
+ expect(get).not.toHaveBeenCalled();
+ expect(prompt.consequences).toBeNull();
+ });
+
+ it('opens on the dialog even when the preview fails: the plan is the backend’s', async () => {
+ const get = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const prompt = await entityDeletePrompt('case-1', [rows[0]], { get });
+
+ expect(prompt.consequences).toBeNull();
+ expect(prompt.confirmLabel).toBe('Delete everywhere');
+ });
+});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 002d41f..9874ef8 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -17,7 +17,7 @@ export const CASE_WORKSPACE = {
id: 'case',
label: 'Case',
icon: 'graph',
- tools: ['board', 'graph', 'timeline'],
+ tools: ['board', 'graph', 'timeline', 'sheet'],
};
/** The rail, in investigation order. */
@@ -35,6 +35,7 @@ export const TOOL_LABELS = {
board: 'Board',
graph: 'Graph',
timeline: 'Timeline',
+ sheet: 'Sheet',
media: 'Media',
files: 'Files',
reverse: 'Reverse Search',
diff --git a/frontend/src/tools/Board.render.test.js b/frontend/src/tools/Board.render.test.js
new file mode 100644
index 0000000..f968933
--- /dev/null
+++ b/frontend/src/tools/Board.render.test.js
@@ -0,0 +1,280 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The table, driven the way an analyst drives it.
+ *
+ * `Board.test.js` reads the source for what the tool is wired to; this drives the
+ * one gesture that removes case material in bulk, because a delete that ticks the
+ * wrong rows is the one mistake the tests have to catch before a user does.
+ */
+
+const TYPES = [
+ { type: 'place', label: 'Place', family: 'material', hint: 'somewhere', fields: [] },
+ { type: 'media', label: 'Media', family: 'material', hint: 'a file', fields: [] },
+ { type: 'person', label: 'Person', family: 'actor', hint: 'somebody', fields: [] },
+];
+
+const ROWS = [
+ { id: 'e1', type: 'place', label: 'Quai sud', attrs: {}, provenance: { at: '2026-08-01' } },
+ { id: 'e2', type: 'media', label: 'Clip', attrs: {}, provenance: { at: '2026-08-02' } },
+ { id: 'e3', type: 'person', label: 'Witness', attrs: {}, provenance: { at: '2026-08-03' } },
+ { id: 'e4', type: 'place', label: 'Pont nord', attrs: {}, provenance: { at: '2026-08-04' } },
+];
+
+const SUMMARY = {
+ total: ROWS.length,
+ by_type: { place: 2, media: 1, person: 1 },
+ by_status: {},
+ by_folder: {},
+ by_source: {},
+ unlinked: 0,
+};
+
+const get = vi.fn(async (url) => {
+ if (url.includes('/entity-types')) return TYPES;
+ if (url.includes('/catalog/summary')) return SUMMARY;
+ if (url.includes('/catalog/entities')) {
+ return { items: ROWS, total: ROWS.length, next_cursor: null };
+ }
+ if (url.includes('/catalog/attributes')) return { attrs: [] };
+ if (url.includes('/dependents')) return { cascade: [], tombstone: [] };
+ if (url.includes('/analysis-views')) return { views: [] };
+ return {};
+});
+const post = vi.fn(async () => ({ status: 'deleted', deleted: ['e1', 'e4'], trash: 'trash-1' }));
+const del = vi.fn(async () => ({ status: 'deleted', deleted: ['e1'], trash: 'trash-2' }));
+vi.mock('../lib/api.js', () => ({
+ api: { get, post, del, patch: vi.fn(), put: vi.fn() },
+ ApiError: Error,
+}));
+
+const toast = vi.fn();
+const reloadCase = vi.fn(async () => {});
+const uiState = { tool: 'board', openBoardEntity: null, drawInGraph: null, openGraphEntity: null };
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('../components/views.fixture.svelte.js');
+ return {
+ caseState,
+ reloadCase,
+ toast,
+ uiState,
+ registerCaseChangeGuard: () => () => {},
+ };
+});
+vi.mock('../components/EntityDetails.svelte', async () => await import('../components/Modal.svelte'));
+
+const { default: Board } = await import('./Board.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() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Board, { target });
+ flushSync();
+ await settle();
+ return target;
+}
+
+/** The boxes of the rows themselves, in the order the table shows them. */
+const boxes = () => [...target.querySelectorAll('.table tbody td.pick input')];
+const headBox = () => target.querySelector('.table thead th.pick input');
+const bar = () => target.querySelector('.picked');
+const dialog = () => document.querySelector('[role="alertdialog"]');
+
+async function tick(index, { shift = false } = {}) {
+ boxes()[index].dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, shiftKey: shift }));
+ flushSync();
+ await settle();
+}
+
+async function tickHead() {
+ headBox().click();
+ flushSync();
+ await settle();
+}
+
+async function press(label, root = document.body) {
+ const button = [...root.querySelectorAll('button')].find((b) => b.textContent.trim().includes(label));
+ button.click();
+ flushSync();
+ await settle();
+ return button;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.querySelectorAll('[role="alertdialog"]').forEach((node) => node.remove());
+});
+
+describe('ticking rows', () => {
+ it('gives every row a box, and says how many are ticked', async () => {
+ await open();
+ expect(boxes()).toHaveLength(ROWS.length);
+ expect(bar()).toBeNull(); // nothing ticked, nothing to act on
+
+ await tick(0);
+ await tick(2);
+
+ expect(bar().textContent).toContain('2 selected');
+ expect(boxes().map((box) => box.checked)).toEqual([true, false, true, false]);
+ });
+
+ it('does not open the row it ticks: the box is not the row', async () => {
+ await open();
+ await tick(1);
+
+ expect(target.querySelector('.table tbody input:checked')).not.toBeNull();
+ expect(document.querySelector('.modal, [role="dialog"]')).toBeNull();
+ });
+
+ it('shift carries the run from the last box touched', async () => {
+ await open();
+ await tick(0);
+ await tick(3, { shift: true });
+
+ expect(boxes().every((box) => box.checked)).toBe(true);
+ expect(bar().textContent).toContain('4 selected');
+
+ // and takes it back the same way: the run is measured from the box last
+ // touched, and a shift on a ticked box unticks everything it covers
+ await tick(1, { shift: true });
+ expect(boxes().map((box) => box.checked)).toEqual([true, false, false, false]);
+ });
+
+ it('the heading box clears a part-ticked table rather than completing it', async () => {
+ // the reported bug: ticking everything but one row and pressing the heading box
+ // ticked the row that had been deliberately left out
+ await open();
+ await tickHead();
+ await tick(2);
+ expect(bar().textContent).toContain('3 selected');
+
+ await tickHead();
+
+ expect(bar()).toBeNull();
+ expect(boxes().some((box) => box.checked)).toBe(false);
+ });
+
+ it('the heading box shows which of the three states the table is in', async () => {
+ await open();
+ expect(headBox().checked).toBe(false);
+ expect(headBox().indeterminate).toBe(false);
+
+ await tick(0);
+ expect(headBox().indeterminate).toBe(true);
+
+ await tickHead(); // clears, from the dash
+ expect(headBox().indeterminate).toBe(false);
+ expect(headBox().checked).toBe(false);
+
+ await tickHead(); // and takes the whole table from empty
+ expect(headBox().checked).toBe(true);
+ expect(headBox().indeterminate).toBe(false);
+ });
+
+ it('Clear leaves no box behind, ticked or not', async () => {
+ await open();
+ await tick(0);
+ await tick(1);
+ await tick(2);
+ await press('Clear', target);
+
+ expect(boxes().map((box) => box.checked)).toEqual([false, false, false, false]);
+ });
+
+ it('the heading box covers the rows loaded, and clears them', async () => {
+ await open();
+ headBox().click();
+ flushSync();
+ await settle();
+ expect(bar().textContent).toContain('4 selected');
+
+ headBox().click();
+ flushSync();
+ await settle();
+ expect(bar()).toBeNull();
+ });
+
+ it('Clear drops the ticks without touching the case', async () => {
+ await open();
+ await tick(0);
+ await press('Clear', target);
+
+ expect(bar()).toBeNull();
+ expect(post).not.toHaveBeenCalled();
+ expect(del).not.toHaveBeenCalled();
+ });
+});
+
+describe('deleting what is ticked', () => {
+ it('counts the selection before it runs, and promises the way back', async () => {
+ await open();
+ await tick(0);
+ await tick(3);
+ await press('Delete', target);
+
+ expect(dialog().textContent).toContain('Delete 2 items?');
+ expect(dialog().textContent).toContain('restore it from Trash');
+ // nothing has gone yet: the dialog is the whole point
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('sends the selection as one act, so one Undo takes it back', async () => {
+ await open();
+ await tick(0);
+ await tick(3);
+ await press('Delete', target);
+ await press('Delete all');
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/entities/delete', {
+ ids: ['e1', 'e4'],
+ });
+ expect(reloadCase).toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith(
+ 'Deleted 2 items',
+ 'info',
+ 7000,
+ expect.objectContaining({ label: 'Undo' })
+ );
+ expect(bar()).toBeNull(); // the ticks went with the rows
+ });
+
+ it('one ticked row still goes over its own route, with its plan previewed', async () => {
+ await open();
+ await tick(1);
+ await press('Delete', target);
+
+ expect(get).toHaveBeenCalledWith('/api/cases/case-a/entities/e2/dependents');
+ expect(dialog().textContent).toContain('Clip');
+
+ await press('Delete everywhere');
+ expect(del).toHaveBeenCalledWith('/api/cases/case-a/entities/e2');
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('Cancel leaves the case and the ticks alone', async () => {
+ await open();
+ await tick(0);
+ await press('Delete', target);
+ await press('Cancel');
+
+ expect(post).not.toHaveBeenCalled();
+ expect(del).not.toHaveBeenCalled();
+ expect(bar().textContent).toContain('1 selected');
+ });
+});
diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelte
index c1bdf82..a368956 100644
--- a/frontend/src/tools/Board.svelte
+++ b/frontend/src/tools/Board.svelte
@@ -47,7 +47,8 @@
import { entityIcon } from '../lib/entityIcon.js';
import { fileUrl } from '../lib/fileUrl.js';
import { folderOf } from '../lib/folderTree.js';
- import { deletedToast } from '../lib/trash.js';
+ import { deletedToast, deleteEntities, entityDeletePrompt } from '../lib/trash.js';
+ import { toggleCheck } from '../lib/gridSelect.js';
import {
chipsOf,
clearAxis,
@@ -111,6 +112,10 @@
let busyId = $state(null); // the row whose review action is in flight
let discarding = $state(false); // Details closing with unsaved fields on screen
let dirty = $state(false); // Details has edits the panel's Save has not taken
+ let selected = $state([]); // the ticked rows, by id
+ let anchor = null; // the last box touched, which shift measures a run from
+ let confirmState = $state(null); // the delete being asked about, or null
+ let confirmBusy = $state(false);
/** The families the case actually holds, read off the summary: a filter offering a
* family nothing is filed under is offering an empty answer. */
@@ -385,6 +390,90 @@
}
}
+ // ── ticked rows ──────────────────────────────────────────────────────────────
+ /**
+ * Several rows at once, because the mistake is rarely one row.
+ *
+ * An import of the wrong folder, a scraper run that filed forty of the wrong
+ * thing, a paste into the case next to the intended one: undoing that used to
+ * mean opening Details forty times. A box per row gathers what goes, and the
+ * delete behind them lands as **one** trash group, so the Undo in the toast
+ * takes the whole act back rather than the last row of it.
+ *
+ * The boxes cover what is loaded. The table is bounded like every list here, so
+ * a selection cannot claim rows nobody has seen, and the count beside *Show
+ * more* is what says the rest is still out there.
+ */
+ const ticked = $derived(new Set(selected));
+ /** The ticked rows themselves, in the order the table is showing them. It is what
+ * the bar counts and what Delete sends, so the number on screen is never a row
+ * the table has since stopped showing. */
+ const chosen = $derived(rows.filter((entity) => ticked.has(entity.id)));
+ const allTicked = $derived(rows.length > 0 && chosen.length === rows.length);
+
+ function tick(entity, shift) {
+ const result = toggleCheck(
+ selected,
+ entity.id,
+ { shift },
+ rows.map((row) => row.id),
+ anchor
+ );
+ selected = result.selected;
+ anchor = result.anchor;
+ }
+
+ function tickAll(on) {
+ selected = on ? rows.map((row) => row.id) : [];
+ anchor = null;
+ }
+
+ function untickAll() {
+ selected = [];
+ anchor = null;
+ }
+
+ // A tick belongs to the answer it was made in. Change the question, the case or
+ // the reading and the boxes go: a row that scrolled out of the narrowing would
+ // still be going, unseen, when Delete is pressed.
+ $effect(() => {
+ caseState.current?.id;
+ JSON.stringify(filter);
+ JSON.stringify(analysisSearch.period);
+ totalling;
+ snapshotReading;
+ untrack(untickAll);
+ });
+
+ async function askDeleteSelected() {
+ if (snapshotReading || confirmState || !caseState.current || !chosen.length) return;
+ const going = chosen;
+ const caseId = caseState.current.id;
+ confirmState = {
+ ...(await entityDeletePrompt(caseId, going)),
+ action: async () => {
+ const result = await deleteEntities(caseId, going.map((entity) => entity.id));
+ await reloadCase();
+ untickAll();
+ deletedToast(caseId, result, going[0].label);
+ },
+ };
+ }
+
+ async function runConfirm() {
+ const asked = confirmState;
+ if (!asked) return;
+ confirmBusy = true;
+ try {
+ await asked.action();
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ confirmBusy = false;
+ confirmState = null;
+ }
+ }
+
let loadedFor = null;
$effect(() => {
const id = caseState.current?.id;
@@ -782,12 +871,15 @@
openId = null;
snapshotOpen = null;
filter = normalizeFilter(view.spec?.query?.filter);
+ // Board and Graph read one saved question, and each surface restores only the
+ // presentation it saved. A Graph view opened here brings its question to the rows
+ // and leaves the analyst in the tool they are working in; its lens, folds and
+ // arrangement wait for the Graph, which restores them off the same active view.
+ // The table's own sort is left alone, because such a view never stated one.
+ if (view.surface !== 'board') return;
const board = view.spec?.board ?? {};
sortKey = typeof board.sortKey === 'string' ? board.sortKey : '';
sortDesc = board.sortDesc === true;
- // Board and Graph read one saved question, so a Graph view opened here is a
- // request for the other drawing of it. The Timeline keeps its own views.
- if (view.surface === 'graph') uiState.tool = 'graph';
}
let appliedViewId = null;
@@ -948,6 +1040,19 @@
/>
</p>
+ <!-- What the ticks come to, and the one thing they are for. Outside the scrolling
+ body so a selection made at the top of eight hundred rows is still actionable
+ at the bottom of them. -->
+ {#if chosen.length}
+ <div class="picked">
+ <span><strong>{chosen.length}</strong> selected</span>
+ <button class="btn btn-ghost btn-sm" onclick={untickAll}>Clear</button>
+ <button class="btn btn-ghost btn-sm drop" onclick={askDeleteSelected}>
+ <Icon name="trash" size={12} /> Delete
+ </button>
+ </div>
+ {/if}
+
<!-- Dropping a file onto the list files it, the way the Media Library takes one.
`dragleave` is guarded on the container itself: the event fires for every
child the pointer crosses, so an unguarded handler flickers the overlay off
@@ -1047,6 +1152,25 @@
<table class="table">
<thead>
<tr>
+ {#if !snapshotReading}
+ <!-- The heading's box reads the selection rather than the rows: ticked
+ with anything ticked, dashed while it is only part of the table.
+ So a click on a part-ticked table **clears** it — the browser would
+ otherwise complete the selection, ticking the very row that had
+ been left out on purpose, and the state it lands on is the one the
+ box was already showing. -->
+ <th class="pick">
+ <input
+ type="checkbox"
+ aria-label={chosen.length ? 'Clear the selection' : 'Select the rows loaded'}
+ title={chosen.length ? 'Clear the selection' : 'Select the rows loaded'}
+ checked={chosen.length > 0}
+ indeterminate={chosen.length > 0 && !allTicked}
+ onclick={(e) => e.stopPropagation()}
+ onchange={() => tickAll(!chosen.length)}
+ />
+ </th>
+ {/if}
{#each [
{ key: 'label', label: identityColumn },
{ key: 'type', label: 'Type' },
@@ -1093,6 +1217,23 @@
}
}}
>
+ {#if !snapshotReading}
+ <!-- The click is taken from the row underneath, never from the box
+ itself: a click always flips the box it is on, so the browser's
+ own toggle and the state it produces agree, and the rest of a
+ shift-run is written from the state. -->
+ <td class="pick">
+ <input
+ type="checkbox"
+ aria-label="Select {entity.label}"
+ checked={ticked.has(entity.id)}
+ onclick={(e) => {
+ e.stopPropagation();
+ tick(entity, e.shiftKey);
+ }}
+ />
+ </td>
+ {/if}
<td>
{#if entity.thumb}
<img
@@ -1247,6 +1388,22 @@
</Modal>
{/if}
+{#if confirmState}
+ <ConfirmDialog
+ title={confirmState.title}
+ message={confirmState.message}
+ detail={confirmState.detail}
+ consequences={confirmState.consequences}
+ restorable={confirmState.restorable}
+ confirmLabel={confirmState.confirmLabel}
+ tone={confirmState.tone}
+ icon={confirmState.icon}
+ busy={confirmBusy}
+ onconfirm={runConfirm}
+ oncancel={() => (confirmState = null)}
+ />
+{/if}
+
{#if discarding}
<ConfirmDialog
title="Discard changes?"
@@ -1262,6 +1419,11 @@
.spacer {
flex: 1;
}
+ /* One height across the header. Views comes from a shared component and is `btn-sm`,
+ the tool's own two are not, and three buttons of two heights read as a mistake.
+ Stated from the same tokens a plain `.btn` is built from — its text plus its
+ padding and rule — rather than as a number that would drift from them. */
+ .tool-header :global(.btn) { min-height: calc(var(--fs-sm) * 1.5 + 12px); }
/* The count reads first because it is the answer; the control that decides how that
answer is drawn sits at the other end, directly above what it governs. */
.answer {
@@ -1294,6 +1456,27 @@
.answer .as-link:hover {
text-decoration: underline;
}
+ /* What the ticks come to. It appears only with a selection, so it is the one bar
+ in the tool that changes the height of what is under it, and it sits above the
+ scrolling body rather than floating over the rows it is about. */
+ .picked {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 16px 6px;
+ padding: 5px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .picked strong {
+ color: var(--text-1);
+ }
+ .picked .drop:hover {
+ color: var(--danger);
+ }
/* The one scrolling region. `.tool` is a full-height flex column, so the body
needs min-height:0 or the table pushes the column taller than the viewport and
nothing scrolls at all. */
@@ -1347,6 +1530,19 @@
border-bottom: 1px solid var(--border);
white-space: nowrap;
}
+ /* The boxes take the width they need and no more, so the identity column keeps
+ the room it had. */
+ .table th.pick,
+ .table td.pick {
+ width: 1%;
+ padding: 6px 8px 6px 2px;
+ }
+ .table .pick input {
+ display: block;
+ margin: 0;
+ cursor: pointer;
+ accent-color: var(--accent);
+ }
.sorter {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/Board.test.js b/frontend/src/tools/Board.test.js
index 1707cd4..ef08d51 100644
--- a/frontend/src/tools/Board.test.js
+++ b/frontend/src/tools/Board.test.js
@@ -273,7 +273,7 @@ describe('a proposal can be settled here', () => {
});
it('dismisses through the standard delete, so it stays recoverable', () => {
- expect(source).toContain("import { deletedToast } from '../lib/trash.js'");
+ expect(source).toContain("from '../lib/trash.js'");
expect(source).toContain('deletedToast(caseId, result, entity.label)');
});
@@ -365,6 +365,27 @@ describe('where a graph-only type is read', () => {
});
});
+describe('opening a saved view of the other surface', () => {
+ it('brings its question to the rows without moving the analyst', () => {
+ // The two surfaces share one question and restore only what each of them saved:
+ // a Graph view's lens and arrangement wait for the Graph rather than dragging the
+ // analyst there. Handing the question over is a separate, explicit act.
+ const body = source.slice(
+ source.indexOf('async function openAnalysisView'),
+ source.indexOf('let appliedViewId'),
+ );
+ expect(body).toContain("if (view.surface !== 'board') return;");
+ // No tool switch here. "Draw these N" stays: that handoff is asked for.
+ expect(body).not.toContain('uiState.tool');
+ });
+
+ it('leaves the table sorted as it is when the view states no sort', () => {
+ expect(source).toMatch(
+ /if \(view\.surface !== 'board'\) return;\s*const board = view\.spec\?\.board \?\? \{\};/
+ );
+ });
+});
+
describe('handing the question to the drawing', () => {
it('sends the question, never the rows it matched', () => {
// ids would be capped, would bloat the URL and would go stale on the next save;
@@ -495,3 +516,31 @@ describe('Ctrl+V on the table', () => {
expect(source).toContain('{#if pasted && !snapshotReading}');
});
});
+
+describe('several rows at once', () => {
+ // the gesture itself is driven in `Board.render.test.js`; this holds the wiring
+ // that a rendered click cannot see
+ it('deletes a selection through the trash’s own dialog and route', () => {
+ // one wording and one endpoint for the gesture, shared with the organizer, so
+ // the two surfaces cannot promise different things about the same act
+ expect(source).toContain('entityDeletePrompt');
+ expect(source).toContain('deleteEntities');
+ expect(source).not.toContain('/entities/delete');
+ });
+
+ it('measures a shift-run over the rows on screen, with the shared selection math', () => {
+ expect(source).toContain("import { toggleCheck } from '../lib/gridSelect.js'");
+ expect(source).toContain('rows.map((row) => row.id)');
+ });
+
+ it('drops the ticks when the question they were made in changes', () => {
+ // a row that scrolled out of the narrowing would still be going, unseen
+ expect(source).toContain('untrack(untickAll)');
+ });
+
+ it('offers no box on a frozen reading, where every case write is off', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).toMatch(/\{#if !snapshotReading\}[\s\S]{0,500}<th class="pick">/);
+ expect(source).toContain('if (snapshotReading || confirmState || !caseState.current');
+ });
+});
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index 10cc9bf..547f350 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -23,12 +23,13 @@
import { sortFileEntities } from '../lib/fileSort.js';
import {
deletedToast,
+ deleteEntities,
emptyTrash,
+ entityDeletePrompt,
formatSize,
purgeGroup,
readTrash,
restoreGroup,
- RESTORABLE,
} from '../lib/trash.js';
import { createPagedList } from '../lib/pagedList.svelte.js';
import Icon from '../components/Icon.svelte';
@@ -44,8 +45,6 @@
post: 'post', place: 'pin', 'inspect-session': 'inspect', bookmark: 'link',
};
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
- // Entity types backed by a file on disk — deleting them drops the file too.
- const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);
// ── case data ──────────────────────────────────────────────────────────────
// Bounded loading: a first page (200) off the catalog, not the whole graph on
@@ -270,6 +269,15 @@
? visibleEntities
: (searching ? completeFolderEntities.filter(matches) : completeFolderEntities)
);
+ // Every row a selection can name. List view renders the whole open folder, so
+ // resolving selected ids against the first catalog page alone dropped every
+ // row past 200: a delete silently spared them, and a move reported a count it
+ // had not moved.
+ const selectable = $derived(
+ completeFolderEntities === null
+ ? confirmed
+ : [...new Map([...confirmed, ...completeFolderEntities].map((e) => [e.id, e])).values()]
+ );
const curFolders = $derived(searching ? [] : sortFolders(current.children));
const curEntities = $derived(sortEntities(completeVisibleEntities));
const entityOrder = $derived(curEntities.map((e) => e.id));
@@ -419,7 +427,7 @@
draggingIds = [];
dropTarget = null;
if (!ids.length) return;
- const ents = confirmed.filter((e) => ids.includes(e.id));
+ const ents = selectable.filter((e) => ids.includes(e.id));
// no-op when dropped on the folder they already sit in
if (ents.every((e) => (folderOf(e) ?? '') === folder)) return;
try {
@@ -537,39 +545,15 @@
}
async function askDeleteEntities(ids) {
- const ents = confirmed.filter((e) => ids.includes(e.id));
+ const ents = selectable.filter((e) => ids.includes(e.id));
if (!ents.length) return;
- const multi = ents.length > 1;
- // The authoritative plan is the backend's; a single delete previews its
- // dependents endpoint rather than mirroring the whole graph client-side.
- let consequences = null;
- if (!multi) {
- try {
- consequences = await api.get(
- `/api/cases/${caseState.current.id}/entities/${ents[0].id}/dependents`
- );
- } catch {
- /* no preview — the delete still enforces the plan server-side */
- }
- }
+ // The dialog and the route are the trash's, shared with every other surface
+ // that deletes several things at once, so one gesture keeps one wording.
confirmState = {
- title: multi ? `Delete ${ents.length} items?` : 'Delete everywhere?',
- message: multi
- ? `${ents.length} items will be removed from the case and their tools.`
- : `“${ents[0].label}” will be removed from the case and its tool.`,
- detail: ents.some((e) => FILE_BACKED.has(e.type))
- ? `Moves ${multi ? 'the items and their files' : 'the item and its files'} to the case trash.`
- : `Moves ${multi ? 'the items' : 'the item'} to the case trash.`,
- consequences,
- restorable: RESTORABLE,
- confirmLabel: multi ? 'Delete all' : 'Delete everywhere',
- tone: 'default',
- icon: 'trash',
+ ...(await entityDeletePrompt(caseState.current.id, ents)),
action: async () => {
const caseId = caseState.current.id;
- const result = multi
- ? await api.post(`/api/cases/${caseId}/entities/delete`, { ids: ents.map((e) => e.id) })
- : await api.del(`/api/cases/${caseId}/entities/${ents[0].id}`);
+ const result = await deleteEntities(caseId, ents.map((e) => e.id));
await reloadCase();
selected = [];
deletedToast(caseId, result, ents[0].label);
diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.js
index a3e62a5..d612995 100644
--- a/frontend/src/tools/Files.test.js
+++ b/frontend/src/tools/Files.test.js
@@ -185,3 +185,14 @@ describe('Ctrl+V on the desktop', () => {
expect(source).toMatch(/<PasteDialog[^>]*folders=\{allFolders\}/s);
});
});
+
+describe('Files — acting on what the view actually shows', () => {
+ it('resolves a selection against the complete folder, not the first page', () => {
+ // List view renders `completeFolderEntities` (the whole open folder) while
+ // move and delete filtered `confirmed` (the first 200 rows case-wide), so
+ // any row past page one silently no-opped.
+ expect(source).toContain('const selectable = $derived(');
+ expect(source).toContain('const ents = selectable.filter((e) => ids.includes(e.id));');
+ expect(source).not.toContain('const ents = confirmed.filter((e) => ids.includes(e.id));');
+ });
+});
diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelte
index 6fca653..505a240 100644
--- a/frontend/src/tools/Graph.svelte
+++ b/frontend/src/tools/Graph.svelte
@@ -109,6 +109,7 @@
relationQualifier,
relationReading,
relationVerb,
+ retractionWarning,
} from '../lib/relations.svelte.js';
import {
CARD,
@@ -141,11 +142,15 @@
import { createBookmark } from '../lib/bookmarks.js';
import { windowWords } from '../lib/timeline.js';
import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
+ import { graphPlate } from '../lib/graphPlate.js';
+ import { plateFilename } from '../lib/plate.js';
import Icon, { paths } from '../components/Icon.svelte';
import AnalysisViews from '../components/AnalysisViews.svelte';
+ import PlateExport from '../components/PlateExport.svelte';
import AnalysisPeriodBar from '../components/AnalysisPeriodBar.svelte';
import FilterBar from '../components/FilterBar.svelte';
import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityCreate from '../components/EntityCreate.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
import PasteDialog from '../components/PasteDialog.svelte';
@@ -462,6 +467,8 @@
let dirty = $state(false);
/** The edge under the panel. An edge is a statement, and often the finding. */
let chosenLink = $state(null);
+ /** A stated edge waiting on the answer to "remove it?": `{ id, words }`. */
+ let retractingEdge = $state(null);
/** A relation being drawn: where it started, where the pointer is, what it can
* legally land on, and the menu once it has landed. */
let drawing = $state(null);
@@ -862,6 +869,7 @@
});
const lensHint = $derived(lenses.find((entry) => entry.id === lens)?.hint ?? '');
+ const lensLabel = $derived(lenses.find((entry) => entry.id === lens)?.label ?? lens);
/**
* Finding a node by name. On a case drawn at a few hundred nodes, hunting one by
@@ -3461,11 +3469,25 @@
holdOn(back);
}
+ /** Ask before an edge goes, unless it is only a proposal.
+ *
+ * The panel is opened to *read* an edge, and Remove sat beside Confirm and the rating —
+ * two controls that change nothing — as the one permanent write in the app that asked
+ * nothing. Worded in `retractionWarning` so this reads the same as the same act in
+ * Details. */
+ function askDropLink(edge) {
+ if (snapshotReading) return;
+ const words = retractionWarning(edge);
+ if (words) retractingEdge = { id: edge.id, words };
+ else dropLink(edge.id);
+ }
+
/** Drop an edge. The case keeps the two entities; only the statement goes. */
async function dropLink(linkId) {
if (snapshotReading) return;
const cid = caseState.current?.id;
if (!cid) return;
+ retractingEdge = null;
say('');
try {
await api.del(`/api/cases/${cid}/links/${linkId}`);
@@ -4565,6 +4587,57 @@
};
}
+ /**
+ * The drawing as a page, for the export dialog.
+ *
+ * Handed the scene the canvas is built from and nothing else: the same placement, the
+ * same bends, the same legend the panel shows. Serialising is `lib/graphPlate.js`, so
+ * a plate cannot say something about the drawing that the drawing does not.
+ */
+ function capturePlate() {
+ if (!placed.length) return null;
+ const view = catalogViews.activeView?.name ?? '';
+ const at = new Date().toISOString();
+ // Two ways the drawing is narrower than the case, and both have to be said. A fold
+ // tidies, a focus cuts; the plate resizes to what is left either way, so neither is
+ // visible on the page unless it is written there.
+ const outsideFocus = hiding
+ ? placed.reduce((count, node) => count + (hiding.has(node.id) ? 0 : 1), 0)
+ : 0;
+ const page = graphPlate({
+ meta: {
+ caseName: caseState.current?.name ?? '',
+ surface: 'Graph',
+ view,
+ title: `Graph · ${lensLabel}`,
+ lens: lensLabel,
+ // The question says the window itself — `searchSaid` ends on the fact-time
+ // chip — so the plate does not print it a second time under it.
+ question: searchSaid,
+ aside: [
+ foldedCount ? `${foldedCount} node${foldedCount === 1 ? '' : 's'} folded away` : '',
+ outsideFocus
+ ? `${outsideFocus} node${outsideFocus === 1 ? '' : 's'} outside the focus`
+ : '',
+ ].filter(Boolean).join(' · '),
+ at,
+ },
+ families: legend.filter((entry) => entry.on && entry.count),
+ strokes,
+ placed,
+ edges,
+ bends,
+ byId,
+ hidden: hiding,
+ chainTypes: CHAIN_TYPES,
+ verbOf: (link) => relationVerb(link.type),
+ });
+ return {
+ ...page,
+ filename: plateFilename({ surface: 'graph', view, lens: lensLabel, at }),
+ };
+ }
+
let appliedViewId = null;
async function applyGraphView(view) {
@@ -4612,11 +4685,11 @@
}
async function openAnalysisView(view) {
- if (view.surface !== 'graph') {
- // The only other surface in this family is the Board: same question, rows.
- uiState.tool = 'board';
- return;
- }
+ // The only other surface in this family is the Board. Its rows are the same
+ // question, and that question reaches the drawing through the shared Search+ on
+ // its own — so there is nothing to restore here, and no reason to take the analyst
+ // out of the tool they are in. The Board applies its sort from the same view.
+ if (view.surface !== 'graph') return;
await applyGraphView(view);
}
@@ -4814,6 +4887,8 @@
onleave={leaveAnalysisReading}
/>
+ <PlateExport surface="graph" plate={capturePlate} disabled={!caseState.current} />
+
<span class="spacer"></span>
{#if payload}
@@ -4952,7 +5027,7 @@
the canvas: a mode with no words is a mode nobody can get out of. -->
{#if drawing}
<span class="count connecting">
- Connecting from {shortLabel(byId.get(drawing.from)?.label ?? '', 18)} — click the
+ Connecting from {shortLabel(byId.get(drawing.from)?.label ?? '', 18)}. Click the
other end
<button
class="as-link"
@@ -5176,7 +5251,7 @@
<div class="focus walk">
<span class="on">
<Icon name="arrowRight" size={13} />
- Path from {shortLabel(byId.get(asking.from)?.label ?? '', 22)} — click the other
+ Path from {shortLabel(byId.get(asking.from)?.label ?? '', 22)}. Click the other
end, or find it by name
</span>
<button class="icon-btn" onclick={() => (asking = null)} title="Give it up (Esc)">
@@ -5629,7 +5704,7 @@
Confirm
</button>
{/if}
- <button class="btn btn-ghost" onclick={() => dropLink(chosenEdge.id)}>Remove</button>
+ <button class="btn btn-ghost" onclick={() => askDropLink(chosenEdge)}>Remove</button>
</div>{/if}
{/if}
<ul class="neighbours">
@@ -5865,6 +5940,18 @@
</Modal>
{/if}
+{#if retractingEdge}
+ <ConfirmDialog
+ title={retractingEdge.words.title}
+ message={retractingEdge.words.message}
+ detail={retractingEdge.words.detail}
+ confirmLabel={retractingEdge.words.confirmLabel}
+ tone="danger"
+ onconfirm={() => dropLink(retractingEdge.id)}
+ oncancel={() => (retractingEdge = null)}
+ />
+{/if}
+
<style>
.graph-tool {
display: flex;
diff --git a/frontend/src/tools/Graph.test.js b/frontend/src/tools/Graph.test.js
index 3386c77..dd2c6a2 100644
--- a/frontend/src/tools/Graph.test.js
+++ b/frontend/src/tools/Graph.test.js
@@ -1737,11 +1737,21 @@ describe('the wrapper is an edge, and the count is what it says', () => {
expect(split).toBeGreaterThan(start);
expect(source.slice(start, split)).not.toMatch(/dropLink|ruleOn|rateEdge|qualifyEdge/);
const row = source.slice(split, end);
- expect(row).toContain('dropLink(chosenEdge.id)');
+ expect(row).toContain('askDropLink(chosenEdge)');
expect(row).toContain('rateEdge(chosenEdge.id');
expect(row).toContain('qualifyEdge(chosenEdge,');
});
+ it('asks before a stated edge is removed, and not before a proposal', () => {
+ // The panel is opened to read an edge, and Remove sat beside Confirm and the rating —
+ // two controls that write nothing — as the one permanent act that asked nothing.
+ // Nothing holds a removed edge: re-filing one mints a new id, date and author.
+ expect(source).toContain('const words = retractionWarning(edge);');
+ expect(source).toContain('if (words) retractingEdge = { id: edge.id, words };');
+ expect(source).toContain('else dropLink(edge.id);');
+ expect(source).toContain('onconfirm={() => dropLink(retractingEdge.id)}');
+ });
+
it('says where a folded type lives when it cannot be handed back', () => {
// The safeguard's fold: this reading does not draw a note at all, so the panel
// names the lens that does instead of offering an act it would refuse.
@@ -2077,3 +2087,48 @@ describe('Ctrl+V on the drawing', () => {
expect(source).toContain('{#if pasted && !snapshotReading}');
});
});
+
+describe('opening a saved view of the other surface', () => {
+ it('draws the shared question where it stands, rather than opening the Board', () => {
+ const body = source.slice(
+ source.indexOf('async function openAnalysisView'),
+ source.indexOf('async function leaveAnalysisReading'),
+ );
+ expect(body).toContain("if (view.surface !== 'graph') return;");
+ // No tool switch here. The one on a node's panel stays: that one is asked for.
+ expect(body).not.toContain('uiState.tool');
+ // The mirror is what carries the question across, and it runs while hidden.
+ expect(source).toContain('untrack(() => (searchFilter = normalizeFilter(analysisSearch.filter)))');
+ });
+});
+
+describe('exporting the drawing', () => {
+ it('serialises the scene the canvas is built from, rather than the canvas', () => {
+ // No `toDataURL`, no second layout: the same placement, bends and byId the Konva
+ // stage reads go to `lib/graphPlate.js`, which is why a plate cannot drift.
+ expect(source).toContain('graphPlate({');
+ expect(source).toContain('placed,\n edges,\n bends,\n byId,');
+ expect(source).toContain('hidden: hiding');
+ expect(source).not.toContain('stage.toDataURL');
+ });
+
+ it('carries the reading, not just the picture', () => {
+ expect(source).toContain("surface: 'Graph'");
+ expect(source).toContain('lens: lensLabel');
+ expect(source).toContain('question: searchSaid');
+ expect(source).toContain('families: legend.filter((entry) => entry.on && entry.count)');
+ expect(source).toContain('strokes,');
+ });
+
+ it('says how many nodes the folds and the focus are holding back', () => {
+ // A narrowed picture presented as the whole case is the one lie a plate could tell,
+ // and the drawing resizes to what is left either way — so both have to be written.
+ expect(source).toContain('node${foldedCount === 1');
+ expect(source).toContain('node${outsideFocus === 1');
+ expect(source).toContain('placed.reduce((count, node) => count + (hiding.has(node.id) ? 0 : 1), 0)');
+ });
+
+ it('offers the export beside the saved views', () => {
+ expect(source).toContain('<PlateExport surface="graph" plate={capturePlate}');
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index ed942cd..e0ca027 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -102,6 +102,9 @@
// the live session (reset on source / case change)
const _firstCollage = makeCollage('Collage 1');
+ // Bumped every time the session is cleared, so work started against the old
+ // one can tell it is stale (`resetSession`, `capture`).
+ let sessionRun = 0;
const session = $state({
source: null,
videoAdjust: {},
@@ -199,7 +202,8 @@
}
// Frame tab: Enter applies the crop (→ committed preview), Esc leaves editing.
if (activeTab === 'frame' && cropEditing) {
- if (e.key === 'Enter' || e.key === 'Escape') { e.preventDefault(); commitCrop(); }
+ if (e.key === 'Enter') { e.preventDefault(); commitCrop(); }
+ else if (e.key === 'Escape') { e.preventDefault(); cancelCrop(); }
return;
}
// Selection tab: ←/→ step one frame (Shift = 1s), ,/. mpv-style aliases
@@ -237,6 +241,7 @@
// applied (Enter / Apply), a committed *preview* showing the cropped result.
// Re-opening crop (button or double-click) goes back to editing the original.
let cropEditing = $state(false);
+ let cropBefore = null; // the crop editing opened on — what Escape puts back
let frameOrientationBusy = $state(false);
const videoFilters = $derived(filters.filter((f) => VIDEO_ADJUST_IDS.includes(f.id)));
@@ -539,6 +544,10 @@
}
function resetSession() {
+ // Everything still in flight against the session being cleared belongs to a
+ // document that no longer exists. `session` is one object mutated in place,
+ // so a pending render has no way to notice on its own (see `capture`).
+ sessionRun += 1;
for (const fr of session.frames) if (fr.url?.startsWith('blob:')) URL.revokeObjectURL(fr.url);
session.source = null;
session.videoAdjust = {};
@@ -569,6 +578,7 @@
rotating = false;
frameAspect = null;
cropEditing = false;
+ cropBefore = null;
anchorCollageHistory();
}
@@ -676,11 +686,20 @@
// -- frame capture (Selection) -------------------------------------------
async function capture(time) {
+ // The render and the measurement below are two round trips, and a slow video
+ // leaves room to discard the session or pick another source in between. The
+ // frame that lands is evidence, so a stale one must be dropped rather than
+ // pushed into whatever document is open by then.
+ const run = sessionRun;
try {
const sourceOps = rotationOps(videoRotation);
const url = await renderUrl(session.source.path, time, sourceOps);
const frame = makeFrame(session.source.path, time, url);
const dim = await imageSize(url);
+ if (run !== sessionRun) {
+ if (url.startsWith('blob:')) URL.revokeObjectURL(url);
+ return;
+ }
frame.sourceOps = sourceOps;
frame.w = dim.w;
frame.h = dim.h;
@@ -690,7 +709,7 @@
session.activeFrameId = frame.id;
toast('Frame added to tray. Not saved yet', 'ok');
} catch (e) {
- toast(e.message, 'danger');
+ if (run === sessionRun) toast(e.message, 'danger');
}
}
@@ -819,12 +838,14 @@
frameRotMatrix = IDENTITY;
frameAspect = null;
cropEditing = false;
+ cropBefore = null;
shared.cropMode = false;
});
// Enter crop editing (original + box); arm a fresh draw if there's no box yet.
function beginCrop() {
if (!activeFrame) return;
+ cropBefore = activeFrame.crop ? { ...activeFrame.crop } : null;
cropEditing = true;
if (!activeFrame.crop) shared.cropMode = true;
}
@@ -832,6 +853,16 @@
function commitCrop() {
cropEditing = false;
shared.cropMode = false;
+ cropBefore = null;
+ }
+ // Escape leaves crop editing the way it found it: the box drawn since
+ // `beginCrop` is dropped rather than applied. Escape committing was the one
+ // key in the tool that made a change the analyst was backing out of.
+ function cancelCrop() {
+ if (activeFrame) activeFrame.crop = cropBefore;
+ cropEditing = false;
+ shared.cropMode = false;
+ cropBefore = null;
}
// Wheel zooms toward the pointer (never below the fitted size); at 1× the pan
diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.js
index 9421f37..d69f7ce 100644
--- a/frontend/src/tools/Inspector.test.js
+++ b/frontend/src/tools/Inspector.test.js
@@ -186,3 +186,23 @@ describe('Inspect sessions', () => {
saveUi.note = '';`);
});
});
+
+describe('Inspect — work that outlived what it was started against', () => {
+ it('drops a frame whose session was cleared while it rendered', () => {
+ // `session` is one object mutated in place, so a capture awaiting two round
+ // trips cannot notice a discard or a source switch on its own — the frame
+ // landed in the new session and became the active one.
+ expect(source).toContain('let sessionRun = 0;');
+ expect(source).toContain('sessionRun += 1;');
+ expect(source).toMatch(/async function capture\(time\) \{[\s\S]*?const run = sessionRun;/);
+ expect(source).toMatch(/const dim = await imageSize\(url\);\s*\n\s*if \(run !== sessionRun\)/);
+ });
+
+ it('lets Escape leave the crop it found rather than applying the new one', () => {
+ expect(source).toContain("if (e.key === 'Enter') { e.preventDefault(); commitCrop(); }");
+ expect(source).toContain("else if (e.key === 'Escape') { e.preventDefault(); cancelCrop(); }");
+ expect(source).toContain('function cancelCrop()');
+ expect(source).toContain('activeFrame.crop = cropBefore');
+ expect(source).toContain('cropBefore = activeFrame.crop ? { ...activeFrame.crop } : null;');
+ });
+});
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index b50b8e3..f4c5329 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -20,9 +20,11 @@
import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
import { gotoPoint } from '../lib/navigate.js';
import { revealMediaFolder } from '../lib/reveal.js';
+ import { thisBrowser } from '../lib/thisBrowser.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import Icon from '../components/Icon.svelte';
import PasteDialog from '../components/PasteDialog.svelte';
+ import SourceDialog from '../components/SourceDialog.svelte';
import SearchInput from '../components/SearchInput.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -64,6 +66,8 @@
// cookie affordance, shown only when a download hits a login wall:
// {url, index, title, platform, guidance, browser, busy}
let authPrompt = $state(null);
+ // Telegram's public page omits the file URL for videos it marks as too big.
+ let telegramPrompt = $state(null); // {url}
// browsers yt-dlp can read a session from; the Chromium subset can't be read
// on Windows (locked/app-bound store) so we steer those to the file fallback
@@ -127,10 +131,13 @@
);
// --- free-text search + sort ---
+ // Newest first, which is what the library is opened for: the files that just came in are
+ // the ones being worked on, and A–Z put them wherever their filename happened to fall.
+ // The same order the server already answers with by default (`GET .../media/page`).
let query = $state('');
- let sort = $state('name');
- let sortDirection = $state('asc');
- let headerSort = $state(null);
+ let sort = $state('newest');
+ let sortDirection = $state('desc');
+ let headerSort = $state('added');
const LIST_SORTS = [
{ id: 'name', label: 'Name' },
{ id: 'type', label: 'Type' },
@@ -142,7 +149,7 @@
query.length > 0 || catFilter !== null || folderFilter !== null || gpsOnly || !collectedOnly
);
const filtersActive = $derived(
- browseFiltersActive || sort !== 'name' || sortDirection !== 'asc'
+ browseFiltersActive || sort !== 'newest' || sortDirection !== 'desc'
);
// Also shown for a case whose files are all working ones: the grid is empty
// because the switch is on, and the switch is in this bar.
@@ -255,9 +262,9 @@
folderFilter = null;
gpsOnly = false;
collectedOnly = true;
- sort = 'name';
- sortDirection = 'asc';
- headerSort = null;
+ sort = 'newest';
+ sortDirection = 'desc';
+ headerSort = 'added';
reloadIfServerBacked();
}
@@ -418,8 +425,11 @@
path ? { path } : {}
);
if (path) {
+ // Keyed by case *and* path, the way `markBrokenThumb` recorded it —
+ // deleting the bare path never matched, so a regenerated thumbnail kept
+ // showing the broken placeholder until the case was switched.
const next = new Set(brokenThumbs);
- next.delete(path);
+ next.delete(`${id}/${path}`);
brokenThumbs = next;
}
await refresh();
@@ -462,25 +472,76 @@
}
}
- async function importFiles(fileList) {
+ // ── import ───────────────────────────────────────────────────────────────
+ // A downloaded file that reaches the case as an import carries no address of
+ // its own: the analyst fetched it elsewhere, and only they know where from. So
+ // the batch is asked once, on the way in, and the answer sticks for the session
+ // — one thread's worth of files rarely arrives in a single drop.
+ let pendingImport = $state(null); // {files: File[]} waiting on the dialog
+ let importBusy = $state(false);
+ let statingSource = $state(null); // {paths} — a landed batch, stated afterwards
+ let statingBusy = $state(false);
+ let lastSource = $state(''); // prefills whichever dialog opens next
+
+ function importFiles(fileList) {
const files = [...fileList];
- if (!files.length) return;
- const c = await ensureCase();
- let added = 0;
- let dups = 0;
- for (const file of files) {
- const form = new FormData();
- form.append('file', file);
- try {
- const res = await api.post(`/api/cases/${c.id}/media/upload`, form);
- res.duplicate ? dups++ : added++;
- } catch (e) {
- toast(`${file.name}: ${e.message}`, 'danger');
+ if (files.length) pendingImport = { files };
+ }
+
+ async function runImport(files, sourceUrl) {
+ if (importBusy) return;
+ importBusy = true;
+ try {
+ const c = await ensureCase();
+ let dups = 0;
+ const landed = [];
+ for (const file of files) {
+ const form = new FormData();
+ form.append('file', file);
+ if (sourceUrl) form.append('source_url', sourceUrl);
+ try {
+ const res = await api.post(`/api/cases/${c.id}/media/upload`, form);
+ if (res.duplicate) dups++;
+ else if (res.item?.path) landed.push(res.item.path);
+ } catch (e) {
+ toast(`${file.name}: ${e.message}`, 'danger');
+ }
}
+ lastSource = sourceUrl;
+ pendingImport = null;
+ await Promise.all([refresh(), reloadCase()]);
+ if (landed.length) {
+ const count = `${landed.length} file${landed.length > 1 ? 's' : ''}`;
+ // Nothing stated: the offer to say it sits on the batch that just landed,
+ // rather than one panel per file, later, once it has been forgotten.
+ const offer = sourceUrl
+ ? null
+ : { label: 'Set source', onClick: () => (statingSource = { paths: landed }) };
+ toast(`${count} added to the case`, 'ok', offer ? 6000 : 3800, offer);
+ }
+ if (dups) toast(`${dups} duplicate${dups > 1 ? 's' : ''} skipped (same SHA-256)`, 'warn');
+ } finally {
+ importBusy = false;
+ }
+ }
+
+ /** State one origin for a batch already in the case. */
+ async function saveStatedSource(sourceUrl) {
+ if (statingBusy || !statingSource) return;
+ statingBusy = true;
+ try {
+ const cid = caseState.current.id;
+ for (const path of statingSource.paths)
+ await api.patch(`/api/cases/${cid}/media`, { path, source_url: sourceUrl });
+ lastSource = sourceUrl;
+ statingSource = null;
+ await Promise.all([refresh(), reloadCase()]);
+ toast('Source saved', 'ok');
+ } catch (e) {
+ toast(`Could not save the source: ${e.message}`, 'danger');
+ } finally {
+ statingBusy = false;
}
- await Promise.all([refresh(), reloadCase()]);
- if (added) toast(`${added} file${added > 1 ? 's' : ''} added to the case`, 'ok');
- if (dups) toast(`${dups} duplicate${dups > 1 ? 's' : ''} skipped (same SHA-256)`, 'warn');
}
async function download() {
@@ -562,7 +623,9 @@
return;
}
jobs = jobs.filter((j) => j.id !== jobId);
- if (status.status === 'done' && status.result?.needs_auth) {
+ if (status.status === 'done' && status.result?.telegram_only) {
+ telegramPrompt = { url: job.url };
+ } else if (status.status === 'done' && status.result?.needs_auth) {
// login wall — offer a cookie source and retry, nothing downloaded yet
authPrompt = {
url: job.url,
@@ -570,7 +633,7 @@
title: job.title ?? null,
platform: status.result.platform ?? '',
guidance: status.result.guidance ?? '',
- browser: 'firefox',
+ browser: thisBrowser(),
busy: false,
};
} else if (status.status === 'done' && status.result?.multi) {
@@ -1012,7 +1075,7 @@
{#if mediaPoint(item)}
<button
class="btn btn-ghost btn-sm"
- title={`Metadata says ${pointLabel(item)} — show it on the map`}
+ title={`Show ${pointLabel(item)} on the map`}
onclick={() => showOnMap(item)}
>
<Icon name="pin" size={14} />
@@ -1110,7 +1173,7 @@
{#if mediaPoint(item)}
<button
class="gps-badge badge"
- title={`Metadata says ${pointLabel(item)} — show it on the map`}
+ title={`Show ${pointLabel(item)} on the map`}
aria-label={`Show ${pointLabel(item)} on the map`}
onclick={(e) => showOnMap(item, e)}
>
@@ -1128,7 +1191,9 @@
<span class="meta">
{fmtSize(item.size)} ·
<span class="mono" title={item.sha256}>{item.sha256.slice(0, 8)}</span>
- {#if item.source?.type === 'download'}
+ <!-- Any file that has an origin says so, fetched or stated: what the
+ row is for is getting back to where the thing came from. -->
+ {#if item.source?.webpage_url ?? item.source?.url}
· <a href={item.source.webpage_url ?? item.source.url} target="_blank" rel="noreferrer">source</a>
{/if}
</span>
@@ -1248,6 +1313,25 @@
</Modal>
{/if}
+{#if telegramPrompt}
+ <Modal title="This video needs Telegram" onclose={() => (telegramPrompt = null)} width="440px">
+ <p class="telegram-hint">Save it in Telegram, then import the file here.</p>
+ <div class="modal-actions">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={() => (telegramPrompt = null)}>Close</button>
+ <a
+ class="btn btn-primary"
+ href={telegramPrompt.url}
+ target="_blank"
+ rel="noreferrer"
+ onclick={() => (telegramPrompt = null)}
+ >
+ <Icon name="external" size={14} /> Open in Telegram
+ </a>
+ </div>
+ </Modal>
+{/if}
+
<!-- cookie affordance: shown only when a download hits a login wall. The first
attempt is always cookie-less, so this never interrupts public media. -->
{#if authPrompt}
@@ -1421,6 +1505,29 @@
/>
{/if}
+<!-- Where a dropped batch came from: asked once on the way in, and again on the
+ batch that landed without an answer. -->
+{#if pendingImport}
+ <SourceDialog
+ count={pendingImport.files.length}
+ value={lastSource}
+ busy={importBusy}
+ onconfirm={(source) => runImport(pendingImport.files, source)}
+ onclose={() => (pendingImport = null)}
+ />
+{/if}
+
+{#if statingSource}
+ <SourceDialog
+ mode="state"
+ count={statingSource.paths.length}
+ value={lastSource}
+ busy={statingBusy}
+ onconfirm={saveStatedSource}
+ onclose={() => (statingSource = null)}
+ />
+{/if}
+
<style>
.tool {
position: relative;
@@ -1901,7 +2008,8 @@
}
/* cookie affordance */
- .auth-hint {
+ .auth-hint,
+ .telegram-hint {
font-size: var(--fs-sm);
color: var(--text-2);
margin: 0 0 14px;
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
index 47fe953..006c8fa 100644
--- a/frontend/src/tools/MediaLibrary.test.js
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -110,7 +110,7 @@ describe('Media Library positions', () => {
// the row is read by its filename; coordinates belong in the tooltip and on
// the map, not appended to every title
expect(source).toContain('function pointLabel(item)');
- expect(source).toContain('title={`Metadata says ${pointLabel(item)} — show it on the map`}');
+ expect(source).toContain('title={`Show ${pointLabel(item)} on the map`}');
expect(source).toContain('<Icon name="pin" size={11} />');
expect(source).not.toContain('{pointLabel(item)}<');
});
@@ -243,8 +243,16 @@ describe('Media Library browse controls', () => {
expect(source).toContain('mediaDisplayKind(item)');
});
+ it('opens on the newest files, which is what the library is opened for', () => {
+ // A–Z put a file that arrived a minute ago wherever its filename happened to fall.
+ // The same order the server answers with by default, so the two modes agree.
+ expect(source).toContain("let sort = $state('newest')");
+ expect(source).toContain("let sortDirection = $state('desc')");
+ expect(source).toContain("let headerSort = $state('added')");
+ expect(source).toContain("sort !== 'newest' || sortDirection !== 'desc'");
+ });
+
it('offers grids plus a plain, sortable details list', () => {
- expect(source).toContain("let sort = $state('name')");
expect(source).toContain("let view = $state('large')");
expect(source).toContain("{ id: 'small', label: 'Small'");
expect(source).toContain("{ id: 'large', label: 'Large'");
@@ -310,7 +318,7 @@ describe('Media Library browse controls', () => {
it('offers a right-side reset button for all browse filters', () => {
expect(source).toContain('function resetFilters()');
- expect(source).toContain("query = '';\n catFilter = null;\n folderFilter = null;\n gpsOnly = false;\n collectedOnly = true;\n sort = 'name';\n sortDirection = 'asc';");
+ expect(source).toContain("query = '';\n catFilter = null;\n folderFilter = null;\n gpsOnly = false;\n collectedOnly = true;\n sort = 'newest';\n sortDirection = 'desc';");
expect(source).toContain('class="btn btn-ghost btn-sm reset-filters"');
expect(source).toContain('Reset filters');
expect(source).toContain('<Icon name="reset" size={13} /> Reset filters');
@@ -354,6 +362,22 @@ describe('Media Library gated-download cookie affordance', () => {
});
});
+describe('Media Library Telegram size wall', () => {
+ it('turns the typed job result into an actionable Telegram prompt', () => {
+ expect(source).toContain("status.status === 'done' && status.result?.telegram_only");
+ expect(source).toContain('telegramPrompt = { url: job.url }');
+ expect(source).toContain('<Modal title="This video needs Telegram"');
+ expect(source).toContain('Save it in Telegram, then import the file here.');
+ });
+
+ it('opens the original link without adding a downloader or login flow', () => {
+ expect(source).toContain('href={telegramPrompt.url}');
+ expect(source).toContain('target="_blank"');
+ expect(source).toContain('rel="noreferrer"');
+ expect(source).toContain('Open in Telegram');
+ });
+});
+
describe('row and card actions fit', () => {
const source = readFileSync(new URL('./MediaLibrary.svelte', import.meta.url), 'utf8');
@@ -437,3 +461,42 @@ describe('Ctrl+V on the grid', () => {
expect(source).toContain("toast('Already in the case (same SHA-256)', 'warn')");
});
});
+
+describe('where an imported file came from', () => {
+ it('asks the batch once, on the way in', () => {
+ // a file the analyst downloaded elsewhere carries no address of its own, and
+ // the drop is the first moment anyone can say one
+ expect(source).toContain("import SourceDialog from '../components/SourceDialog.svelte'");
+ expect(source).toContain('pendingImport = { files }');
+ expect(source).toContain('onconfirm={(source) => runImport(pendingImport.files, source)}');
+ });
+
+ it('carries the stated origin on every file of the batch', () => {
+ expect(source).toContain("if (sourceUrl) form.append('source_url', sourceUrl)");
+ });
+
+ it('remembers the last one stated, since a thread arrives in several drops', () => {
+ expect(source).toContain('lastSource = sourceUrl');
+ expect(source).toContain('value={lastSource}');
+ });
+
+ it('offers the batch that landed without one the chance to say it', () => {
+ expect(source).toContain("label: 'Set source'");
+ expect(source).toContain('statingSource = { paths: landed }');
+ expect(source).toContain("api.patch(`/api/cases/${cid}/media`, { path, source_url: sourceUrl })");
+ });
+
+ it('shows a source link on any file that has one, fetched or stated', () => {
+ expect(source).toContain('{#if item.source?.webpage_url ?? item.source?.url}');
+ expect(source).not.toContain("{#if item.source?.type === 'download'}");
+ });
+});
+
+describe('Media Library — broken thumbnails', () => {
+ it('clears the broken flag under the key it was recorded with', () => {
+ // Recorded as `${caseId}/${path}`, so deleting the bare path never matched
+ // and a regenerated thumbnail kept showing the placeholder.
+ expect(source).toContain('next.delete(`${id}/${path}`);');
+ expect(source).not.toContain('next.delete(path);');
+ });
+});
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
index aec5a6a..651d5f2 100644
--- a/frontend/src/tools/Notebook.svelte
+++ b/frontend/src/tools/Notebook.svelte
@@ -72,6 +72,7 @@
let saved = $state(true);
let editVersion = 0;
let saveTimer;
+ let pendingSave = null; // the debounced write, callable before its timer fires
// The whole entity set — notes to list, references and media to insert, and the
// targets `[[mentions]]` resolve to — read off the bounded catalog rather than
@@ -289,6 +290,7 @@
function cancelPendingSave() {
clearTimeout(saveTimer);
saveTimer = undefined;
+ pendingSave = null; // deliberately dropped: the note is being deleted or reset
editVersion += 1;
}
@@ -344,7 +346,24 @@
const targetKey = key;
const contents = text;
const version = ++editVersion;
- saveTimer = setTimeout(() => save(target, targetKey, contents, version), 700);
+ // Kept beside the timer so the edit can be written *now* by anything that
+ // has to get it onto disk before it acts (see runExport). The arguments are
+ // the ones captured here, not the live fields: by the time this is flushed
+ // the analyst may be on another note.
+ pendingSave = () => save(target, targetKey, contents, version);
+ saveTimer = setTimeout(() => {
+ pendingSave = null;
+ save(target, targetKey, contents, version);
+ }, 700);
+ }
+
+ /** Write a debounced edit immediately, if one is still waiting. */
+ async function flushPendingSave() {
+ const write = pendingSave;
+ clearTimeout(saveTimer);
+ saveTimer = undefined;
+ pendingSave = null;
+ if (write) await write();
}
async function save(target, targetKey, contents, version) {
@@ -400,13 +419,18 @@
*
* The backend renders from what is on disk, so a pending edit is flushed
* first — otherwise the analyst exports the note as it was 700 ms ago.
+ *
+ * The debounced save is flushed, never merely cancelled: the timer may hold
+ * the only copy of an edit made in *another* tab, since switching tabs resets
+ * `saved` without touching it. Dropping it lost that edit while the header
+ * still read "Saved".
*/
async function runExport(noteIds) {
if (!caseState.current || exportBusy) return;
const caseId = caseState.current.id;
exportBusy = true;
try {
- clearTimeout(saveTimer);
+ await flushPendingSave();
if (!saved) await save(endpoint, key, text, editVersion);
const result = await exportNotes(caseId, noteIds);
exportOpen = false;
diff --git a/frontend/src/tools/Notebook.test.js b/frontend/src/tools/Notebook.test.js
index a1b4958..9cc8090 100644
--- a/frontend/src/tools/Notebook.test.js
+++ b/frontend/src/tools/Notebook.test.js
@@ -77,3 +77,21 @@ describe('Notebook note creation', () => {
});
});
+
+describe('Notebook — the debounced save and the export', () => {
+ const notebook = readFileSync(new URL('./Notebook.svelte', import.meta.url), 'utf8');
+
+ it('writes a pending edit before exporting instead of dropping it', () => {
+ // Switching tabs resets `saved` without touching the timer, so the timer can
+ // hold the only copy of another tab's edit. Cancelling it lost that edit
+ // while the header still read "Saved".
+ expect(notebook).toContain('await flushPendingSave();');
+ expect(notebook).toContain('async function flushPendingSave()');
+ expect(notebook).toContain('if (write) await write();');
+ expect(notebook).not.toMatch(/exportBusy = true;\s*\n\s*try \{\s*\n\s*clearTimeout\(saveTimer\);/);
+ });
+
+ it('still drops the pending edit when the note is being deleted or reset', () => {
+ expect(notebook).toMatch(/function cancelPendingSave\(\) \{[\s\S]*?pendingSave = null;/);
+ });
+});
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index e2403a7..6f9e04f 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -18,7 +18,7 @@
applyPostTemplateStructure, newPostMediaTweet, proofSourceMediaPaths,
normalizePostMediaPickerTarget, postMediaForType, renumberMediaTweetText, retargetMediaTweetText,
normalizePostTarget, POST_TARGETS, postCharacterCount, postComposeUrl, postReportMarkdown,
- postTarget, templateUsesPostField, togglePostMedia,
+ postTarget, templateUsesPostField, togglePostMedia, pointLines,
} from '../lib/post.js';
import { bidiSafe } from '../lib/bidi.js';
import { matchesQuery } from '../lib/mediaFilter.js';
@@ -35,6 +35,9 @@
let description = $state('');
let mention = $state(prefs.postMention);
let source = $state('');
+ /** The Source box grows with what it holds, up to four lines: a proof read from a
+ * thread carries an address per post, and one row would hide all but the first. */
+ const sourceRows = $derived(Math.min(4, Math.max(1, source.split('\n').length)));
let proofPng = $state(null);
let proofVer = $state(0); // cache-buster: bumped whenever proofPng is (re)assigned
let tweet1 = $state('');
@@ -238,7 +241,10 @@
});
async function resolveCoords() {
- const value = coordsText.trim();
+ // The first line is the conclusion: it is what the place, the plus code, the
+ // DMS and the map links are an address for. The rest are points the picture
+ // also shows, carried into the tweet as written.
+ const value = pointLines(coordsText)[0]?.coords ?? '';
if (!value) {
geo = null;
regenerate();
@@ -249,6 +255,11 @@
regenerate();
lookupPlace();
} catch {
+ // The old point does not survive text that no longer resolves to it.
+ // Leaving it in place kept the facts card, the tweet, the copy buttons and
+ // the saved report publishing a location the input no longer shows.
+ geo = null;
+ regenerate();
toast('Could not parse coordinates', 'danger');
}
}
@@ -277,6 +288,7 @@
description,
lat: geo?.lat,
lon: geo?.lon,
+ coordsText,
mention,
source,
});
@@ -899,14 +911,16 @@
}
function reportContent(title = draftTitle(), evidence = {}) {
+ const points = pointLines(coordsText);
const coordinates = geo
? `${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`
- : coordsText.trim();
+ : points[0]?.coords ?? '';
return postReportMarkdown({
title,
place,
plusCode: geo?.plus_code,
coordinates,
+ points,
dms: geo?.dms,
mapLinks: geo?.links,
description,
@@ -1089,14 +1103,17 @@
title={fieldDisabledByTemplate('coordinates') ? TEMPLATE_FIELD_HINT : undefined}
>
<label class="label" for="pc-coords">Coordinates</label>
- <input
+ <!-- One point per line. A proof showing three impacts hands over three,
+ and the first one is what the facts below are an address for. -->
+ <textarea
id="pc-coords"
- class="input mono"
+ class="input mono coords-input"
+ rows={Math.min(4, Math.max(1, pointLines(coordsText).length))}
placeholder="10.303315, -66.874095"
bind:value={coordsText}
onchange={resolveCoords}
disabled={fieldDisabledByTemplate('coordinates')}
- />
+ ></textarea>
{#if geo}
<div class="geo-facts card">
<button class="fact mono" onclick={() => copy(`${geo.lat.toFixed(6)}, ${geo.lon.toFixed(6)}`)} title="Copy">
@@ -1157,14 +1174,17 @@
title={fieldDisabledByTemplate('source') ? TEMPLATE_FIELD_HINT : undefined}
>
<label class="label" for="pc-source">Source</label>
- <input
+ <!-- A box of several lines: a proof read from a thread rests on the post that
+ published it and the ones under it, and each address is a line. -->
+ <textarea
id="pc-source"
- class="input"
+ class="textarea post-source"
+ rows={sourceRows}
placeholder="https://instagram.com/… (original post)"
bind:value={source}
onchange={regenerate}
disabled={fieldDisabledByTemplate('source')}
- />
+ ></textarea>
</div>
{#if caseState.current}
@@ -1641,6 +1661,11 @@
line-height: 1.6;
min-height: 0;
}
+ /* One line reads as the box it used to be; several grow it, up to a point. */
+ .post-source {
+ min-height: 0;
+ line-height: 1.5;
+ }
.media-tabs {
display: flex;
gap: 4px;
@@ -1751,6 +1776,8 @@
cursor: not-allowed;
}
.field.template-disabled .input { pointer-events: none; }
+ /* Grows with the points it holds, up to four lines, then scrolls. */
+ .coords-input { resize: vertical; line-height: 1.5; }
.field.template-disabled:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
index a7d449f..f6b926e 100644
--- a/frontend/src/tools/PostComposer.test.js
+++ b/frontend/src/tools/PostComposer.test.js
@@ -94,3 +94,16 @@ describe('Post naming', () => {
expect(source).toContain("!isDefaultName(item.title, 'proof')");
});
});
+
+describe('Post Composer — coordinates that no longer parse', () => {
+ const composer = readFileSync(new URL('./PostComposer.svelte', import.meta.url), 'utf8');
+
+ it('stops publishing the old point when a re-parse fails', () => {
+ // The facts card, the tweet text, the copy buttons and the saved report all
+ // read `geo`. Leaving the previous one in place kept every one of them
+ // stating a location the input no longer showed.
+ expect(composer).toMatch(
+ /\} catch \{[\s\S]*?geo = null;\s*\n\s*regenerate\(\);\s*\n\s*toast\('Could not parse coordinates'/
+ );
+ });
+});
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 77bcbcf..4ee0dee 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,5 +1,5 @@
<script>
- import { onMount } from 'svelte';
+ import { onMount, untrack } from 'svelte';
import { fileUrl } from '../lib/fileUrl.js';
import Konva from 'konva';
import { api } from '../lib/api.js';
@@ -20,15 +20,21 @@
import ProofCanvas from './proof/ProofCanvas.svelte';
import ProofLayersPanel from './proof/ProofLayersPanel.svelte';
import NewProofDialog from './proof/NewProofDialog.svelte';
+ import ImportProofDialog from './proof/ImportProofDialog.svelte';
import PanelCategories from './proof/PanelCategories.svelte';
- import { bindPanelPointerLifecycle, createCanvasRenderGate } from './proof/canvasLifecycle.js';
+ import { bindPanelPointerLifecycle, createCanvasRenderGate,
+ discardDraft,
+} from './proof/canvasLifecycle.js';
+ import { closeStrandedGesture } from '../lib/konvaGesture.js';
import {
ANNO_COLORS, PAD, GAP, ROW_GAP, PANEL_H, TWEET_GUIDES,
CAPTION_SIZE, LEGEND_SIZE, FOOTER_SIZE,
BG, TEXT_MAIN, normSpace, textColors,
layoutPanels, panelsBottom, freeNormalizeDelta, legendLineHeight, footerBand,
attributionLine, docSize, offsetShape, autoLayoutRows,
- autoCoords, formatCoords, autoSource,
+ autoCoords, formatCoords, autoSourceUrls, proofSource, statedSources,
+ specPoints, footerLines, coordsPostLines, proofCoordsLines, MAX_POINTS,
+ normalizeMaterial, resolveSourceUrls,
toSpec, newId, loadImage, orderedFeatureColors, notesFromShapes,
templateFromProof, applyProofStyle, normalizeProofStyle, newSignatureText,
anchoredPos, anchoredOffset, SIG_TEXT_SIZE,
@@ -43,15 +49,23 @@
filterProofPanelItems, hasProofCanvasContent, proofExportOptions, panelPreview,
} from '../lib/composer.js';
import {
+ canFill,
+ fillPaint,
movedBy,
nextPanelRow,
notesAfterRemoval,
nudgeShape,
PANEL_SCALE_MAX,
PANEL_SCALE_MIN,
+ pointsWithTransform,
scaleFromNode,
+ textBoxPad,
viewCentrePoint,
} from '../lib/proofEdits.js';
+ import {
+ ICON_BOX, ICON_SIZE_MIN, PROOF_ICONS,
+ glyphInk, iconByName, iconOrigin, iconSizeFor, isSolidIcon,
+ } from '../lib/proofIcons.js';
import {
assetName, base64Of, PASTE_TYPES, MAX_PASTES, MAX_PASTE_BYTES,
} from '../lib/pasteAsset.js';
@@ -64,7 +78,7 @@
const SCALE_STEP = 0.05;
const DRAW_TOOLS = [
- { id: 'select', icon: 'hand', label: 'Select / move', shortcut: 'v' },
+ { id: 'select', icon: 'cursor', label: 'Select / move', shortcut: 'v' },
{ id: 'rect', icon: 'square', label: 'Box', shortcut: 'r' },
{ id: 'ellipse', icon: 'circle', label: 'Ellipse', shortcut: 'e' },
{ id: 'arrow', icon: 'arrow', label: 'Arrow', shortcut: 'a' },
@@ -79,8 +93,16 @@
const proof = $state({
title: '', panels: [], pastes: [], shapes: [], notes: {}, legendOrder: [],
templateId: null, // selected saved house style; its values remain copied below
- coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual override
- pov: false, // the point is where the camera stood, not what it filmed
+ // What the proof concludes on, one row per point, the first one the conclusion.
+ // Always at least one row: an empty one reads as the coordinates the panels
+ // give it, which is what the field has always shown.
+ points: [{ coords: '', label: '', pov: false }],
+ sources: null, // null → traced from the panels; a list → what the analyst states
+ // Case files the proof rests on without composing them, brought in from a stated
+ // source address. They join the chain on save, and the point with it.
+ material: [],
+ footerCoords: false, // whether the plate prints the proof's points
+ footerText: true, // whether the plate prints its credit line
captionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',
footerEnabled: true, // false → no footer line at all
footerColor: null, // null → auto from the background
@@ -110,6 +132,10 @@
// Saved proof slug, or null before the first save.
let savedName = $state(null);
let dirty = $state(false);
+ // The document as it stands on disk, so an undo that walks all the way back
+ // to it can say the proof is saved again. null until a save or an open has
+ // put something there to match.
+ let savedSnapshot = null;
// A named proof can exist before it has content. This distinguishes the
// initial composer shell from a template-only proof the user just created.
let proofStarted = $state(false);
@@ -152,12 +178,25 @@
.catch(() => { if (live) proofEntities = []; });
Promise.all([api.get(`/api/cases/${id}/media`), api.get(`/api/cases/${id}/satellite`)])
.then(([media, sat]) => {
- if (live) presentPaths = new Set([...media, ...sat].map((it) => it.path));
+ if (!live) return;
+ presentPaths = new Set([...media, ...sat].map((it) => it.path));
+ caseMedia = media;
})
- .catch(() => { if (live) presentPaths = new Set(); });
+ .catch(() => { if (live) { presentPaths = new Set(); caseMedia = []; } });
return () => { live = false; };
});
+ /** The case's own media, kept for one question: whether a stated address is already
+ * in the case. Answered by tracing each file back the way a panel's source line is
+ * traced, so a frame cut from a downloaded clip counts as that clip's address. */
+ let caseMedia = $state([]);
+ const heldAddresses = $derived.by(() => {
+ const byPath = new Map(caseMedia.map((one) => [one.path, one]));
+ const found = new Set();
+ for (const one of caseMedia) for (const url of resolveSourceUrls(one, byPath)) found.add(url);
+ return found;
+ });
+
// Panels whose media was deleted: the image already drawn stays on the canvas,
// but the panel is flagged so a re-save is not silently building on a ghost.
const gonePanels = $derived(
@@ -166,14 +205,26 @@
let tool = $state('select');
let color = $state(ANNO_COLORS[0]);
let strokeW = $state(4);
+ // Fill opacity for the closed kinds, 0 to 1. Nothing is filled until the
+ // analyst asks: a box drawn over the evidence must not hide it by default.
+ let fillOpacity = $state(0);
+ let iconName = $state(PROOF_ICONS[0].name); // symbol the stamp tool places
let guide = $state(null); // null | '16:9' | '4:5' — tweet centre-crop overlay
- let selectedId = $state(null);
+ // The picked annotations. A press replaces the set, shift adds to it, and a
+ // marquee dragged over the page takes everything it touches. Panels, overlays
+ // and the signature stay single: each is one object, not a family.
+ let selectedIds = $state([]);
let selectedPanelId = $state(null); // free-layout only: panel picked for move/resize
let selectedPasteId = $state(null); // pasted image picked for move/resize/frame
let selectedSig = $state(null); // null | 'logo' | 'text' — signature picked for resize
let picker = $state(false);
let pickerItems = $state([]);
let newProofOpen = $state(false);
+ // Importing a published proof is a third way into the same tool, beside
+ // composing one and opening a saved one. It writes a proof like any other, so
+ // the only thing this screen owns is the door — and that door is in the New
+ // proof dialog rather than the toolbar, which has no room left for a button.
+ let importOpen = $state(false);
let newProofTemplateId = $state('');
let newProofPanelPaths = $state([]);
let newProofQuery = $state('');
@@ -244,8 +295,11 @@
$effect(() => {
const json = docSnapshot(); // reads every document field → tracked
- if (histBusy) return;
+ // Cleared before the guard, not after it: an undo sets `histBusy` and then
+ // returns here, so a timer armed in the 350 ms before it would survive and
+ // push the pre-undo document back onto the stack.
clearTimeout(histTimer);
+ if (histBusy) return;
histTimer = setTimeout(() => {
history.push(json);
syncHist();
@@ -259,9 +313,11 @@
proofStarted = true;
if (pathDraft) finishPath(false);
proof.title = spec.title ?? freshTitle();
- proof.coordsText = spec.coordsText ?? '';
- proof.pov = spec.pov === true;
- proof.source = spec.source ?? '';
+ proof.points = editablePoints(spec);
+ proof.footerCoords = spec.footerCoords === true;
+ proof.footerText = spec.footerText !== false;
+ proof.sources = statedSources(spec.sources ?? spec.source ?? null);
+ proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
proof.footerSize = style.footerSize;
@@ -296,7 +352,7 @@
})
.catch(() => {});
}
- selectedId = null;
+ selectedIds = [];
selectedPanelId = null;
selectedPasteId = null;
selectedSig = null;
@@ -304,7 +360,10 @@
appliedTemplate = template
? { id: template.id, name: template.name, prevStyle: templateFromProof(proof) }
: null;
- dirty = true;
+ // Undoing back to the saved document is not an edit. Measured after the
+ // restore rather than off the snapshot string, since the values above come
+ // back normalised and a raw spec need not match its own normal form.
+ dirty = docSnapshot() !== savedSnapshot;
requestAnimationFrame(fit);
// outlast the capture debounce so the restore itself is not re-recorded
setTimeout(() => (histBusy = false), 400);
@@ -328,8 +387,12 @@
let canvasRenderGate;
let drawing = null; // {panel, node, start, box, kind}
let pathDraft = null; // {panel, box, node, points:[]} — multi-click curve in progress
+ let dragMoved = false; // did the press that is ending turn into a drag?
+ let marquee = null; // {start, add, base, node} — rectangle picking over the page
+ let marqueeEnded = false; // did the press that is ending draw a marquee?
let spacePan = false; // hold-space panning (manual, so it wins over shape drags)
let panDrag = null; // {sx, sy, ox, oy} — space/middle-drag pan in progress
+ let gestureSeq = 0; // bumped by every press, so a deferred settle can tell whose
let textEdit = $state(null); // {id, value, left, top, size} — inline text editor
onMount(() => {
@@ -379,9 +442,37 @@
stage.on('dblclick dbltap', () => { if (pathDraft) finishPath(true); });
// The release can happen outside the canvas. Capture it at window level so
- // a deferred rebuild is never left waiting after an interrupted drag.
- const beginPointer = () => canvasRenderGate?.beginPointer();
- const settlePointer = () => canvasRenderGate?.endPointer();
+ // a deferred rebuild is never left waiting after an interrupted drag, and
+ // so a gesture the browser stopped reporting is ended rather than left
+ // running against the pointer.
+ const closeStranded = () => {
+ if (stage) closeStrandedGesture({ transformer, stage, isDragging: () => Konva.isDragging() });
+ };
+ const beginPointer = () => {
+ closeStranded(); // a new press proves the last gesture is over, however it ended
+ gestureSeq += 1;
+ canvasRenderGate?.beginPointer();
+ };
+ const settlePointer = () => {
+ canvasRenderGate?.endPointer();
+ // The pan is the one gesture that cannot wait: it follows the live
+ // pointer, so a move arriving before the frame below would slide the view
+ // after the button was let go. Ended twice on a normal release, which
+ // costs nothing — whichever handler gets there first does it.
+ if (panDrag) endPan();
+ // A frame later for the rest, so a gesture that ended normally has
+ // already closed itself and only a stranded one is left to end. This
+ // listener runs in the capture phase, ahead of the handlers that close
+ // them.
+ const seq = gestureSeq;
+ requestAnimationFrame(() => {
+ closeStranded();
+ // A press that landed inside the frame we waited opened a new gesture:
+ // what is in hand now is not what this release left behind, and
+ // settling it would commit a stroke still being drawn.
+ if (seq === gestureSeq) settleStrandedGesture();
+ });
+ };
// Capture before Konva dispatches the event: selected annotations stop
// bubbling at their node, so a Stage listener alone cannot see every press.
containerEl.addEventListener('pointerdown', beginPointer, true);
@@ -434,6 +525,19 @@
if (tool !== 'curve' && pathDraft) finishPath(false);
});
+ // Picking up a drawing tool puts the document out of reach: nothing on the
+ // canvas is hit-tested or handled, so a press that starts inside an existing
+ // element draws a new one instead of dragging the old. Drawing finds its
+ // surface geometrically (see surfaceAt), never through Konva's hit graph.
+ $effect(() => {
+ tool; // the tool alone: the document has its own rebuild below
+ untrack(() => {
+ if (!stage) return;
+ syncCanvasListening();
+ if (proofHasContent) refreshCanvasUi();
+ });
+ });
+
// Rebuild only when published document content changes. Selection is UI-only
// and gets a lightweight refresh below, without recreating every image node.
$effect(() => {
@@ -446,6 +550,9 @@
proof.captionSize, proof.legendSize, proof.footerSize, proof.footer,
proof.footerEnabled, proof.footerColor,
proof.footerAlign,
+ // the plate prints these when asked, and printing them changes its height:
+ // both have to reach the rebuild, or the picture lags a line behind
+ proof.footerCoords, proof.footerText, proof.points,
proof.bg, proof.space,
proof.layout,
proof.panelDirection,
@@ -458,7 +565,7 @@
});
$effect(() => {
- selectedId;
+ selectedIds;
selectedPanelId;
selectedPasteId;
selectedSig;
@@ -473,6 +580,7 @@
legendSize: proof.legendSize,
footerSize: proof.footerSize,
footerEnabled: proof.footerEnabled !== false,
+ footerLines: footerLines(proof, prefs.coordFormat).length,
});
// Layout boxes + document measure for the active layout mode. Pasted images
@@ -491,13 +599,16 @@
proof.notes = {};
proof.legendOrder = [];
proof.templateId = null;
- proof.coordsText = '';
- proof.source = '';
+ proof.points = [blankPoint()];
+ proof.sources = null;
+ proof.material = [];
proof.captionSize = CAPTION_SIZE;
proof.legendSize = LEGEND_SIZE;
proof.footerSize = FOOTER_SIZE;
proof.footer = '';
proof.footerEnabled = true;
+ proof.footerCoords = false;
+ proof.footerText = true;
proof.footerColor = null;
proof.footerAlign = 'left';
proof.captionsEnabled = true;
@@ -510,8 +621,9 @@
proof.palette = [...ANNO_COLORS];
color = proof.palette[0];
savedName = null;
+ savedSnapshot = null;
proofStarted = false;
- selectedId = null;
+ selectedIds = [];
selectedPanelId = null;
selectedPasteId = null;
selectedSig = null;
@@ -580,9 +692,46 @@
// Pick the logo or the @handle so the transformer wraps it — click a corner to
// resize it right on the canvas. Content selections drop, so only one thing
// ever carries the handles.
+ /**
+ * Pick an annotation, or add it to the ones already picked.
+ *
+ * Shift is the additive key everywhere: on the canvas, and on the rows in the
+ * side column. Picking an annotation drops the panel, overlay or signature
+ * that was picked, since those are transformed on their own terms.
+ */
+ function pickShape(id, additive = false) {
+ if (!additive) selectedIds = [id];
+ else if (selectedIds.includes(id)) selectedIds = selectedIds.filter((x) => x !== id);
+ else selectedIds = [...selectedIds, id];
+ selectedPanelId = null;
+ selectedPasteId = null;
+ selectedSig = null;
+ }
+
+ /**
+ * Press and click on one annotation's node.
+ *
+ * A press on an element that is already part of the family leaves the family
+ * alone, so the whole of it can be dragged from any member. Collapsing to the
+ * one pressed waits for the click, which only lands if the press did not turn
+ * into a drag.
+ */
+ function bindShapePick(node, s) {
+ node.on('pointerdown', (e) => {
+ if (tool !== 'select') return;
+ e.cancelBubble = true;
+ dragMoved = false;
+ if (e.evt.shiftKey || !selectedIds.includes(s.id)) pickShape(s.id, e.evt.shiftKey);
+ });
+ node.on('click tap', (e) => {
+ if (tool !== 'select' || dragMoved || e.evt.shiftKey) return;
+ if (selectedIds.length > 1) pickShape(s.id);
+ });
+ }
+
function selectSig(which) {
selectedSig = which;
- selectedId = null;
+ selectedIds = [];
selectedPanelId = null;
selectedPasteId = null;
}
@@ -590,16 +739,48 @@
function selectPaste(id) {
if (tool !== 'select') return;
selectedPasteId = id;
- selectedId = null;
+ selectedIds = [];
selectedPanelId = null;
selectedSig = null;
}
function selectPanel(id) {
- if (tool !== 'select') return;
+ if (tool !== 'select' || marqueeEnded) return;
selectedPanelId = id;
selectedPasteId = null;
- selectedId = null;
+ selectedIds = [];
+ selectedSig = null;
+ }
+
+ /**
+ * Picking from the rows in the side column.
+ *
+ * On the canvas a press with a drawing tool in hand means "draw here", so the
+ * pick handlers above refuse it. A row cannot mean anything else, so instead
+ * of refusing it takes the hand back to Select — where the pick has handles,
+ * answers Delete and can be recoloured. Lighting a row nothing answers to was
+ * a selection visible in one column and absent from the other.
+ */
+ function pickShapeRow(id, additive = false) {
+ tool = 'select';
+ pickShape(id, additive);
+ }
+
+ /** Clicking the lit row again lets go, which is how the thumbnails read. */
+ function pickPanelRow(id) {
+ tool = 'select';
+ marqueeEnded = false;
+ selectedPanelId = selectedPanelId === id ? null : id;
+ selectedPasteId = null;
+ selectedIds = [];
+ selectedSig = null;
+ }
+
+ function pickPasteRow(id) {
+ tool = 'select';
+ selectedPasteId = selectedPasteId === id ? null : id;
+ selectedPanelId = null;
+ selectedIds = [];
selectedSig = null;
}
@@ -833,7 +1014,7 @@
if (next === null) return;
proof.panels[index].row = next;
normalizeRows();
- selectedId = null;
+ selectedIds = [];
dirty = true;
requestAnimationFrame(fit);
}
@@ -923,7 +1104,7 @@
);
proof.panels.forEach((p, i) => { p.row = rows[i]; p.scale = 1; });
normalizeRows();
- selectedId = null;
+ selectedIds = [];
dirty = true;
requestAnimationFrame(fit);
}
@@ -933,7 +1114,7 @@
proof.shapes = proof.shapes.filter((s) => s.panel !== panel.id);
proof.panels.splice(index, 1);
normalizeRows();
- selectedId = null;
+ selectedIds = [];
selectedPanelId = null;
dirty = true;
requestAnimationFrame(fit);
@@ -1066,7 +1247,7 @@
if (!paste) return;
proof.shapes = proof.shapes.filter((s) => s.panel !== paste.id);
proof.pastes.splice(index, 1);
- selectedId = null;
+ selectedIds = [];
if (selectedPasteId === paste.id) selectedPasteId = null;
dirty = true;
}
@@ -1128,59 +1309,171 @@
// ---- drawing ----------------------------------------------------------------------
+ /**
+ * Who may answer the pointer: only Select, and only when space is not held.
+ *
+ * Konva fills a shape's hit canvas whether or not the shape has a fill, so an
+ * outlined box is hit across its whole inside. Left listening while a drawing
+ * tool is active, a stroke started inside an ellipse dragged that ellipse
+ * instead — and the drag ate the gesture, so the new element died under the
+ * minimum size. Both layers go quiet together: the handles on `uiLayer` sit
+ * over the same pixels the analyst is drawing on.
+ */
+ function syncCanvasListening() {
+ const live = tool === 'select' && !spacePan;
+ docLayer?.listening(live);
+ uiLayer?.listening(live);
+ }
+
function docPoint() {
const p = stage.getPointerPosition();
return { x: (p.x - stage.x()) / stage.scaleX(), y: (p.y - stage.y()) / stage.scaleY() };
}
+ /** The rectangle between two document points, however it was dragged. */
+ function marqueeBox(a, b) {
+ return {
+ x: Math.min(a.x, b.x), y: Math.min(a.y, b.y),
+ width: Math.abs(b.x - a.x), height: Math.abs(b.y - a.y),
+ };
+ }
+
+ /**
+ * The annotations a marquee catches: every one it touches, not only the ones
+ * it swallows whole, which is the forgiving rule and the one Slides uses.
+ *
+ * Measured off the drawn nodes rather than the stored geometry, so a rotated
+ * text, a stroke's width and a panel's scale are all already accounted for.
+ */
+ function shapesTouching(box) {
+ const caught = [];
+ for (const s of proof.shapes) {
+ const node = docLayer.findOne(`#${s.id}`);
+ if (!node) continue;
+ const r = node.getClientRect({ relativeTo: docLayer });
+ const misses = r.x > box.x + box.width || r.x + r.width < box.x
+ || r.y > box.y + box.height || r.y + r.height < box.y;
+ if (!misses) caught.push(s.id);
+ }
+ return caught;
+ }
+
// Annotations are drawn on whatever surface is under the pointer — a panel or
// a pasted image. Pasted images are in front, so they claim the point first.
function surfaceAt(doc) {
return surfaceHitTest(surfacesOf(), doc);
}
+ /** Take hold of the view. The cursor says so, since the tool's own crosshair
+ * would otherwise promise a stroke while the page slides. */
+ function startPan() {
+ const p = stage.getPointerPosition();
+ panDrag = { sx: p.x, sy: p.y, ox: stage.x(), oy: stage.y() };
+ if (containerEl) containerEl.style.cursor = 'grabbing';
+ }
+
+ function endPan() {
+ panDrag = null;
+ if (containerEl) containerEl.style.cursor = spacePan ? 'grab' : '';
+ }
+
function onPointerDown(e) {
// space-drag / middle-drag pans regardless of the active tool
if (spacePan || e.evt.button === 1) {
e.evt.preventDefault();
- const p = stage.getPointerPosition();
- panDrag = { sx: p.x, sy: p.y, ox: stage.x(), oy: stage.y() };
+ startPan();
return;
}
+ // Only the primary button acts. A right-drag used to draw a whole
+ // annotation under the context menu the browser was opening over it, and in
+ // Select it cleared the selection and opened a marquee.
+ if ((e.evt.button ?? 0) > 0) return;
if (tool === 'select') {
- const onEmpty = e.target === stage || e.target.name() === 'bg';
- stage.draggable(onEmpty);
- if (onEmpty) {
- selectedId = null;
+ dragMoved = false;
+ marqueeEnded = false;
+ const add = e.evt.shiftKey;
+ // Where a drag can mean nothing else, it means picking. On the page around
+ // the panels, and across a panel the grid pins in place — an overlay or a
+ // free-layout panel is dragged instead, and the room outside the page
+ // still pans, which is the gesture that was there before the marquee.
+ const onPage = e.target.name() === 'bg';
+ const parentId = e.target.getParent()?.id() ?? '';
+ const onPinnedPanel = e.target.name() === 'panel-hit'
+ && proof.layout !== 'free'
+ && proof.panels.some((p) => `pg-${p.id}` === parentId);
+ const onEmpty = e.target === stage || onPage;
+ stage.draggable(e.target === stage);
+ // The rectangle about to be dragged replaces what was picked, so let go of
+ // it at the press: handles left standing over a marquee read as a second
+ // selection rather than the one being replaced.
+ if ((onEmpty || onPinnedPanel) && !add) {
+ selectedIds = [];
selectedPanelId = null;
selectedPasteId = null;
selectedSig = null;
}
+ if (onPage || onPinnedPanel) {
+ marquee = { start: docPoint(), add, base: [...selectedIds], node: null };
+ }
return;
}
stage.draggable(false);
const hit = surfaceAt(docPoint());
- if (!hit) return;
+ // Nothing to draw on under the pointer. The room around the page pans in
+ // Select, and it is the same room: a drag that cannot mean an annotation
+ // means the view, rather than nothing at all.
+ if (!hit) {
+ startPan();
+ return;
+ }
// `panel` here is the surface the annotation binds to: the shape's `panel`
// field holds a panel id or a pasted image's id.
const panel = hit.item;
const group = docLayer.findOne(`#pg-${panel.id}`);
if (!group) return;
- // text is placed with a single click (no drag) then edited in the side list
+ // Text is placed with a single click and typed on the spot: placing a label
+ // and saying what it says are one act, so the editor opens over it rather
+ // than leaving the word "Text" on the panel to be found and double-clicked.
+ // The tool goes back to Select because the next act is the editing.
if (tool === 'text') {
const s = {
id: newId('s'), panel: panel.id, kind: 'text', color,
x: hit.nx, y: hit.ny, text: 'Text', fontSize: 28,
};
proof.shapes.push(s);
- selectedId = s.id;
+ selectedIds = [s.id];
tool = 'select';
dirty = true;
+ // A frame later, because the press that placed the label has a default
+ // action still to come: the browser moves focus off whatever is focused
+ // when a click lands on something that cannot hold it, and an editor
+ // opened inside the pointerdown was blurred — and so committed and
+ // closed — before the analyst could type into it.
+ requestAnimationFrame(() => startTextEdit(s));
+ return;
+ }
+ // A symbol is stamped with one click. Unlike text the tool stays in hand
+ // afterwards, because marking six vehicles is one act, not six.
+ if (tool === 'icon') {
+ const entry = iconByName(iconName);
+ if (!entry) return;
+ const s = {
+ id: newId('s'), panel: panel.id, kind: 'icon', name: entry.name, color,
+ x: hit.nx, y: hit.ny, size: iconSizeFor(hit.box.baseScale),
+ ...(isSolidIcon(entry.name) ? {} : { strokeWidth: strokeW }),
+ ...(fillOpacity > 0 ? { fillOpacity } : {}),
+ };
+ proof.shapes.push(s);
+ selectedIds = [s.id];
+ dirty = true;
return;
}
// curve: each click drops a vertex; double-click / Enter finishes
if (tool === 'curve') {
- if (pathDraft && pathDraft.panel.id !== panel.id) return;
+ // A vertex dropped on another surface ends the curve where it was and
+ // opens the next one there. Ignoring the click made the canvas look dead
+ // whenever a curve strayed a few pixels past its panel.
+ if (pathDraft && pathDraft.panel.id !== panel.id) finishPath(true);
if (!pathDraft) {
const node = new Konva.Line({
points: [hit.nx, hit.ny], tension: 0.5, stroke: color,
@@ -1207,11 +1500,16 @@
return;
}
const common = { stroke: color, strokeWidth: sw, listening: false };
+ // the draft is drawn with the fill it will be committed with, so the analyst
+ // sees what the box hides while dragging it, not after
+ const paint = canFill(tool) ? fillPaint(color, fillOpacity) : null;
let node;
if (tool === 'rect') {
- node = new Konva.Rect({ x: hit.nx, y: hit.ny, width: 1, height: 1, cornerRadius: 2, ...common });
+ node = new Konva.Rect({
+ x: hit.nx, y: hit.ny, width: 1, height: 1, cornerRadius: 2, fill: paint, ...common,
+ });
} else if (tool === 'ellipse') {
- node = new Konva.Ellipse({ x: hit.nx, y: hit.ny, radiusX: 1, radiusY: 1, ...common });
+ node = new Konva.Ellipse({ x: hit.nx, y: hit.ny, radiusX: 1, radiusY: 1, fill: paint, ...common });
} else {
node = new Konva.Arrow({
points: [hit.nx, hit.ny, hit.nx, hit.ny],
@@ -1226,6 +1524,21 @@
}
function onPointerMove() {
+ if (marquee) {
+ dragMoved = true;
+ const box = marqueeBox(marquee.start, docPoint());
+ if (!marquee.node) {
+ marquee.node = new Konva.Rect({
+ fill: 'rgba(232, 163, 61, 0.12)', stroke: '#e8a33d',
+ strokeWidth: 1 / stage.scaleX(), dash: [4 / stage.scaleX(), 3 / stage.scaleX()],
+ listening: false,
+ });
+ uiLayer.add(marquee.node);
+ }
+ marquee.node.setAttrs(box);
+ uiLayer.batchDraw();
+ return;
+ }
if (panDrag) {
const p = stage.getPointerPosition();
stage.position({ x: panDrag.ox + p.x - panDrag.sx, y: panDrag.oy + p.y - panDrag.sy });
@@ -1269,15 +1582,37 @@
docLayer.batchDraw();
}
- function onPointerUp() {
- if (panDrag) {
- panDrag = null;
- return;
- }
- if (tool === 'select') {
- stage.draggable(false);
- return;
- }
+ /**
+ * Apply the rectangle dragged over the page, then take it down.
+ *
+ * The box is read off the node rather than recomputed from the pointer: the
+ * node holds what was drawn, which is what the analyst was looking at — and
+ * it is still the right answer when the release landed somewhere the canvas
+ * never heard about it.
+ */
+ function applyMarquee() {
+ if (!marquee) return;
+ const node = marquee.node;
+ const box = node
+ ? { x: node.x(), y: node.y(), width: node.width(), height: node.height() }
+ : null;
+ node?.destroy();
+ uiLayer.batchDraw();
+ const { add, base } = marquee;
+ marquee = null;
+ // A rectangle nobody dragged is a click on the page, which has already
+ // cleared the selection. Below a couple of pixels it is the same thing.
+ if (!box || (box.width <= 2 && box.height <= 2)) return;
+ // The press that opened this rectangle may have been on a panel, and Konva
+ // still calls that a click. Say the rectangle happened, so the panel
+ // underneath does not take the selection back.
+ marqueeEnded = true;
+ const caught = shapesTouching(box);
+ selectedIds = add ? [...new Set([...base, ...caught])] : caught;
+ }
+
+ /** Fold the draft in hand into an annotation, or drop it for being too small. */
+ function commitDrawing() {
if (!drawing) return;
const { node, kind, panel } = drawing;
const box = drawing.box;
@@ -1303,14 +1638,58 @@
if (shape) {
const s = {
id: newId('s'), panel: panel.id, color,
- strokeWidth: strokeW, ...shape,
+ strokeWidth: strokeW,
+ // only the kinds that can hold one carry the field, and only once asked
+ ...(canFill(kind) && fillOpacity > 0 ? { fillOpacity } : {}),
+ ...shape,
};
proof.shapes.push(s);
- selectedId = s.id;
+ selectedIds = [s.id];
dirty = true;
}
}
+ function onPointerUp() {
+ if (marquee) {
+ applyMarquee();
+ return;
+ }
+ // The window hears the release first and has ended a pan already (see
+ // settlePointer). This stands for the release it does not hear.
+ if (panDrag) {
+ endPan();
+ return;
+ }
+ if (tool === 'select') {
+ stage.draggable(false);
+ // A tool can change under an unreleased pointer, so Select may be holding
+ // someone else's draft. Settle it below rather than returning on it.
+ if (!drawing) return;
+ }
+ commitDrawing();
+ }
+
+ /**
+ * End a gesture the composer runs itself whose release it never heard.
+ *
+ * Konva listens for pointerup on its container and nowhere else, so letting go
+ * over the side column — a hand's width from the canvas edge, and where the
+ * pointer lands whenever a stroke is drawn near the right of a panel — never
+ * reached the handlers above. What was left kept following a bare pointer: a
+ * draft that stretched with no button held, a marquee nothing destroyed and no
+ * selection to show for it. The release happened, so it lands here exactly as
+ * it would have there — which is what `closeStrandedGesture` already does for
+ * the gestures Konva owns. (The pan is ended earlier, in `settlePointer`.)
+ *
+ * Runs a frame after the window heard the release, so a gesture that ended on
+ * the canvas has already settled itself and there is nothing here to find.
+ */
+ function settleStrandedGesture() {
+ if (!stage) return;
+ if (marquee) applyMarquee();
+ if (drawing) commitDrawing();
+ }
+
function finishPath(commit) {
if (!pathDraft) return;
const { node, points, panel } = pathDraft;
@@ -1324,8 +1703,10 @@
strokeWidth: strokeW, points: pts, tension: 0.5,
};
proof.shapes.push(s);
- selectedId = s.id;
- tool = 'select';
+ selectedIds = [s.id];
+ // The tool stays in hand, like the box, the line and the arrow it belongs
+ // beside: three curves in a row is one act, and reaching for `c` between
+ // each of them was the only place a shape tool put the pen down.
dirty = true;
} else {
proof.shapes = [...proof.shapes]; // force rebuild to drop the preview
@@ -1473,18 +1854,25 @@
fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
}));
});
- if (proof.panels.length && proof.footerEnabled !== false) {
+ const printed = proof.footerEnabled !== false ? footerLines(proof, prefs.coordFormat) : [];
+ if (proof.panels.length && printed.length) {
const footerSize = proof.footerSize ?? 13;
- const footerText = proof.footer?.trim() || attributionLine(proof.panels);
- docLayer.add(new Konva.Text({
- x: pad,
- y: height - pad - footerBand(footerSize) + Math.round((footerBand(footerSize) - footerSize) / 2),
- width: width - pad * 2,
- text: footerText,
- align: proof.footerAlign === 'right' ? 'right' : 'left',
- fontSize: footerSize, fill: proof.footerColor || tc.faint,
- fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
- }));
+ // The coordinates the proof prints sit above its credit line, each on the
+ // line `footerLines` measured them at — one source for the height and for
+ // the drawing, or a proof that grew a line would overflow its own picture.
+ const lines = printed;
+ const band = footerBand(footerSize);
+ lines.forEach((line, i) => {
+ docLayer.add(new Konva.Text({
+ x: pad,
+ y: height - pad - band * (lines.length - i) + Math.round((band - footerSize) / 2),
+ width: width - pad * 2,
+ text: line,
+ align: proof.footerAlign === 'right' ? 'right' : 'left',
+ fontSize: footerSize, fill: proof.footerColor || tc.faint,
+ fontFamily: 'system-ui, sans-serif', ellipsis: true, wrap: 'none', listening: false,
+ }));
+ });
}
// Pasted images, over the panels and the legend: pixels laid on top of the
@@ -1628,8 +2016,11 @@
// A whole panel can be selected instead (both modes): corner anchors only
// (aspect locked, elements scale along), never rotated. In grid mode the
// resize keeps only the scale — the grid re-flows the position.
- const selectedNode = selectedId ? docLayer.findOne(`#${selectedId}`) : null;
- const panelNode = !selectedNode && selectedPanelId
+ const selectedNodes = selectedIds
+ .map((id) => docLayer.findOne(`#${id}`))
+ .filter(Boolean);
+ const selectedNode = selectedNodes.length === 1 ? selectedNodes[0] : null;
+ const panelNode = !selectedNodes.length && selectedPanelId
? docLayer.findOne(`#pg-${selectedPanelId}`)
: null;
// Panels are scale-clamped *during* the gesture: letting the transform run
@@ -1639,10 +2030,10 @@
// the logo or the @handle, picked for a corner-resize (aspect locked).
// a pasted image resizes from its corners with its aspect locked, within the
// same kind of scale bounds a panel has
- const pasteNode = !selectedNode && !panelNode && selectedPasteId
+ const pasteNode = !selectedNodes.length && !panelNode && selectedPasteId
? docLayer.findOne(`#pg-${selectedPasteId}`)
: null;
- const sigNode = !selectedNode && !panelNode && !pasteNode && selectedSig
+ const sigNode = !selectedNodes.length && !panelNode && !pasteNode && selectedSig
? docLayer.findOne(selectedSig === 'logo' ? '#sig-logo' : '#sig-text')
: null;
const boundPanel = panelNode ? proof.panels.find((p) => p.id === selectedPanelId) : null;
@@ -1657,24 +2048,47 @@
(newBox.width / stage.scaleX()) * (boundPanel.natural[1] / (boundPanel.natural[0] * PANEL_H));
return impliedScale < PANEL_SCALE_MIN || impliedScale > PANEL_SCALE_MAX ? oldBox : newBox;
});
- transformer.keepRatio(!!sigNode || !!pasteNode);
+ // Handles belong to Select. A drawing tool ignores what is selected, so
+ // showing anchors it will not answer would be a promise the canvas breaks;
+ // the selection itself is kept, and comes back with the hand.
+ const handles = tool === 'select';
+ // Several annotations at once get the border and nothing else: dragging any
+ // one of them drags the rest (Konva moves every node the transformer holds),
+ // while resizing and rotating a family stays out of this first pass.
transformer.nodes(
- selectedNode
- ? [selectedNode]
- : panelNode ? [panelNode] : pasteNode ? [pasteNode] : sigNode ? [sigNode] : []
+ !handles
+ ? []
+ : selectedNodes.length
+ ? selectedNodes
+ : panelNode ? [panelNode] : pasteNode ? [pasteNode] : sigNode ? [sigNode] : []
);
const selKind = selectedShape?.kind;
- transformer.rotateEnabled(selKind === 'text' || selKind === 'rect' || selKind === 'ellipse');
+ transformer.keepRatio(!!sigNode || !!pasteNode || selKind === 'icon');
+ transformer.rotateEnabled(
+ selKind === 'text' || selKind === 'rect' || selKind === 'ellipse' || selKind === 'icon'
+ || selKind === 'freehand'
+ );
+ // 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
+ // is the one kind with neither vertex handles (too many points to show) nor
+ // a shape to speak of, so it takes the full set: without them a selected
+ // 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 === 'rect' || selKind === 'ellipse' || selKind === 'freehand'
? ['top-left', 'top-right', 'bottom-left', 'bottom-right', 'middle-left', 'middle-right', 'top-center', 'bottom-center']
- : selKind === 'text' || panelNode || pasteNode || sigNode
+ : selKind === 'text' || selKind === 'icon' || panelNode || pasteNode || sigNode
? ['top-left', 'top-right', 'bottom-left', 'bottom-right']
: []
);
- drawEndHandles(surfacesOf());
- drawPanelMoveControls(boxes);
- drawGuide(width, height);
+ if (handles) {
+ drawEndHandles(surfacesOf());
+ drawPanelMoveControls(boxes);
+ } else {
+ endHandles.destroyChildren();
+ panelCtrls.destroyChildren();
+ }
+ drawGuide(width, height); // the tweet crop is a view, not a handle: it stays
uiLayer.batchDraw();
}
@@ -1819,7 +2233,7 @@
let anchor;
if (s.kind === 'rect') {
anchor = { x: node.x() + (s.w ?? 0) / 2, y: node.y() + (s.h ?? 0) / 2 };
- } else if (s.kind === 'ellipse' || s.kind === 'text') {
+ } else if (s.kind === 'ellipse' || s.kind === 'text' || s.kind === 'icon') {
anchor = { x: node.x(), y: node.y() };
} else {
const pts = s.points.map((v, i) => v + (i % 2 === 0 ? node.x() : node.y()));
@@ -1853,7 +2267,7 @@
const boxed = s.frame || s.bg;
let node; // the draggable/transformable/selectable node (group when boxed)
if (boxed) {
- const pad = Math.round((s.fontSize ?? 28) * 0.28);
+ const pad = textBoxPad(s.fontSize);
const w = textNode.width() + pad * 2;
const h = textNode.height() + pad * 2;
const frameSW = Math.max(2, Math.round((s.fontSize ?? 28) * 0.07));
@@ -1880,20 +2294,15 @@
textNode.draggable(true);
node = textNode;
}
- node.on('pointerdown', (e) => {
- if (tool === 'select') {
- e.cancelBubble = true;
- selectedId = s.id;
- selectedPanelId = null;
- selectedPasteId = null;
- selectedSig = null;
- }
- });
+ bindShapePick(node, s);
node.on('dblclick dbltap', (e) => {
e.cancelBubble = true;
- startTextEdit(s, textNode);
+ startTextEdit(s);
+ });
+ node.on('dragstart', () => {
+ dragMoved = true;
+ node.getParent()?.moveToTop();
});
- node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
const { fromBox, toBox } = rebindOnDrop(s, node);
const p = toBox ? remapPanelXY(node.x(), node.y(), fromBox, toBox) : { x: node.x(), y: node.y() };
@@ -1912,16 +2321,22 @@
});
return node;
}
+ if (s.kind === 'icon') return makeIconNode(s, panelScale);
const sw = (s.strokeWidth ?? 4) / panelScale;
const common = {
id: s.id, stroke: s.color, strokeWidth: sw, rotation: s.rotation ?? 0,
draggable: true, hitStrokeWidth: Math.max(sw * 3, 14 / panelScale),
};
+ const paint = canFill(s.kind) ? fillPaint(s.color, s.fillOpacity) : null;
let node;
if (s.kind === 'rect') {
- node = new Konva.Rect({ x: s.x, y: s.y, width: s.w, height: s.h, cornerRadius: 2, ...common });
+ node = new Konva.Rect({
+ x: s.x, y: s.y, width: s.w, height: s.h, cornerRadius: 2, fill: paint, ...common,
+ });
} else if (s.kind === 'ellipse') {
- node = new Konva.Ellipse({ x: s.x, y: s.y, radiusX: s.w / 2, radiusY: s.h / 2, ...common });
+ node = new Konva.Ellipse({
+ x: s.x, y: s.y, radiusX: s.w / 2, radiusY: s.h / 2, fill: paint, ...common,
+ });
} else if (s.kind === 'curve' || s.kind === 'freehand') {
node = new Konva.Line({
points: s.points, tension: s.tension ?? (s.kind === 'freehand' ? 0.25 : 0.5),
@@ -1936,16 +2351,11 @@
...common,
});
}
- node.on('pointerdown', (e) => {
- if (tool === 'select') {
- e.cancelBubble = true;
- selectedId = s.id;
- selectedPanelId = null;
- selectedPasteId = null;
- selectedSig = null;
- }
+ bindShapePick(node, s);
+ node.on('dragstart', () => {
+ dragMoved = true;
+ node.getParent()?.moveToTop();
});
- node.on('dragstart', () => node.getParent()?.moveToTop());
node.on('dragend', () => {
if (s.kind === 'rect' || s.kind === 'ellipse') {
const { fromBox, toBox } = rebindOnDrop(s, node);
@@ -1977,6 +2387,13 @@
s.x = node.x(); s.y = node.y();
s.w = Math.abs(node.radiusX() * 2 * node.scaleX());
s.h = Math.abs(node.radiusY() * 2 * node.scaleY());
+ } else if (s.kind === 'freehand') {
+ // The whole transform goes into the samples — the scale, the turn and
+ // the move the anchors implied — and the node goes back to identity.
+ // A stroke has no origin to keep a rotation against.
+ s.points = pointsWithTransform(s.points, node.getTransform().getMatrix());
+ node.position({ x: 0, y: 0 });
+ node.rotation(0);
}
s.rotation = node.rotation();
node.scale({ x: 1, y: 1 });
@@ -1985,17 +2402,102 @@
return node;
}
- // ---- inline text editing (double-click a label on the canvas) ---------------
- function startTextEdit(s, node) {
- const panelScale = surfacesOf().find((x) => x.id === s.panel)?.box.scale ?? 1;
- const abs = node.getAbsolutePosition(); // container px, stage transform included
- selectedId = s.id;
+ /**
+ * A stamped symbol.
+ *
+ * The glyph is drawn in its own 24-unit box and scaled to `size`, so one
+ * number governs it and stretching is not expressible. The group sits on the
+ * 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.
+ */
+ function makeIconNode(s, panelScale) {
+ const entry = iconByName(s.name);
+ const size = s.size ?? iconSizeFor(panelScale);
+ const origin = iconOrigin(s.name, size);
+ const group = new Konva.Group({
+ id: s.id, x: s.x, y: s.y, rotation: s.rotation ?? 0, draggable: true,
+ });
+ // A stroked glyph is mostly holes, so a press has to land on the box rather
+ // than on a 2px line. Invisible to the eye, not to the hit canvas.
+ group.add(new Konva.Rect({
+ x: origin.x, y: origin.y, width: size, height: size, fill: '#000', opacity: 0,
+ }));
+ const disc = s.fillOpacity ?? 0;
+ if (disc > 0) {
+ group.add(new Konva.Circle({
+ x: origin.x + size / 2, y: origin.y + size / 2, radius: size / 2,
+ fill: fillPaint(s.color, disc),
+ // The ring stays at full opacity so a sheer disc keeps an edge; without
+ // it a badge at 30% has no silhouette left to read against the imagery.
+ stroke: s.color, strokeWidth: Math.max(size * 0.035, 0.5), listening: false,
+ }));
+ }
+ if (entry) {
+ const k = size / ICON_BOX;
+ const ink = glyphInk(s.color, disc);
+ group.add(new Konva.Path({
+ data: entry.path, x: origin.x, y: origin.y, scaleX: k, scaleY: k, listening: false,
+ ...(isSolidIcon(s.name)
+ ? { fill: ink, fillRule: 'evenodd' }
+ : {
+ stroke: ink,
+ // the glyph is drawn scaled, so the width is divided back out:
+ // a bigger symbol is a bigger drawing, not a fatter outline
+ strokeWidth: (s.strokeWidth ?? 4) / panelScale / k,
+ lineCap: 'round', lineJoin: 'round',
+ }),
+ }));
+ }
+ 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', () => {
+ // Uniform by construction: the transformer keeps the ratio and offers
+ // corners only, so either axis answers for the new side.
+ 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;
+ }
+
+ // ---- inline text editing (placed, or double-clicked on the canvas) ---------
+ /**
+ * Open the editor over a label.
+ *
+ * Positioned from the surface's layout box rather than from a Konva node: a
+ * label placed a moment ago has no node yet — the document rebuild is held
+ * back until the gesture settles — and the editor has to open on the click
+ * that placed it rather than a frame later. The box carries the same
+ * transform the node would have been read through.
+ */
+ function startTextEdit(s) {
+ const box = surfacesOf().find((x) => x.id === s.panel)?.box;
+ if (!box) return;
+ // A boxed label insets its glyph by the padding the frame uses, so the
+ // editor opens over the words instead of over the corner.
+ const inset = s.frame || s.bg ? textBoxPad(s.fontSize) : 0;
+ selectedIds = [s.id];
textEdit = {
id: s.id,
value: s.text ?? '',
- left: abs.x,
- top: abs.y,
- size: (s.fontSize ?? 28) * panelScale * stage.scaleX(),
+ left: stage.x() + (box.x + (s.x + inset) * box.scale) * stage.scaleX(),
+ top: stage.y() + (box.y + (s.y + inset) * box.scale) * stage.scaleY(),
+ size: (s.fontSize ?? 28) * box.scale * stage.scaleX(),
color: s.color,
};
}
@@ -2051,7 +2553,7 @@
if (!target) return;
const s = { ...offsetShape(clipboard, 26), id: newId('s'), panel: target };
proof.shapes.push(s);
- selectedId = s.id;
+ selectedIds = [s.id];
// cascade further pastes so repeated Ctrl+V steps down-right
clipboard = offsetShape(s, 0);
dirty = true;
@@ -2062,11 +2564,22 @@
pasteShape();
}
+ /** Delete every picked annotation, and drop the legend notes left with nothing. */
+ function deleteSelected() {
+ const going = new Set(selectedIds);
+ const gone = proof.shapes.filter((s) => going.has(s.id));
+ if (!gone.length) return;
+ proof.shapes = proof.shapes.filter((s) => !going.has(s.id));
+ for (const s of gone) proof.notes = notesAfterRemoval(proof.notes, proof.shapes, s);
+ selectedIds = [];
+ dirty = true;
+ }
+
function deleteShape(id) {
const gone = proof.shapes.find((s) => s.id === id);
proof.shapes = proof.shapes.filter((s) => s.id !== id);
proof.notes = notesAfterRemoval(proof.notes, proof.shapes, gone);
- if (selectedId === id) selectedId = null;
+ selectedIds = selectedIds.filter((x) => x !== id);
dirty = true;
}
@@ -2083,21 +2596,26 @@
const canMoveShapeUp = (i) => hasGroupNeighbor(proof.shapes, i, -1, (s) => s.panel);
const canMoveShapeDown = (i) => hasGroupNeighbor(proof.shapes, i, 1, (s) => s.panel);
- const KIND_ICON = { rect: 'square', ellipse: 'circle', arrow: 'arrow', line: 'line', curve: 'curve', freehand: 'freehand', text: 'text' };
- const KIND_LABEL = { rect: 'Box', ellipse: 'Ellipse', arrow: 'Arrow', line: 'Line', curve: 'Curve', freehand: 'Freehand', text: 'Text' };
+ 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' };
- // Color / stroke controls live-edit the selected shape when there is one, and
- // always remember the pick as the default for the next drawn shape — the last
- // colour/width you touched stays your working colour, whether or not something
- // was selected at the time.
+ // 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
+ // stays your working value. "In hand" means Select: with a drawing tool the
+ // 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 (selectedShape) {
- const oldColor = selectedShape.color;
- selectedShape.color = c;
- // carry the legend note over if this color is otherwise unused
- if (canReassignLegendNote(proof.notes, oldColor, c, proof.shapes, selectedShape)) {
- proof.notes[c] = proof.notes[oldColor];
- delete proof.notes[oldColor];
+ if (editableShapes.length) {
+ const before = [...new Set(editableShapes.map((s) => s.color))];
+ for (const s of editableShapes) 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) {
+ if (old === c) continue;
+ if (canReassignLegendNote(proof.notes, old, c, proof.shapes, null)) {
+ proof.notes[c] = proof.notes[old];
+ delete proof.notes[old];
+ }
}
dirty = true;
}
@@ -2107,26 +2625,38 @@
function setStroke(w) {
// Font size is a text-only property, so editing it must not overwrite the
// stroke-width default used for the next drawn shape.
- if (selectedShape?.kind === 'text') {
- selectedShape.fontSize = w;
+ if (editableShape?.kind === 'text') {
+ editableShape.fontSize = w;
dirty = true;
return;
}
- if (selectedShape) {
- selectedShape.strokeWidth = w;
+ for (const s of editableShapes) {
+ if (s.kind === 'text') continue; // a font size is not a stroke width
+ if (s.kind === 'icon' && isSolidIcon(s.name)) continue; // a silhouette has no outline
+ s.strokeWidth = w;
dirty = true;
}
strokeW = w;
}
+ /** Fill opacity, 0 (none) to 1. Only the closed kinds take one. */
+ function setFill(value) {
+ const opacity = Math.min(1, Math.max(0, value));
+ for (const s of editableShapes) {
+ if (!canFill(s.kind)) continue;
+ s.fillOpacity = opacity;
+ dirty = true;
+ }
+ fillOpacity = opacity;
+ }
+
// Arrow-key nudge of the selected element, in panel-natural pixels.
const NUDGE = {
ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1],
};
function nudgeSelected(dx, dy) {
- const s = selectedShape;
- if (!s) return;
- Object.assign(s, nudgeShape(s, dx, dy));
+ if (!editableShapes.length) return;
+ for (const s of editableShapes) Object.assign(s, nudgeShape(s, dx, dy));
dirty = true;
}
@@ -2136,16 +2666,31 @@
exportMenuOpen = false;
return;
}
+ // A dialog takes the keyboard with it. A one-letter tool key must not change
+ // the tool on the canvas behind it, and its Escape closes the dialog — that
+ // is not also a reason to put the pen down underneath.
+ if (modalOpen) return;
if (['INPUT', 'TEXTAREA', 'SELECT'].includes(e.target.tagName)) return;
if (pathDraft && (e.key === 'Enter' || e.key === 'Escape')) {
finishPath(e.key === 'Enter');
return;
}
+ // Escape mid-drag abandons the shape being drawn, and the tool stays in
+ // hand: cancelling a stroke is no reason to put the pen down. Without this
+ // the draft outlives the keypress and the pointer keeps stretching a shape
+ // that nothing can drop.
+ if (e.key === 'Escape' && drawing) {
+ drawing = discardDraft(drawing);
+ docLayer.batchDraw();
+ return;
+ }
// clipboard / undo / save chords
if (e.ctrlKey || e.metaKey) {
const k = e.key.toLowerCase();
// Ctrl+V is deliberately absent: the paste event decides between an image
// in the system clipboard and a copied annotation (see onPaste).
+ // Copying and duplicating stay open to a drawing tool: they read the last
+ // element rather than changing it, and what they add lands in plain sight.
if (k === 'c' && selectedId) { e.preventDefault(); copyShape(); }
else if (k === 'd' && selectedId) { e.preventDefault(); duplicateShape(); }
else if (k === 'z') { e.preventDefault(); e.shiftKey ? redo() : undo(); }
@@ -2153,7 +2698,7 @@
else if (k === 's') { e.preventDefault(); save(); }
return; // don't fall through to the single-letter tool shortcuts
}
- if (NUDGE[e.key] && selectedId) {
+ if (NUDGE[e.key] && editableShapes.length) {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
nudgeSelected(NUDGE[e.key][0] * step, NUDGE[e.key][1] * step);
@@ -2163,23 +2708,35 @@
// hold space to pan, whatever the active tool — even over an element
e.preventDefault();
spacePan = true;
- docLayer.listening(false);
+ syncCanvasListening();
containerEl.style.cursor = 'grab';
return;
}
- if ((e.key === 'Delete' || e.key === 'Backspace') && selectedId) {
- deleteShape(selectedId);
- } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedPanelId) {
+ // Deleting is a Select act like the others: with a drawing tool in hand the
+ // selection is out of reach, and a key must not erase what is not shown.
+ const erase = (e.key === 'Delete' || e.key === 'Backspace') && tool === 'select';
+ if (erase && editableShapes.length) {
+ deleteSelected();
+ } else if (erase && selectedPanelId) {
const idx = proof.panels.findIndex((p) => p.id === selectedPanelId);
if (idx >= 0) removePanel(idx);
- } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedPasteId) {
+ } else if (erase && selectedPasteId) {
removePaste(proof.pastes.findIndex((p) => p.id === selectedPasteId));
} else if (e.key === 'Escape') {
- selectedId = null;
- selectedPanelId = null;
- selectedPasteId = null;
- selectedSig = null;
- tool = 'select';
+ // Escape unwinds one level per press: the draft in hand first (above),
+ // then what is picked, and only with nothing left to drop does it put the
+ // pen down. One key, one meaning: drop the most local thing still
+ // standing. Before this it kept the pen while cancelling a stroke and laid
+ // it down when there was no stroke to cancel, so which of the two opposite
+ // things it meant turned on being three pixels from where a drag started.
+ if (visiblePick) {
+ selectedIds = [];
+ selectedPanelId = null;
+ selectedPasteId = null;
+ selectedSig = null;
+ } else {
+ tool = 'select';
+ }
} else if (e.key === 'v') tool = 'select';
else if (e.key === 'r') tool = 'rect';
else if (e.key === 'e') tool = 'ellipse';
@@ -2188,6 +2745,7 @@
else if (e.key === 'c') tool = 'curve';
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 === 'f') fit();
}
@@ -2195,7 +2753,7 @@
if (e.key === ' ' && spacePan) {
spacePan = false;
panDrag = null;
- docLayer?.listening(true);
+ syncCanvasListening();
if (containerEl) containerEl.style.cursor = '';
}
}
@@ -2339,19 +2897,19 @@
let orphanOffer = $state(null);
let orphanDeleting = $state(false);
- /** Say yes to the point: it is filed exactly as the automatic path files it. */
+ /** Say yes to the points: they are filed exactly as the automatic path files
+ * them, and from the spec rather than from what this tab still holds. */
async function acceptPlaceOffer() {
if (!placeOffer || placeSaving) return;
placeSaving = true;
const offer = placeOffer;
try {
- const place = await api.post(
+ const filed = await api.post(
`/api/cases/${caseState.current.id}/proofs/${encodeURIComponent(offer.name)}/place`,
- { lat: offer.lat, lon: offer.lon }
);
placeOffer = null;
await reloadCase();
- toast(`Saved the point as a place: ${place.label}`, 'ok', 2600);
+ toast(placedLabel(filed), 'ok', 2600);
} catch (e) {
toast(`Could not save the point: ${e.message}`, 'danger', 6000);
} finally {
@@ -2359,6 +2917,26 @@
}
}
+ /** The points the question is about, one per line, named when the analyst
+ * named them — the map is where they will be read, so it names coordinates
+ * rather than the file. */
+ function offeredPoints(points) {
+ return points
+ .map((one) => {
+ const where = formatCoords({ lat: one.lat, lon: one.lon }, prefs.coordFormat);
+ return one.label ? `${one.label} — ${where}` : where;
+ })
+ .join('\n') + '\n\nnot saved in this case yet.';
+ }
+
+ /** What a save says about the places it wrote. One is named; several are counted,
+ * because a toast listing five labels is a paragraph nobody reads. */
+ function placedLabel(filed) {
+ const places = filed ?? [];
+ if (places.length === 1) return `Saved the point as a place: ${places[0].label}`;
+ return `Saved ${places.length} points as places`;
+ }
+
/** Say yes to dropping the point the proof moved off. Deleted like any entity,
* so it lands in the trash and comes back from there. */
async function deleteOrphanPlaces() {
@@ -2422,20 +3000,24 @@
savedName = result.name;
proof.title = result.title;
dirty = false;
+ savedSnapshot = docSnapshot();
await reloadCase();
toast(`Proof saved: ${result.png}`, 'ok');
- // The point this proof carries. Filed already, or a question — the server
- // answers with nothing at all when the case already holds that point, so
+ // The points this proof carries. Filed already, or a question — the server
+ // answers with nothing at all when the case already holds them, so
// re-saving never asks twice.
- if (result.place?.filed) toast(`Saved the point as a place: ${result.place.label}`, 'ok', 2600);
- else if (result.place) placeOffer = { name: result.name, ...result.place };
+ if (result.place?.filed?.length) toast(placedLabel(result.place.filed), 'ok', 2600);
+ if (result.place?.asking?.length) {
+ placeOffer = { name: result.name, points: result.place.asking };
+ }
// Corrected coordinates take the old point back. The place stays on the map
// until the analyst says otherwise, so it is a question, not a cleanup.
orphanOffer = result.orphans?.length ? result.orphans : null;
if (andPost) {
uiState.postProof = {
title: result.title,
- coordsText: displayedCoords,
+ // every point, one per line: the post cites the first and carries the rest
+ coordsText: coordsPostLines(proofCoordsLines(proof, prefs.coordFormat)).join('\n'),
source: displayedSource,
attribution: attributionLine(proof.panels),
png: result.png,
@@ -2518,8 +3100,16 @@
}
}
+ // Bumped by every open, so panels still streaming in for a proof the analyst
+ // has moved on from stop writing into the document that replaced it. The open
+ // list stays up while a proof loads, so clicking a second one is one gesture
+ // away — and the merged result overwrote the second proof on Save.
+ let openRun = 0;
+
async function openProof(entry) {
+ const run = ++openRun;
const spec = await api.get(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);
+ if (run !== openRun) return;
const style = normalizeProofStyle(spec);
resetDoc();
proofStarted = true;
@@ -2528,9 +3118,11 @@
// during the load has to write back over this proof, not file a new one.
savedName = entry.name;
proof.title = spec.title;
- proof.coordsText = spec.coordsText ?? '';
- proof.pov = spec.pov === true;
- proof.source = spec.source ?? '';
+ proof.points = editablePoints(spec);
+ proof.footerCoords = spec.footerCoords === true;
+ proof.footerText = spec.footerText !== false;
+ proof.sources = statedSources(spec.sources ?? spec.source ?? null);
+ proof.material = normalizeMaterial(spec.material);
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
proof.footerSize = style.footerSize;
@@ -2550,9 +3142,11 @@
for (const p of spec.panels) {
try {
const img = await loadImage(fileUrl(caseState.current.id, p.src));
+ if (run !== openRun) return;
imgCache.set(p.src, img);
proof.panels.push({ ...p, id: p.id ?? newId('p'), row: p.row ?? 0, img });
} catch {
+ if (run !== openRun) return;
toast(`Missing panel image: ${p.src}`, 'warn');
}
}
@@ -2563,9 +3157,11 @@
const img = await loadImage(
fileUrl(caseState.current.id, `proofs/${entry.name}.assets/${p.asset}`)
);
+ if (run !== openRun) return;
pasteAssets.set(p.asset, { img, data: null, pending: false });
proof.pastes.push({ ...p, id: p.id ?? newId('x'), img });
} catch {
+ if (run !== openRun) return;
toast('An overlay of this proof is missing', 'warn');
}
}
@@ -2583,15 +3179,105 @@
}
openList = null;
dirty = false;
+ savedSnapshot = docSnapshot();
anchorHistory();
requestAnimationFrame(fit);
}
- const selectedShape = $derived(proof.shapes.find((s) => s.id === selectedId));
- const activeColor = $derived(selectedShape?.color ?? color);
+ const selectedShapes = $derived(proof.shapes.filter((s) => selectedIds.includes(s.id)));
+ // The one annotation, when exactly one is picked. Everything keyed to a single
+ // kind reads this: the transformer's anchors, the endpoint handles, the size
+ // slider's range. A family of five has no kind of its own.
+ const selectedId = $derived(selectedIds.length === 1 ? selectedIds[0] : null);
+ const selectedShape = $derived(selectedShapes.length === 1 ? selectedShapes[0] : null);
+ // The selection as the controls and the keyboard see it: only Select edits
+ // what is already drawn. A drawing tool leaves the selection standing but out
+ // of reach, so nothing is silently recoloured, moved or deleted behind a
+ // gesture meant for the next element.
+ const editableShapes = $derived(tool === 'select' ? selectedShapes : []);
+ // Whether a pick is showing at all: the canvas handles and the lit rows in the
+ // side column answer to this together, so the two columns never disagree about
+ // what is selected.
+ const selectionLive = $derived(tool === 'select');
+ // What the analyst can see picked. A selection held for the hand's return is
+ // not something Escape has to clear before it can put the pen down.
+ const visiblePick = $derived(
+ selectionLive
+ && (selectedIds.length > 0 || !!selectedPanelId || !!selectedPasteId || !!selectedSig)
+ );
+ // Every dialog that can sit over the composer. A modal owns the keyboard while
+ // it is up, and this is what keeps the canvas shortcuts out from under it.
+ const modalOpen = $derived(
+ picker || newProofOpen || importOpen || openList !== null || discardConfirm
+ || replaceWithNewConfirm || exportPicker || overwritePrompt !== null
+ || placeOffer !== null || orphanOffer !== null || deleteEntry !== null
+ || sourcePick !== null
+ );
+ const editableShape = $derived(editableShapes.length === 1 ? editableShapes[0] : null);
+ const fillableSelection = $derived(editableShapes.some((s) => canFill(s.kind)));
+ // A solid symbol is a silhouette: there is no outline to widen, so the
+ // control stays away rather than sitting there doing nothing.
+ const solidIconOnly = $derived(
+ editableShapes.length
+ ? editableShapes.every((s) => s.kind === 'icon' && isSolidIcon(s.name))
+ : tool === 'icon' && isSolidIcon(iconName),
+ );
+ const activeColor = $derived(editableShape?.color ?? color);
+ const activeFill = $derived(
+ canFill(editableShape?.kind) ? (editableShape.fillOpacity ?? 0) : fillOpacity
+ );
const featureList = $derived(orderedFeatureColors(proof.shapes, proof.legendOrder));
// Swap a legend entry with its neighbour, persisting the whole resulting
+ // ---- the points the proof concludes on -----------------------------------
+ //
+ // One row per point, the first one the conclusion. A proof with a single point
+ // is the common case and looks exactly as it always did: one field, no cross,
+ // no arrow, nothing to move.
+
+ function blankPoint() {
+ return { coords: '', label: '', pov: false };
+ }
+
+ /** The spec's points as editable rows, always at least one. */
+ function editablePoints(spec) {
+ const stated = specPoints(spec).map((one) => ({ ...one }));
+ return stated.length ? stated : [blankPoint()];
+ }
+
+ /** Add a row. The first one is materialised from the panels first: an empty
+ * field means "whatever the imagery says", and that answer has to become the
+ * conclusion in writing before a second point can sit under it. */
+ function addPoint() {
+ if (proof.points.length >= MAX_POINTS) return;
+ if (!proof.points[0].coords.trim()) proof.points[0].coords = displayedCoords;
+ proof.points = [...proof.points, blankPoint()];
+ dirty = true;
+ }
+
+ function removePoint(i) {
+ proof.points = proof.points.filter((_, at) => at !== i);
+ if (!proof.points.length) proof.points = [blankPoint()];
+ dirty = true;
+ }
+
+ /** Move a row up. This is how the conclusion is chosen — POV never reorders
+ * anything, or checking it would take a coordinate out of a tweet in silence. */
+ function raisePoint(i) {
+ if (i <= 0) return;
+ const order = [...proof.points];
+ [order[i - 1], order[i]] = [order[i], order[i - 1]];
+ proof.points = order;
+ dirty = true;
+ }
+
+ /** A camera stood in one place, so lighting one point puts the others out. */
+ function togglePov(i) {
+ const on = !proof.points[i].pov;
+ proof.points = proof.points.map((one, at) => ({ ...one, pov: on && at === i }));
+ dirty = true;
+ }
+
// order — this also promotes any color that was only implicitly ordered
// (first-use) into an explicit, saved position.
function moveLegendColor(i, delta) {
@@ -2607,9 +3293,158 @@
// the value auto-derived from the panels (reactive — deleting the first
// satellite panel falls back to the next, adding media fills the source).
const displayedCoords = $derived(
- proof.coordsText.trim() || formatCoords(autoCoords(proof.panels), prefs.coordFormat)
+ proof.points[0]?.coords.trim() || formatCoords(autoCoords(proof.panels), prefs.coordFormat)
);
- const displayedSource = $derived(proof.source.trim() || autoSource(proof.panels));
+ const displayedSource = $derived(proofSource(proof));
+ const autoSources = $derived(autoSourceUrls(proof.panels));
+ /** What the Source boxes show: the analyst's own list once there is one — **empty
+ * included**, since emptying every box is them saying the proof has no public source
+ * — else the addresses traced from the panels, else one box to type the first into.
+ * There is always a box: a field with no box is a field nobody can use. */
+ const sourceRows = $derived.by(() => {
+ const rows = proof.sources ?? autoSources;
+ return rows.length ? rows : [''];
+ });
+
+ /** Editing a traced row is what turns the whole list into the proof's own: the traced
+ * ones come along, so stating a fourth address never means retyping three the panels
+ * already knew. */
+ function editSource(at, value) {
+ proof.sources = sourceRows.map((row, i) => (i === at ? value : row));
+ dirty = true;
+ }
+
+ function addSource() {
+ proof.sources = [...sourceRows, ''];
+ dirty = true;
+ }
+
+ //: One http(s) address and nothing else, which is what one box holds.
+ const ONE_ADDRESS = /^https?:\/\/\S+$/i;
+
+ /** An address the proof states that the case holds nothing from.
+ *
+ * Only the ones stated here: an address traced *off* a panel is, by construction,
+ * already in the case, so offering to fetch it would be offering to fetch a file
+ * sitting two rows above. */
+ function missingSource(url) {
+ const address = url.trim();
+ return (
+ proof.sources !== null && ONE_ADDRESS.test(address) && !heldAddresses.has(address)
+ );
+ }
+
+ /** Bring what a stated address holds into the case, and let the proof rest on it.
+ *
+ * A geolocation read from a thread rests on files the case has never seen — the clip
+ * under the photos, the second angle — and until now the only way in was to leave the
+ * composer, download them in Media and come back. What lands is filed as ordinary
+ * media and recorded as this proof's `material`, which is what puts it in the chain
+ * and, through the chain, on the point.
+ */
+ let sourceJob = $state(null); // { url, progress } while one address is being fetched
+ let sourcePick = $state(null); // { url, items } when the address holds several files
+
+ async function fetchSource(url, indexes = null) {
+ const c = caseState.current;
+ const address = url.trim();
+ if (!c || !address || sourceJob) return;
+ sourceJob = { url: address, progress: {} };
+ try {
+ // Everything it holds, one call each: the analyst named this address as material,
+ // so what hangs off it is material — the same answer the sheet road gives.
+ const landed = [];
+ for (const index of indexes ?? [null]) {
+ const path = await runSourceJob(c.id, address, index);
+ if (path === 'multi') return; // the picker took over; nothing downloaded yet
+ if (path) landed.push(path);
+ }
+ await refreshCaseMedia(c.id);
+ toast(
+ landed.length > 1
+ ? `${landed.length} files added to the case`
+ : 'Added to the case',
+ 'ok',
+ 1800,
+ );
+ } catch (e) {
+ toast(`${address} could not be downloaded: ${e.message}`, 'danger', 6000);
+ } finally {
+ sourceJob = null;
+ }
+ }
+
+ async function runSourceJob(caseId, url, index) {
+ const { job_id } = await api.post(`/api/cases/${caseId}/media/download`, {
+ url, index, title: null, use_cookies: false,
+ });
+ for (;;) {
+ const status = await api.get(`/api/jobs/${job_id}`);
+ sourceJob = { url, progress: status.progress ?? {} };
+ if (status.status === 'running') {
+ await new Promise((resolve) => setTimeout(resolve, 700));
+ continue;
+ }
+ if (status.status !== 'done') throw new Error(status.error || 'the download failed');
+ const result = status.result ?? {};
+ if (result.multi) {
+ // Ticked by default: the address was stated as material, so what it carries is.
+ // Except what the extractor cannot vouch for — past the first attachment it
+ // cannot say whether a clip is the post's own or the one it quotes.
+ sourcePick = {
+ url,
+ items: (result.items ?? []).map((one) => ({ ...one, picked: one.own !== false })),
+ };
+ return 'multi';
+ }
+ if (result.needs_auth) {
+ throw new Error('this link asks for a login. Download it from Media, then come back');
+ }
+ const path = result.item?.path ?? result.entity?.attrs?.path;
+ if (path) {
+ // Paired with the address that brought it, so taking that source off the proof
+ // takes this file out of its chain too.
+ proof.material = [
+ ...proof.material.filter((one) => one.path !== path),
+ { path, url },
+ ];
+ dirty = true;
+ }
+ return path ?? null;
+ }
+ }
+
+ /** What a file landing in the case has to update.
+ *
+ * The composer's own two readings, and the app's: a media downloaded here is a case
+ * entity like any other, so Board, Graph and the catalog have to hear about it. They
+ * read the case handed round in state, and without this the file was on disk and
+ * invisible everywhere else until a reload.
+ */
+ async function refreshCaseMedia(caseId) {
+ caseMedia = await api.get(`/api/cases/${caseId}/media`).catch(() => caseMedia);
+ presentPaths = new Set([...caseMedia.map((one) => one.path), ...presentPaths]);
+ await reloadCase();
+ }
+
+ function takeSourcePick() {
+ const picked = sourcePick.items.filter((one) => one.picked).map((one) => one.index);
+ const { url } = sourcePick;
+ sourcePick = null;
+ if (picked.length) fetchSource(url, picked);
+ }
+
+ function dropSource(at) {
+ proof.sources = sourceRows.filter((_, i) => i !== at);
+ dirty = true;
+ }
+
+ /** Hand the list back to the panels. The only way back from an emptied one, which is
+ * why the arrow shows the moment the proof states anything of its own. */
+ function resetSources() {
+ proof.sources = null;
+ dirty = true;
+ }
</script>
<svelte:window onkeydown={onKeydown} onkeyup={onKeyup} onpaste={onPaste} />
@@ -2695,10 +3530,17 @@
bind:tool
palette={proof.palette}
{activeColor}
- {selectedShape}
+ {activeFill}
+ selectedShape={editableShape}
+ selectedCount={editableShapes.length}
+ {fillableSelection}
+ showStroke={!solidIconOnly}
+ {iconName}
+ setIconName={(name) => { iconName = name; tool = 'icon'; }}
{strokeW}
{setColor}
{setStroke}
+ {setFill}
{fit}
layout={proof.layout}
{setLayoutMode}
@@ -2790,30 +3632,63 @@
<Icon name="alert" size={13} />
</span>
{/if}
- {#if proof.coordsText.trim()}
- <button class="meta-reset" title="Reset to the coordinates from the imagery" onclick={() => { proof.coordsText = ''; dirty = true; }}>
+ {#if proof.points.some((one) => one.coords.trim())}
+ <button class="meta-reset" title="Reset to the coordinates from the imagery" onclick={() => { proof.points = [blankPoint()]; dirty = true; }}>
<Icon name="reset" size={12} />
</button>
{/if}
+ {#if proof.points.length < MAX_POINTS}
+ <button
+ class="meta-add"
+ class:alone={!proof.points.some((one) => one.coords.trim())}
+ title="Add a point"
+ onclick={addPoint}
+ >
+ <Icon name="plus" size={12} />
+ </button>
+ {/if}
</div>
- <input
- class="input meta-input"
- class:warn={!displayedCoords}
- placeholder="lat, lon"
- value={displayedCoords}
- oninput={(e) => { proof.coordsText = e.target.value; dirty = true; }}
- />
- <!-- 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. -->
- <label class="meta-check" title="The point is where the camera stood, not what it filmed">
- <input
- type="checkbox"
- checked={proof.pov}
- onchange={(e) => { proof.pov = e.currentTarget.checked; dirty = true; }}
- />
- <span>POV</span>
- </label>
+ <!-- One row per point the proof concludes on, the first one the
+ 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; }}
+ />
+ <input
+ class="input point-label"
+ placeholder="label"
+ value={point.label}
+ oninput={(e) => { proof.points[i].label = e.target.value; dirty = true; }}
+ />
+ <!-- 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>
+ {#if i > 0}
+ <button class="point-move" title="Make this the proof's conclusion" onclick={() => raisePoint(i)}>
+ <Icon name="chevronUp" size={13} />
+ </button>
+ <button class="point-drop" title="Remove this point" onclick={() => removePoint(i)}>
+ <Icon name="x" size={13} />
+ </button>
+ {/if}
+ </div>
+ {/each}
+ {#if proof.points.length > 1}
+ <div class="point-hint">Order decides the conclusion.</div>
+ {/if}
</div>
<div class="meta-field">
<div class="meta-head">
@@ -2824,28 +3699,65 @@
<Icon name="alert" size={13} />
</span>
{/if}
- {#if proof.source.trim()}
- <button class="meta-reset" title="Reset to the source traced from the media" onclick={() => { proof.source = ''; dirty = true; }}>
+ {#if proof.sources !== null}
+ <button class="meta-reset" title="Reset to the sources traced from the media" onclick={resetSources}>
<Icon name="reset" size={12} />
</button>
{/if}
+ <button
+ class="meta-add"
+ class:alone={proof.sources === null}
+ title="Add a source"
+ onclick={addSource}
+ >
+ <Icon name="plus" size={12} />
+ </button>
</div>
- <input
- class="input meta-input"
- class:warn={!displayedSource}
- placeholder="https://…"
- value={displayedSource}
- oninput={(e) => { proof.source = e.target.value; dirty = true; }}
- />
+ <!-- One row per address. A proof read from a thread rests on the post that
+ published it, the photos beside it and the clip under those, and each of
+ 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)}
+ />
+ {#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
+ that holds it. -->
+ <button
+ class="meta-fetch"
+ title="The case has nothing from this address. Download it"
+ disabled={!!sourceJob}
+ onclick={() => fetchSource(row)}
+ >
+ <Icon name={sourceJob?.url === row.trim() ? 'clock' : 'download'} size={12} />
+ </button>
+ {/if}
+ {#if sourceRows.length > 1}
+ <button class="meta-drop" title="Remove this source" onclick={() => dropSource(at)}>
+ <Icon name="x" size={12} />
+ </button>
+ {/if}
+ </div>
+ {/each}
</div>
<ProofLayersPanel
{proof}
{collapsed}
{gonePanels}
- bind:selectedPanelId
- bind:selectedPasteId
- bind:selectedId
+ {selectedPanelId}
+ {selectedPasteId}
+ {selectedIds}
+ {selectionLive}
+ selectShape={pickShapeRow}
+ selectPanelRow={pickPanelRow}
+ selectPasteRow={pickPasteRow}
{activeColor}
caseId={caseState.current?.id}
scaleMin={PANEL_SCALE_MIN}
@@ -2923,15 +3835,35 @@
bind:value={proof.footerSize} oninput={() => (dirty = true)} />
<span class="size-val">{proof.footerSize}</span>
</div>
- <label class="adv-label" for="footer-text">Footer text</label>
- <textarea
- id="footer-text"
- class="input footer-input"
- rows="2"
- placeholder={attributionLine(proof.panels)}
- bind:value={proof.footer}
- oninput={() => (dirty = true)}
- ></textarea>
+ <!-- The footer lines that change the picture's height, so they
+ wait to be asked for. -->
+ <label class="sig-check">
+ <input
+ type="checkbox"
+ checked={proof.footerCoords === true}
+ onchange={(e) => { proof.footerCoords = e.currentTarget.checked; dirty = true; }}
+ />
+ <span>Show coordinates</span>
+ </label>
+ <label class="sig-check">
+ <input
+ type="checkbox"
+ checked={proof.footerText !== false}
+ onchange={(e) => { proof.footerText = e.currentTarget.checked; dirty = true; }}
+ />
+ <span>Show text</span>
+ </label>
+ {#if proof.footerText !== false}
+ <label class="adv-label" for="footer-text">Footer text</label>
+ <textarea
+ id="footer-text"
+ class="input footer-input"
+ rows="2"
+ placeholder={attributionLine(proof.panels)}
+ bind:value={proof.footer}
+ oninput={() => (dirty = true)}
+ ></textarea>
+ {/if}
<div class="size-row">
<span>Footer alignment</span>
<select class="input" bind:value={proof.footerAlign}
@@ -3044,10 +3976,22 @@
caseId={caseState.current?.id}
togglePanel={toggleNewProofPanel}
requestCreation={requestNewProofCreation}
+ startImport={() => { newProofOpen = false; importOpen = true; }}
close={() => (newProofOpen = false)}
/>
{/if}
+{#if importOpen && caseState.current}
+ <ImportProofDialog
+ caseId={caseState.current.id}
+ onclose={() => (importOpen = false)}
+ oncreated={async (created) => {
+ await reloadCase();
+ openProof({ name: created.proof.name });
+ }}
+ />
+{/if}
+
{#if replaceWithNewConfirm}
<ConfirmDialog
title="Create a new proof?"
@@ -3108,12 +4052,12 @@
read, so the question names the coordinates rather than the file. -->
{#if placeOffer}
<ConfirmDialog
- title="Save this point as a place?"
- message={`${formatCoords({ lat: placeOffer.lat, lon: placeOffer.lon }, prefs.coordFormat)} is not saved in this case yet.`}
- detail={placeOffer.pov
- ? 'It joins the map, and the footage this proof composes will say it was recorded there.'
- : 'It joins the map, and this proof and the files it composes will say they show it.'}
- confirmLabel="Save the point"
+ title={placeOffer.points.length === 1 ? 'Save this point as a place?' : 'Save these points as places?'}
+ message={offeredPoints(placeOffer.points)}
+ detail={placeOffer.points.some((one) => one.pov)
+ ? 'They join the map, and the footage this proof composes will say it was recorded at the marked one.'
+ : 'They join the map, and this proof and the files it composes will say they show them.'}
+ confirmLabel={placeOffer.points.length === 1 ? 'Save the point' : 'Save the points'}
tone="default"
icon="pin"
busy={placeSaving}
@@ -3216,6 +4160,39 @@
</Modal>
{/if}
+<!-- A stated address holding several files. Ticked by default: it was named as the
+ proof's material, so what hangs off it is material. -->
+{#if sourcePick}
+ <Modal title="What to bring in" onclose={() => (sourcePick = null)} width="520px">
+ <p class="picker-hint">
+ This address has {sourcePick.items.length} attachments. Ticked ones join the case
+ and the proof rests on them.
+ {#if sourcePick.items.some((one) => one.own === false)}
+ The video extractor also reports what a post quotes, so only the first is ticked.
+ {/if}
+ </p>
+ <ul class="src-pick">
+ {#each sourcePick.items as item (item.index)}
+ <li>
+ <label class="src-pick-row">
+ <input type="checkbox" bind:checked={item.picked} />
+ <span class="src-pick-title">{item.title}</span>
+ <span class="badge">{item.kind}</span>
+ </label>
+ </li>
+ {/each}
+ </ul>
+ <div class="picker-actions">
+ <button class="btn btn-sm" onclick={() => (sourcePick = null)}>Cancel</button>
+ <button
+ class="btn btn-primary btn-sm"
+ disabled={!sourcePick.items.some((one) => one.picked)}
+ onclick={takeSourcePick}
+ >Bring them in</button>
+ </div>
+ </Modal>
+{/if}
+
{#if openList}
<Modal title="Open a saved proof" onclose={() => (openList = null)} width="560px">
{#if !openList.length}
@@ -3390,16 +4367,44 @@
border-radius: var(--r-sm);
}
.meta-reset:hover { color: var(--text-1); background: var(--bg-2); }
- .meta-check {
+ .meta-add {
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 1px;
+ border-radius: var(--r-sm);
+ }
+ .meta-add.alone { margin-left: auto; } /* no reset button to sit beside */
+ .meta-add:hover { color: var(--text-1); background: var(--bg-2); }
+ .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-drop {
display: inline-flex;
- align-items: center;
- gap: 5px;
- margin-top: 5px;
- font-size: var(--fs-xs);
color: var(--text-3);
+ padding: 2px;
+ border-radius: var(--r-sm);
+ }
+ .meta-drop:hover { color: var(--danger, #e05c5c); background: var(--bg-2); }
+ .meta-fetch {
+ display: inline-flex;
+ color: var(--warn, #e8a33d);
+ padding: 2px;
+ border-radius: var(--r-sm);
+ }
+ .meta-fetch:hover:not(:disabled) { color: var(--text-1); background: var(--bg-2); }
+ .meta-fetch:disabled { opacity: 0.5; }
+ .src-pick { list-style: none; margin: 10px 0; padding: 0; display: grid; gap: 4px; }
+ .src-pick-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
cursor: pointer;
}
- .meta-check:hover { color: var(--text-1); }
+ .src-pick-row:hover { background: var(--bg-2); }
+ .src-pick-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.tpl-settings-link {
margin-left: auto;
display: inline-flex;
@@ -3424,6 +4429,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-pov, .point-move, .point-drop {
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 2px;
+ border-radius: var(--r-sm);
+ }
+ .point-pov:hover, .point-move:hover { color: var(--text-1); background: var(--bg-2); }
+ .point-pov.on { color: var(--accent, #6ea8fe); background: var(--bg-2); }
+ .point-drop:hover { color: var(--danger, #e05c5c); background: var(--bg-2); }
+ .point-hint { margin-top: 5px; font-size: var(--fs-xs); color: var(--text-3); }
.adv-toggle {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index 0bba380..2a1b70f 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -8,6 +8,7 @@ import ProofComposer from './ProofComposer.svelte';
import {
bindPanelPointerLifecycle,
createCanvasRenderGate,
+ discardDraft,
} from './proof/canvasLifecycle.js';
const source = readFileSync(new URL('./ProofComposer.svelte', import.meta.url), 'utf8');
@@ -150,6 +151,34 @@ describe('Proof Composer empty canvas', () => {
});
});
+describe('Proof Composer drawing tools own the canvas', () => {
+ it('mutes the document and its handles while a drawing tool is active', () => {
+ const rule = source.slice(
+ source.indexOf('function syncCanvasListening'),
+ source.indexOf('function docPoint'),
+ );
+
+ expect(rule).toContain("const live = tool === 'select' && !spacePan;");
+ expect(rule).toContain('docLayer?.listening(live);');
+ expect(rule).toContain('uiLayer?.listening(live);');
+ // Hold-space panning went through its own switch once. Two rules meant the
+ // second could hand the canvas back while a drawing tool still held it.
+ expect(source).not.toContain('docLayer.listening(false)');
+ expect(source).not.toContain('docLayer?.listening(true)');
+ });
+
+ it('leaves the colour, size and keyboard acts to the tool that can show them', () => {
+ expect(source).toContain("const editableShapes = $derived(tool === 'select' ? selectedShapes : []);");
+
+ const controls = source.slice(
+ source.indexOf('function setColor'),
+ source.indexOf('// Arrow-key nudge'),
+ );
+ expect(controls).not.toContain('selectedShape');
+ expect(source).toContain("(e.key === 'Delete' || e.key === 'Backspace') && tool === 'select'");
+ });
+});
+
describe('Proof Composer panel pointer lifecycle', () => {
function fakeGroup() {
const handlers = new Map();
@@ -448,7 +477,9 @@ describe('Proof Composer pasted images', () => {
});
it('resizes a pasted image from its corners with the aspect locked', () => {
- expect(source).toContain('transformer.keepRatio(!!sigNode || !!pasteNode)');
+ // the list has grown a symbol since; what this test guards is that a paste
+ // is still on it, not who else joined
+ expect(source).toMatch(/transformer\.keepRatio\([^)]*!!pasteNode/);
expect(source).toContain('implied < PASTE_SCALE_MIN || implied > PASTE_SCALE_MAX');
expect(source).toContain('|| pasteNode || sigNode');
});
@@ -489,25 +520,75 @@ describe('POV', () => {
it('asks what the point means, since the composition cannot say', () => {
// recorded-at and shows are independent: a rooftop shot is recorded
// somewhere it never shows
- expect(source).toContain('pov: false');
- expect(source).toContain('proof.pov = spec.pov === true');
- expect(source).toContain('The point is where the camera stood, not what it filmed');
- expect(source).toContain('<span>POV</span>');
+ expect(source).toContain('title="Point of view"');
+ expect(source).toContain('onclick={() => togglePov(i)}');
+ });
+
+ it('lights one point at most, because a camera stood in one place', () => {
+ expect(source).toContain('proof.points.map((one, at) => ({ ...one, pov: on && at === i }))');
+ });
+});
+
+describe('the points a proof states', () => {
+ it('keeps a single-point proof looking exactly as it did', () => {
+ // no cross, no arrow: there is nothing to remove and nothing to move
+ expect(source).toContain('{#if i > 0}');
+ expect(source).toContain('placeholder="lat, lon"');
+ expect(source).toContain('placeholder="label"');
+ });
+
+ it('materialises the auto point before a second one sits under it', () => {
+ // an empty field means "whatever the imagery says", and that answer has to
+ // become the conclusion in writing before the list can grow
+ expect(source).toContain("if (!proof.points[0].coords.trim()) proof.points[0].coords = displayedCoords;");
+ });
+
+ it('chooses the conclusion by order, never by POV', () => {
+ expect(source).toContain('function raisePoint(i)');
+ expect(source).toContain("Make this the proof's conclusion");
+ });
+
+ it('caps the list where the engine caps it', () => {
+ expect(source).toContain('if (proof.points.length >= MAX_POINTS) return;');
+ });
+
+ it('grows the list from the head, the way the sources do', () => {
+ const head = source.slice(source.indexOf('<span>Coordinates</span>'), source.indexOf('placeholder="lat, lon"'));
+ expect(head).toContain('{#if proof.points.length < MAX_POINTS}');
+ expect(head).toContain('title="Add a point"');
+ expect(head).toContain('onclick={addPoint}');
+ expect(source).not.toContain('class="point-add"');
+ });
+
+ it('redraws the plate when a point or the footer switch changes', () => {
+ // both feed the footer, and the footer decides the picture's height: a
+ // rebuild that does not read them leaves the export a line behind
+ const rebuild = source.slice(source.indexOf('Rebuild only when published document'));
+ expect(rebuild.slice(0, rebuild.indexOf('requestRebuild')))
+ .toContain('proof.footerCoords, proof.footerText, proof.points,');
+ });
+
+ it('measures the footer at the number of lines it will print', () => {
+ expect(source).toContain('footerLines: footerLines(proof, prefs.coordFormat).length');
+ expect(source).toContain(
+ "const printed = proof.footerEnabled !== false ? footerLines(proof, prefs.coordFormat) : [];"
+ );
+ expect(source).toContain('if (proof.panels.length && printed.length) {');
});
});
describe("the point a proof concludes on", () => {
- it('files it silently, or asks — never both, and never for a point already saved', () => {
- // the server answers with nothing when the case holds that point already
- expect(source).toContain('if (result.place?.filed)');
- expect(source).toContain('else if (result.place) placeOffer =');
+ it('files what it can and asks about the rest, never for a point already saved', () => {
+ // the server answers with nothing when the case holds those points already
+ expect(source).toContain('if (result.place?.filed?.length)');
+ expect(source).toContain('if (result.place?.asking?.length)');
});
it('asks with the coordinates, since the map is where the point will be read', () => {
expect(source).toContain('Save this point as a place?');
- expect(source).toContain('is not saved in this case yet.');
- expect(source).toContain('this proof and the files it composes will say they show it');
- expect(source).toContain('was recorded there');
+ expect(source).toContain("'Save these points as places?'");
+ expect(source).toContain('this proof and the files it composes will say they show them');
+ expect(source).toContain('was recorded at the marked one');
});
it('answers through the proof, so the edge is filed with the point', () => {
@@ -535,3 +616,414 @@ describe("the point a proof concludes on", () => {
expect(source).toContain('restorable={RESTORABLE}');
});
});
+
+describe('Proof Composer — one document at a time', () => {
+ const composer = readFileSync(new URL('./ProofComposer.svelte', import.meta.url), 'utf8');
+
+ it('stops an earlier open from streaming panels into the proof that replaced it', () => {
+ // The open list stays up while a proof loads, so clicking a second entry is
+ // one gesture away. Without a guard, A's panels kept arriving into the
+ // document now bound to B's name, and Save wrote the hybrid over B.
+ expect(composer).toContain('let openRun = 0;');
+ expect(composer).toContain('const run = ++openRun;');
+ expect(composer.match(/if \(run !== openRun\) return;/g)?.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it('cancels a pending history capture before an undo restores the document', () => {
+ // The clear has to come before the histBusy guard, or a timer armed in the
+ // 350 ms before the undo survives it and pushes the pre-undo state back.
+ expect(composer).toMatch(
+ /const json = docSnapshot\(\);[\s\S]*?clearTimeout\(histTimer\);\s*\n\s*if \(histBusy\) return;/
+ );
+ });
+});
+
+
+describe('a draft left in hand', () => {
+ it('destroys the node and hands back nothing', () => {
+ const destroy = vi.fn();
+ expect(discardDraft({ node: { destroy } })).toBeNull();
+ expect(destroy).toHaveBeenCalledOnce();
+ });
+
+ it('survives a draft that never got a node', () => {
+ expect(discardDraft(null)).toBeNull();
+ expect(discardDraft({})).toBeNull();
+ });
+
+ it('abandons the shape being drawn when Escape lands mid-drag', () => {
+ // Escape used to switch the tool to Select and leave `drawing` armed, so
+ // the release below took the Select branch and the draft never settled.
+ const escape = source.slice(source.indexOf('function onKeydown'), source.indexOf('function onKeyup'));
+
+ expect(escape).toContain("if (e.key === 'Escape' && drawing)");
+ expect(escape).toContain('drawing = discardDraft(drawing)');
+ });
+
+ it('never lets Select swallow the release that settles a draft', () => {
+ const up = source.slice(source.indexOf('function onPointerUp'), source.indexOf('function finishPath'));
+ const select = up.indexOf("if (tool === 'select')");
+
+ expect(select).toBeGreaterThan(-1);
+ // the Select branch holds no nested block, so the next brace closes it:
+ // whatever return it makes has to be guarded on there being no draft
+ const branch = up.slice(select, up.indexOf('}', select));
+ expect(branch).toContain('if (!drawing) return;');
+ expect(branch).not.toMatch(/\n\s*return;/);
+ });
+});
+
+describe('stamping a symbol', () => {
+ const down = source.slice(source.indexOf('function onPointerDown'), source.indexOf('function onPointerMove'));
+
+ it('places one on a single click and keeps the tool in hand', () => {
+ // text switches to Select after placing because the next act is editing it;
+ // marking six vehicles is one act, so the stamp stays armed
+ expect(down).toContain("if (tool === 'icon')");
+ expect(down).toContain("kind: 'icon', name: entry.name");
+ const stamp = down.slice(down.indexOf("if (tool === 'icon')"), down.indexOf("// curve:"));
+ expect(stamp).toContain('selectedIds = [s.id]');
+ expect(stamp).not.toContain("tool = 'select'");
+ });
+
+ it('sizes it against the panel, so it reads the same on any resolution', () => {
+ expect(down).toContain('size: iconSizeFor(hit.box.baseScale)');
+ });
+
+ it('gives a solid silhouette no stroke width to carry', () => {
+ expect(down).toContain('...(isSolidIcon(entry.name) ? {} : { strokeWidth: strokeW })');
+ const setStroke = source.slice(source.indexOf('function setStroke'), source.indexOf('/** Fill opacity'));
+ expect(setStroke).toContain("if (s.kind === 'icon' && isSolidIcon(s.name)) continue;");
+ });
+
+ it('scales but never deforms: corners only, ratio locked', () => {
+ const tr = source.slice(source.indexOf('transformer.rotateEnabled('), source.indexOf('if (handles) {'));
+ const anchors = tr.slice(tr.indexOf('enabledAnchors'));
+
+ expect(anchors).toContain("selKind === 'text' || selKind === 'icon'");
+ // the middle handles are the ones that would let it be squashed
+ expect(anchors).not.toMatch(/selKind === 'icon'[^?]*'middle-left'/);
+ expect(source).toMatch(/transformer\.keepRatio\([^)]*selKind === 'icon'/);
+ // and it reads selKind only after selKind exists: a const referenced above
+ // its declaration throws, which takes the whole effect down with it —
+ // panel handles and move arrows included
+ expect(source.indexOf('const selKind = selectedShape?.kind;'))
+ .toBeLessThan(source.indexOf('transformer.keepRatio('));
+ });
+
+ it('hangs the shape on the point it names rather than a corner', () => {
+ const node = source.slice(source.indexOf('function makeIconNode'), source.indexOf('// ---- inline text editing'));
+
+ 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'");
+ });
+
+ it('turns the fill into a badge disc behind the glyph', () => {
+ const node = source.slice(source.indexOf('function makeIconNode'), source.indexOf('// ---- inline text editing'));
+
+ expect(node).toContain('const disc = s.fillOpacity ?? 0');
+ expect(node).toContain('fill: fillPaint(s.color, disc)');
+ expect(node).toContain('glyphInk(s.color, disc)');
+ // a stroked glyph is mostly holes, so the press lands on the box
+ expect(node).toContain("fill: '#000', opacity: 0");
+ });
+
+ it('divides the scale back out of the stroke, so a big symbol is not a fat one', () => {
+ const node = source.slice(source.indexOf('function makeIconNode'), source.indexOf('// ---- inline text editing'));
+
+ expect(node).toContain('strokeWidth: (s.strokeWidth ?? 4) / panelScale / k');
+ });
+
+ it('reaches the stamp with a key nothing else claims', () => {
+ expect(source).toContain("else if (e.key === 's') tool = 'icon';");
+ });
+});
+
+// ---- gestures the composer runs itself --------------------------------------
+// The three below — drawing, marquee, pan — are handled in this file rather than
+// by Konva, so the stranded-gesture net that covers the transformer and node
+// drags (konvaGesture.js) never reached them.
+
+const canvasSource = readFileSync(new URL('./proof/ProofCanvas.svelte', import.meta.url), 'utf8');
+const down = source.slice(source.indexOf('function onPointerDown'), source.indexOf('function onPointerMove'));
+const keys = source.slice(source.indexOf('function onKeydown'), source.indexOf('function onKeyup'));
+
+describe('a release the canvas never hears', () => {
+ const mount = source.slice(
+ source.indexOf('onMount(() => {'),
+ source.indexOf('// reset the document when the case changes'),
+ );
+ const settle = source.slice(
+ source.indexOf('function settleStrandedGesture'),
+ source.indexOf('function finishPath'),
+ );
+ const marquee = source.slice(
+ source.indexOf('function applyMarquee'),
+ source.indexOf('/** Fold the draft in hand'),
+ );
+
+ it('settles the gestures this file runs itself', () => {
+ // Letting go over the side column — a hand's width from the canvas edge —
+ // left a draft stretching under a bare pointer and a marquee standing with
+ // no selection to show for it.
+ expect(settle).toContain('if (marquee) applyMarquee();');
+ expect(settle).toContain('if (drawing) commitDrawing();');
+ });
+
+ it('ends the pan on the spot, since it follows the live pointer', () => {
+ // A frame's wait is invisible for a draft — it only moves on a pointermove
+ // over the canvas — but a pan reads every move, so one arriving before the
+ // frame slid the view after the button was let go.
+ expect(mount).toContain('if (panDrag) endPan();');
+ expect(mount.indexOf('if (panDrag) endPan();')).toBeLessThan(mount.indexOf('const seq = gestureSeq;'));
+ expect(settle).not.toContain('endPan');
+ });
+
+ it('hangs on the same window release that closes the gestures Konva owns', () => {
+ expect(mount).toContain('settleStrandedGesture();');
+ expect(mount).toContain("window.addEventListener('pointerup', settlePointer, true)");
+ expect(mount).toContain("window.addEventListener('pointercancel', settlePointer, true)");
+ expect(mount).toContain("window.addEventListener('blur', settlePointer)");
+ });
+
+ it('never settles a gesture a fresh press has already replaced', () => {
+ // The settle waits a frame so a normal release can close itself first. A
+ // press landing inside that frame opens a new draft, and committing that
+ // one would end a stroke still being drawn.
+ expect(mount).toContain('gestureSeq += 1;');
+ expect(mount).toContain('const seq = gestureSeq;');
+ expect(mount).toContain('if (seq === gestureSeq) settleStrandedGesture();');
+ });
+
+ it('reads the marquee off its node rather than a pointer that has left', () => {
+ expect(marquee).toContain('width: node.width(), height: node.height()');
+ expect(marquee).not.toContain('docPoint()');
+ expect(marquee).toContain('node?.destroy();');
+ expect(marquee).toContain('marquee = null;');
+ });
+
+ it('commits the draft through the one path a normal release uses', () => {
+ // Two commit paths would be two answers to "what did that stroke become".
+ const up = source.slice(source.indexOf('function onPointerUp'), source.indexOf('function settleStrandedGesture'));
+ expect(up).toContain('commitDrawing();');
+ expect(up).toContain('applyMarquee();');
+ expect(up).toContain('endPan();');
+ });
+});
+
+describe('the button that draws', () => {
+ it('is the primary one; the middle one pans', () => {
+ expect(down).toContain('if (spacePan || e.evt.button === 1)');
+ expect(down).toContain('if ((e.evt.button ?? 0) > 0) return;');
+ });
+
+ it('turns the right button away before either tool can answer it', () => {
+ // A right-drag drew a whole annotation under the context menu opening over
+ // it; in Select it cleared the selection and opened a marquee.
+ expect(down.indexOf('(e.evt.button ?? 0) > 0'))
+ .toBeLessThan(down.indexOf("if (tool === 'select')"));
+ });
+});
+
+describe('Escape', () => {
+ it('unwinds one level per press instead of meaning two opposite things', () => {
+ expect(keys).toContain("if (e.key === 'Escape' && drawing)");
+ expect(keys).toMatch(/if \(visiblePick\) \{[\s\S]*?\} else \{\s*tool = 'select';/);
+ });
+
+ it('never clears a pick and puts the pen down in the same press', () => {
+ const rung = keys.slice(keys.indexOf('if (visiblePick) {'), keys.indexOf("} else if (e.key === 'v')"));
+ const cleared = rung.slice(0, rung.indexOf('} else {'));
+
+ expect(cleared).toContain('selectedIds = [];');
+ expect(cleared).toContain('selectedPanelId = null;');
+ expect(cleared).not.toContain("tool = 'select'");
+ });
+
+ it('counts only a pick that shows, so one held for later is not a rung', () => {
+ const derived = source.slice(
+ source.indexOf('const visiblePick = $derived('),
+ source.indexOf('// Every dialog that can sit over'),
+ );
+
+ expect(derived).toContain('selectionLive');
+ expect(derived).toContain('selectedIds.length > 0');
+ expect(derived).toContain('!!selectedSig');
+ });
+});
+
+describe('a dialog over the composer', () => {
+ it('keeps the one-letter tool keys off the canvas behind it', () => {
+ expect(keys).toContain('if (modalOpen) return;');
+ expect(keys.indexOf('if (modalOpen) return;')).toBeLessThan(keys.indexOf("e.key === 'r'"));
+ // and Escape belongs to the dialog closing, not to the tool underneath
+ expect(keys.indexOf('if (modalOpen) return;')).toBeLessThan(keys.indexOf('if (visiblePick) {'));
+ });
+
+ it('still lets the export menu answer its own Escape first', () => {
+ expect(keys.indexOf('exportMenuOpen = false;')).toBeLessThan(keys.indexOf('if (modalOpen) return;'));
+ });
+
+ it('names every dialog that can be up', () => {
+ const derived = source.slice(
+ source.indexOf('// Every dialog that can sit over'),
+ source.indexOf('const editableShape ='),
+ );
+
+ for (const flag of [
+ 'picker', 'newProofOpen', 'importOpen', 'openList', 'discardConfirm',
+ 'replaceWithNewConfirm', 'exportPicker', 'overwritePrompt', 'placeOffer',
+ 'orphanOffer', 'deleteEntry', 'sourcePick',
+ ]) {
+ expect(derived).toContain(flag);
+ }
+ });
+});
+
+describe('picking from the side column', () => {
+ const bodyOf = (name) => {
+ const at = source.indexOf(`function ${name}`);
+ return source.slice(at, source.indexOf('\n }', at));
+ };
+
+ it('takes the hand back to Select, since a row cannot mean "draw here"', () => {
+ // The canvas refuses instead: there a press means draw. A row that lit up
+ // orange while Delete, the handles and the colour all ignored it was a
+ // selection visible in one column and absent from the other.
+ for (const name of ['pickShapeRow', 'pickPanelRow', 'pickPasteRow']) {
+ expect(bodyOf(name)).toContain("tool = 'select';");
+ }
+ });
+
+ it('wires the rows to those rather than to the raw pick the canvas guards', () => {
+ expect(source).toContain('selectShape={pickShapeRow}');
+ expect(source).toContain('selectPanelRow={pickPanelRow}');
+ expect(source).toContain('selectPasteRow={pickPasteRow}');
+ expect(source).not.toContain('bind:selectedPanelId');
+ expect(source).not.toContain('bind:selectedPasteId');
+ });
+
+ it('lights a row only while the pick can be acted on', () => {
+ expect(source).toContain("const selectionLive = $derived(tool === 'select');");
+ expect(source).toContain('{selectionLive}');
+ });
+
+ it('clears a marquee that would otherwise swallow the row click', () => {
+ expect(bodyOf('pickPanelRow')).toContain('marqueeEnded = false;');
+ });
+});
+
+describe('the curve tool', () => {
+ it('stays in hand like the box, the line and the arrow beside it', () => {
+ const finish = source.slice(
+ source.indexOf('function finishPath'),
+ source.indexOf('function commitPasteNode'),
+ );
+
+ expect(finish).toContain("kind: 'curve'");
+ expect(finish).not.toContain("tool = 'select'");
+ });
+
+ it('ends where it was and opens the next one on a vertex dropped elsewhere', () => {
+ // The click used to be dropped in silence, which reads as a dead canvas.
+ expect(down).toContain('if (pathDraft && pathDraft.panel.id !== panel.id) finishPath(true);');
+ });
+});
+
+describe('placing a label', () => {
+ it('opens the editor on the click that places it', () => {
+ const text = down.slice(down.indexOf("if (tool === 'text')"), down.indexOf("if (tool === 'icon')"));
+
+ // A frame later, or the press that placed it takes the focus straight back
+ // out of the editor: the browser moves focus off whatever holds it when a
+ // click lands on something that cannot, so an editor opened inside the
+ // pointerdown was blurred, committed and closed before a key could reach it.
+ expect(text).toContain('requestAnimationFrame(() => startTextEdit(s));');
+ expect(text).toContain("tool = 'select';"); // the next act is the typing
+ });
+
+ it('places the editor off the surface box, since there is no node yet', () => {
+ const start = source.slice(
+ source.indexOf('function startTextEdit'),
+ source.indexOf('function commitTextEdit'),
+ );
+
+ expect(start).toContain('surfacesOf().find((x) => x.id === s.panel)?.box');
+ expect(start).not.toContain('getAbsolutePosition');
+ // and over the words of a boxed label, not over its corner
+ expect(start).toContain('textBoxPad(s.fontSize)');
+ expect(source).toContain('const pad = textBoxPad(s.fontSize);');
+ });
+
+ it('holds more than one line, the way Konva draws it', () => {
+ expect(canvasSource).toContain('<textarea');
+ expect(canvasSource).not.toContain('<input\n class="text-edit"');
+ expect(canvasSource).toContain("if (event.key === 'Enter' && !event.shiftKey)");
+ expect(canvasSource).toContain('white-space: pre;');
+ expect(canvasSource).toContain("rows={textEdit.value.split('\\n').length}");
+ });
+});
+
+describe('the room around the page', () => {
+ it('pans under a drawing tool, the way it does under Select', () => {
+ // Same room, same drag: it answered only to Select, so with a box in hand
+ // the press was lost and the crosshair promised a stroke it never drew.
+ expect(down).toContain('if (!hit) {\n startPan();');
+ });
+
+ it('says so with the cursor while the view slides', () => {
+ expect(source).toContain("containerEl.style.cursor = 'grabbing';");
+ expect(source).toContain("containerEl.style.cursor = spacePan ? 'grab' : '';");
+ });
+});
+
+describe('a freehand stroke', () => {
+ it('resizes and turns like the shapes beside it', () => {
+ // It is the one kind with neither vertex handles nor a shape to speak of,
+ // so a dashed frame with nothing to pull read as a broken selection.
+ const ui = source.slice(source.indexOf('transformer.rotateEnabled('), source.indexOf('if (handles) {'));
+
+ expect(ui).toMatch(/rotateEnabled\([\s\S]*?selKind === 'freehand'/);
+ expect(ui).toMatch(/enabledAnchors\([\s\S]*?selKind === 'freehand'[\s\S]*?'middle-left'/);
+ });
+
+ it('keeps its samples off the handles, which would bury the stroke', () => {
+ expect(source).toContain("const POINT_KINDS = new Set(['line', 'arrow', 'curve']);");
+ });
+
+ it('folds the whole transform into its samples, having nowhere else to put it', () => {
+ const at = source.indexOf("} else if (s.kind === 'freehand') {");
+ const fold = source.slice(at, source.indexOf('s.rotation = node.rotation();', at));
+
+ expect(fold).toContain('pointsWithTransform(s.points, node.getTransform().getMatrix())');
+ expect(fold).toContain('node.position({ x: 0, y: 0 });');
+ expect(fold).toContain('node.rotation(0);'); // nothing left on the node to rotate around
+ });
+});
+
+describe('the unsaved badge', () => {
+ it('goes away when an undo walks back to what is on disk', () => {
+ const apply = source.slice(source.indexOf('function applySnapshot'), source.indexOf('function undo()'));
+
+ expect(apply).toContain('dirty = docSnapshot() !== savedSnapshot;');
+ expect(apply).not.toContain('dirty = true;');
+ });
+
+ it('remembers the document every save and every open leaves there', () => {
+ const save = source.slice(
+ source.indexOf('async function performSave'),
+ source.indexOf('/** Open the list fresh'),
+ );
+ const open = source.slice(
+ source.indexOf('async function openProof('),
+ source.indexOf('const selectedShapes'),
+ );
+ const reset = source.slice(source.indexOf('function resetDoc'), source.indexOf('function discardProof'));
+
+ expect(save).toContain('savedSnapshot = docSnapshot();');
+ expect(open).toContain('savedSnapshot = docSnapshot();');
+ expect(reset).toContain('savedSnapshot = null;');
+ });
+});
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 2bf7491..ab79fb4 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -11,6 +11,7 @@
import {
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
+ import { wrapLon } from '../lib/coords.js';
import { mapLinks } from '../lib/maplinks.js';
import * as measure from '../lib/measure.js';
import { markerGeometry, markerSvg } from '../lib/mapMarkers.js';
@@ -27,6 +28,7 @@
import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';
import { clampSize, scaledCapture } from '../lib/captureSize.js';
import { panelWidth } from '../lib/panelWidth.js';
+ import PlaceSearch from './satellite/PlaceSearch.svelte';
import { assignFolder } from '../lib/filing.js';
import { saveRelation } from '../lib/relations.svelte.js';
import { openEntity } from '../lib/navigate.js';
@@ -82,6 +84,7 @@
import SavedTree from './satellite/SavedTree.svelte';
import SavedSearch from './satellite/SavedSearch.svelte';
import SavedOverlay from './satellite/SavedOverlay.svelte';
+ import SheetPointsOverlay from './satellite/SheetPointsOverlay.svelte';
import TemporalMapOverlay from './satellite/TemporalMapOverlay.svelte';
let mapEl;
@@ -115,6 +118,9 @@
let temporalMapLoading = $state(false);
let temporalMapError = $state('');
let temporalMapSeq = 0;
+ /** A sheet's coordinate column, handed over as points. Session-only, like the layer
+ * above it, and never part of a capture or a proof. */
+ let sheetPoints = $state(null); // { points, sheet, column }
// Persist geography or My-work folder grouping across reloads.
const GROUP_KEY = 'azimut:satelliteSavedGroup';
let savedGroup = $state(loadSavedGroup());
@@ -429,7 +435,25 @@
uiState.refViewers = uiState.refViewers.filter((v) => v.id !== id);
}
- onMount(async () => {
+ // Svelte only honours a cleanup returned from a *synchronous* onMount, and the
+ // setup below has to await the providers and the saved home view. So onMount
+ // stays synchronous and hands back a teardown that runs whatever the async
+ // build registered. Tools are never unmounted today, which is exactly why an
+ // async onMount would have gone on quietly returning a promise nobody calls.
+ onMount(() => {
+ let teardown = null;
+ let gone = false;
+ build().then((cleanup) => {
+ if (gone) cleanup?.();
+ else teardown = cleanup;
+ });
+ return () => {
+ gone = true;
+ teardown?.();
+ };
+ });
+
+ async function build() {
refreshUsage(); // prefs drive the eco/soft-block fallbacks from the start
providers = await api.get('/api/satellite/providers');
await prefsReady; // the home view has to land before the map is built
@@ -460,7 +484,10 @@
}).addTo(map);
map.on('moveend zoomend', () => {
const c = map.getCenter();
- center = { lat: c.lat, lon: c.lng, zoom: map.getZoom() };
+ // Leaflet keeps counting past ±180° when the analyst pans across the date
+ // line, and every coordinate the app sends is bounded to it — an unwrapped
+ // centre made Capture answer 422 and blocked work over the Pacific.
+ center = { lat: c.lat, lon: wrapLon(c.lng), zoom: map.getZoom() };
});
map.on('rotate', () => {
bearing = Math.round(map.getBearing());
@@ -492,7 +519,7 @@
offActivated();
map.remove();
};
- });
+ }
function onKeydown(e) {
if (uiState.tool !== 'satellite') return;
@@ -1231,6 +1258,8 @@
temporalMap = null;
temporalMapLoading = false;
temporalMapError = '';
+ // The points came out of another case's sheet, so they go with it.
+ sheetPoints = null;
}
if (!id) {
return;
@@ -1299,6 +1328,25 @@
}
});
+ /**
+ * A sheet's column of coordinates, taken as it was handed over.
+ *
+ * No request, unlike the layer below: a sheet's coordinates are text in a CSV, not
+ * entities the case can be asked about, so there is nothing to re-ask and the points
+ * themselves travel. Framed on what arrived, because a layer that lands off screen
+ * reads as a layer that did not land.
+ */
+ $effect(() => {
+ const handed = uiState.mapSheetPoints;
+ if (!mapReady || !handed?.points?.length) return;
+ uiState.mapSheetPoints = null;
+ sheetPoints = handed;
+ const bounds = L.latLngBounds(handed.points.map((point) => [point.lat, point.lon]));
+ tick().then(() => {
+ if (map && bounds.isValid()) map.fitBounds(bounds, { padding: [48, 48], maxZoom: 17 });
+ });
+ });
+
$effect(() => {
const handed = uiState.mapTimelineRange;
const caseId = caseState.current?.id;
@@ -1601,6 +1649,18 @@
}
}
+ /** Fly to a row the search bar proposed. A saved item is opened the way the
+ * panel opens it — same view, same bearing — and anything else is a point
+ * with a sensible zoom for what it is: a city, a street, a coordinate. */
+ function goToSuggestion(item) {
+ if (item.row) {
+ openSaved(item.row);
+ return;
+ }
+ if (!map || !Number.isFinite(item.lat) || !Number.isFinite(item.lon)) return;
+ map.setView([item.lat, item.lon], item.zoom ?? Math.max(map.getZoom(), 13));
+ }
+
function setBearing(deg) {
if (!map) return;
map.setBearing(((deg % 360) + 360) % 360);
@@ -3054,23 +3114,15 @@
<div class="tool-header">
<h2>Satellite</h2>
<div class="spacer"></div>
- <form
- class="go-form"
- onsubmit={(e) => {
- e.preventDefault();
- goTo();
- }}
- >
- <input
- class="input"
- placeholder={'50.4501, 30.5234 · 48°51\'29"N 2°17\'40"E · a place name'}
- bind:value={coordsText}
- title="Coordinates (decimal, DMS, MGRS, plus code) or a place name"
- />
- <button type="submit" class="btn" disabled={!coordsText.trim() || searching}>
- <Icon name="search" size={15} /> {searching ? '…' : 'Go'}
- </button>
- </form>
+ <PlaceSearch
+ bind:value={coordsText}
+ savedRows={saved}
+ centre={{ lat: center.lat, lon: center.lon }}
+ units={prefs.units}
+ {searching}
+ onpick={goToSuggestion}
+ onsubmit={goTo}
+ />
</div>
<div class="body">
@@ -3102,6 +3154,22 @@
/>
{/if}
+ {#if sheetPoints}
+ <SheetPointsOverlay map={mapReady ? map : null} points={sheetPoints.points} />
+ <!-- Both temporary layers can be on at once, so this one sits under the other
+ rather than on top of it. -->
+ <div class="temporal-layer-card" class:stacked={temporalMap} aria-label="Sheet map layer">
+ <div>
+ <strong>Sheet</strong>
+ <span>{sheetPoints.sheet} · {sheetPoints.column}</span>
+ </div>
+ <p>{sheetPoints.points.length} point{sheetPoints.points.length === 1 ? '' : 's'} read from the column</p>
+ <nav aria-label="Close the sheet layer">
+ <button class="quiet" onclick={() => (sheetPoints = null)}>Close</button>
+ </nav>
+ </div>
+ {/if}
+
{#if temporalMap}
<TemporalMapOverlay
map={mapReady ? map : null}
@@ -3754,7 +3822,7 @@
{#if extGateOpen}
<Modal title="Capture needs the browser extension" onclose={() => (extGateOpen = false)} width="460px">
<p class="shot-hint">
- Google's terms allow nothing programmatic out of this basemap — a capture
+ Google's terms allow nothing programmatic out of this basemap. A capture
here is a <strong>screenshot of the tab</strong>, and the Azimut Capture
extension is what takes it (one grab per click, no screen-share prompt,
works in fullscreen). Other basemaps are not affected.
@@ -3926,11 +3994,6 @@
.spacer {
flex: 1;
}
- .go-form {
- display: flex;
- gap: 8px;
- width: min(420px, 36vw);
- }
.body {
flex: 1;
display: flex;
@@ -3951,6 +4014,7 @@
inset: 0;
background: var(--bg-2);
}
+ .temporal-layer-card.stacked { top: 150px; }
.temporal-layer-card {
position: absolute;
z-index: 720;
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index b33a5de..cb211e0 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -385,3 +385,49 @@ describe('accepting a proposed point from the Saved panel', () => {
expect(modal.slice(0, modal.indexOf('/>'))).toContain('onaccept={acceptSaved}');
});
});
+
+describe('Satellite — lifecycle and the date line', () => {
+ it('registers a teardown Svelte will actually call', () => {
+ // Svelte only honours a cleanup returned from a *synchronous* onMount, and
+ // the setup awaits the providers and the saved home view.
+ expect(source).toContain('onMount(() => {');
+ expect(source).not.toContain('onMount(async () => {');
+ expect(source).toContain('async function build()');
+ expect(source).toContain('teardown?.();');
+ });
+
+ it('folds the map centre back inside the bounds every route enforces', () => {
+ // Leaflet keeps counting past ±180 across the antimeridian; the capture
+ // route bounds lon to ±180, so an unwrapped centre answered 422.
+ expect(source).toContain("import { wrapLon } from '../lib/coords.js';");
+ expect(source).toContain('center = { lat: c.lat, lon: wrapLon(c.lng), zoom: map.getZoom() };');
+ });
+});
+
+describe('Satellite — the search bar', () => {
+ it('is the suggesting combobox, fed by the case and the map centre', () => {
+ expect(source).toContain("import PlaceSearch from './satellite/PlaceSearch.svelte';");
+ expect(source).toContain('<PlaceSearch');
+ expect(source).toContain('savedRows={saved}');
+ expect(source).toContain('centre={{ lat: center.lat, lon: center.lon }}');
+ expect(source).toContain('units={prefs.units}');
+ // the plain form it replaces is gone, not left beside it
+ expect(source).not.toContain('class="go-form"');
+ });
+
+ it('keeps the old Enter behaviour as the fallback', () => {
+ // Enter with nothing highlighted still parses or geocodes the raw text
+ expect(source).toContain('onsubmit={goTo}');
+ expect(source).toContain("await api.get(`/api/geo/geocode?q=");
+ });
+
+ it('opens a chosen saved item the way the panel does', () => {
+ // same view and bearing as the tree and the modal — one road to a saved place
+ expect(source).toContain('function goToSuggestion(item)');
+ expect(source).toContain('if (item.row) {\n openSaved(item.row);');
+ });
+
+ it('flies to a proposed point at the zoom that suits what it is', () => {
+ expect(source).toContain('map.setView([item.lat, item.lon], item.zoom ?? Math.max(map.getZoom(), 13));');
+ });
+});
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index c2771f1..983ac96 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -206,13 +206,15 @@
// back. A file written before those sections existed is a bare settings blob,
// so it gets wrapped into the current shape.
let settingsFile = $state(null);
- let exportDirs = $state({ notes: '', media: '', proofs: '' });
+ let exportDirs = $state({ notes: '', media: '', proofs: '', views: '' });
let exportPickerKind = $state(null);
const EXPORT_KINDS = [
{ id: 'notes', label: 'Note PDFs' },
{ id: 'media', label: 'Media copies' },
{ id: 'proofs', label: 'Proof PNGs' },
+ { id: 'views', label: 'Analysis plates' },
+ { id: 'sheets', label: 'Sheet CSVs' },
];
async function resetExportDestination(kind) {
@@ -516,7 +518,7 @@
// a live sample so the format choice is legible before it's applied elsewhere
const coordSample = $derived(
- formatCoords(Number(home.lat) || 48.8584, Number(home.lon) || 2.2945, prefs.coordFormat)
+ formatCoords(Number(home.lat) || 43, Number(home.lon) || 25, prefs.coordFormat)
);
onMount(() => {
diff --git a/frontend/src/tools/Sheet.fromProofs.render.test.js b/frontend/src/tools/Sheet.fromProofs.render.test.js
new file mode 100644
index 0000000..1f4b4f3
--- /dev/null
+++ b/frontend/src/tools/Sheet.fromProofs.render.test.js
@@ -0,0 +1,236 @@
+// @vitest-environment happy-dom
+/**
+ * A sheet built out of the case's proofs, driven the way an analyst drives it.
+ *
+ * Two claims that only the mounted grid can hold. The columns the **case** owns are read
+ * and not typed into — a view somebody can type over is a view that starts lying the
+ * first time they do — while still opening the entity behind them, which is the one thing
+ * that separates `locked` from the other roles the app writes.
+ *
+ * And Refresh is a **press**, offered only where there is something to refresh. A sheet
+ * that rewrote itself on open would move a file under somebody who came to read it.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const PROOFS_SHEET = {
+ id: 'e_sheet',
+ title: 'My geolocations',
+ path: 'sheets/My geolocations.csv',
+ columns: ['id', 'Title', 'Source media', 'Place', 'Coordinates', 'In case', 'Status', 'Notes'],
+ rows: [
+ ['r1', 'Rooftop shot', 'GX010234', 'Rooftop', '47.10000, 37.50000', 'YES', 'done', ''],
+ ['r2', 'Bridge shot', 'GX010235', '', '', 'NO', 'done', 'worth keeping'],
+ ],
+ meta: {
+ version: 6,
+ widths: {},
+ hidden: [],
+ sort: null,
+ colours: {},
+ frozen: null,
+ progress: 'Status',
+ roles: {
+ Title: { kind: 'locked' },
+ 'Source media': { kind: 'locked' },
+ Place: { kind: 'locked' },
+ Coordinates: { kind: 'computed', of: 'point', from: 'Place' },
+ 'In case': { kind: 'computed', of: 'in_case' },
+ Status: { kind: 'state', values: ['to do', 'in progress', 'done', 'ruled out'] },
+ },
+ links: {
+ r1: { Title: 'e_proof1', 'Source media': 'e_media1', Place: 'e_place1' },
+ r2: { 'Source media': 'e_media2' },
+ },
+ built: { r1: 'e_proof1', r2: 'e_proof2' },
+ },
+ stamp: '1000-64',
+ assigned: false,
+};
+
+/** The same sheet with nothing built into it: a table somebody typed or imported. */
+const PLAIN_SHEET = {
+ ...PROOFS_SHEET,
+ columns: ['id', 'Subject', 'Status'],
+ rows: [['r1', 'Quai sud', 'ruled out']],
+ meta: { version: 6, widths: {}, hidden: [], sort: null, colours: {}, links: {}, frozen: null },
+};
+
+let sheet = PROOFS_SHEET;
+
+const get = vi.fn();
+const put = vi.fn(async (_path, body) => ({ status: 'saved', stamp: '2000-64', ...body }));
+const post = vi.fn();
+const patch = vi.fn(async () => ({}));
+const del = vi.fn(async () => ({}));
+vi.mock('../lib/api.js', () => ({ api: { get, put, post, patch, del }, ApiError: Error }));
+
+const toast = vi.fn();
+const uiState = { tool: 'sheet', mapSheetPoints: null, timelineRange: null };
+const reloadCase = vi.fn(async () => {});
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('../components/views.fixture.svelte.js');
+ return { caseState, toast, uiState, reloadCase };
+});
+vi.mock('../components/EntityDetails.svelte', async () => await import('../components/Modal.svelte'));
+
+const { default: Sheet } = await import('./Sheet.svelte');
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 12; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+function route(path) {
+ if (path.endsWith('/sheets')) {
+ return Promise.resolve({
+ sheets: [{ id: sheet.id, title: sheet.title, path: sheet.path, rows: 2, columns: 8 }],
+ });
+ }
+ if (path.includes('/sheets/')) return Promise.resolve(structuredClone(sheet));
+ if (path.includes('/entity-types')) return Promise.resolve([]);
+ if (path.includes('/relation-types')) return Promise.resolve([]);
+ if (path.includes('/confidence-levels')) return Promise.resolve([]);
+ if (path.includes('/catalog/summary')) return Promise.resolve({ total: 2, by_type: {} });
+ return Promise.resolve({});
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Sheet, { target });
+ await settle();
+ return target;
+}
+
+const rows = () => [...target.querySelectorAll('.rows:not(.ghost) .row')];
+const cellAt = (row, index) => rows()[row].querySelectorAll('.cell:not(.gutter)')[index];
+const button = (label) =>
+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));
+
+/** Double-click a cell and say whether an editor opened. */
+function tryEdit(row, index) {
+ cellAt(row, index).dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+ const editor = target.querySelector('.editor');
+ return editor !== null;
+}
+
+beforeEach(async () => {
+ sheet = PROOFS_SHEET;
+ get.mockReset();
+ put.mockClear();
+ post.mockReset();
+ toast.mockClear();
+ get.mockImplementation(route);
+ const { caseState } = await import('../components/views.fixture.svelte.js');
+ caseState.id = 'case-a';
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target = null;
+ document.body.innerHTML = '';
+});
+
+describe('the columns the case owns', () => {
+ it('refuses an edit in all three, and in the two the app answers', async () => {
+ await open();
+ expect(tryEdit(0, 1)).toBe(false); // Title
+ expect(tryEdit(0, 2)).toBe(false); // Source media
+ expect(tryEdit(0, 3)).toBe(false); // Place
+ expect(tryEdit(0, 4)).toBe(false); // Coordinates
+ expect(tryEdit(0, 5)).toBe(false); // In case
+ });
+
+ it('leaves the analyst their own two', async () => {
+ await open();
+ expect(tryEdit(0, 6)).toBe(true); // Status
+ });
+
+ it('still opens the entity behind a locked cell', async () => {
+ await open();
+ // The mark `linkable()` admits on `locked` and refuses on every other written role.
+ expect(cellAt(0, 1).querySelector('.link-mark')).not.toBeNull();
+ expect(cellAt(0, 2).querySelector('.link-mark')).not.toBeNull();
+ expect(cellAt(0, 3).querySelector('.link-mark')).not.toBeNull();
+ // Nothing points at a coordinate or at a YES, so nothing is offered on them.
+ expect(cellAt(0, 4).querySelector('.link-mark')).toBeNull();
+ expect(cellAt(0, 5).querySelector('.link-mark')).toBeNull();
+ });
+
+ it('keeps the row whose proof is gone, with its note and its NO', async () => {
+ await open();
+ const cells = [...rows()[1].querySelectorAll('.cell:not(.gutter) .value')].map((node) =>
+ node.textContent.trim(),
+ );
+ expect(cells[1]).toBe('Bridge shot');
+ expect(cells[5]).toBe('NO');
+ expect(cells[7]).toBe('worth keeping');
+ // Its link was swept when the proof went; the row is what survives to say so.
+ expect(cellAt(1, 1).querySelector('.link-mark')).toBeNull();
+ });
+});
+
+describe('bringing the sheet level with the case', () => {
+ it('offers Refresh on a sheet that was built out of the case', async () => {
+ await open();
+ expect(button('Refresh')).not.toBeUndefined();
+ });
+
+ it('offers it on nothing else, because there would be nothing to refresh', async () => {
+ sheet = PLAIN_SHEET;
+ await open();
+ expect(button('Refresh')).toBeUndefined();
+ });
+
+ it('sends the table on screen with its stamp, and says what came back', async () => {
+ await open();
+ post.mockResolvedValue({
+ status: 'saved',
+ columns: sheet.columns,
+ rows: [...sheet.rows, ['r3', 'New shot', '', '', '', 'YES', 'done', '']],
+ meta: sheet.meta,
+ stamp: '3000-64',
+ added: 1,
+ updated: 0,
+ gone: 1,
+ });
+ button('Refresh').click();
+ await settle();
+
+ const [path, body] = post.mock.calls[0];
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet/refresh');
+ expect(body.stamp).toBe('1000-64');
+ expect(body.rows).toHaveLength(2);
+ expect(toast).toHaveBeenCalledWith('1 row added, 1 proof no longer in the case.');
+ expect(rows()).toHaveLength(3);
+ });
+
+ it('says so plainly when the sheet was already level', async () => {
+ await open();
+ post.mockResolvedValue({
+ status: 'saved',
+ columns: sheet.columns,
+ rows: sheet.rows,
+ meta: sheet.meta,
+ stamp: '3000-64',
+ added: 0,
+ updated: 0,
+ gone: 0,
+ });
+ button('Refresh').click();
+ await settle();
+ expect(toast).toHaveBeenCalledWith('Already level with the case.');
+ });
+
+ it('never runs on its own: opening the sheet writes nothing', async () => {
+ await open();
+ expect(post).not.toHaveBeenCalled();
+ expect(put).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/tools/Sheet.render.test.js b/frontend/src/tools/Sheet.render.test.js
new file mode 100644
index 0000000..5b5f1d3
--- /dev/null
+++ b/frontend/src/tools/Sheet.render.test.js
@@ -0,0 +1,3954 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The grid, driven the way an analyst drives it.
+ *
+ * `lib/sheet.test.js` owns the table logic; this owns what the screen does with
+ * it — that a cell edit reaches the file, that the search does not leak into the
+ * grid's own keyboard, and that a linked cell can be opened.
+ */
+
+const SHEET = {
+ id: 'e_sheet',
+ title: 'Candidates',
+ path: 'sheets/Candidates.csv',
+ columns: ['id', 'Subject', 'Status'],
+ rows: [
+ ['r1', 'Quai sud', 'ruled out'],
+ ['r2', 'Pont nord', ''],
+ ['r3', 'Gare est', 'to check'],
+ ],
+ meta: { version: 1, widths: {}, hidden: [], sort: null, colours: {}, links: {}, frozen: null },
+ stamp: '1000-64',
+ assigned: false,
+};
+
+const get = vi.fn();
+const put = vi.fn(async (_path, body) => ({ status: 'saved', stamp: '2000-64', ...body }));
+const post = vi.fn();
+const patch = vi.fn(async () => ({}));
+const del = vi.fn(async () => ({}));
+vi.mock('../lib/api.js', () => ({ api: { get, put, post, patch, del }, ApiError: Error }));
+
+const toast = vi.fn();
+const uiState = { tool: 'sheet', mapSheetPoints: null, timelineRange: null };
+const reloadCase = vi.fn(async () => {});
+vi.mock('../lib/state.svelte.js', async () => {
+ const { caseState } = await import('../components/views.fixture.svelte.js');
+ return { caseState, toast, uiState, reloadCase };
+});
+vi.mock('../components/EntityDetails.svelte', async () => await import('../components/Modal.svelte'));
+
+const { caseState } = await import('../components/views.fixture.svelte.js');
+const { default: Sheet } = await import('./Sheet.svelte');
+
+let live = null;
+let target = null;
+
+/** Drain the microtask queue and paint. Generously: a press can run through a chain of
+ * awaits — an export flushes a pending save, and that save queues behind whatever write
+ * is already in the air — and a count too tight reads as "the button did nothing". */
+async function settle() {
+ for (let index = 0; index < 12; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+/**
+ * Type into the search box and let the narrowing land.
+ *
+ * What is typed and what the grid is filtered on answer on different clocks: the box has to
+ * echo the keystroke at once and the pass over the rows runs a moment later, so a test that
+ * only drains microtasks reads the table unfiltered.
+ */
+async function typeSearch(term) {
+ const box = target.querySelector('.search input');
+ box.value = term;
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ await new Promise((resolve) => setTimeout(resolve, 220));
+ await settle();
+}
+
+function route(path) {
+ if (path.endsWith('/sheets')) {
+ return Promise.resolve({
+ sheets: [{ id: SHEET.id, title: SHEET.title, path: SHEET.path, rows: 3, columns: 3 }],
+ });
+ }
+ if (path.includes('/sheets/')) return Promise.resolve(structuredClone(SHEET));
+ if (path.includes('/entity-types')) {
+ return Promise.resolve([
+ {
+ type: 'person',
+ label: 'Person',
+ family: 'subject',
+ manual: true,
+ promotable: true,
+ attrs: [{ key: 'role', label: 'Role', kind: 'text' }],
+ },
+ {
+ type: 'organization',
+ label: 'Organization',
+ family: 'subject',
+ manual: true,
+ promotable: true,
+ attrs: [],
+ },
+ {
+ type: 'vehicle',
+ label: 'Vehicle',
+ family: 'subject',
+ manual: true,
+ promotable: true,
+ attrs: [],
+ },
+ {
+ type: 'place',
+ label: 'Place',
+ family: 'place',
+ manual: false,
+ promotable: true,
+ attrs: [],
+ },
+ ]);
+ }
+ if (path.includes('/relation-types')) {
+ return Promise.resolve([
+ {
+ type: 'member-of', label: 'is a member of', inverse_label: 'has member',
+ manual: true, action: 'relation', ratable: true,
+ from_types: ['person'], to_types: ['organization'],
+ },
+ {
+ type: 'associated-with', label: 'is associated with',
+ inverse_label: 'is associated with', manual: true, action: 'relation', ratable: true,
+ from_types: ['person', 'organization'], to_types: ['person', 'organization'],
+ },
+ {
+ type: 'owns', label: 'owns', inverse_label: 'is owned by',
+ manual: true, action: 'relation', ratable: true,
+ from_types: ['person'], to_types: ['vehicle'],
+ },
+ ]);
+ }
+ if (path.includes('/confidence-levels')) {
+ return Promise.resolve([
+ { value: 3, label: 'Certain' },
+ { value: 2, label: 'Probable' },
+ { value: 1, label: 'Possible' },
+ ]);
+ }
+ if (path.includes('/catalog/summary')) {
+ return Promise.resolve({ total: 3, by_type: { person: 2, vehicle: 1 } });
+ }
+ if (path.includes('/catalog/entities')) {
+ const all = [
+ { id: 'e_person', label: 'Witness A', type: 'person', folder: 'witnesses' },
+ { id: 'e_other', label: 'Witness B', type: 'person' },
+ { id: 'e_van', label: 'AB-123', type: 'vehicle' },
+ { id: 'e_late', label: 'Zulu depot', type: 'place' },
+ ];
+ const asked = new URL(path, 'http://x').searchParams;
+ let items = asked.get('type') ? all.filter((i) => i.type === asked.get('type')) : all;
+ if (asked.get('order') === '-label') items = [...items].reverse();
+ // Two per page, so the paging and the count are exercised rather than assumed.
+ const from = Number(asked.get('cursor') ?? 0);
+ const slice = items.slice(from, from + 2);
+ return Promise.resolve({
+ items: slice,
+ total: items.length,
+ next_cursor: from + 2 < items.length ? String(from + 2) : null,
+ });
+ }
+ return Promise.resolve({});
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Sheet, { target });
+ await settle();
+ return target;
+}
+
+/** The rows the sheet actually holds. Not the ghost — the grid always ends on an empty
+ * line that is an offer rather than a row — and not the pinned copy, which is one of
+ * these drawn a second time under the heading. */
+const rows = () => [...target.querySelectorAll('.rows:not(.ghost) .row')];
+const ghostRow = () => target.querySelector('.ghost .row');
+/** Grow the sheet the way the grid offers it: by writing in the empty line it ends on.
+ * There is no button for this any more, which is the point — a footer button for the most
+ * ordinary thing a grid does was a trip to the bottom of the screen and back. */
+const addGhostRow = () => target.querySelector('.ghost .ghost-cell').click();
+const cellsOf = (row) => [...row.querySelectorAll('.cell:not(.gutter) .value')];
+const text = (row) => cellsOf(row).map((cell) => cell.textContent.trim());
+const button = (label) =>
+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));
+/** A button of the confirmation that is open. Scoped to the dialog rather than to the
+ * document: it is portalled onto `body` so it survives a tool going fullscreen, and
+ * its `Delete` and the question bar's `Delete` are two different buttons. */
+const inDialog = (label) =>
+ [...document.querySelectorAll('[role="alertdialog"] button')].find((node) =>
+ node.textContent.trim().startsWith(label),
+ );
+/**
+ * Open a heading's short menu — the frequent gestures — and hand it back.
+ *
+ * The `...` used to open the setup panel straight away. It opens this instead, because
+ * insert, duplicate, rename and split had no door at all while a role editor had one, and
+ * the panel is now this menu's last row.
+ */
+async function headingMenu(columnIndex) {
+ target.querySelectorAll('.heading-menu')[columnIndex].click();
+ await settle();
+ return document.querySelector('.heading-menu[role="menu"]');
+}
+
+/** A row of that menu, by what it says. */
+const inHeadingMenu = (label) =>
+ [...document.querySelectorAll('.heading-menu[role="menu"] button')].find((node) =>
+ node.textContent.trim().startsWith(label),
+ );
+
+/** The setup panel, which is two presses from the heading now: the short menu, then its
+ * last row. Everything the panel used to be reached by goes through here. */
+async function setupOf(columnIndex) {
+ await headingMenu(columnIndex);
+ inHeadingMenu('Set up this column')?.click();
+ await settle();
+ return target.querySelector('.column-panel');
+}
+
+/** Open a column's filter, which lives on its heading's funnel rather than in the
+ * panel: the panel is where a column is set up, the funnel is what is asked of it. */
+async function askOf(columnIndex) {
+ target.querySelectorAll('.heading-filter')[columnIndex].click();
+ await settle();
+ return target.querySelector('.filter-menu');
+}
+/** Press an element the way a browser does: the pointer goes down, then the click lands.
+ * The grid places its cursor on `pointerdown`, because a spreadsheet's selection is a
+ * drag, and `.click()` alone is not what a mouse sends. */
+const press = (node, options = {}) => {
+ node.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, ...options }));
+ node.dispatchEvent(new MouseEvent('click', { bubbles: true, ...options }));
+};
+
+beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Harbour' };
+ caseState.rev = 0;
+ // Every handler the grid puts on `window` fires only while the sheet is the tool on
+ // screen — tools stay mounted and are hidden with CSS, so without that guard a Delete
+ // pressed over the map emptied cells here. The handoffs leave this pointing elsewhere.
+ uiState.tool = 'sheet';
+ uiState.mapSheetPoints = null;
+ uiState.timelineRange = null;
+ get.mockImplementation(route);
+ put.mockClear();
+ post.mockClear();
+ patch.mockClear();
+ toast.mockClear();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ document.body.innerHTML = '';
+ vi.useRealTimers();
+});
+
+describe('opening a sheet', () => {
+ it('draws the case table with its headings', async () => {
+ await open();
+ const headings = [...target.querySelectorAll('.heading-name span')].map((n) => n.textContent);
+ expect(headings).toEqual(['id', 'Subject', 'Status']);
+ expect(rows()).toHaveLength(3);
+ expect(text(rows()[0])).toEqual(['r1', 'Quai sud', 'ruled out']);
+ });
+
+ it('counts what is shown against what the sheet holds', async () => {
+ await open();
+ expect(target.querySelector('.count').textContent.replace(/\s+/g, ' ')).toContain('3 of 3');
+ });
+
+ /**
+ * A cell may say the same thing twice, and the grid draws it.
+ *
+ * Two identical links pasted one after the other, or a word repeated in a column of
+ * words, are ordinary text — and they were fatal: the chips and the links were drawn
+ * from keyed blocks keyed on the value, so the second one aborted the render of the
+ * whole grid. The sheet then stayed on "Opening." on every visit, with nothing wrong
+ * with the file at all.
+ */
+ it('draws a cell that holds the same value twice', async () => {
+ const doubled = {
+ ...structuredClone(SHEET),
+ columns: ['id', 'Sources', 'Status'],
+ rows: [['r1', 'https://x.com/a/1 https://x.com/a/1', 'seen, seen']],
+ meta: {
+ ...structuredClone(SHEET.meta),
+ roles: { Status: { kind: 'choice', values: ['seen'], multi: ',' } },
+ },
+ };
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(structuredClone(doubled))
+ : route(path),
+ );
+ await open();
+
+ expect(rows()).toHaveLength(1);
+ expect(rows()[0].querySelectorAll('.cell-url')).toHaveLength(2);
+ expect(rows()[0].querySelectorAll('.cell-chip')).toHaveLength(2);
+ });
+
+ it('says so when the file on disk carries no key column', async () => {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({ ...structuredClone(SHEET), assigned: true })
+ : route(path),
+ );
+ await open();
+ expect(target.querySelector('.notice')?.textContent).toContain('id');
+ });
+});
+
+describe('the question asked of the rows', () => {
+ it('narrows the table and keeps the denominator', async () => {
+ await open();
+ await typeSearch('gare');
+
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Gare est');
+ expect(target.querySelector('.count').textContent.replace(/\s+/g, ' ')).toContain('1 of 3');
+ });
+
+ it('does not let a letter typed in the search reach the grid', async () => {
+ await open();
+ // A cell is under the cursor, the way it would be after a click.
+ press(target.querySelector('.row .cell:not(.gutter)'));
+ await settle();
+
+ const search = target.querySelector('.search input');
+ search.focus();
+ search.dispatchEvent(new KeyboardEvent('keydown', { key: 'g', bubbles: true }));
+ await settle();
+
+ expect(target.querySelector('.editor')).toBeNull();
+ });
+});
+
+describe('editing a cell', () => {
+ it('writes the table back to the case', async () => {
+ vi.useFakeTimers();
+ await open();
+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];
+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const editor = target.querySelector('.editor');
+ expect(editor).not.toBeNull();
+ editor.value = 'Quai nord';
+ editor.dispatchEvent(new Event('input', { bubbles: true }));
+ editor.dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put).toHaveBeenCalledTimes(1);
+ const [path, body] = put.mock.calls[0];
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet');
+ expect(body.rows[0]).toEqual(['r1', 'Quai nord', 'ruled out']);
+ });
+
+ it('leaves the key column alone', async () => {
+ await open();
+ const key = rows()[0].querySelectorAll('.cell:not(.gutter)')[0];
+ key.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.editor')).toBeNull();
+ });
+});
+
+describe('the cell under the cursor', () => {
+ const bar = () => target.querySelector('.cell-bar-box');
+
+ /** Drawn from the start, and empty. It used to arrive with the cursor, which pushed the
+ * grid down under the pointer mid-click and painted a selection nobody aimed at. */
+ it('is there before a cell is picked, and takes nothing', async () => {
+ await open();
+ expect(bar().disabled).toBe(true);
+ expect(target.querySelector('.cell-bar-where')).toBeNull();
+ });
+
+ it('shows the cell the cursor is on, and says which one', async () => {
+ await open();
+ press(rows()[1].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+
+ expect(bar().value).toBe('Pont nord');
+ expect(target.querySelector('.cell-bar-where').textContent.replace(/\s+/g, ' ').trim())
+ .toBe('2Subject');
+ });
+
+ it('writes the cell and steps down on Enter', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+
+ bar().value = 'Quai nord';
+ bar().dispatchEvent(new Event('input', { bubbles: true }));
+ bar().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put).toHaveBeenCalledTimes(1);
+ expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'Quai nord', 'ruled out']);
+ // The cursor went down a row, and the box came with it.
+ expect(bar().value).toBe('Pont nord');
+ });
+
+ it('lets go of what was typed on Escape', async () => {
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+
+ bar().value = 'Quai nord';
+ bar().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ bar().dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+
+ expect(bar().value).toBe('Quai sud');
+ expect(text(rows()[0])).toEqual(['r1', 'Quai sud', 'ruled out']);
+ });
+
+ /** The blur arrives after the grid has already moved the cursor to the cell that was
+ * clicked, so a draft that only knew its text landed in the wrong row. */
+ it('writes what was typed into the cell it was typed for, not the one clicked next', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+
+ bar().value = 'Quai nord';
+ bar().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ // The pointer lands on another row, and only then does the box let go.
+ press(rows()[2].querySelectorAll('.cell:not(.gutter)')[1]);
+ bar().dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'Quai nord', 'ruled out']);
+ expect(put.mock.calls[0][1].rows[2]).toEqual(['r3', 'Gare est', 'to check']);
+ });
+
+ it('goes back to nothing picked on Escape', async () => {
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+ expect(bar().disabled).toBe(false);
+
+ target.querySelector('.grid').dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),
+ );
+ await settle();
+
+ expect(target.querySelector('.cell.cursor')).toBeNull();
+ expect(bar().disabled).toBe(true);
+ });
+
+ it('refuses the key column, and says why', async () => {
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[0]);
+ await settle();
+
+ expect(bar().readOnly).toBe(true);
+ expect(bar().title).toContain('handle');
+ });
+
+ it('follows the cell editor rather than showing a stale value', async () => {
+ await open();
+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];
+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ await settle();
+
+ const editor = target.querySelector('.editor');
+ editor.value = 'Quai ouest';
+ editor.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+
+ expect(bar().value).toBe('Quai ouest');
+ });
+});
+
+describe('rows and columns', () => {
+ it('appends a row already carrying its key', async () => {
+ vi.useFakeTimers();
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(rows()).toHaveLength(4);
+ expect(put.mock.calls[0][1].rows).toHaveLength(4);
+ expect(put.mock.calls[0][1].rows[3][0]).toMatch(/^r[0-9a-f]{10}$/);
+ });
+
+ it('paints the ticked rows and records the colour beside the table', async () => {
+ vi.useFakeTimers();
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ flushSync();
+
+ target.querySelector('.swatches .c-red').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].meta.colours).toEqual({ r1: 'red' });
+ // A colour is the grid's, not the file's, so it goes down the sidecar's own route and
+ // the CSV is left byte-identical. Rewriting the file to record a paint moved the
+ // modification time the stamp is made of, and the analyst's next save then answered a
+ // conflict nobody caused.
+ expect(put.mock.calls[0][0]).toBe('/api/cases/case-a/sheets/e_sheet/meta');
+ expect(put.mock.calls[0][1].columns).toBeUndefined();
+ expect(put.mock.calls[0][1].rows).toBeUndefined();
+ });
+
+ it('sorts on a heading and puts the sort back on the third click', async () => {
+ await open();
+ const heading = target.querySelectorAll('.heading-name')[2];
+ heading.click();
+ await settle();
+ expect(text(rows()[0])[2]).toBe('ruled out'); // blanks sink, r-uled before t-o check
+
+ heading.click();
+ await settle();
+ expect(text(rows()[0])[2]).toBe('to check');
+
+ heading.click();
+ await settle();
+ expect(text(rows()[0])[0]).toBe('r1'); // back to the file's own order
+ });
+});
+
+describe('a cell pointing at an entity', () => {
+ /** Open the picker on one cell and let its two requests land. */
+ async function pickerOn(rowIndex, columnIndex) {
+ rows()[rowIndex].querySelectorAll('.cell:not(.gutter)')[columnIndex]
+ .querySelector('.cell-link')
+ .click();
+ await vi.advanceTimersByTimeAsync(0);
+ flushSync();
+ }
+
+ it('leads with what the case holds, per type, before a key is pressed', async () => {
+ // The analyst usually does not know the label: the cell says `3rd Bde` and the
+ // case holds `3rd Separate Brigade`. A bare search bar only works when you
+ // already know the answer, so the counts come first.
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2); // an empty cell: nothing to seed the box with
+
+ const chips = [...document.querySelectorAll('.picker .types .chip')].map((chip) =>
+ chip.textContent.replace(/\s+/g, ' ').trim(),
+ );
+ expect(chips).toEqual(['Everything 3', 'person 2', 'vehicle 1']);
+ expect([...document.querySelectorAll('.picker .result .label')].map((n) => n.textContent))
+ .toEqual(['Witness A', 'Witness B']);
+ });
+
+ it('says how much of the answer is on screen, and loads the rest', async () => {
+ // A list silently cut at its first page reads as "that is all there is".
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+
+ expect(document.querySelector('.picker .shown').textContent.replace(/\s+/g, ' ').trim())
+ .toBe('2 of 4 shown');
+
+ const more = document.querySelector('.picker .more');
+ expect(more.textContent.trim()).toBe('Load 2 more');
+ more.click();
+ await vi.advanceTimersByTimeAsync(0);
+ flushSync();
+
+ expect([...document.querySelectorAll('.picker .result .label')].map((n) => n.textContent))
+ .toEqual(['Witness A', 'Witness B', 'AB-123', 'Zulu depot']);
+ expect(document.querySelector('.picker .more')).toBeNull();
+ });
+
+ it('orders the whole matching set, not the page already loaded', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+
+ [...document.querySelectorAll('.picker .order')]
+ .find((node) => node.textContent.trim() === 'Z→A')
+ .click();
+ await vi.advanceTimersByTimeAsync(0);
+ flushSync();
+
+ // Reversed on the server across all four, so the first page changes entirely —
+ // which a client-side sort of the loaded two could not do.
+ expect([...document.querySelectorAll('.picker .result .label')].map((n) => n.textContent))
+ .toEqual(['Zulu depot', 'AB-123']);
+ });
+
+ it('narrows to one type on a click', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+
+ [...document.querySelectorAll('.picker .types .chip')]
+ .find((chip) => chip.textContent.includes('vehicle'))
+ .click();
+ await vi.advanceTimersByTimeAsync(0);
+ flushSync();
+
+ expect([...document.querySelectorAll('.picker .result .label')].map((n) => n.textContent))
+ .toEqual(['AB-123']);
+ });
+
+ it('picks with the keyboard, without reaching for the mouse', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+
+ const box = document.querySelector('.picker input');
+ box.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
+ flushSync();
+ box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].meta.links).toEqual({ r2: { Status: 'e_other' } });
+ });
+
+ it('marks the entity the cell already points at', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+ document.querySelectorAll('.picker .result')[0].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await pickerOn(1, 2);
+ expect(document.querySelector('.picker .result.linked .label').textContent).toBe('Witness A');
+ // The modal mounts on the body, so this one is not reachable through `target`.
+ const clear = [...document.querySelectorAll('.picker button')].find(
+ (node) => node.textContent.trim() === 'Clear the link',
+ );
+ expect(clear).not.toBeUndefined();
+ });
+
+ it('records the link and names the entity in the file', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 1);
+
+ const result = [...document.querySelectorAll('.picker .result')][0];
+ expect(result.textContent).toContain('Witness A');
+ result.click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const body = put.mock.calls[0][1];
+ expect(body.meta.links).toEqual({ r2: { Subject: 'e_person' } });
+ // The cell already held "Pont nord", so the link does not overwrite it.
+ expect(body.rows[1][1]).toBe('Pont nord');
+ });
+
+ it('fills an empty cell with the entity name, so the CSV still says it', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 2);
+
+ [...document.querySelectorAll('.picker .result')][0].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[1][2]).toBe('Witness A');
+ });
+
+ it('drops the link when the cell that held it is emptied', async () => {
+ // A blank cell still holding a link is a link nobody can see, reach or clear — and it
+ // would keep its `mentions` edge on every save, so the case would go on believing a
+ // row that says nothing.
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 1);
+ [...document.querySelectorAll('.picker .result')][0].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].meta.links).toEqual({ r2: { Subject: 'e_person' } });
+
+ press(rows()[1].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const body = put.mock.calls.at(-1)[1];
+ expect(body.rows[1][1]).toBe('');
+ expect(body.meta.links).toEqual({});
+ });
+
+ it('lets go of a link the case has deleted, without saving anything', async () => {
+ // the link is an id in the sidecar, so the delete elsewhere cannot reach the copy on
+ // screen: the cell kept a live-looking link, and the next save wrote the dead id back
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ meta: { ...SHEET.meta, links: { r1: { Subject: 'e_gone' }, r2: { Subject: 'e_kept' } } },
+ })
+ : route(path),
+ );
+ post.mockResolvedValueOnce({ missing: ['e_gone'] });
+ await open();
+ const mark = (index) =>
+ rows()[index].querySelectorAll('.cell:not(.gutter)')[1].querySelector('.link-mark');
+ expect(mark(0)).not.toBeNull();
+
+ caseState.rev += 1; // something was deleted on another screen
+ await settle();
+
+ expect(post).toHaveBeenCalledWith('/api/cases/case-a/entities/missing', {
+ ids: ['e_gone', 'e_kept'],
+ });
+ expect(mark(0)).toBeNull();
+ expect(mark(1)).not.toBeNull(); // the live one is untouched
+ expect(toast).toHaveBeenCalledWith('Dropped 1 link to deleted items', 'info');
+ // the file was cleared by the delete itself, so the screen has nothing to write back
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it('asks nothing of a case change when the sheet points at nobody', async () => {
+ await open();
+ caseState.rev += 1;
+ await settle();
+
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('opens the entity a cell points at', async () => {
+ vi.useFakeTimers();
+ await open();
+ await pickerOn(1, 1);
+ [...document.querySelectorAll('.picker .result')][0].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const mark = rows()[1].querySelectorAll('.cell:not(.gutter)')[1].querySelector('.link-mark');
+ expect(mark).not.toBeNull();
+ mark.click();
+ await vi.advanceTimersByTimeAsync(0);
+ flushSync();
+
+ // The assertion is the wrapper, not the panel: EntityDetails is panel content with
+ // no chrome of its own, and hosting it bare rendered it into nowhere — the mark
+ // appeared to do nothing at all. Board and Timeline both wrap it in a Modal.
+ const dialogs = [...document.querySelectorAll('[role="dialog"]')];
+ expect(dialogs.some((node) => node.getAttribute('aria-label') === 'Details')).toBe(true);
+ });
+});
+
+describe('backing out of what is open over the grid', () => {
+ // A menu left open by a stray click is the most common way to be stuck in a grid,
+ // so every popover answers Escape and a click beside it.
+ const open_ = (label) => {
+ button(label).click();
+ flushSync();
+ };
+
+ it('closes the column panel on Escape', async () => {
+ await open();
+ await setupOf(1);
+ expect(target.querySelector('.column-panel')).not.toBeNull();
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.column-panel')).toBeNull();
+ });
+
+ it('leaves the column panel open when the pointer lands in the grid', async () => {
+ // A panel is not a popover: working on a column means clicking cells of it, and a
+ // panel that closed on the first of those would be unusable.
+ await open();
+ await setupOf(1);
+
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ await settle();
+ expect(target.querySelector('.column-panel')).not.toBeNull();
+ });
+
+ it('follows the next heading rather than closing, and closes on its own', async () => {
+ // The one thing the panel does that the menu could not: six roles are six clicks.
+ await open();
+ await setupOf(1);
+ expect(target.querySelector('.column-panel .name').value).toBe('Subject');
+
+ await setupOf(2);
+ expect(target.querySelector('.column-panel .name').value).toBe('Status');
+
+ target.querySelector('.column-panel header .btn-ghost').click();
+ await settle();
+ expect(target.querySelector('.column-panel')).toBeNull();
+ });
+
+ it('deletes a column from its heading, from the grid and from the file', async () => {
+ // Pressed rather than called: the button is what was broken once, and the logic under
+ // it was green the whole time. A test that calls `removeColumn` proves the arithmetic
+ // and nothing about the button that never reached it.
+ vi.useFakeTimers();
+ await open();
+ await setupOf(2);
+ expect(target.querySelector('.column-panel .name').value).toBe('Status');
+
+ await headingMenu(2);
+ inHeadingMenu('Delete this column').click();
+ await settle();
+ // A column carries a role, a note and a width nothing else remembers, so the
+ // click is confirmed before the cells go.
+ expect(document.querySelector('[role="alertdialog"]').textContent).toContain('Status');
+ inDialog('Delete the column').click();
+ await settle();
+
+ expect([...target.querySelectorAll('.heading-name span')].map((n) => n.textContent)).toEqual([
+ 'id',
+ 'Subject',
+ ]);
+ expect(target.querySelector('.column-panel')).toBeNull();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].columns).toEqual(['id', 'Subject']);
+ expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'Quai sud']);
+ });
+
+ it('takes the deleted column out of what the sidecar remembers', async () => {
+ vi.useFakeTimers();
+ await open();
+ // A width on the doomed column, so the sidecar has something to lose with it.
+ await headingMenu(2);
+ inHeadingMenu('Delete this column').click();
+ await settle();
+ inDialog('Delete the column').click();
+ await settle();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(Object.keys(put.mock.calls[0][1].meta.widths)).not.toContain('Status');
+ expect(put.mock.calls[0][1].meta.roles?.Status).toBeUndefined();
+ });
+
+ it('gives the right slot to one panel at a time', async () => {
+ await open();
+ rows()[0].querySelector('.cell-open').click();
+ await settle();
+ expect(target.querySelector('.panel')).not.toBeNull();
+ expect(target.querySelector('.column-panel')).toBeNull();
+
+ await setupOf(1);
+ expect(target.querySelector('.column-panel')).not.toBeNull();
+ expect(target.querySelectorAll('.panel')).toHaveLength(1);
+ });
+
+ it('closes the columns menu and the sheet list the same way', async () => {
+ await open();
+ open_('Columns');
+ expect(target.querySelector('.columns-menu')).not.toBeNull();
+ document.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ await settle();
+ expect(target.querySelector('.columns-menu')).toBeNull();
+
+ open_('1 sheet');
+ expect(target.querySelector('.sheet-menu')).not.toBeNull();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.sheet-menu')).toBeNull();
+ });
+
+ it('closes the fill bar and the row panel on Escape', async () => {
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ await settle();
+ open_('Fill a column');
+ expect(target.querySelector('.fill-bar')).not.toBeNull();
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.fill-bar')).toBeNull();
+
+ rows()[0].querySelector('.cell-open').click();
+ await settle();
+ expect(target.querySelector('.panel')).not.toBeNull();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.panel')).toBeNull();
+ });
+
+ it('leaves Escape to the cell editor while a cell is being typed in', async () => {
+ await open();
+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[1];
+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ await settle();
+ expect(target.querySelector('.editor')).not.toBeNull();
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.editor')).toBeNull();
+ });
+});
+
+describe('two writers on one file', () => {
+ // The premise is that the file is the artifact, so the analyst may have it open in
+ // a spreadsheet too. The grid must not win a race it cannot see.
+ it('presents the stamp it read, so the server can refuse a stale save', async () => {
+ vi.useFakeTimers();
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].stamp).toBe('1000-64');
+ });
+
+ it('asks rather than overwriting when the file has moved on', async () => {
+ vi.useFakeTimers();
+ const conflict = Object.assign(new Error('this file changed on disk'), { status: 409 });
+ put.mockRejectedValueOnce(conflict);
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const notice = target.querySelector('.notice.danger');
+ expect(notice.textContent).toContain('changed on disk');
+ // The banner says it, once. A toast on top would say the same thing and vanish.
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it('writes nothing more until the analyst has answered', async () => {
+ vi.useFakeTimers();
+ put.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }));
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put).toHaveBeenCalledTimes(1);
+
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(put).toHaveBeenCalledTimes(1);
+ });
+
+ it('reloads the file and loses the grid version of it', async () => {
+ vi.useFakeTimers();
+ put.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }));
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({ ...structuredClone(SHEET), stamp: '9000-70' })
+ : route(path),
+ );
+ // Asked first: this drops the analyst's own unsaved row, and the undo stack with it.
+ button('Reload').click();
+ flushSync();
+ inDialog('Reload').click();
+ await vi.advanceTimersByTimeAsync(10);
+ flushSync();
+
+ expect(rows()).toHaveLength(3); // the appended row is gone
+ expect(target.querySelector('.notice.danger')).toBeNull();
+ });
+
+ it('does not ask before reading a file that costs the grid nothing', async () => {
+ vi.useFakeTimers();
+ await open();
+ // The soft banner: the file moved on, nothing was refused and nothing is unsaved.
+ get.mockImplementation((path) =>
+ path.endsWith('/stamp')
+ ? Promise.resolve({ stamp: '9000-70' })
+ : path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({ ...structuredClone(SHEET), stamp: '9000-70' })
+ : route(path),
+ );
+ window.dispatchEvent(new Event('focus'));
+ await vi.advanceTimersByTimeAsync(10);
+ flushSync();
+
+ button('Reload').click();
+ await vi.advanceTimersByTimeAsync(10);
+ flushSync();
+
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(target.querySelector('.notice')).toBeNull();
+ });
+
+ it('overwrites on request, by sending no stamp at all', async () => {
+ vi.useFakeTimers();
+ put.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }));
+ await open();
+ addGhostRow();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // Asked first: this drops whatever a colleague or a spreadsheet wrote.
+ button('Overwrite').click();
+ flushSync();
+ inDialog('Overwrite').click();
+ await vi.advanceTimersByTimeAsync(10);
+ flushSync();
+
+ expect(put.mock.calls[1][1].stamp).toBeUndefined();
+ expect(target.querySelector('.notice.danger')).toBeNull();
+ });
+});
+
+describe('the clipboard', () => {
+ function pasteInto(text) {
+ const event = new Event('paste', { bubbles: true, cancelable: true });
+ event.clipboardData = { getData: () => text };
+ window.dispatchEvent(event);
+ flushSync();
+ }
+
+ it('lands a block of cells where the cursor is', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+
+ pasteInto('Quai nord\tconfirmed\nPont sud\tto check');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const body = put.mock.calls[0][1];
+ expect(body.rows[0]).toEqual(['r1', 'Quai nord', 'confirmed']);
+ expect(body.rows[1]).toEqual(['r2', 'Pont sud', 'to check']);
+ });
+
+ it('turns a wall of links into one row per link', async () => {
+ // The "to be sorted" inbox every field binder keeps, in one gesture.
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+
+ pasteInto('https://a.example/one\nhttps://b.example/two\nhttps://c.example/three');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows.map((row) => row[1])).toEqual([
+ 'https://a.example/one',
+ 'https://b.example/two',
+ 'https://c.example/three',
+ ]);
+ });
+
+ it('grows the sheet when the links outnumber the rows', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[2].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+
+ pasteInto('https://a.example/one\nhttps://b.example/two\nhttps://c.example/three');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const body = put.mock.calls[0][1];
+ expect(body.rows).toHaveLength(5);
+ expect(body.rows[4][1]).toBe('https://c.example/three');
+ expect(body.rows[4][0]).toMatch(/^r[0-9a-f]{10}$/);
+ });
+
+ it('says so when a pasted block was wider than the sheet', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[2]);
+ flushSync();
+
+ pasteInto('a\tb\tc');
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(toast).toHaveBeenCalledWith(expect.stringContaining('did not fit'));
+ });
+
+ it('leaves a paste into the search box to the search box', async () => {
+ vi.useFakeTimers();
+ await open();
+ const search = target.querySelector('.search input');
+ search.focus();
+ const event = new Event('paste', { bubbles: true, cancelable: true });
+ event.clipboardData = { getData: () => 'a\tb' };
+ search.dispatchEvent(event);
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put).not.toHaveBeenCalled();
+ });
+
+ it('pulls a selection across the cells the pointer passes, as a spreadsheet does', async () => {
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync(); // a browser paints between the press and the first move
+ // Held, and dragged across to a far corner without releasing.
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new PointerEvent('pointerenter', { bubbles: true }));
+ await settle();
+ document.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }));
+ await settle();
+
+ expect(target.querySelector('.foot').textContent).toContain('2 × 2 selected');
+ // Released, so passing over another cell no longer extends it.
+ rows()[2]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new PointerEvent('pointerenter', { bubbles: true }));
+ await settle();
+ expect(target.querySelector('.foot').textContent).toContain('2 × 2 selected');
+ });
+
+ it('lands a block on the rows the search left on screen', async () => {
+ // Copied off a narrowed screen, pasted back onto it. Walking the file instead would
+ // write the block into rows the analyst filtered away and cannot watch it land on.
+ vi.useFakeTimers();
+ await open();
+ const box = target.querySelector('.search input');
+ box.value = 'e';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(250);
+ flushSync();
+ // 'Quai sud' (ruled out) and 'Gare est' match; the row between them is off the
+ // screen, and it is the one a paste that walked the file would have written.
+ expect(rows()).toHaveLength(2);
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+
+ pasteInto('one\ntwo');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows.map((row) => row[1])).toEqual(['one', 'Pont nord', 'two']);
+ });
+
+ it('copies an empty rectangle as empty, rather than leaving an older clipboard in place', async () => {
+ // The grid is not selectable text, so a copy the tool declines is a copy nobody
+ // makes: the keystroke looked like it worked and the next paste brought back
+ // whatever had been copied before it.
+ await open();
+ press(rows()[1].querySelectorAll('.cell:not(.gutter)')[2]);
+ flushSync();
+
+ let written = null;
+ const event = new Event('copy', { bubbles: true, cancelable: true });
+ event.clipboardData = { setData: (_type, value) => (written = value) };
+ window.dispatchEvent(event);
+
+ expect(written).toBe('');
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('copies the selected range as a block a spreadsheet reads back', async () => {
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[1]);
+ flushSync();
+ // Shift-click the far corner: two rows by two columns.
+ press(rows()[1].querySelectorAll('.cell:not(.gutter)')[2], { shiftKey: true });
+ flushSync();
+
+ let written = null;
+ const event = new Event('copy', { bubbles: true, cancelable: true });
+ event.clipboardData = { setData: (_type, value) => (written = value) };
+ window.dispatchEvent(event);
+
+ expect(written).toBe('Quai sud\truled out\nPont nord\t');
+ });
+});
+
+describe('the bars around the grid', () => {
+ it('keeps the ways of starting a sheet under one button', async () => {
+ // Five buttons in a header that also carries a title, a subtitle, the sheet list, an
+ // export and a delete ran off the edge of a laptop screen. They are asked once per
+ // sheet; the grid's own controls are asked all day.
+ await open();
+ expect(button('Import a file')).toBeUndefined();
+ button('New').click();
+ await settle();
+
+ const rows_ = [...target.querySelectorAll('.new-menu .menu-row')].map((node) =>
+ node.textContent.trim(),
+ );
+ expect(rows_).toEqual([
+ 'Blank sheet',
+ 'Import a file',
+ 'Paste a table',
+ 'From the case',
+ 'Add rows to this sheet',
+ ]);
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(target.querySelector('.new-menu')).toBeNull();
+ });
+
+ it('draws what the chosen rows can do over the grid, not in the question bar', async () => {
+ // In the question bar these ten controls wrapped it onto a second line, which pushed
+ // the table down a row height under the pointer that had just ticked the row.
+ await open();
+ expect(target.querySelector('.selection')).toBeNull();
+ rows()[0].querySelector('.gutter input').click();
+ await settle();
+
+ const bar = target.querySelector('.selection');
+ expect(bar).not.toBeNull();
+ expect(bar.closest('.grid-wrap')).not.toBeNull();
+ expect(target.querySelector('.question').textContent).not.toContain('Promote');
+ });
+
+ it('drops the selection from the bar, the way Escape does', async () => {
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ rows()[1].querySelector('.gutter input').click();
+ await settle();
+ expect(target.querySelector('.selection .count').textContent).toContain('2 ticked');
+
+ target.querySelector('[aria-label="Drop the selection"]').click();
+ await settle();
+ expect(target.querySelector('.selection')).toBeNull();
+ expect(target.querySelectorAll('.row.ticked')).toHaveLength(0);
+ });
+});
+
+describe('working on many rows at once', () => {
+ it('ticks everything shown, and only what is shown', async () => {
+ await open();
+ await typeSearch('quai');
+
+ target.querySelector('.head .gutter input').click();
+ await settle();
+ expect(target.querySelector('.question .count').textContent).toContain('1 of 3');
+ expect(target.querySelector('.selection .count').textContent).toContain('1 ticked');
+ });
+
+ it('ticks a range on shift-click, in the order the grid draws', async () => {
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ flushSync();
+ rows()[2].querySelector('.gutter input').dispatchEvent(
+ new MouseEvent('click', { bubbles: true, shiftKey: true }),
+ );
+ await settle();
+
+ expect(target.querySelector('.selection .count').textContent).toContain('3 ticked');
+ });
+
+ it('fills one column for every ticked row, as one step', async () => {
+ vi.useFakeTimers();
+ await open();
+ target.querySelector('.head .gutter input').click();
+ flushSync();
+ button('Fill a column').click();
+ flushSync();
+
+ [...target.querySelectorAll('.fill-columns .chip')]
+ .find((chip) => chip.textContent.trim() === 'Status')
+ .click();
+ flushSync();
+ const value = target.querySelector('.fill-bar input');
+ value.value = 'geolocated';
+ value.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ target.querySelector('.fill-bar .btn-primary').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows.map((row) => row[2])).toEqual([
+ 'geolocated',
+ 'geolocated',
+ 'geolocated',
+ ]);
+ });
+
+ it('says how many rows are about to go before they go', async () => {
+ vi.useFakeTimers();
+ await open();
+ target.querySelector('.head .gutter input').click();
+ flushSync();
+ button('Delete').click();
+ await settle();
+
+ expect(document.querySelector('[role="alertdialog"]').textContent).toContain('Delete 3 rows');
+ expect(rows()).toHaveLength(3);
+
+ inDialog('Cancel').click();
+ await settle();
+ expect(rows()).toHaveLength(3);
+ });
+
+ it('deletes them once the count has been read', async () => {
+ vi.useFakeTimers();
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ flushSync();
+ button('Delete').click();
+ await settle();
+ inDialog('Delete').click();
+ await settle();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(rows()).toHaveLength(2);
+ expect(put.mock.calls[0][1].rows.map((row) => row[0])).toEqual(['r2', 'r3']);
+ });
+
+ it('copies a cell down the selection and walks the whole run back at once', async () => {
+ vi.useFakeTimers();
+ await open();
+ press(rows()[0].querySelectorAll('.cell:not(.gutter)')[2]);
+ flushSync();
+ press(rows()[2].querySelectorAll('.cell:not(.gutter)')[2], { shiftKey: true });
+ flushSync();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'd', ctrlKey: true, bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows.map((row) => row[2])).toEqual([
+ 'ruled out',
+ 'ruled out',
+ 'ruled out',
+ ]);
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'z', ctrlKey: true, bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[1][1].rows.map((row) => row[2])).toEqual([
+ 'ruled out',
+ '',
+ 'to check',
+ ]);
+ });
+});
+
+describe('reading the table', () => {
+ it('opens a link in a cell instead of showing a hundred characters of it', async () => {
+ get.mockImplementation((path) => {
+ if (path.includes('/sheets/') && !path.endsWith('/sheets')) {
+ const sheet = structuredClone(SHEET);
+ sheet.rows[0][1] = 'https://t.me/channel/1234?single';
+ return Promise.resolve(sheet);
+ }
+ return route(path);
+ });
+ await open();
+ const link = rows()[0].querySelector('.cell-url');
+ expect(link.getAttribute('href')).toBe('https://t.me/channel/1234?single');
+ expect(link.textContent.trim()).toBe('t.me/…');
+ });
+
+ it('reads one row down a panel, because fourteen columns do not read across', async () => {
+ await open();
+ rows()[1].querySelector('.cell-open').click();
+ await settle();
+
+ const panel = target.querySelector('.panel');
+ expect(panel).not.toBeNull();
+ expect([...panel.querySelectorAll('.label span')].map((n) => n.textContent)).toEqual([
+ 'id',
+ 'Subject',
+ 'Status',
+ ]);
+ expect(panel.querySelector('.progress').textContent).toContain('1 of 2 filled');
+ });
+
+ it('writes an edit made in the panel back to the file', async () => {
+ vi.useFakeTimers();
+ await open();
+ rows()[1].querySelector('.cell-open').click();
+ flushSync();
+
+ // The key column is read-only in the panel, so the boxes are Subject then Status.
+ const field = [...target.querySelectorAll('.panel textarea')][0];
+ field.value = 'Pont sud';
+ field.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[1][1]).toBe('Pont sud');
+ });
+
+ it('narrows on what a column does not hold, which no list of values can do', async () => {
+ await open();
+ const menu = await askOf(1);
+
+ // Holding, then Without: the two halves of one question, in that order.
+ const without = [...menu.querySelectorAll('.field input')][1];
+ without.value = 'ruled';
+ without.dispatchEvent(new Event('input', { bubbles: true }));
+ without.dispatchEvent(new Event('blur', { bubbles: true }));
+ await settle();
+
+ expect(rows()).toHaveLength(2);
+ expect(target.querySelector('.question .chip').textContent).toContain('without ruled');
+ });
+
+ it('narrows on a word a column must hold, which is all a prose column offers', async () => {
+ await open();
+ const menu = await askOf(1);
+
+ const holding = [...menu.querySelectorAll('.field input')][0];
+ holding.value = 'ruled';
+ holding.dispatchEvent(new Event('input', { bubbles: true }));
+ holding.dispatchEvent(new Event('blur', { bubbles: true }));
+ await settle();
+
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Quai sud');
+ expect(target.querySelector('.question .chip').textContent).toContain('with ruled');
+ });
+
+ it('narrows on the rows with nothing in a column yet', async () => {
+ await open();
+ await askOf(1);
+ button('Empty').click();
+ await settle();
+
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Pont nord');
+ });
+
+ it('keeps the funnel lit on a column that is being asked something', async () => {
+ await open();
+ await askOf(1);
+ button('Empty').click();
+ await settle();
+
+ const funnels = [...target.querySelectorAll('.heading-filter')];
+ expect(funnels[1].classList.contains('asking')).toBe(true);
+ expect(funnels[0].classList.contains('asking')).toBe(false);
+ });
+
+ it('filters on the value under the pointer, from the cell itself', async () => {
+ await open();
+ const cell = [...rows()[0].querySelectorAll('.cell:not(.gutter)')][2];
+ cell.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 40, clientY: 60 }));
+ await settle();
+
+ button('Only “ruled out”').click();
+ await settle();
+
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Quai sud');
+ expect(target.querySelector('.cell-menu')).toBeNull();
+ });
+
+ it('offers the empty rows when the cell right-clicked holds nothing', async () => {
+ await open();
+ const cell = [...rows()[1].querySelectorAll('.cell:not(.gutter)')][2];
+ cell.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 40, clientY: 60 }));
+ await settle();
+
+ button('Only the empty ones').click();
+ await settle();
+
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Pont nord');
+ });
+
+ it('says what is asked of a column in the panel, without offering it twice', async () => {
+ await open();
+ await askOf(1);
+ button('Empty').click();
+ await settle();
+ await setupOf(2);
+
+ const panel = target.querySelector('.column-panel');
+ expect(panel.querySelector('.asked').textContent).toContain('empty');
+ // The filter is set on the heading and nowhere else: two places to ask one
+ // question is what splitting the two doors was for.
+ expect([...panel.querySelectorAll('button')].map((n) => n.textContent.trim())).not.toContain(
+ 'Empty',
+ );
+
+ panel.querySelector('.asked .clear').click();
+ await settle();
+ expect(rows()).toHaveLength(3);
+ });
+
+ it('keeps a chosen column in view and records it beside the table', async () => {
+ vi.useFakeTimers();
+ await open();
+ await headingMenu(1);
+ inHeadingMenu('Keep it in view').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].meta.frozen).toBe('Subject');
+ // The key column sticks at the gutter, the chosen one just past it.
+ const sticky = [...rows()[0].querySelectorAll('.cell.sticky')];
+ expect(sticky.map((cell) => cell.style.left)).toEqual(['34px', '194px']);
+ });
+
+ it('moves a column in the file, where a collaborator will see it', async () => {
+ vi.useFakeTimers();
+ await open();
+ const headings = [...target.querySelectorAll('.head .heading')];
+ headings[2].querySelector('.grip').dispatchEvent(
+ new PointerEvent('pointerdown', { bubbles: true }),
+ );
+ flushSync();
+ expect(target.querySelectorAll('.heading.dragged')).toHaveLength(1);
+
+ headings[1].dispatchEvent(new PointerEvent('pointerenter', { bubbles: true }));
+ flushSync();
+ expect(target.querySelectorAll('.heading.target')).toHaveLength(1);
+
+ document.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].columns).toEqual(['id', 'Status', 'Subject']);
+ expect(put.mock.calls[0][1].rows[0]).toEqual(['r1', 'ruled out', 'Quai sud']);
+ });
+
+ it('reaches the search from the grid, and adds a row from anywhere', async () => {
+ vi.useFakeTimers();
+ await open();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'f', ctrlKey: true, bubbles: true }));
+ flushSync();
+ expect(document.activeElement).toBe(target.querySelector('.search input'));
+
+ window.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Enter', ctrlKey: true, bubbles: true }),
+ );
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows).toHaveLength(4);
+ });
+});
+
+describe('a column that knows what it holds', () => {
+ /** A sheet shaped like the binders: a status, a coordinate column half filled, a date
+ * written the European way, and a list of equipment with a quantity in it. */
+ const BINDER = {
+ ...SHEET,
+ columns: ['id', 'Title', 'Status', 'Coordinates', 'Date', 'Equipments'],
+ rows: [
+ ['r1', 'Quai sud', 'done', '48.85660, 2.35220', '31/01/2026', 'Buk-M2E, 2x S-125'],
+ ['r2', 'Pont nord', '', '', '01/02/2026', ''],
+ ['r3', 'Gare est', 'OK en cours', '48.85, 2.35', 'AFTER', 'ZU23-2'],
+ ],
+ meta: {
+ version: 2,
+ widths: {},
+ hidden: [],
+ sort: null,
+ colours: {},
+ links: {},
+ frozen: null,
+ roles: {
+ Status: { kind: 'state', values: ['to do', 'in progress', 'done'] },
+ Coordinates: { kind: 'latlon' },
+ Date: { kind: 'when', shape: 'date', dayFirst: true },
+ Equipments: { kind: 'choice', multi: ', ' },
+ },
+ notes: {},
+ progress: 'Coordinates',
+ },
+ };
+
+ async function openBinder(overrides = {}) {
+ const sheet = { ...structuredClone(BINDER), ...overrides };
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(sheet)
+ : route(path),
+ );
+ await open();
+ }
+
+ const chipsIn = (row, columnIndex) =>
+ [...row.querySelectorAll('.cell:not(.gutter)')[columnIndex].querySelectorAll('.cell-chip')].map(
+ (chip) => chip.textContent.replace(/\s+/g, ' ').trim(),
+ );
+
+ it('draws a set of values as one chip per value', async () => {
+ await openBinder();
+ // The cell's own words, each one a chip. Reading `2x S-125` as two of `S-125` was a
+ // count kept in a column of values, and a count belongs in a number column.
+ expect(chipsIn(rows()[0], 5)).toEqual(['Buk-M2E', '2x S-125']);
+ // A state column is a set of values too, so it draws the same way.
+ expect(chipsIn(rows()[0], 2)).toEqual(['done']);
+ });
+
+ it('marks a value outside the column own words without hiding it', async () => {
+ // The binders write outside their vocabulary on every page. A lens that hid that
+ // would hide the work.
+ await openBinder();
+ const chip = rows()[2].querySelector('.cell-chip');
+ expect(chip.textContent.trim()).toBe('OK en cours');
+ expect(chip.classList.contains('unknown')).toBe(true);
+ });
+
+ it('filters on a chip when it is clicked', async () => {
+ await openBinder();
+ rows()[0].querySelectorAll('.cell-chip')[0].click();
+ await settle();
+ expect(rows()).toHaveLength(1);
+ });
+
+ it('says when a point claims less than it looks like it claims', async () => {
+ // `48.85, 2.35` is a kilometre, not a building, and it looks identical to an address
+ // until the badge is there.
+ await openBinder();
+ expect(rows()[0].querySelector('.badge')).toBeNull();
+ expect(rows()[2].querySelector('.badge').textContent.trim()).toBe('±1113m');
+ });
+
+ it('sorts a European date by the date, not by the characters', async () => {
+ await openBinder();
+ target.querySelectorAll('.heading-name')[4].click();
+ await settle();
+ expect(text(rows()[0])[4]).toBe('31/01/2026');
+ // The cell the role cannot read goes last, not into the middle of January.
+ expect(text(rows().at(-1))[4]).toBe('AFTER');
+ });
+
+ it('counts progress off the column the sheet says carries it', async () => {
+ await openBinder();
+ const foot = target.querySelector('.foot .progress').textContent.replace(/\s+/g, ' ');
+ expect(foot).toContain('Coordinates');
+ expect(foot).toContain('2 filled');
+ expect(foot).toContain('1 left');
+ });
+
+ it('opens on every row, and the rows left are one click and never a surprise', async () => {
+ // A filter was once posted on open, off the progress column's empty rows. It could not
+ // tell "the analyst cleared their filters" from "this sheet has never been asked
+ // anything" — both are an empty table in the sidecar — so it came back on every
+ // reopen, which reads as a filter appearing from nowhere. The footer was already
+ // offering exactly those rows, named and asked for.
+ const sheet = structuredClone(BINDER);
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(sheet)
+ : route(path),
+ );
+ await open();
+
+ expect(rows()).toHaveLength(3);
+ expect(target.querySelector('.question .chip')).toBeNull();
+
+ target.querySelector('.foot .progress-left').click();
+ await settle();
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Pont nord');
+ const chip = target.querySelector('.question .chip');
+ expect(chip.textContent.replace(/\s+/g, ' ')).toContain('Coordinates empty');
+ });
+
+ it('counts a state column by its buckets when that is the progress column', async () => {
+ await openBinder({
+ meta: { ...structuredClone(BINDER.meta), progress: 'Status' },
+ });
+ const foot = target.querySelector('.foot .progress').textContent.replace(/\s+/g, ' ');
+ expect(foot).toContain('1 done');
+ expect(foot).toContain('1 other'); // `OK en cours` is outside the vocabulary
+ expect(foot).toContain('1 empty');
+ });
+
+ it('offers a progress column when the sheet names none, without applying it', async () => {
+ // A declared status column is what it offers first; the emptiest column is the
+ // fallback for the binder that has no status at all.
+ await openBinder({ meta: { ...structuredClone(BINDER.meta), progress: null } });
+ const offer = target.querySelector('.suggest-progress');
+ expect(offer.textContent).toContain('Status');
+ expect(rows()).toHaveLength(3); // nothing filtered until it is accepted
+
+ offer.click();
+ await settle();
+ expect(target.querySelector('.foot .progress')).not.toBeNull();
+ });
+
+ it('refuses to open an editor on a column the app writes', async () => {
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { ...BINDER.meta.roles, Title: { kind: 'computed', of: 'has_point' } },
+ },
+ });
+ rows()[0]
+ .querySelectorAll('.cell:not(.gutter)')[1]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ await settle();
+ expect(target.querySelector('.editor')).toBeNull();
+ });
+
+ it('says so when a role lost the column it named', async () => {
+ // Renaming a column in a spreadsheet takes its role — and its map layer — with it.
+ await openBinder({ dropped_roles: ['Coordinates'] });
+ expect(target.querySelector('.notice').textContent).toContain('Coordinates');
+ });
+
+ it('hands a column of points to the map, and only the readable ones', async () => {
+ await openBinder();
+ await setupOf(3);
+ button('Show on the map').click();
+ await settle();
+
+ expect(uiState.mapSheetPoints.points).toHaveLength(2);
+ expect(uiState.mapSheetPoints.column).toBe('Coordinates');
+ expect(uiState.mapSheetPoints.points[0]).toMatchObject({ lat: 48.8566, label: 'Quai sud' });
+ expect(uiState.tool).toBe('satellite');
+ });
+
+ it('sends one cell to the map from the row being read, and offers nothing on a cell it cannot read', async () => {
+ await openBinder();
+ uiState.mapSheetPoints = null;
+ const mapButton = (row) =>
+ row.querySelectorAll('.cell:not(.gutter)')[3].querySelector('.cell-map');
+ // Nothing to see: the cell is empty, so the grid offers no map to see it on.
+ expect(mapButton(rows()[1])).toBeNull();
+
+ mapButton(rows()[2]).click();
+ await settle();
+
+ expect(uiState.mapSheetPoints.points).toEqual([
+ { lat: 48.85, lon: 2.35, label: 'Gare est', decimals: 2 },
+ ]);
+ expect(uiState.mapSheetPoints.column).toBe('Coordinates');
+ expect(uiState.tool).toBe('satellite');
+ });
+
+ it('writes a number column unit beside the heading, where a spreadsheet writes it', async () => {
+ // Set on the column and shown nowhere but the footer, a unit reads as not taken.
+ await openBinder({
+ columns: [...BINDER.columns, 'Range'],
+ rows: BINDER.rows.map((row, index) => [...row, ['12', '', '40'][index]]),
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ ...BINDER.meta.roles,
+ Range: { kind: 'number', unit: 'km', summary: 'sum' },
+ },
+ },
+ });
+ const heading = [...target.querySelectorAll('.heading-name')][6];
+ expect(heading.textContent.replace(/\s+/g, ' ').trim()).toBe('Range km');
+ // Once, in the heading: the cells keep the digits the file holds, and nothing is
+ // written after them until the column asks for it.
+ expect(text(rows()[0])[6]).toBe('12');
+ expect(rows()[0].querySelectorAll('.cell:not(.gutter)')[6].querySelector('.cell-unit'))
+ .toBeNull();
+ // And the footer names the reading it is giving: a total and an average are the
+ // same digits from the strip.
+ expect(
+ target.querySelector('.foot .progress').textContent.replace(/\s+/g, ' ').trim(),
+ ).toBe('Range total 52 km over 2');
+ });
+
+ it('writes the unit after every cell when the column asks, and never after a blank', async () => {
+ await openBinder({
+ columns: [...BINDER.columns, 'Share'],
+ rows: BINDER.rows.map((row, index) => [...row, ['40', '', '60'][index]]),
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ ...BINDER.meta.roles,
+ Share: { kind: 'number', unit: '%', unitInCells: true, summary: 'mean' },
+ },
+ },
+ });
+ const unitIn = (index) =>
+ rows()[index].querySelectorAll('.cell:not(.gutter)')[6].querySelector('.cell-unit');
+ expect(unitIn(0).textContent).toBe('%');
+ // A blank means unknown, and `%` on its own would be a reading of nothing.
+ expect(unitIn(1)).toBeNull();
+ // Beside the value, never inside it: what is copied out of the grid is the file.
+ expect(text(rows()[0])[6]).toBe('40');
+ });
+
+ it('turns the unit on in the cells from the column panel, and records it beside the file', async () => {
+ vi.useFakeTimers();
+ await openBinder({
+ columns: [...BINDER.columns, 'Share'],
+ rows: BINDER.rows.map((row, index) => [...row, ['40', '', '60'][index]]),
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { ...BINDER.meta.roles, Share: { kind: 'number', unit: '%', summary: 'mean' } },
+ },
+ });
+ await setupOf(6);
+ const check = [...target.querySelectorAll('.column-panel .check')].find((node) =>
+ node.textContent.includes('after every cell'),
+ );
+ check.querySelector('input').click();
+ await settle();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls.at(-1)[1].meta.roles.Share.unitInCells).toBe(true);
+ expect(
+ rows()[0].querySelectorAll('.cell:not(.gutter)')[6].querySelector('.cell-unit').textContent,
+ ).toBe('%');
+ });
+
+ it('hands the window a column of dates covers to the Timeline', async () => {
+ await openBinder();
+ await setupOf(4);
+ button('Open the Timeline on this period').click();
+ await settle();
+
+ expect(uiState.timelineRange.from).toBe('2026-01-31T00:00:00.000Z');
+ expect(uiState.tool).toBe('timeline');
+ });
+
+ it('edits a vocabulary as rows: the order, the colour and what uses each value', async () => {
+ // The textarea was smaller and it hid all three — the colour was typed as
+ // `done #green`, which nothing on screen taught.
+ vi.useFakeTimers();
+ await openBinder();
+ await setupOf(2);
+
+ const entries = () => [...target.querySelectorAll('.column-panel .vocab .entry')];
+ expect(entries().map((entry) => entry.querySelector('.word').value)).toEqual([
+ 'to do',
+ 'in progress',
+ 'done',
+ ]);
+ expect(entries().map((entry) => entry.querySelector('.held').textContent)).toEqual([
+ '0',
+ '0',
+ '1',
+ ]);
+ // And the values nothing uses are said out loud rather than left to be counted.
+ expect(target.querySelector('.column-panel .menu-note').textContent).toContain(
+ 'to do, in progress',
+ );
+
+ entries()[2].querySelector('[aria-label="Move done up"]').click();
+ await settle();
+ expect(entries().map((entry) => entry.querySelector('.word').value)).toEqual([
+ 'to do',
+ 'done',
+ 'in progress',
+ ]);
+
+ entries()[0].querySelector('.dot').click();
+ await settle();
+ target.querySelector('.column-panel .palette [aria-label="Paint to do red"]').click();
+ await settle();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const saved = put.mock.calls.at(-1)[1].meta.roles.Status;
+ expect(saved.values).toEqual(['to do', 'done', 'in progress']);
+ expect(saved.colours).toEqual({ 'to do': 'red' });
+ });
+
+ it('takes the words the cells use into the list, keeping the order already set', async () => {
+ vi.useFakeTimers();
+ await openBinder();
+ await setupOf(2);
+
+ const adopt = [...target.querySelectorAll('.column-panel .menu-row')].find((node) =>
+ node.textContent.includes('the cells use'),
+ );
+ expect(adopt.textContent.replace(/\s+/g, ' ')).toContain('Add the 1 word');
+ adopt.click();
+ await settle();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls.at(-1)[1].meta.roles.Status.values).toEqual([
+ 'to do',
+ 'in progress',
+ 'done',
+ 'OK en cours',
+ ]);
+ });
+
+ it('draws a yes/no column as boxes when it asks to be, and cycles three states', async () => {
+ vi.useFakeTimers();
+ const meta = structuredClone(BINDER.meta);
+ meta.roles.Checked = { kind: 'boolean', values: ['YES', 'NO'], tick: true };
+ await openBinder({
+ columns: [...BINDER.columns, 'Checked'],
+ rows: BINDER.rows.map((row, index) => [...row, ['YES', '', 'NO'][index]]),
+ meta,
+ });
+
+ const boxOf = (row) => rows()[row].querySelector('.cell-tick');
+ expect([0, 1, 2].map((row) => boxOf(row).dataset.state)).toEqual(['yes', 'blank', 'no']);
+ // A box is read the way a box is read: only yes carries a mark, no is the empty
+ // box, and blank is that box faded rather than a second glyph to learn.
+ expect([0, 1, 2].map((row) => boxOf(row).querySelectorAll('svg').length)).toEqual([1, 0, 0]);
+
+ // Blank is not no: the third state is what says nobody has been through that row.
+ boxOf(1).click();
+ flushSync();
+ expect(boxOf(1).dataset.state).toBe('yes');
+ boxOf(1).click();
+ flushSync();
+ boxOf(1).click();
+ flushSync();
+ expect(boxOf(1).dataset.state).toBe('blank');
+
+ await vi.advanceTimersByTimeAsync(1000);
+ // The file keeps the words either way: a tick is how the cell is drawn.
+ expect(put.mock.calls.at(-1)[1].rows.map((row) => row[6])).toEqual(['YES', '', 'NO']);
+ });
+
+ it('keeps a box clicked while the save is in the air', async () => {
+ // The save reply carries the sheet as the server cleaned it, and adopting it used to
+ // be unconditional — so a box clicked during the round trip was flipped back under
+ // the analyst's hand, and the revert was then written on the next pass.
+ vi.useFakeTimers();
+ const meta = structuredClone(BINDER.meta);
+ meta.roles.Checked = { kind: 'boolean', values: ['YES', 'NO'], tick: true };
+ await openBinder({
+ columns: [...BINDER.columns, 'Checked'],
+ rows: BINDER.rows.map((row) => [...row, '']),
+ meta,
+ });
+
+ let land = null;
+ put.mockImplementationOnce(
+ (_path, body) =>
+ new Promise((resolve) => {
+ // The sheet as the server would hand it back: what was sent, at a new stamp.
+ land = () =>
+ resolve(JSON.parse(JSON.stringify({ ...body, status: 'saved', stamp: '2000-64' })));
+ }),
+ );
+
+ const boxOf = (row) => rows()[row].querySelector('.cell-tick');
+ boxOf(1).click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put).toHaveBeenCalledTimes(1);
+ expect(put.mock.calls[0][1].rows[1][6]).toBe('YES');
+
+ // Clicked again before the reply lands: the reply still says YES.
+ boxOf(1).click();
+ flushSync();
+ expect(boxOf(1).dataset.state).toBe('no');
+ land();
+ await settle();
+
+ expect(boxOf(1).dataset.state).toBe('no');
+ expect(target.querySelector('.save-state')?.textContent.trim()).toBe('Unsaved');
+
+ // And the second write carries NO, with the stamp the first one came back with.
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put).toHaveBeenCalledTimes(2);
+ expect(put.mock.calls[1][1].rows[1][6]).toBe('NO');
+ expect(put.mock.calls[1][1].stamp).toBe('2000-64');
+ });
+
+ it('shows a word a tick column cannot read rather than swallowing it', async () => {
+ const meta = structuredClone(BINDER.meta);
+ meta.roles.Checked = { kind: 'boolean', values: ['YES', 'NO'], tick: true };
+ await openBinder({
+ columns: [...BINDER.columns, 'Checked'],
+ rows: BINDER.rows.map((row, index) => [...row, index === 0 ? 'maybe' : '']),
+ meta,
+ });
+
+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[6];
+ expect(cell.querySelector('.cell-tick').dataset.state).toBe('other');
+ expect(cell.querySelector('.value').textContent.trim()).toBe('maybe');
+ });
+
+ it('counts a list column value by value in the filter menu', async () => {
+ await openBinder();
+ const menu = await askOf(4);
+
+ const offered = [...menu.querySelectorAll('.values .row-btn')].map((node) =>
+ node.textContent.replace(/\s+/g, ' ').trim(),
+ );
+ // `Buk-M2E, 2x S-125` is two answers, counted one row each.
+ expect(offered).toContain('Buk-M2E 1');
+ expect(offered).toContain('2x S-125 1');
+ expect(offered).toContain('ZU23-2 1');
+ });
+
+ it('narrows the offers to what is being typed, and Enter takes the one lit', async () => {
+ vi.useFakeTimers();
+ await openBinder();
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const box = target.querySelector('.editor');
+ box.value = 'in';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ expect(
+ [...target.querySelectorAll('.offers .offer:not(.add)')].map((n) => n.textContent.trim()),
+ ).toEqual(['in progress']);
+
+ box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[1][2]).toBe('in progress');
+ });
+
+ it('offers to take a word the column has never heard of into its own list', async () => {
+ // The column panel could always do this, and that is two screens away from the
+ // moment it is wanted.
+ vi.useFakeTimers();
+ await openBinder();
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const box = target.querySelector('.editor');
+ box.value = 'OK en cours';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+
+ const adopt = target.querySelector('.offers .offer.add');
+ expect(adopt.textContent).toContain('OK en cours');
+ adopt.click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].meta.roles.Status.values).toContain('OK en cours');
+ });
+
+ it('flips a yes/no cell on one click of its chip', async () => {
+ // The tooltip said two words is a toggle while the only way to do it was a
+ // double-click or Enter.
+ vi.useFakeTimers();
+ await openBinder({
+ rows: [['r1', 'Quai sud', '', '', '', 'YES'], ['r2', 'Pont nord', '', '', '', 'NO']],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { Equipments: { kind: 'boolean', values: ['YES', 'NO'] } },
+ },
+ });
+ rows()[0].querySelectorAll('.cell:not(.gutter)')[5].querySelector('.cell-chip').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[0][5]).toBe('NO');
+ expect(target.querySelector('.question .chip')).toBeNull(), 'a flip is not a filter';
+ });
+
+ it('says in the heading what each column is', async () => {
+ await openBinder();
+ const marks = [...target.querySelectorAll('.head .cell.heading')].map(
+ (heading) => heading.querySelector('.role-mark')?.getAttribute('title') ?? '',
+ );
+ expect(marks).toEqual([
+ '',
+ '',
+ 'State: Status',
+ 'Point: Coordinates',
+ 'Date or time: Date',
+ 'Values: Equipments',
+ ]);
+ });
+
+ it('marks a cell its column cannot read, and offers those cells as a filter', async () => {
+ await openBinder({
+ columns: ['id', 'Title', 'Rounds'],
+ rows: [['r1', 'Quai sud', '12'], ['r2', 'Pont nord', 'unknown'], ['r3', 'Gare est', '8']],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ progress: null,
+ roles: { Rounds: { kind: 'number', summary: 'sum', unit: '' } },
+ },
+ });
+ expect(rows()[1].querySelectorAll('.cell:not(.gutter)')[2].querySelector('.badge.bad'))
+ .not.toBeNull();
+
+ const footer = target.querySelector('.foot .progress');
+ expect(footer.textContent.replace(/\s+/g, ' ')).toContain('20 over 2');
+ footer.querySelector('.progress-left').click();
+ await settle();
+ expect(rows()).toHaveLength(1);
+ expect(text(rows()[0])[1]).toBe('Pont nord');
+ });
+
+ it('gives a number column the one answer it was told to give, in its own unit', async () => {
+ await openBinder({
+ columns: ['id', 'Title', 'Share'],
+ rows: [['r1', 'Quai sud', '40'], ['r2', 'Pont nord', '60']],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ progress: null,
+ roles: { Share: { kind: 'number', summary: 'mean', unit: '%' } },
+ },
+ });
+ // Named, not just given: an average and a total are the same digits from the footer.
+ expect(
+ target.querySelector('.foot .progress').textContent.replace(/\s+/g, ' ').trim(),
+ ).toBe('Share average 50 % over 2');
+ });
+
+ it('acts on the rows dragged across when none are ticked', async () => {
+ // There were two selections and they disagreed: a screenful selected by dragging
+ // offered no way to paint it, and forty ticked rows could not be copied.
+ vi.useFakeTimers();
+ await openBinder();
+ const cellsOfRow = (index) => rows()[index].querySelectorAll('.cell:not(.gutter)');
+ cellsOfRow(0)[1].dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }));
+ cellsOfRow(2)[1].dispatchEvent(new PointerEvent('pointerenter', { bubbles: true }));
+ document.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }));
+ flushSync();
+
+ expect(target.querySelector('.selection .count').textContent).toContain(
+ '3 selected',
+ );
+ target.querySelector('.swatches .swatch').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(Object.keys(put.mock.calls[0][1].meta.colours)).toEqual(['r1', 'r2', 'r3']);
+ });
+
+ it('keeps a bulk fill off the columns the app writes', async () => {
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { ...BINDER.meta.roles, Date: { kind: 'stamped' } },
+ },
+ });
+ rows()[0].querySelector('.gutter input').click();
+ await settle();
+ button('Fill a column').click();
+ await settle();
+
+ const offered = [...target.querySelectorAll('.fill-columns .chip')].map((n) => n.textContent);
+ expect(offered).not.toContain('Date');
+ expect(offered).not.toContain('id');
+ expect(offered).toContain('Title');
+ });
+
+ it('says when a row has been edited since the case took it', async () => {
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ links: { r1: { Title: 'e_person' }, r2: { Title: 'e_other' } },
+ promoted: { r1: { Title: 'Quai nord' }, r2: { Title: 'Pont nord' } },
+ },
+ });
+ const mark = (index) => rows()[index].querySelectorAll('.cell:not(.gutter)')[1].querySelector('.link-mark');
+ expect(mark(0).classList.contains('moved')).toBe(true);
+ expect(mark(0).getAttribute('title')).toContain('Edited since');
+ expect(mark(1).classList.contains('moved')).toBe(false);
+ });
+
+ it('rewrites a column of points in one form, in one undoable step', async () => {
+ // The only action here that touches the file, and the only way the file itself gets
+ // better: a role never rewrites a cell.
+ vi.useFakeTimers();
+ await openBinder();
+ await setupOf(3);
+ button('Rewrite as').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows.map((row) => row[3])).toEqual([
+ '48.85660, 2.35220',
+ '',
+ '48.85000, 2.35000',
+ ]);
+ });
+
+ /** The panel a row is read down, on the columns that were set up carefully. It used to
+ * put a bare box on every one of them, so the panel was a worse place to work than the
+ * row it was showing. */
+ const panelField = (name) =>
+ [...target.querySelectorAll('.panel .field')].find(
+ (node) => node.querySelector('.label span')?.textContent === name,
+ );
+
+ it('offers the column own words in the row panel, and writes what is picked', async () => {
+ vi.useFakeTimers();
+ await openBinder();
+ rows()[1].querySelector('.cell-open').click();
+ flushSync();
+
+ const words = [...panelField('Status').querySelectorAll('.word')];
+ expect(words.map((node) => node.textContent.trim())).toEqual([
+ 'to do',
+ 'in progress',
+ 'done',
+ ]);
+ words[1].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[1][2]).toBe('in progress');
+ });
+
+ it('builds a list in the panel on a column that holds several values', async () => {
+ vi.useFakeTimers();
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ ...structuredClone(BINDER.meta.roles),
+ Equipments: { kind: 'choice', multi: ', ', values: ['Buk-M2E', 'ZU23-2'] },
+ },
+ },
+ });
+ rows()[1].querySelector('.cell-open').click();
+ flushSync();
+
+ const words = [...panelField('Equipments').querySelectorAll('.word')];
+ words[0].click();
+ flushSync();
+ words[1].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[1][5]).toBe('Buk-M2E, ZU23-2');
+ });
+
+ it('answers a yes/no field in the panel, and writes no box for a column the app fills', async () => {
+ vi.useFakeTimers();
+ await openBinder({
+ columns: ['id', 'Title', 'Checked', 'Added on'],
+ rows: [['r1', 'Quai sud', '', '']],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ Checked: { kind: 'boolean', values: ['yes', 'no'] },
+ 'Added on': { kind: 'stamped' },
+ },
+ progress: null,
+ },
+ });
+ rows()[0].querySelector('.cell-open').click();
+ flushSync();
+
+ panelField('Checked').querySelector('.answer').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[0][2]).toBe('yes');
+ // The app rewrites that column on every save, so the panel says so rather than
+ // offering a box whose value is gone by the next one.
+ expect(panelField('Added on').querySelector('textarea')).toBeNull();
+ expect(panelField('Added on').querySelector('.written')).not.toBeNull();
+ });
+
+ it('shows what a column says twice, and paints those rows', async () => {
+ await openBinder({
+ rows: [
+ ['r1', 'Quai sud', '', '', '', ''],
+ ['r2', 'Quai sud', '', '', '', ''],
+ ['r3', 'Gare est', '', '', '', ''],
+ ],
+ });
+ await setupOf(1);
+ button('Show duplicates').click();
+ await settle();
+
+ const reading = target.querySelector('.reading');
+ expect(reading.textContent).toContain('Quai sud');
+ reading.querySelector('.found .chip').click();
+ await settle();
+ expect(target.querySelector('.selection .count').textContent).toContain('2 ticked');
+ });
+
+ it('finds points too close to be two places', async () => {
+ await openBinder({
+ rows: [
+ ['r1', 'A', '', '48.856600, 2.352200', '', ''],
+ ['r2', 'B', '', '48.856610, 2.352210', '', ''],
+ ['r3', 'C', '', '50.100000, 3.000000', '', ''],
+ ],
+ });
+ await setupOf(3);
+ button('Find points too close').click();
+ await settle();
+ expect(target.querySelector('.reading').textContent).toContain('1 pair');
+ });
+
+ it('undoes a role the server writes cells for, cells and all', async () => {
+ // Declaring `On map` makes the server write YES/NO into the file. Undoing the role
+ // has to take those back too, or the column keeps its answers after the role that
+ // produced them is gone and the undo reads as having done nothing.
+ vi.useFakeTimers();
+ put.mockImplementation(async (_path, body) => ({
+ status: 'saved',
+ stamp: '2000-64',
+ ...body,
+ // What the server does on a computed column.
+ rows: body.meta.roles?.Title
+ ? body.rows.map((row) => [...row.slice(0, 1), 'YES', ...row.slice(2)])
+ : body.rows,
+ }));
+ await openBinder({ meta: { ...structuredClone(BINDER.meta), roles: {} } });
+
+ await setupOf(1);
+ button('Answered by the app').click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(text(rows()[0])[1]).toBe('YES');
+
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'z', ctrlKey: true, bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(text(rows()[0])[1]).toBe('Quai sud');
+ expect(put.mock.calls.at(-1)[1].meta.roles.Title).toBeUndefined();
+ });
+
+ it('offers a calendar on a date column, spelled the way the column spells dates', async () => {
+ // The picker hands over an ISO date whatever the locale; what lands in the cell is
+ // this column's own form, or picking a date would restyle the file from a click.
+ vi.useFakeTimers();
+ await openBinder();
+ rows()[0]
+ .querySelectorAll('.cell:not(.gutter)')[4]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const calendar = target.querySelector('.offers input[type="date"]');
+ expect(calendar.value).toBe('2026-01-31');
+ calendar.value = '2026-03-04';
+ calendar.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ target.querySelector('.editor').dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[0][4]).toBe('04/03/2026');
+ });
+
+ it('offers a clock, not a calendar, on a column of bare times', async () => {
+ // The role reads "a date or a time" because the binders write all three shapes. A
+ // calendar here would offer to put a date where the analyst deliberately did not: the
+ // binder's `Local time` holds `01:57` for an event whose date is in the sheet's title.
+ vi.useFakeTimers();
+ await openBinder({
+ rows: [
+ ['r1', 'Quai sud', '', '', '01:57', ''],
+ ['r2', 'Pont nord', '', '', '02:10', ''],
+ ],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { ...BINDER.meta.roles, Date: { kind: 'when', shape: 'time', dayFirst: true } },
+ },
+ });
+ rows()[0]
+ .querySelectorAll('.cell:not(.gutter)')[4]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const picker = target.querySelector('.offers input');
+ expect(picker.getAttribute('type')).toBe('time');
+ expect(picker.value).toBe('01:57');
+ picker.value = '03:20';
+ picker.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ target.querySelector('.editor').dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[0][4]).toBe('03:20');
+ });
+
+ it('offers a date and a time together on a column that holds both', async () => {
+ vi.useFakeTimers();
+ await openBinder({
+ rows: [
+ ['r1', 'Quai sud', '', '', '31/01/2026 06:42', ''],
+ ['r2', 'Pont nord', '', '', '01/02/2026 07:15', ''],
+ ],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { ...BINDER.meta.roles, Date: { kind: 'when', shape: 'datetime', dayFirst: true } },
+ },
+ });
+ rows()[0]
+ .querySelectorAll('.cell:not(.gutter)')[4]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const picker = target.querySelector('.offers input');
+ expect(picker.getAttribute('type')).toBe('datetime-local');
+ expect(picker.value).toBe('2026-01-31T06:42');
+ picker.value = '2026-03-04T09:05';
+ picker.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ target.querySelector('.editor').dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[0][4]).toBe('04/03/2026 09:05');
+ });
+
+ it('offers the vocabulary on a state column, and keeps the box free to type in', async () => {
+ vi.useFakeTimers();
+ await openBinder();
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const offers = [...target.querySelectorAll('.offers .offer')].map((node) =>
+ node.textContent.trim(),
+ );
+ expect(offers).toEqual(['to do', 'in progress', 'done']);
+ // The box is still there, because `OK en cours` has to remain typeable.
+ expect(target.querySelector('.editor')).not.toBeNull();
+
+ target.querySelectorAll('.offers .offer')[1].click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[1][2]).toBe('in progress');
+ });
+
+ it('builds a multi-value cell one value at a time', async () => {
+ vi.useFakeTimers();
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ ...BINDER.meta.roles,
+ Equipments: { kind: 'choice', multi: ', ', values: ['Buk-M2E', 'ZU23-2'] },
+ },
+ },
+ });
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[5]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const offers = () => [...target.querySelectorAll('.offers .offer')];
+ offers()[0].click();
+ flushSync();
+ offers()[1].click();
+ flushSync();
+ target.querySelector('.editor').dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].rows[1][5]).toBe('Buk-M2E, ZU23-2');
+ });
+
+ it('flips a yes/no column on a click, without opening anything', async () => {
+ // Two words is a toggle, not a menu, and making the analyst pick from a list of two is
+ // a click too many on the column they will touch most.
+ vi.useFakeTimers();
+ await openBinder({
+ rows: [['r1', 'Quai sud', '', '', '', 'YES'], ['r2', 'Pont nord', '', '', '', '']],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { Equipments: { kind: 'boolean', values: ['YES', 'NO'] } },
+ },
+ });
+ const cell = rows()[0].querySelectorAll('.cell:not(.gutter)')[5];
+ cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+ expect(target.querySelector('.editor')).toBeNull();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls[0][1].rows[0][5]).toBe('NO');
+
+ // And an empty cell answers with the first word.
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[5]
+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].rows[1][5]).toBe('YES');
+ });
+
+ it('totals a number column over the rows on screen, not the whole sheet', async () => {
+ // Filtering to what is left and then being told the total of everything answers a
+ // question nobody asked.
+ await openBinder({
+ rows: [
+ ['r1', 'Quai sud', '', '', '', '3'],
+ ['r2', 'Pont nord', '', '', '', '1 200'],
+ ['r3', 'Gare est', '', '', '', 'Only 9 in service?'],
+ ],
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: { Equipments: { kind: 'number' } },
+ },
+ });
+ const foot = () => target.querySelector('.foot .progress').textContent.replace(/\s+/g, ' ');
+ expect(foot()).toContain('1203');
+ expect(foot()).toContain('over 2'); // the prose cell is not a number and is not counted
+
+ await typeSearch('quai');
+ expect(foot()).toContain('3');
+ expect(foot()).toContain('over 1');
+ });
+
+ it('paints a chip in the colour its own vocabulary gives it', async () => {
+ await openBinder({
+ meta: {
+ ...structuredClone(BINDER.meta),
+ roles: {
+ ...BINDER.meta.roles,
+ Status: {
+ kind: 'state',
+ values: ['to do', 'in progress', 'done'],
+ colours: { done: 'green' },
+ },
+ },
+ },
+ });
+ const chip = rows()[0].querySelectorAll('.cell:not(.gutter)')[2].querySelector('.cell-chip');
+ expect(chip.textContent.trim()).toBe('done');
+ expect(chip.classList.contains('tinted')).toBe(true);
+ expect(chip.classList.contains('c-green')).toBe(true);
+ });
+
+ it('keeps a line of instruction for whoever opens the sheet next', async () => {
+ vi.useFakeTimers();
+ await openBinder();
+ await setupOf(2);
+ const box = [...target.querySelectorAll('.column-panel .field input')].at(-1);
+ box.value = 'where this row got to';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ box.dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls[0][1].meta.notes).toEqual({ Status: 'where this row got to' });
+ });
+});
+
+describe('a whole sheet into the case, in one declaration', () => {
+ /** A binder's line: a person, the unit they are in, the van they own, the page it rests
+ * on and the point it happened at. Which is the shape no older road could promote —
+ * each of them saw one column and an edge needs two. */
+ const ROSTER = {
+ ...SHEET,
+ columns: ['id', 'Name', 'Unit', 'Van', 'Source', 'Coordinates'],
+ rows: [
+ ['r1', 'Ivanov', '3rd Brigade', 'AB-123', 'https://example.org/a', '48.85, 2.35'],
+ ['r2', 'Petrov', '3rd Brigade', '', 'https://example.org/b', ''],
+ ['r3', '', '', '', '', ''],
+ ],
+ meta: { ...structuredClone(SHEET.meta), roles: { Coordinates: { kind: 'latlon' } } },
+ };
+
+ const PLAN = {
+ entities: [
+ {
+ mode: 'row',
+ column: 'Name',
+ counts: { make: 2, join: 0, update: 0, skip: 1, error: 0 },
+ rows: [
+ { key: 'r1', label: 'Ivanov', action: 'make', reason: '', entity: null,
+ entity_label: '', attrs: {}, problems: [], candidates: [] },
+ { key: 'r2', label: 'Petrov', action: 'make', reason: '', entity: null,
+ entity_label: '', attrs: {}, problems: [],
+ candidates: [{ id: 'e_other', label: 'Petrov' }] },
+ { key: 'r3', label: '', action: 'skip', reason: "nothing in 'Name' to name it",
+ entity: null, entity_label: '', attrs: {}, problems: [], candidates: [] },
+ ],
+ },
+ {
+ mode: 'value',
+ column: 'Unit',
+ counts: { make: 1, join: 0, update: 0, skip: 0, error: 0 },
+ rows: [
+ { key: '3rd Brigade', value: '3rd Brigade', action: 'make', reason: '',
+ entity: null, entity_label: '', candidates: [] },
+ ],
+ },
+ ],
+ joins: [
+ { from: 'Name', to: 'Unit', verb: 'member-of', label: 'is a member of',
+ ratable: true, rows: 2, blocked: [] },
+ ],
+ };
+
+ async function openRoster() {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(structuredClone(ROSTER))
+ : route(path),
+ );
+ await open();
+ target.querySelector('.head .gutter input').click();
+ await settle();
+ button('To the case').click();
+ await settle();
+ return document.querySelector('.to-case');
+ }
+
+ /** Answer one of the screen's selects, the way an analyst does. */
+ async function choose(label, value) {
+ const select = document.querySelector(`.to-case select[aria-label="${label}"]`);
+ select.value = value;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ await settle();
+ return select;
+ }
+
+ const press_ = (label) =>
+ [...document.querySelectorAll('.to-case button')]
+ .find((node) => node.textContent.trim().startsWith(label))
+ .click();
+
+ /** The declaration the screen sends: a subject, a column of words, and the join the
+ * vocabulary allows between them. */
+ async function declare(plan = PLAN) {
+ await openRoster();
+ await choose('What Name is', 'row');
+ await choose('What Name becomes', 'person');
+ await choose('What Unit is', 'value');
+ await choose('What Unit becomes', 'organization');
+ await choose('How Name and Unit are joined', 'member-of:out');
+ post.mockResolvedValueOnce(plan);
+ press_('Preview');
+ await settle();
+ return document.querySelector('.to-case');
+ }
+
+ it('says what one pass would do before the case changes', async () => {
+ const dialog = await declare();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet/promote/preview');
+ expect(body.keys).toEqual(['r1', 'r2', 'r3']);
+ expect(body.subject).toMatchObject({ column: 'Name', type: 'person' });
+ expect(body.values).toEqual([
+ { column: 'Unit', type: 'organization', attach: {}, skip: [] },
+ ]);
+ expect(body.joins).toEqual([{ from: 'Name', to: 'Unit', verb: 'member-of' }]);
+
+ // Both layers, counted: the entities each column makes, and the edges between them.
+ expect([...dialog.querySelectorAll('.plan-row .mark')].map((n) => n.textContent)).toEqual([
+ 'New',
+ 'New',
+ 'Left out',
+ 'New',
+ ]);
+ expect(dialog.querySelector('.plan-row.skip .why').textContent).toContain('nothing in');
+ expect(dialog.querySelector('.join-plan').textContent).toContain('Name is a member of Unit');
+ // The button says how much it will write, over both layers, so the press is not a leap.
+ expect(dialog.textContent).toContain('Send 5');
+ });
+
+ it('offers to attach a row to the name the case already holds', async () => {
+ const dialog = await declare();
+ const picker = dialog.querySelector('.plan-row .tiny');
+ expect([...picker.options].map((option) => option.textContent)).toEqual([
+ 'Create it',
+ 'Attach to Petrov',
+ ]);
+
+ post.mockResolvedValueOnce({
+ ...PLAN,
+ entities: [
+ {
+ ...PLAN.entities[0],
+ counts: { make: 1, join: 1, update: 0, skip: 1, error: 0 },
+ rows: PLAN.entities[0].rows.map((row) =>
+ row.key === 'r2'
+ ? { ...row, action: 'join', entity: 'e_other', entity_label: 'Petrov' }
+ : row,
+ ),
+ },
+ PLAN.entities[1],
+ ],
+ });
+ picker.value = 'e_other';
+ picker.dispatchEvent(new Event('change', { bubbles: true }));
+ await settle();
+
+ // Which is the whole of what the old *link these cells* screen did, minus the screen:
+ // a name the case already holds is pointed at rather than filed a second time.
+ expect(post.mock.calls.at(-1)[1].subject.attach).toEqual({ r2: 'e_other' });
+ expect(dialog.querySelector('.plan-row.join')).not.toBeNull();
+ });
+
+ it('sends the ticked rows, saving the table it was given', async () => {
+ await declare();
+ post.mockResolvedValueOnce({
+ status: 'promoted',
+ entities: [
+ { mode: 'row', column: 'Name', make: 2, join: 0, update: 0, skip: 1, error: 0 },
+ { mode: 'value', column: 'Unit', make: 1, join: 0, update: 0, skip: 0, error: 0 },
+ ],
+ joins: [{ from: 'Name', to: 'Unit', verb: 'member-of', drawn: 2, failed: [] }],
+ columns: ROSTER.columns,
+ rows: ROSTER.rows,
+ meta: { ...ROSTER.meta, links: { r1: { Name: 'e_new' } } },
+ stamp: '3000-70',
+ });
+ press_('Send 5');
+ await settle();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet/promote');
+ expect(body.stamp).toBe('1000-64');
+ expect(body.rows).toEqual(ROSTER.rows);
+ expect(body.subject).toMatchObject({ column: 'Name', type: 'person' });
+ // Counted apart, because "six sent" hides what the case actually gained — and the
+ // edges are counted apart again, being the half no older road could draw.
+ expect(toast).toHaveBeenCalledWith('3 added · 2 edges · 1 left out');
+ });
+
+ it('opens the sync points over the declaration, and Escape gives it back', async () => {
+ // A binder's synchro sheet: the rows carry offsets against one shot that has no time
+ // yet, which is the one thing between them and real hours.
+ const SYNCHRO = {
+ ...ROSTER,
+ columns: ['id', 'Name', 'start synchro'],
+ rows: [['r1', 'Video A', '-00:01:50']],
+ meta: {
+ ...structuredClone(SHEET.meta),
+ roles: { 'start synchro': { kind: 'offset', anchor: 'IGLA launch' } },
+ anchors: { 'IGLA launch': { at: '' } },
+ },
+ };
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(structuredClone(SYNCHRO))
+ : route(path),
+ );
+ await open();
+ target.querySelector('.head .gutter input').click();
+ await settle();
+ button('To the case').click();
+ await settle();
+ await choose('What Name is', 'row');
+ await choose('What start synchro is', 'statement');
+ press_('From a sync point');
+ await settle();
+
+ press_('Date it');
+ await settle();
+ // Both are on screen: the declaration is what sent the analyst there, so closing it to
+ // ask for one date would be asking them to make it twice.
+ expect(document.querySelector('.anchors')).not.toBeNull();
+ expect(document.querySelector('.to-case')).not.toBeNull();
+
+ // And Escape answers the one on top, not both.
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(document.querySelector('.anchors')).toBeNull();
+ expect(document.querySelector('.to-case')).not.toBeNull();
+ });
+
+ it('turns a refusal into the same banner a stale save gets', async () => {
+ await declare();
+ post.mockRejectedValueOnce(Object.assign(new Error('conflict'), { status: 409 }));
+ press_('Send 5');
+ await settle();
+
+ expect(target.querySelector('.notice.danger')).not.toBeNull();
+ });
+});
+
+describe('the sheet itself', () => {
+ it('renames through the entity, so the file follows', async () => {
+ await open();
+ const name = target.querySelector('.title-input');
+ name.value = 'Shortlist';
+ name.dispatchEvent(new Event('input', { bubbles: true }));
+ name.dispatchEvent(new Event('blur', { bubbles: true }));
+ await settle();
+
+ expect(patch).toHaveBeenCalledWith('/api/cases/case-a/entities/e_sheet', {
+ label: 'Shortlist',
+ });
+ });
+
+ it('offers a way in when the case holds none', async () => {
+ get.mockImplementation((path) =>
+ path.endsWith('/sheets') ? Promise.resolve({ sheets: [] }) : route(path),
+ );
+ await open();
+ expect(target.querySelector('.empty')).not.toBeNull();
+ expect(button('New sheet')).not.toBeUndefined();
+ });
+
+ it('exports the rows on screen rather than the file on disk', async () => {
+ // The case folder already holds the CSV. What the analyst does not have is this
+ // reading of it: the rows the filter left, in the columns that are drawn.
+ post.mockResolvedValue({ file: 'Candidates.csv', path: '/w/case/exports' });
+ await open();
+ await typeSearch('quai');
+
+ button('Export').click();
+ await settle();
+ button('Save 1 rows on screen').click();
+ await settle();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet/csv');
+ expect(body.columns).toEqual(['id', 'Subject', 'Status']);
+ expect(body.rows).toEqual([['r1', 'Quai sud', 'ruled out']]);
+ // Where it landed, because a file nobody can find is a file exported twice.
+ expect(toast.mock.calls.at(-1)[0]).toContain('1 of 3 rows');
+ // Named the way the rest of the app names a destination, and carrying a way to get
+ // there: a sentence about a folder is a folder the analyst then goes hunting for.
+ expect(toast.mock.calls.at(-1)[0]).toContain('exports');
+ expect(toast.mock.calls.at(-1)[3].label).toBe('Show');
+ });
+
+ it('leaves out a hidden column, because the export is what is on screen', async () => {
+ post.mockResolvedValue({ file: 'Candidates.csv', path: '/w/case/exports' });
+ await open();
+ button('Columns').click();
+ await settle();
+ target.querySelectorAll('.column-row input')[1].click();
+ await settle();
+
+ button('Export').click();
+ await settle();
+ button('Save 3 rows on screen').click();
+ await settle();
+
+ expect(post.mock.calls.at(-1)[1].columns).toEqual(['id', 'Subject']);
+ });
+});
+
+describe('the map of a sheet too wide to read at once', () => {
+ it('says what each column is and what is being asked of it', async () => {
+ await open();
+ await askOf(1);
+ button('Empty').click();
+ await settle();
+
+ button('Columns').click();
+ await settle();
+ const listed = [...target.querySelectorAll('.column-row')];
+ expect(listed.map((row) => row.querySelector('.column-name').textContent)).toEqual([
+ 'Subject',
+ 'Status',
+ ]);
+ expect(listed[1].querySelector('.column-ask').classList.contains('on')).toBe(true);
+ expect(listed[0].querySelector('.column-ask').classList.contains('on')).toBe(false);
+ });
+
+ it('opens the filter of a column from the list, bringing it back into view', async () => {
+ await open();
+ button('Columns').click();
+ await settle();
+ // Hidden, which is exactly the case the list exists for: there is no heading to
+ // click, so asking something of it has to unhide it first.
+ target.querySelectorAll('.column-row input')[1].click();
+ await settle();
+ expect([...target.querySelectorAll('.heading-name span')].map((n) => n.textContent)).toEqual([
+ 'id',
+ 'Subject',
+ ]);
+
+ target.querySelectorAll('.column-row .column-ask')[1].click();
+ await settle();
+
+ expect([...target.querySelectorAll('.heading-name span')].map((n) => n.textContent)).toContain(
+ 'Status',
+ );
+ expect(target.querySelector('.filter-menu').getAttribute('aria-label')).toBe('Filter Status');
+ });
+});
+
+/**
+ * The gestures a heading and a gutter owe an analyst.
+ *
+ * The complaint this answers was precise: the actions on a column were behind a `...`
+ * nobody presses, half of what a column needs was not there at all, and a row could not
+ * be inserted where the work is. So these press the real controls — a right-click, a
+ * menu row, a double-click on a heading — rather than calling the functions under them.
+ */
+describe('what a heading and a gutter can do', () => {
+ const headings = () => [...target.querySelectorAll('.heading-name span')].map((n) => n.textContent);
+ const rightClick = (node) => {
+ node.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ flushSync();
+ };
+
+ it('opens the short menu on a right-click, which is what a spreadsheet does', async () => {
+ await open();
+ rightClick(target.querySelectorAll('.head .cell.heading')[1]);
+ await settle();
+ expect(document.querySelector('.heading-menu[role="menu"]')).not.toBeNull();
+ expect(inHeadingMenu('Insert a column left')).toBeDefined();
+ });
+
+ it('inserts a column beside the one being worked on, on either side', async () => {
+ await open();
+ await headingMenu(1);
+ inHeadingMenu('Insert a column right').click();
+ await settle();
+ // It lands in rename, so its heading is a box rather than a label until Escape.
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(headings()).toEqual(['id', 'Subject', 'Column', 'Status']);
+
+ await headingMenu(1);
+ inHeadingMenu('Insert a column left').click();
+ await settle();
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(headings()).toEqual(['id', 'Column 2', 'Subject', 'Column', 'Status']);
+ });
+
+ it('lands the cursor in the column it just inserted, renaming it', async () => {
+ await open();
+ await headingMenu(1);
+ inHeadingMenu('Insert a column right').click();
+ await settle();
+ expect(target.querySelector('.heading-rename')).not.toBeNull();
+ });
+
+ it('duplicates a column with its cells and its lens', async () => {
+ vi.useFakeTimers();
+ await open();
+ await headingMenu(2);
+ inHeadingMenu('Duplicate this column').click();
+ await settle();
+
+ expect(headings()).toEqual(['id', 'Subject', 'Status', 'Status copy']);
+ expect(text(rows()[0]).slice(1)).toEqual(['Quai sud', 'ruled out', 'ruled out']);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].columns).toEqual(['id', 'Subject', 'Status', 'Status copy']);
+ vi.useRealTimers();
+ });
+
+ it('renames a heading in place on a double-click', async () => {
+ vi.useFakeTimers();
+ await open();
+ const heading = target.querySelectorAll('.heading-name')[1];
+ heading.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
+ flushSync();
+
+ const box = target.querySelector('.heading-rename');
+ expect(box.value).toBe('Subject');
+ box.value = 'Candidate';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ box.dispatchEvent(new Event('blur', { bubbles: true }));
+ await settle();
+
+ expect(headings()).toEqual(['id', 'Candidate', 'Status']);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].columns).toContain('Candidate');
+ vi.useRealTimers();
+ });
+
+ it('sorts from the menu in the direction the row names', async () => {
+ await open();
+ await headingMenu(1);
+ inHeadingMenu('Sort Z → A').click();
+ await settle();
+ expect(text(rows()[0])[1]).toBe('Quai sud');
+
+ await headingMenu(1);
+ inHeadingMenu('Sort A → Z').click();
+ await settle();
+ expect(text(rows()[0])[1]).toBe('Gare est');
+ });
+
+ it('numbers the rows, because the key is a handle and not a position', async () => {
+ await open();
+ expect([...target.querySelectorAll('.row-number')].map((n) => n.textContent)).toEqual([
+ '1',
+ '2',
+ '3',
+ ]);
+ });
+
+ it('inserts a row where the analyst is reading, not four hundred rows below', async () => {
+ await open();
+ rightClick(rows()[0].querySelector('.cell.gutter'));
+ await settle();
+ [...document.querySelectorAll('.row-menu button')]
+ .find((node) => node.textContent.includes('Insert a row below'))
+ .click();
+ await settle();
+
+ expect(rows()).toHaveLength(4);
+ expect(text(rows()[1]).slice(1)).toEqual(['', '']);
+ });
+
+ it('duplicates a row under itself, keyed anew and ticked', async () => {
+ await open();
+ rightClick(rows()[2].querySelector('.cell.gutter'));
+ await settle();
+ [...document.querySelectorAll('.row-menu button')]
+ .find((node) => node.textContent.includes('Duplicate'))
+ .click();
+ await settle();
+
+ expect(rows()).toHaveLength(4);
+ expect(text(rows()[3]).slice(1)).toEqual(['Gare est', 'to check']);
+ expect(target.querySelectorAll('.row.ticked')).toHaveLength(1);
+ });
+
+ it('asks before deleting the rows the gutter menu is about', async () => {
+ await open();
+ rightClick(rows()[0].querySelector('.cell.gutter'));
+ await settle();
+ [...document.querySelectorAll('.row-menu button')]
+ .find((node) => node.textContent.includes('Delete'))
+ .click();
+ await settle();
+
+ expect(document.querySelector('[role="alertdialog"]').textContent).toContain('Delete 1 row');
+ inDialog('Delete').click();
+ await settle();
+ expect(rows()).toHaveLength(2);
+ });
+});
+
+describe('the passes that fix an imported column', () => {
+ const cleanRow = (label) =>
+ [...document.querySelectorAll('.clean .pass')].find((node) =>
+ node.textContent.trim().startsWith(label),
+ );
+
+ async function openClean(columnIndex, label = 'Find and replace') {
+ await headingMenu(columnIndex);
+ inHeadingMenu(label === 'Find and replace' ? 'Find and replace' : 'Split, merge or tidy').click();
+ await settle();
+ return document.querySelector('.clean');
+ }
+
+ it('says how many cells a replace would touch before it is pressed', async () => {
+ await open();
+ await openClean(2);
+ const find = document.querySelector('.clean .field .input');
+ find.value = 'ruled out';
+ find.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ expect(document.querySelector('.clean .says').textContent).toContain('1 cell would change');
+ });
+
+ it('replaces a word across the rows on screen, in one undoable step', async () => {
+ vi.useFakeTimers();
+ await open();
+ await openClean(2);
+ const [find, replace] = document.querySelectorAll('.clean .field .input');
+ find.value = 'ruled out';
+ find.dispatchEvent(new Event('input', { bubbles: true }));
+ replace.value = 'dropped';
+ replace.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+ [...document.querySelectorAll('.clean button')]
+ .find((node) => node.textContent.trim() === 'Replace')
+ .click();
+ await settle();
+
+ expect(text(rows()[0])[2]).toBe('dropped');
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].rows[0][2]).toBe('dropped');
+ vi.useRealTimers();
+ });
+
+ it('splits a column into as many as its separator makes, keeping the original', async () => {
+ await open();
+ await openClean(1, 'Split');
+ const separator = document.querySelector('.clean .narrow');
+ separator.value = ' ';
+ separator.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+
+ [...document.querySelectorAll('.clean button')]
+ .find((node) => node.textContent.trim() === 'Split')
+ .click();
+ await settle();
+
+ expect([...target.querySelectorAll('.heading-name span')].map((n) => n.textContent)).toEqual([
+ 'id',
+ 'Subject',
+ 'Subject 1',
+ 'Subject 2',
+ 'Status',
+ ]);
+ expect(text(rows()[0]).slice(1)).toEqual(['Quai sud', 'Quai', 'sud', 'ruled out']);
+ });
+});
+
+describe('the case, as rows to work through', () => {
+ it('builds a worklist out of a type and opens it', async () => {
+ post.mockImplementation(async (path) =>
+ path.endsWith('/from-case')
+ ? { id: 'e_built', label: 'Person to check', type: 'sheet', taken: 2, total: 2 }
+ : {},
+ );
+ await open();
+ // The ways of starting a sheet live under one button now: five of them in the header
+ // was five sixths of a bar that also has to fit a title, the sheet list and an export.
+ button('New').click();
+ await settle();
+ button('From the case').click();
+ await settle();
+
+ // The modal is portalled onto the body, so its buttons are not under `target`.
+ const inModal = (label) =>
+ [...document.querySelectorAll('.from-case button')].find((node) =>
+ node.textContent.trim().startsWith(label),
+ );
+ inModal('Person').click();
+ await settle();
+ inModal('Build the sheet').click();
+ await settle();
+
+ const [path, body] = post.mock.calls.find(([route]) => route.endsWith('/from-case'));
+ expect(path).toBe('/api/cases/case-a/sheets/from-case');
+ expect(body.type).toBe('person');
+ expect(body.title).toBe('Person to check');
+ });
+});
+
+describe('what the grid draws for a column that says what it holds', () => {
+ it('marks what the search found, in the cell rather than only in the count', async () => {
+ await open();
+ await typeSearch('quai');
+ expect(rows()[0].querySelector('.value mark').textContent).toBe('Quai');
+ });
+
+ it('offers the @ where pointing a cell somewhere means something', async () => {
+ // A status is not a thing the case holds an entity for, and an `@` on every cell read
+ // as an offer to point one at a person.
+ await open();
+ const plain = rows()[0].querySelectorAll('.cell:not(.gutter)');
+ expect(plain[1].querySelector('.cell-link')).not.toBeNull();
+ expect(plain[2].querySelector('.cell-link')).not.toBeNull();
+ unmount(live);
+
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ meta: { ...structuredClone(SHEET.meta), roles: { Status: { kind: 'state' } } },
+ })
+ : route(path),
+ );
+ await open();
+ const withRole = rows()[0].querySelectorAll('.cell:not(.gutter)');
+ expect(withRole[1].querySelector('.cell-link')).not.toBeNull();
+ expect(withRole[2].querySelector('.cell-link')).toBeNull();
+ });
+
+ it('draws a picture column as its pictures', async () => {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ columns: ['id', 'Subject', 'Shot'],
+ rows: [['r1', 'Quai sud', 'https://example.org/a.jpg'], ['r2', 'Pont nord', 'later']],
+ meta: { ...structuredClone(SHEET.meta), roles: { Shot: { kind: 'picture' } } },
+ })
+ : route(path),
+ );
+ await open();
+ expect(rows()[0].querySelector('.cell-shot img').getAttribute('src')).toBe(
+ 'https://example.org/a.jpg',
+ );
+ // A cell that is not an address is shown as it is and marked, never refused.
+ expect(rows()[1].querySelector('.cell-shot')).toBeNull();
+ expect(rows()[1].querySelector('.badge.bad')).not.toBeNull();
+ });
+});
+
+/**
+ * The grid's own shape: the line it ends on, the row it keeps under the heading, how tall
+ * a row is and what its colour means. None of these is in the file — losing all of them
+ * costs presentation and never a finding — and every one of them is written down, because
+ * a reading rebuilt every morning is a reading nobody keeps.
+ */
+describe('how the grid is drawn, and what it remembers of that', () => {
+ const openWith = async (sheet) => {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({ ...structuredClone(SHEET), ...sheet })
+ : route(path),
+ );
+ await open();
+ };
+
+ it('always ends on an empty line, which is not one of the rows', async () => {
+ await open();
+ expect(rows()).toHaveLength(3);
+ expect(ghostRow()).not.toBeNull();
+ // It counts for nothing: the denominator is the file's rows, not the offer.
+ expect(target.querySelector('.count').textContent.replace(/\s+/g, ' ')).toContain('3 of 3');
+ });
+
+ it('makes that line a row when it is written in, with the editor already open', async () => {
+ vi.useFakeTimers();
+ await open();
+ // The second column, because the first is the row's handle and nothing writes there.
+ target.querySelectorAll('.ghost .ghost-cell')[1].click();
+ flushSync();
+ expect(rows()).toHaveLength(4);
+ expect(target.querySelector('.editor')).not.toBeNull();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].rows).toHaveLength(4);
+ });
+
+ it('opens the editor on a column an edit can land in, never on the app own', async () => {
+ // Clicking the handle's own ghost cell must not open a box whose value is overwritten.
+ await open();
+ addGhostRow();
+ await settle();
+ expect(target.querySelector('.editor')).not.toBeNull();
+ expect(target.querySelector('.cell.cursor').dataset.column).toBe('1');
+ });
+
+ it('says so rather than losing a row the filter would hide the instant it exists', async () => {
+ // A blank row answers most filters with nothing, so it was written to the file and
+ // vanished from the screen in the same breath — which reads as the press doing nothing.
+ await open();
+ await typeSearch('gare');
+ expect(rows()).toHaveLength(1);
+
+ addGhostRow();
+ await settle();
+ expect(rows()).toHaveLength(1), 'the filter is the analyst own and is not cleared';
+ expect(target.querySelector('.editor')).toBeNull();
+ expect(toast.mock.calls.at(-1)[0]).toContain('hidden by the current filter');
+
+ // And the offer beside it drops the question, chips and search together.
+ toast.mock.calls.at(-1)[3].onClick();
+ await settle();
+ expect(rows()).toHaveLength(4);
+ expect(target.querySelector('.search input').value).toBe('');
+ });
+
+ it('keeps one row under the heading, drawn a second time rather than moved', async () => {
+ await openWith({ meta: { ...structuredClone(SHEET.meta), pinned: 'r2' } });
+ const pinned = target.querySelector('.pinned .row');
+ expect(pinned).not.toBeNull();
+ expect(text(pinned)[1]).toBe('Pont nord');
+ // The rows that scroll are everything else, so the reference is not counted twice.
+ expect(rows().map((row) => text(row)[1])).toEqual(['Quai sud', 'Gare est']);
+ });
+
+ it('does not draw a reference the filter has taken away', async () => {
+ // A row pinned and then filtered out is not on screen, and drawing it there anyway
+ // would be the grid disagreeing with its own count.
+ await openWith({ meta: { ...structuredClone(SHEET.meta), pinned: 'r2' } });
+ await typeSearch('quai');
+ expect(target.querySelector('.pinned')).toBeNull();
+ expect(rows()).toHaveLength(1);
+ });
+
+ it('pins and unpins from the gutter, through the sidecar alone', async () => {
+ vi.useFakeTimers();
+ await open();
+ rows()[0]
+ .querySelector('.gutter')
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ flushSync();
+ [...document.querySelectorAll('.row-menu button')]
+ .find((node) => node.textContent.includes('Keep it in view'))
+ .click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(put.mock.calls.at(-1)[0]).toBe('/api/cases/case-a/sheets/e_sheet/meta');
+ expect(put.mock.calls.at(-1)[1].meta.pinned).toBe('r1');
+ });
+
+ it('gives the rows room for a note, and writes down which of the two it is', async () => {
+ vi.useFakeTimers();
+ await open();
+ expect(target.querySelector('.grid').classList.contains('tall')).toBe(false);
+ button('Tall rows').click();
+ flushSync();
+ expect(target.querySelector('.grid').classList.contains('tall')).toBe(true);
+ expect(button('Short rows')).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].meta.tall).toBe(true);
+ });
+
+ it('names what a colour means, and only for the colours the sheet uses', async () => {
+ vi.useFakeTimers();
+ await openWith({
+ meta: { ...structuredClone(SHEET.meta), colours: { r1: 'red' }, legend: { red: 'ruled out' } },
+ });
+ // Under the rows carrying it, rather than in one analyst's head on a case that gets
+ // handed over.
+ expect(target.querySelector('.foot .legend-chip').textContent.trim()).toBe('ruled out');
+ expect(target.querySelectorAll('.foot .legend-chip')).toHaveLength(1);
+
+ button('Colours').click();
+ flushSync();
+ const line = [...target.querySelectorAll('.legend-menu .line input')][0];
+ line.value = 'checked twice';
+ line.dispatchEvent(new Event('blur', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].meta.legend.red).toBe('checked twice');
+ });
+
+ it('says nothing about colours when the sheet paints with none', async () => {
+ await open();
+ expect(button('Colours')).toBeUndefined();
+ expect(target.querySelector('.foot .legend-chip')).toBeNull();
+ });
+});
+
+describe('the question the sheet was left on', () => {
+ it('opens on the filter and the search the sidecar held', async () => {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ meta: { ...structuredClone(SHEET.meta), query: 'quai' },
+ })
+ : route(path),
+ );
+ await open();
+ expect(target.querySelector('.search input').value).toBe('quai');
+ expect(rows()).toHaveLength(1);
+ });
+
+ it('writes the search down, through the sidecar alone', async () => {
+ // It is a view change, so it never rewrites the CSV — and never enters the undo stack,
+ // because Ctrl+Z is for what was written, not for what was asked.
+ vi.useFakeTimers();
+ await open();
+ const box = target.querySelector('.search input');
+ box.value = 'gare';
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1500);
+
+ expect(put.mock.calls.at(-1)[0]).toBe('/api/cases/case-a/sheets/e_sheet/meta');
+ expect(put.mock.calls.at(-1)[1].meta.query).toBe('gare');
+ expect(target.querySelector('[title^="Undo"]').disabled).toBe(true);
+ });
+
+ /** Keep only the value under the pointer, which is the fastest filter there is. */
+ async function onlyThisValue(rowIndex, columnIndex) {
+ rows()[rowIndex]
+ .querySelectorAll('.cell:not(.gutter)')[columnIndex]
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ await settle();
+ [...document.querySelectorAll('.cell-menu button')]
+ .find((node) => node.textContent.includes('Only'))
+ .click();
+ await settle();
+ }
+
+ it('takes every chip off at once, once there is more than one to take off', async () => {
+ await open();
+ await onlyThisValue(0, 1);
+ // One chip is already one click to clear, so the offer would be noise.
+ expect(button('Clear all')).toBeUndefined();
+
+ await onlyThisValue(0, 2);
+ expect(target.querySelectorAll('.question .chip')).toHaveLength(2);
+ button('Clear all').click();
+ await settle();
+ expect(target.querySelectorAll('.question .chip')).toHaveLength(0);
+ expect(rows()).toHaveLength(3);
+ });
+});
+
+describe('reading what a file that moved on actually says', () => {
+ it('says the file has changed when the window comes back, without refusing anything', async () => {
+ // A stat is cheap enough to ask on every focus, and hearing it now beats hearing it at
+ // the save — with the analyst's own edits on one side and somebody else's on the other.
+ await open();
+ get.mockImplementation((path) =>
+ path.endsWith('/stamp') ? Promise.resolve({ stamp: '9000-64' }) : route(path),
+ );
+ window.dispatchEvent(new Event('focus'));
+ await settle();
+
+ const notice = target.querySelector('.notice');
+ expect(notice.textContent).toContain('changed on disk');
+ expect(notice.classList.contains('danger')).toBe(false);
+ expect([...notice.querySelectorAll('button')].map((n) => n.textContent.trim())).toEqual([
+ 'See what changed',
+ 'Reload',
+ 'Overwrite',
+ 'Later',
+ ]);
+ });
+
+ it('counts and samples the difference before either irreversible press', async () => {
+ await open();
+ get.mockImplementation((path) => {
+ if (path.endsWith('/stamp')) return Promise.resolve({ stamp: '9000-64' });
+ if (path.includes('/sheets/') && !path.endsWith('/sheets')) {
+ return Promise.resolve({
+ ...structuredClone(SHEET),
+ stamp: '9000-64',
+ rows: [
+ ['r1', 'Quai sud', 'done'],
+ ['r2', 'Pont nord', ''],
+ ['r3', 'Gare est', 'to check'],
+ ['r4', 'Bassin ouest', ''],
+ ],
+ });
+ }
+ return route(path);
+ });
+ window.dispatchEvent(new Event('focus'));
+ await settle();
+ button('See what changed').click();
+ await settle();
+
+ const notice = target.querySelector('.notice');
+ expect(notice.textContent).toContain('1 row not in this grid');
+ expect(notice.textContent).toContain('1 cell written differently');
+ // The sample, which is what makes the count believable.
+ const change = notice.querySelector('.diff-rows li');
+ expect(change.textContent).toContain('Status');
+ expect(change.querySelector('.was').textContent.trim()).toBe('ruled out');
+ // Having read it, the choice is the same two presses and no third one.
+ expect(button('See what changed')).toBeUndefined();
+ });
+
+ it('carries on when the file holds the same table, written again', async () => {
+ // A spreadsheet that opened the file and saved it unchanged rewrote every byte of it,
+ // which moves the stamp and changes nothing.
+ await open();
+ get.mockImplementation((path) =>
+ path.endsWith('/stamp')
+ ? Promise.resolve({ stamp: '9000-64' })
+ : path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({ ...structuredClone(SHEET), stamp: '9000-64' })
+ : route(path),
+ );
+ window.dispatchEvent(new Event('focus'));
+ await settle();
+ button('See what changed').click();
+ await settle();
+
+ expect(target.querySelector('.notice')).toBeNull();
+ expect(toast.mock.calls.at(-1)[0]).toContain('same table');
+ });
+});
+
+describe('one row into many, and many into one', () => {
+ it('splits a cell of values into a row each, from the cell own menu', async () => {
+ vi.useFakeTimers();
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ rows: [['r1', 'Buk-M2E, ZU23-2, S-300', 'to check']],
+ })
+ : route(path),
+ );
+ await open();
+ rows()[0]
+ .querySelectorAll('.cell:not(.gutter)')[1]
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ flushSync();
+ [...document.querySelectorAll('.cell-menu button')]
+ .find((node) => node.textContent.includes('Split into rows'))
+ .click();
+ flushSync();
+
+ expect(rows().map((row) => text(row)[1])).toEqual(['Buk-M2E', 'ZU23-2', 'S-300']);
+ // The rest of the row is copied down, so nothing is lost by splitting it.
+ expect(rows().every((row) => text(row)[2] === 'to check')).toBe(true);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(put.mock.calls.at(-1)[1].rows).toHaveLength(3);
+ });
+
+ it('offers no split on a cell holding nothing', async () => {
+ await open();
+ rows()[1]
+ .querySelectorAll('.cell:not(.gutter)')[2]
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ await settle();
+ expect(
+ [...document.querySelectorAll('.cell-menu button')].some((node) =>
+ node.textContent.includes('Split into rows'),
+ ),
+ ).toBe(false);
+ });
+
+ it('folds the ticked rows into the first of them, keeping its key', async () => {
+ vi.useFakeTimers();
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ rows: [
+ ['r1', 'Quai sud', ''],
+ ['r2', 'Quai sud, harbour side', 'to check'],
+ ],
+ })
+ : route(path),
+ );
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ rows()[1].querySelector('.gutter input').click();
+ flushSync();
+ rows()[0]
+ .querySelector('.gutter')
+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));
+ flushSync();
+ [...document.querySelectorAll('.row-menu button')]
+ .find((node) => node.textContent.includes('Merge'))
+ .click();
+ flushSync();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ // The fullest answer per column, and the surviving row keeps its key so its colour,
+ // its links and its promotion record survive with it.
+ expect(put.mock.calls.at(-1)[1].rows).toEqual([['r1', 'Quai sud, harbour side', 'to check']]);
+ });
+});
+
+describe('the handoffs, on the rows that were chosen', () => {
+ it('sends the ticked rows to the map rather than everything on screen', async () => {
+ // An analyst who has just ticked eleven candidates out of four hundred wants those
+ // eleven drawn, not the field.
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve({
+ ...structuredClone(SHEET),
+ columns: ['id', 'Subject', 'Coordinates'],
+ rows: [
+ ['r1', 'Quai sud', '48.85000, 2.35000'],
+ ['r2', 'Pont nord', '48.86000, 2.36000'],
+ ],
+ meta: { ...structuredClone(SHEET.meta), roles: { Coordinates: { kind: 'latlon' } } },
+ })
+ : route(path),
+ );
+ await open();
+ rows()[1].querySelector('.gutter input').click();
+ await settle();
+ button('Map').click();
+ await settle();
+
+ expect(uiState.tool).toBe('satellite');
+ expect(uiState.mapSheetPoints.points).toHaveLength(1);
+ expect(uiState.mapSheetPoints.points[0].label).toBe('Pont nord');
+ });
+
+ it('says so rather than sending nothing when no column holds points', async () => {
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ await settle();
+ button('Map').click();
+ await settle();
+
+ expect(uiState.tool).toBe('sheet');
+ expect(toast.mock.calls.at(-1)[0]).toContain('No column');
+ });
+});
+
+describe('a row moving up a floor', () => {
+ /** A second sheet for it to land in, with one heading spelled the other way. */
+ const WORKLIST = {
+ id: 'e_worklist', title: 'Worklist', path: 'sheets/Worklist.csv',
+ rows: 1, columns: 3, headings: ['id', 'Subject', 'status'],
+ };
+
+ async function openWithSecondSheet() {
+ get.mockImplementation((path) =>
+ path.endsWith('/sheets')
+ ? Promise.resolve({
+ sheets: [
+ { id: SHEET.id, title: SHEET.title, path: SHEET.path, rows: 3, columns: 3,
+ headings: SHEET.columns },
+ WORKLIST,
+ ],
+ })
+ : route(path),
+ );
+ await open();
+ rows()[0].querySelector('.gutter input').click();
+ await settle();
+ button('Move').click();
+ await settle();
+ }
+
+ /** The dialog is portalled onto the body, so its buttons are not under `target`. */
+ const inDialog = (label) =>
+ [...document.querySelectorAll('.move button')].find((node) =>
+ node.textContent.trim().startsWith(label),
+ );
+
+ it('asks where and then which column, and sends what the screens said', async () => {
+ post.mockImplementation(async () => ({
+ moved: 1, landed: ['r1'], dropped: ['Status'],
+ to: { id: WORKLIST.id, title: 'Worklist', rows: 2 },
+ columns: SHEET.columns, rows: SHEET.rows.slice(1), meta: SHEET.meta, stamp: '3000-64',
+ }));
+ await openWithSecondSheet();
+
+ // Nothing writes off the first screen: the drop is read before it happens.
+ inDialog('Next').click();
+ await settle();
+ expect(post).not.toHaveBeenCalled();
+
+ inDialog('Move 1 row').click();
+ await settle();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toContain('/move');
+ expect(body.keys).toEqual(['r1']);
+ // `Status` at this end, `status` at the other: the name match alone called it a loss.
+ expect(body.mapping).toEqual({ Subject: 'Subject', Status: 'status' });
+ });
+
+ it('offers to put it back, and puts the sheet back as it stood', async () => {
+ post.mockImplementation(async () => ({
+ moved: 1, landed: ['r9'], dropped: [],
+ to: { id: WORKLIST.id, title: 'Worklist', rows: 2 },
+ columns: SHEET.columns, rows: SHEET.rows.slice(1), meta: SHEET.meta, stamp: '3000-64',
+ }));
+ await openWithSecondSheet();
+ inDialog('Next').click();
+ await settle();
+ inDialog('Move 1 row').click();
+ await settle();
+
+ expect(rows()).toHaveLength(2);
+ const [message, kind, , action] = toast.mock.calls.at(-1);
+ expect(message).toContain('1 moved to');
+ expect(kind).toBe('ok');
+
+ post.mockImplementation(async () => ({
+ undone: 1, columns: SHEET.columns, rows: SHEET.rows, meta: SHEET.meta, stamp: '4000-64',
+ }));
+ await action.onClick();
+ await settle();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toContain('/move/undo');
+ // The table as it stood, not the move replayed backwards: a move drops the columns the
+ // other sheet does not have, and a reverse one would hand the rows back with holes.
+ expect(body.rows).toHaveLength(3);
+ expect(body.keys).toEqual(['r9']);
+ expect(body.stamp).toBe('3000-64');
+ expect(rows()).toHaveLength(3);
+ });
+});
+
+describe('a geolocation index into proofs', () => {
+ /** The template's own schema: what to call it, what was filmed, what was published, and
+ * where it turns out to be. The one sheet that can feed a build. */
+ const INDEX = {
+ ...SHEET,
+ columns: ['id', 'Title', 'Source media', 'Geolocation proof', 'Coordinates', 'Notes'],
+ rows: [
+ ['r1', 'Bridge strike', 'https://ex.org/clip', 'https://ex.org/pic', '48.85, 2.35', 'south'],
+ ['r2', 'Depot', 'https://ex.org/two', '', '50.45, 30.52', ''],
+ ],
+ meta: {
+ ...structuredClone(SHEET.meta),
+ roles: {
+ 'Source media': { kind: 'url' },
+ 'Geolocation proof': { kind: 'url' },
+ Coordinates: { kind: 'latlon' },
+ },
+ },
+ };
+
+ const PLAN = {
+ rows: [
+ { key: 'r1', action: 'make', title: 'Bridge strike', coords: '48.85, 2.35',
+ writes: 'a proof, its two files and its point', reason: '' },
+ { key: 'r2', action: 'make', title: 'Depot', coords: '50.45, 30.52',
+ writes: 'the footage, posed on its point', reason: '' },
+ ],
+ counts: { make: 2, join: 0, update: 0, skip: 0, error: 0 },
+ pov: false,
+ verb: 'depicts',
+ };
+
+ async function openIndex(sheet = INDEX) {
+ get.mockImplementation((path) =>
+ path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(structuredClone(sheet))
+ : route(path),
+ );
+ await open();
+ target.querySelector('.head .gutter input').click();
+ await settle();
+ }
+
+ async function openBuild(sheet = INDEX) {
+ await openIndex(sheet);
+ button('Build proofs').click();
+ await settle();
+ return document.querySelector('.build');
+ }
+
+ const press_ = (label) =>
+ [...document.querySelectorAll('.build button')]
+ .find((node) => node.textContent.trim().startsWith(label))
+ .click();
+
+ async function preview(plan = PLAN, sheet = INDEX) {
+ const dialog = await openBuild(sheet);
+ post.mockResolvedValueOnce(plan);
+ press_('Preview');
+ await settle();
+ return dialog;
+ }
+
+ it('is offered only on a sheet that can feed it', async () => {
+ // The offer *is* the answer: a button that has to say "this sheet cannot do that"
+ // should not have been drawn.
+ await openIndex();
+ expect(button('Build proofs')).not.toBeUndefined();
+
+ await openIndex({ ...INDEX, meta: structuredClone(SHEET.meta), rows: SHEET.rows,
+ columns: SHEET.columns });
+ expect(button('Build proofs')).toBeUndefined();
+ });
+
+ it('proposes which column is which, and says what a build would write', async () => {
+ const dialog = await preview();
+
+ const [path, body] = post.mock.calls.at(-1);
+ expect(path).toBe('/api/cases/case-a/sheets/e_sheet/proofs/preview');
+ // Filled in from the sheet's own roles and names: nobody should have to say that a
+ // column called *Geolocation proof* is the published picture.
+ expect(body).toMatchObject({
+ title: 'Title',
+ source: 'Source media',
+ proof: 'Geolocation proof',
+ point: 'Coordinates',
+ note: 'Notes',
+ keys: ['r1', 'r2'],
+ pov: false,
+ skip_states: ['ruled out'],
+ });
+ expect([...dialog.querySelectorAll('.plan-row .mark')].map((n) => n.textContent)).toEqual([
+ 'Build',
+ 'Build',
+ ]);
+ expect(dialog.textContent).toContain('a proof, its two files and its point');
+ expect(dialog.textContent).toContain('Build 2 rows');
+ });
+
+ it('runs it as a job, watches the rows go by, and writes the chips back', async () => {
+ await preview();
+ post.mockResolvedValueOnce({ job_id: 'j1' });
+ get.mockImplementation((path) => {
+ if (path === '/api/jobs/j1') {
+ return Promise.resolve({
+ status: 'done',
+ result: {
+ rows: [
+ { key: 'r1', outcome: 'built', reason: '', made: { proof: 'e_p1' } },
+ { key: 'r2', outcome: 'built', reason: '', made: { source: 'e_m2' } },
+ ],
+ counts: { built: 2, restated: 0, failed: 0 },
+ links: { r1: { Title: 'e_p1' }, r2: { 'Source media': 'e_m2' } },
+ stopped: false,
+ },
+ });
+ }
+ return path.includes('/sheets/') && !path.endsWith('/sheets')
+ ? Promise.resolve(structuredClone(INDEX))
+ : route(path);
+ });
+
+ press_('Build 2 rows');
+ await settle();
+
+ expect(post.mock.calls.at(-1)[0]).toBe('/api/cases/case-a/sheets/e_sheet/proofs');
+ expect(toast).toHaveBeenCalledWith('2 built');
+
+ // The plan on screen now describes what *was* true, so pressing again is not offered
+ // until it has been read again: those rows are built, and the case says so.
+ const dialog = document.querySelector('.build');
+ const labels = [...dialog.querySelectorAll('.modal-row button')]
+ .map((node) => node.textContent.trim());
+ // `Done` is the way out, not a `Close` that reads as walking away from something.
+ expect(labels).toEqual(['Preview again', 'Done']);
+
+ // And the press reads as finished rather than as a plan somebody happens to be
+ // looking at: the heading is past tense, the rows say what they turned out to be,
+ // and the loose end this road leaves is named.
+ expect(dialog.textContent).toContain('What it wrote');
+ expect([...dialog.querySelectorAll('.plan-row .mark')].map((n) => n.textContent)).toEqual([
+ 'Built',
+ 'Built',
+ ]);
+ expect(dialog.querySelector('.progress.done').textContent).toContain('2 built');
+ expect(dialog.textContent).toContain('Each row now points at what it produced');
+ expect(dialog.textContent).toContain('export until it is opened in the composer');
+
+ // The sidecar is the browser's to write: the job hands back which cell points at what,
+ // and the sheet's own save is what records it.
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ await settle();
+ const saved = put.mock.calls.at(-1)[1];
+ expect(saved.meta.links).toEqual({ r1: { Title: 'e_p1' }, r2: { 'Source media': 'e_m2' } });
+ });
+
+ it('stops a press that is running, and keeps what it finished', async () => {
+ await preview();
+ post.mockResolvedValueOnce({ job_id: 'j2' });
+ let answered = 0;
+ get.mockImplementation((path) => {
+ if (path === '/api/jobs/j2') {
+ answered += 1;
+ return answered === 1
+ ? Promise.resolve({
+ status: 'running',
+ progress: { done: 1, total: 2, label: 'Depot' },
+ })
+ : Promise.resolve({
+ status: 'done',
+ result: {
+ rows: [{ key: 'r1', outcome: 'built', reason: '', made: {} }],
+ counts: { built: 1, restated: 0, failed: 0 },
+ links: {},
+ stopped: true,
+ },
+ });
+ }
+ return route(path);
+ });
+
+ press_('Build 2 rows');
+ await settle();
+ const dialog = document.querySelector('.build');
+ expect(dialog.querySelector('.progress').textContent).toContain('1 of 2');
+ // Counted in rows, and drawn: two minutes of downloads with only a word on screen is
+ // a wait nobody can tell from a stall.
+ const bar = dialog.querySelector('.progress .bar');
+ expect(bar.getAttribute('aria-valuenow')).toBe('1');
+ expect(bar.getAttribute('aria-valuemax')).toBe('2');
+ expect(bar.querySelector('.fill').style.width).toBe('50%');
+ // A binder's title is a sentence: unbounded beside the bar, one of them squeezed it to
+ // nothing and set the dialog scrolling sideways. It yields, and carries itself on hover.
+ expect(dialog.querySelector('.progress-meta').title).toBe('Depot');
+
+ post.mockResolvedValueOnce({ stopped: true });
+ press_('Stop');
+ await settle();
+ expect(post.mock.calls.at(-1)[0]).toBe('/api/jobs/j2/cancel');
+
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ await settle();
+ expect(toast).toHaveBeenCalledWith('1 built · stopped');
+ });
+
+ it('names a login wall beside the row, with what to do about it', async () => {
+ // A hundred login prompts being impossible, the wall becomes a word beside the row —
+ // and no checkbox, because a session named in Settings is used on its own by the time
+ // a row still comes back walled. The word says which of the two things it is.
+ const WALL = 'needs a login: name a browser in Settings → Downloads';
+ await preview();
+ post.mockResolvedValueOnce({ job_id: 'j3' });
+ get.mockImplementation((path) =>
+ path === '/api/jobs/j3'
+ ? Promise.resolve({
+ status: 'done',
+ result: {
+ rows: [{ key: 'r1', outcome: 'failed', reason: WALL, made: {} }],
+ counts: { built: 0, restated: 0, failed: 1 },
+ links: {},
+ stopped: false,
+ },
+ })
+ : route(path),
+ );
+ press_('Build 2 rows');
+ await settle();
+
+ const dialog = document.querySelector('.build');
+ expect(dialog.querySelector('.plan-row .why').title).toBe(WALL);
+ expect(dialog.textContent).not.toContain('checkbox');
+ expect(post.mock.calls.at(-1)[1]).not.toHaveProperty('use_cookies');
+ });
+
+ it('goes on building when the screen is closed under it', async () => {
+ // The downloads are already happening: closing is not a cancel, and what a row
+ // produced still has to reach the sidecar. Only `Stop` stops it.
+ await preview();
+ post.mockResolvedValueOnce({ job_id: 'j5' });
+ let answered = 0;
+ get.mockImplementation((path) => {
+ if (path === '/api/jobs/j5') {
+ answered += 1;
+ return answered === 1
+ ? Promise.resolve({ status: 'running', progress: { done: 0, total: 2 } })
+ : Promise.resolve({
+ status: 'done',
+ result: {
+ rows: [{ key: 'r1', outcome: 'built', reason: '', made: {} }],
+ counts: { built: 1, restated: 0, failed: 0 },
+ links: { r1: { Title: 'e_p1' } },
+ stopped: false,
+ },
+ });
+ }
+ return route(path);
+ });
+
+ press_('Build 2 rows');
+ await settle();
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ await settle();
+ expect(document.querySelector('.build')).toBeNull();
+
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ await settle();
+ expect(toast).toHaveBeenCalledWith('1 built');
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ await settle();
+ expect(put.mock.calls.at(-1)[1].meta.links).toEqual({ r1: { Title: 'e_p1' } });
+ });
+
+ it('carries a long title and its reason in full, whatever the row shows', async () => {
+ // A binder's title is a sentence. It used to take the whole line and leave four
+ // characters for the reason — which on a failed row is the only part worth reading.
+ const SAID = "'Unavailable video' could not be reached";
+ await preview({
+ ...PLAN,
+ rows: [
+ { ...PLAN.rows[0],
+ title: 'A gunmen attacked the driver of a motorbike. Thanks to the intervention of the BAC' },
+ PLAN.rows[1],
+ ],
+ });
+ post.mockResolvedValueOnce({ job_id: 'j6' });
+ get.mockImplementation((path) =>
+ path === '/api/jobs/j6'
+ ? Promise.resolve({
+ status: 'done',
+ result: {
+ rows: [{ key: 'r1', outcome: 'failed', reason: SAID, made: {} }],
+ counts: { built: 0, restated: 0, failed: 1 },
+ links: {},
+ stopped: false,
+ },
+ })
+ : route(path),
+ );
+ press_('Build 2 rows');
+ await settle();
+
+ const row = document.querySelector('.build .plan-row');
+ expect(row.querySelector('.who').title).toContain('Thanks to the intervention');
+ expect(row.querySelector('.why').title).toBe(SAID);
+ expect(row.querySelector('.why').textContent.trim()).toBe(SAID);
+ });
+
+ it('leaves out the rows the analyst puts aside', async () => {
+ const dialog = await preview();
+ const aside = [...dialog.querySelectorAll('.plan-row .undo')][1];
+ aside.click();
+ await settle();
+ expect(dialog.textContent).toContain('Build 1 row');
+
+ post.mockResolvedValueOnce({ job_id: 'j4' });
+ get.mockImplementation((path) =>
+ path === '/api/jobs/j4'
+ ? Promise.resolve({
+ status: 'done',
+ result: { rows: [], counts: { built: 1, restated: 0, failed: 0 }, links: {},
+ stopped: false },
+ })
+ : route(path),
+ );
+ press_('Build 1 row');
+ await settle();
+ expect(post.mock.calls.at(-1)[1].skip).toEqual(['r2']);
+ });
+});
diff --git a/frontend/src/tools/Sheet.svelte b/frontend/src/tools/Sheet.svelte
new file mode 100644
index 0000000..c8f3cc6
--- /dev/null
+++ b/frontend/src/tools/Sheet.svelte
@@ -0,0 +1,5699 @@
+<script>
+ /**
+ * The Case Sheet: a table the analyst works in, which is a real CSV in the case.
+ *
+ * Three things an investigation needs and no other tool here does. A **comparison
+ * grid** — candidates down, criteria across — which is how eleven leads out of
+ * twelve get ruled out. A **worklist**: seen, ruled out, to check, the reason
+ * written beside it, and a count that says where you are. And a place for the
+ * **half-facts**: a plate half read, a name with no surname, things too soft to be
+ * entities but too valuable to lose. The graph says what the case believes; a
+ * sheet says what it is checking.
+ *
+ * It is not a spreadsheet. No formulas, no cell types, no second copy of the case:
+ * `sheets/<name>.csv` is the artifact, and it opens in LibreOffice the day Azimut
+ * is gone. What the analyst *found* — a status, a verdict, a note — is a column of
+ * that file. What the *grid* remembers — widths, colours, which column stays in
+ * view, which entity a cell points at — is a sidecar beside it, and losing it costs
+ * presentation only.
+ *
+ * Two consequences of the file being the artifact run through everything here.
+ *
+ * The browser never parses or writes **CSV**: it sends a table and gets a table
+ * back (`engine/sheets.py` owns both ends), so an imported file and a saved grid
+ * cannot drift into two readings of the same rows. A clipboard block is not that
+ * case — it is TSV, and a paste is a patch into a selection whose geometry only
+ * this side knows — so `lib/sheetClipboard.js` owns it and a paste costs no round
+ * trip.
+ *
+ * And the analyst may have the same file open in a spreadsheet. So a read hands out
+ * a stamp, every save presents it back, and a save that would overwrite work the
+ * grid never saw is refused: the banner asks, rather than the file losing.
+ *
+ * What a **heading** offers is split three ways, by how often each is wanted: the funnel
+ * asks something of the rows, a right-click (or the `...`) is the short list of gestures
+ * — sort, insert, duplicate, rename, split, hide, delete — and that list's last row opens
+ * the setup panel, where a column is told what it is. The gutter has a menu of its own for
+ * the same reason. Before that split, the `...` opened the panel and half of what an
+ * analyst does to a column had no door at all.
+ *
+ * No rules live in this file. The table, the selection, the clipboard, the cleaning passes
+ * and the undo stack are all pure modules; what is here is the screen.
+ */
+ import { tick, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { closeOnOutsidePointer } from '../lib/dismiss.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { CASE_FOLDER_LABEL, destinationLabel, readDestinations } from '../lib/exportDest.js';
+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import {
+ DEFAULT_WIDTH,
+ GUTTER_WIDTH,
+ ID_COLUMN,
+ ROW_COLOURS,
+ addColumn,
+ addRow,
+ applyEdits,
+ cellRange,
+ clearFilter,
+ clearFilters,
+ dropChip,
+ duplicateColumn,
+ duplicateRows,
+ emptyMeta,
+ explodeRow,
+ fillDownEdits,
+ fillEdits,
+ filterChips,
+ filterSummary,
+ highlightParts,
+ insertColumn,
+ insertRow,
+ isFilterActive,
+ keyIndex,
+ keysBetween,
+ linkAt,
+ linkedEntityIds,
+ linkLabel,
+ mergeRows,
+ moveColumn,
+ nextSecondSort,
+ nextSort,
+ onlyFilterValue,
+ rangeValues,
+ readFilters,
+ removeColumn,
+ removeRows,
+ renameColumn,
+ renameFilterColumn,
+ rowHeight,
+ rowKey,
+ scrollFromThumb,
+ scrollThumb,
+ serializeFilters,
+ setCells,
+ setColour,
+ setFilterContains,
+ setFilterRange,
+ setFilterWithout,
+ setFrozen,
+ setLegend,
+ setLink,
+ setPinned,
+ setTall,
+ setWidth,
+ shownKeys,
+ stickyOffsets,
+ toggleFilterFill,
+ toggleFilterValue,
+ toggleHidden,
+ tooBigBy,
+ urlsIn,
+ visibleColumns,
+ visibleRows,
+ withoutEntities,
+ } from '../lib/sheet.js';
+ import { appendRows } from '../lib/sheetAppend.js';
+ import { linkRows, looksLikeLinks, parseBlock, pasteBlock, toBlock } from '../lib/sheetClipboard.js';
+ import { describeDiff, diffTables, sameTable } from '../lib/sheetDiff.js';
+ import { exportCsv, provenance, revealSheetExports, toMarkdown, viewTable } from '../lib/sheetExport.js';
+ import { cellsEntry, createSheetHistory, snapshotEntry } from '../lib/sheetHistory.js';
+ import { checkLinks, chunk, readVerdicts, urlsInColumn } from '../lib/sheetLinks.js';
+ import {
+ cellChips,
+ columnProgress,
+ cycleTick,
+ flipBoolean,
+ isChipped,
+ numberTotals,
+ duplicateGroups,
+ formatLatLon,
+ nearbyPairs,
+ parseLatLon,
+ parseWhen,
+ pictureRef,
+ precisionMetres,
+ readsCell,
+ suggestProgressColumn,
+ tickState,
+ } from '../lib/sheetRoles.js';
+ import { backLinks, rowLabel, rowTargets } from '../lib/sheetRows.js';
+ import { SHEET_TEMPLATES, sheetTemplate, templateMeta } from '../lib/sheetTemplates.js';
+ import { canBuild, columnKinds } from '../lib/sheetBuild.js';
+ import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import EntityDetails from '../components/EntityDetails.svelte';
+ import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
+ import SheetAppend from '../components/SheetAppend.svelte';
+ import SheetCellEditor from '../components/SheetCellEditor.svelte';
+ import SheetClean from '../components/SheetClean.svelte';
+ import SheetColumnPanel from '../components/SheetColumnPanel.svelte';
+ import SheetEntityPicker from '../components/SheetEntityPicker.svelte';
+ import SheetFilterMenu from '../components/SheetFilterMenu.svelte';
+ import SheetFromCase from '../components/SheetFromCase.svelte';
+ import SheetGeocode from '../components/SheetGeocode.svelte';
+ import SheetHeadingMenu from '../components/SheetHeadingMenu.svelte';
+ import SheetHelp from '../components/SheetHelp.svelte';
+ import SheetLegend from '../components/SheetLegend.svelte';
+ import SheetAnchors from '../components/SheetAnchors.svelte';
+ import SheetToCase from '../components/SheetToCase.svelte';
+ import SheetBuildProofs from '../components/SheetBuildProofs.svelte';
+ import SheetMove from '../components/SheetMove.svelte';
+ import SheetRowMenu from '../components/SheetRowMenu.svelte';
+ import SheetRowPanel from '../components/SheetRowPanel.svelte';
+
+ const HEAD_H = 32;
+ /** How long the two lines above the grid may be. Mirrors `engine/sheets.MAX_DESCRIPTION`,
+ * which is what actually holds: this only stops the box growing past what is read. */
+ const MAX_DESCRIPTION = 400;
+ const OVERSCAN = 10;
+
+ let sheets = $state([]);
+ let openId = $state(null);
+ let title = $state('');
+ let table = $state({ columns: [], rows: [] });
+ let meta = $state(emptyMeta());
+ /** The file on disk has no key column yet — someone edited it elsewhere. */
+ let assigned = $state(false);
+ /** What the file looked like when it was read. Presented back on every save. */
+ let stamp = $state('');
+ /** The file moved on under the grid: nothing more is written until this is answered. */
+ let conflict = $state(false);
+ let loading = $state(false);
+ let saveState = $state('idle'); // 'idle' | 'dirty' | 'saving' | 'saved' | 'failed'
+ /** Counted up by every edit. A write carries the number the grid was at when it left,
+ * so a reply can be told from an out-of-date one. Not reactive: nothing draws it. */
+ let revision = 0;
+ /** The write in flight, so the next one queues behind it rather than racing it. */
+ let inFlight = null;
+ /**
+ * Whether anything unsaved touches the **table**, rather than only the sidecar.
+ *
+ * What decides which of the two save routes a pass takes. A filter, a colour, a width, a
+ * hidden column and a pinned row are the grid: they go through `PUT .../meta`, which
+ * leaves the CSV byte-identical — because rewriting the file to record that a funnel was
+ * clicked moved its modification time, which is what the stamp is made of, and the
+ * analyst's own next save then answered a conflict nobody caused.
+ *
+ * Sticky until a full save lands: a table change still pending means the sidecar may
+ * refer to a column that is not on disk yet, and the meta route cleans against the file.
+ */
+ let pendingTable = false;
+ /** The file moved on under the grid but nothing is lost yet — said softly, because the
+ * analyst is mid-sentence and the answer is theirs. `{ diff }` once it is read. */
+ let stale = $state(null);
+ let comparing = $state(false);
+
+ /**
+ * What is typed, and what the grid is filtered on.
+ *
+ * Two values because they answer on different clocks: the box has to echo the keystroke
+ * at once, and narrowing twenty thousand rows must not run on every letter of `kherson`.
+ * The delay is short enough to read as instant and long enough that a word costs one pass
+ * rather than seven.
+ */
+ let queryInput = $state('');
+ let query = $state('');
+ let queryTimer = null;
+ let filters = $state({}); // column -> what is asked of it
+ let cursor = $state({ row: -1, column: -1 }); // in table coordinates
+ /** The other end of a selected rectangle, in table coordinates. */
+ let anchor = $state(null);
+ let editing = $state(null); // { row, column, value }
+ let picked = $state(new Set()); // row keys ticked in the gutter
+ /** The last row ticked by hand, so shift-click knows where the range starts. */
+ let lastTicked = $state(null);
+
+ let picker = $state(null); // the sheet menu
+ /** The ways a sheet is started, under one button: a blank one, a file, a paste, the
+ * case's own entities, and rows into the sheet already open. */
+ let newOpen = $state(false);
+ let newAnchor = $state(null);
+ let creating = $state(null); // { title } | { title, text } for an import or a paste
+ /** What is waiting to be confirmed, and which of the three it is. Every delete here
+ * goes through it: a column carries a role and a note nothing else remembers, and a
+ * batch of rows is however many were ticked, which is exactly the number nobody
+ * wants to find out afterwards. */
+ let confirming = $state(null); // { kind: 'sheet' | 'column' | 'rows', ... }
+ let exporting = $state(false);
+ let detailsId = $state(null); // an entity opened from a linked cell
+ let detailsDirty = $state(false); // Details holds edits its own Save has not taken
+ let discarding = $state(false); // asking before those edits are thrown away
+ let linking = $state(null); // { row, column }
+ let rowPanel = $state(null); // a row read down instead of across, by table index
+ /** Which column the right-hand panel is showing, by table index. It follows the
+ * next heading clicked rather than closing, which is what a menu could not do. */
+ let columnPanel = $state(null);
+ let columnsOpen = $state(false);
+ /**
+ * Which heading's filter menu is open, and where to draw it.
+ *
+ * The position travels with the state because the menu is rendered **outside** the
+ * scroller: inside it, `overflow: auto` would clip it and the grid's own scrollbars
+ * would grow to account for a menu that is not content. So it is placed from the
+ * funnel's rectangle, read once — and the grid scrolling closes it, since the
+ * heading it belongs to has moved.
+ */
+ let filterAt = $state(null); // { index, x, y }
+ let filterMenu = $state(null);
+ /** Every heading's funnel, by column name. Bound so the columns list can open the
+ * menu of a column that is not on screen, after bringing it there. */
+ const funnels = $state({});
+ /** A cell's own menu: filtering where the answer actually is, rather than by walking
+ * up to the heading of the column it is in. */
+ let cellMenu = $state(null); // { row, column, value, x, y }
+ let cellMenuEl = $state(null);
+ let filling = $state(null); // { column } while a column is filled in bulk
+ /** The answer being written, kept beside `filling` rather than inside it: an input
+ * bound into an object still reads it once as the object is cleared away. */
+ let fillValue = $state('');
+ let dragColumn = $state(null); // { from, over } while a heading is dragged
+ let dropping = $state(false); // a file is over the grid
+ let selecting = $state(false); // a pointer is held down, pulling a selection
+ // Each popover's own wrapper, holding both its trigger and its panel. Bound so a
+ // pointer landing outside closes it — and so a pointer on the trigger does not,
+ // which would close and reopen it in one click.
+ let pickerAnchor = $state(null);
+ let columnsAnchor = $state(null);
+ /** Roles the file lost, because a column they named is gone. Said, not swallowed. */
+ let droppedRoles = $state([]);
+ /** A reading over one column, shown under the question bar until it is dismissed:
+ * what a column repeats, or which of its points sit on top of each other. */
+ let reading = $state(null);
+ /** What changed in a row this session, keyed by the row's own key rather than its
+ * position, so a sort or a delete cannot move a log onto another row. Session-only:
+ * a durable one would be a new file, which means a Trash and a bundle decision. */
+ let rowLog = $state(new Map());
+ let promoting = $state(false); // the ticked rows are being turned into entities
+ let promoteOpen = $state(false);
+ /** Building proofs out of a geolocation index: the one road out of a sheet that fetches
+ * files, so it runs as a job with a progress and a stop rather than as a request. */
+ let buildOpen = $state(false);
+ let buildJob = $state(null); // { id, progress } while the press is running
+ let buildReport = $state(null); // what the press came back with, until the screen closes
+ /** The named moments an offset column counts from. One sheet, several of them. */
+ let anchorsOpen = $state(false);
+ /** Moving the ticked rows up a floor, into another sheet at the same schema. */
+ let moving = $state(false);
+ /** Which row is being given a case file to carry, by row key. */
+ let attaching = $state(null);
+ /** Entity id → what it is called, for the pieces a row carries. Presentation only: the
+ * sidecar holds ids, and this is what the read answers so the panel can name them. */
+ let pieces = $state({});
+ /** The two lines above the grid, while they are being written. */
+ let describing = $state(false);
+ let describeText = $state('');
+ /** The heading's short menu — the frequent gestures, one press from the heading itself
+ * and from a right-click on it. `{ index, x, y }`. */
+ let headMenu = $state(null);
+ let headMenuEl = $state(null);
+ /** The gutter's own menu, on the row under the pointer. `{ row, x, y }`. */
+ let rowMenu = $state(null);
+ let rowMenuEl = $state(null);
+ /** Which heading is being renamed in place, by table index. Double-click, which is what
+ * a spreadsheet does and what the panel made a two-click trip. */
+ let renaming = $state(null);
+ let renameText = $state('');
+ /** A cleaning pass being set up: `{ column, mode }`. */
+ let cleaning = $state(null);
+ /** A whole column being pointed at the case, by table index. */
+ /** The worklist being built out of the catalog. */
+ let fromCase = $state(false);
+ let building = $state(false);
+ /** A batch of rows being added to the sheet that is already open. */
+ let appending = $state(false);
+ /** A geocoding pass being set up: `{ index, mode }`, forward or reverse. */
+ let geocoding = $state(null);
+ /** Which way to hand the sheet over, when that menu is open. */
+ let exportOpen = $state(false);
+ let exportAnchor = $state(null);
+ /** Where a CSV lands: `null` until Settings answers, `''` for the case's own folder. */
+ let destination = $state(null);
+ let destPicker = $state(false);
+ /** The list of gestures, which nothing else in the tool announces. */
+ let helpOpen = $state(false);
+ /** What each row colour means in this sheet. */
+ let legendOpen = $state(false);
+ let legendAnchor = $state(null);
+ /** Narrowing the sheet list, once a case holds more than a handful. */
+ let sheetTerm = $state('');
+ /** A link sweep in flight: `{ column, done, total }`. */
+ let checking = $state(null);
+
+ const history = createSheetHistory();
+ // The stack itself is plain, so its two answers are mirrored into state the
+ // buttons can read — the same shape Inspect's collage history uses.
+ let canUndo = $state(false);
+ let canRedo = $state(false);
+ let saveTimer = null;
+ let scroller = $state(null);
+ let searchBox = $state(null);
+ let scrollTop = $state(0);
+ let viewport = $state(600);
+ /** What the scroller measures, re-read on every scroll and resize. The bars are
+ * drawn from this rather than from the browser's own. */
+ let extent = $state({ scrollW: 0, clientW: 0, scrollH: 0, clientH: 0, left: 0, top: 0 });
+ let dragging = $state(null); // 'x' | 'y' while a thumb is held
+
+ const caseId = $derived(caseState.current?.id ?? null);
+ const drawn = $derived(visibleColumns(table.columns, meta));
+ const roles = $derived(meta.roles ?? {});
+ /** One row's height, and the reason the grid can hold twenty thousand of them: only the
+ * rows on screen are in the DOM. Fixed for a given sheet, so the arithmetic stays one
+ * division — but the sheet chooses which of the two heights, because a worklist wants
+ * thirty pixels and the column the reasoning is written in cannot live in one line. */
+ const rowH = $derived(rowHeight(meta));
+ const matching = $derived(visibleRows(table, { query, filters, sort: meta.sort, roles }));
+ /** The row kept under the heading, by table index, when it is one of the rows the filter
+ * left: a reference pinned and then filtered away is not on screen, and drawing it there
+ * anyway would be the grid disagreeing with its own count. */
+ const pinnedAt = $derived(
+ meta.pinned
+ ? matching.find((index) => rowKey(table.columns, table.rows[index]) === meta.pinned) ?? -1
+ : -1,
+ );
+ /** What scrolls: everything matching except the pinned row, which is drawn above it. */
+ const shown = $derived(pinnedAt === -1 ? matching : matching.filter((index) => index !== pinnedAt));
+ /** Which column says how far along the work is, and what it says. Any column, with or
+ * without a role: the binder this most has to replace is a geolocation index with no
+ * status column at all, and its question is the fill rate of one column. */
+ const progressAt = $derived(table.columns.indexOf(meta.progress ?? ''));
+ const progress = $derived(
+ progressAt === -1 ? null : columnProgress(table, progressAt, roles[meta.progress]),
+ );
+ const chips = $derived(filterChips(filters));
+ const offsets = $derived(stickyOffsets(drawn, meta));
+ const range = $derived(cellRange(shown, drawn, anchor, cursor));
+ const selectedRows = $derived(new Set(range.rows));
+ const selectedColumns = $derived(new Set(range.columns));
+ /** Whether the selection is more than the one cell under the cursor: what decides
+ * if copying and filling down have something to work on. */
+ const hasRange = $derived(range.rows.length > 1 || range.columns.length > 1);
+ const allShownTicked = $derived(
+ shown.length > 0 && shownKeys(table, shown).every((key) => picked.has(key)),
+ );
+
+ /**
+ * The rows every action that works on *rows* works on.
+ *
+ * There were two selections and they disagreed. Ticking rows in the gutter drove the
+ * fill, the paint, the delete and the promotion; dragging across cells drove the copy,
+ * the fill-down and the clear. So a screenful of rows selected by dragging offered no
+ * way to paint them, and forty ticked rows could not be copied.
+ *
+ * One rule now: **what is ticked, or failing that what is selected.** Ticking is
+ * deliberate and survives a scroll, so it wins where both exist; a drag over three rows
+ * is a selection like any other and gets the same actions. The bar says which of the
+ * two it is holding, because "40 rows" that turn out to be the wrong forty is the one
+ * thing this must not do.
+ */
+ const batchIndices = $derived(
+ picked.size
+ ? table.rows
+ .map((row, index) => index)
+ .filter((index) => picked.has(rowKey(table.columns, table.rows[index])))
+ : range.rows.length > 1
+ ? range.rows
+ : [],
+ );
+ const batchKeys = $derived(batchIndices.map((index) => rowKey(table.columns, table.rows[index])));
+ /** The same rows, said one by one, for the screen that asks before it moves them: a
+ * key, whatever the row is called, and the colour it was painted. */
+ const batchRows = $derived(
+ batchIndices.map((index) => {
+ const row = table.rows[index] ?? [];
+ const at = keyIndex(table.columns);
+ const said = row.find((cell, column) => column !== at && String(cell ?? '').trim());
+ const key = rowKey(table.columns, row);
+ return { key, label: String(said ?? '').trim().slice(0, 90), colour: meta.colours?.[key] };
+ }),
+ );
+ const template = $derived(
+ ['34px', ...drawn.map((column) => `${meta.widths?.[column.name] ?? DEFAULT_WIDTH}px`)].join(' '),
+ );
+ /** The heading row carries one track more than a body row: the button that adds
+ * a column. Without it that button falls onto an implicit second row. */
+ const headTemplate = $derived(`${template} 34px`);
+ const hThumb = $derived(scrollThumb(extent.clientW, extent.scrollW, extent.left));
+ const vThumb = $derived(scrollThumb(extent.clientH, extent.scrollH, extent.top));
+ /** What sits above the scrolling rows and stays there: the heading, and the pinned
+ * reference row when there is one. Everything that turns a scroll position into a row
+ * index goes through it, or the cursor lands underneath the row it was walked to. */
+ const headRoom = $derived(HEAD_H + (pinnedAt === -1 ? 0 : rowH));
+ const first = $derived(Math.max(0, Math.floor((scrollTop - headRoom) / rowH) - OVERSCAN));
+ const last = $derived(
+ Math.min(shown.length, Math.ceil((scrollTop - headRoom + viewport) / rowH) + OVERSCAN),
+ );
+ const window_ = $derived(shown.slice(first, Math.max(first, last)));
+ /** How many rows carry each colour, for the legend: a colour nothing uses is not worth
+ * naming, and the count is what says so. */
+ const colourCounts = $derived(
+ Object.values(meta.colours ?? {}).reduce(
+ (counts, colour) => ({ ...counts, [colour]: (counts[colour] ?? 0) + 1 }),
+ {},
+ ),
+ );
+ /** The colours actually in the sheet, with what they were said to mean. Drawn in the
+ * footer, so the meaning sits under the rows rather than in one analyst's head. */
+ const legendUsed = $derived(
+ ROW_COLOURS.filter((colour) => colourCounts[colour]).map((colour) => ({
+ colour,
+ label: meta.legend?.[colour] ?? '',
+ rows: colourCounts[colour],
+ })),
+ );
+ const sheetsShown = $derived(
+ sheetTerm.trim()
+ ? sheets.filter((sheet) =>
+ String(sheet.title ?? '').toLowerCase().includes(sheetTerm.trim().toLowerCase()),
+ )
+ : sheets,
+ );
+
+ // -- loading ---------------------------------------------------------------
+
+ $effect(() => {
+ const id = caseId;
+ caseState.rev; // re-list when the case reloads: a sheet may have been deleted
+ if (!id) return;
+ untrack(() => list(id));
+ });
+
+ async function list(id) {
+ try {
+ const answer = await api.get(`/api/cases/${id}/sheets`);
+ sheets = answer.sheets ?? [];
+ if (openId && !sheets.some((sheet) => sheet.id === openId)) close();
+ // The one that was being worked on, and the first sheet only as a fallback. A tool
+ // that reopened on sheet number one sent the analyst back through the picker every
+ // morning, and on a case holding nine worklists that is the wrong nine times out of
+ // ten.
+ if (!openId && sheets.length) {
+ const last = lastOpened(id);
+ open(sheets.some((sheet) => sheet.id === last) ? last : sheets[0].id);
+ }
+ } catch {
+ sheets = [];
+ }
+ }
+
+ /** Which sheet this case was last left on. Kept in the browser rather than in the case:
+ * it is where *this* analyst was reading, not something the case believes, and a bundle
+ * carrying it would hand a colleague somebody else's place in the work. */
+ const LAST_KEY = 'azimut.sheet.last';
+
+ function lastOpened(id) {
+ try {
+ return JSON.parse(localStorage.getItem(LAST_KEY) ?? '{}')[id] ?? null;
+ } catch {
+ return null;
+ }
+ }
+
+ function rememberOpened(id, sheetId) {
+ try {
+ const held = JSON.parse(localStorage.getItem(LAST_KEY) ?? '{}');
+ localStorage.setItem(LAST_KEY, JSON.stringify({ ...held, [id]: sheetId }));
+ } catch {
+ // A browser refusing storage is not a reason to refuse the sheet.
+ }
+ }
+
+ async function open(id) {
+ if (id === openId) return;
+ await flush();
+ loading = true;
+ picker = null;
+ try {
+ adopt(await api.get(`/api/cases/${caseId}/sheets/${id}`), { reset: true });
+ openId = id;
+ rememberOpened(caseId, id);
+ } catch (error) {
+ toast(error.message || 'This sheet could not be opened.', 'error');
+ } finally {
+ loading = false;
+ }
+ }
+
+ /** Take a table the server just handed over. `reset` is a different sheet or the
+ * same one re-read from disk, and either way the undo stack no longer describes
+ * anything: keeping it would let an undo replay edits onto rows that moved. */
+ function adopt(sheet, { reset = false } = {}) {
+ title = sheet.title ?? title;
+ table = { columns: sheet.columns ?? [], rows: sheet.rows ?? [] };
+ meta = { ...emptyMeta(), ...(sheet.meta ?? {}) };
+ assigned = Boolean(sheet.assigned);
+ stamp = sheet.stamp ?? '';
+ conflict = false;
+ stale = null;
+ saveState = 'idle';
+ if (sheet.dropped_roles?.length) droppedRoles = sheet.dropped_roles;
+ // What the case files a row carries are called. Answered by the read rather than
+ // stored beside the ids, because a label kept in the sidecar goes stale the moment
+ // the entity is renamed — and merged rather than replaced, since a save answers no
+ // pieces and one attached a second ago would lose its name.
+ if (sheet.pieces) pieces = { ...pieces, ...sheet.pieces };
+ if (reset) {
+ resetView();
+ history.reset();
+ rowLog = new Map();
+ canUndo = false;
+ canRedo = false;
+ // The question the sheet was left on, and only that. A head start used to be posted
+ // on top of it — the progress column's empty rows, as a chip — and it could not tell
+ // "the analyst cleared their filters" from "this sheet has never been asked
+ // anything", because both are an empty table in the sidecar. So it came back every
+ // time the sheet was reopened, which reads exactly as a filter appearing from
+ // nowhere. The footer already offers those rows in one click, named and asked for.
+ filters = readFilters(meta.filters, table.columns);
+ queryInput = meta.query ?? '';
+ query = queryInput;
+ }
+ }
+
+ /**
+ * Open on the rows still to do, when the sheet says which column that is.
+ *
+ * Posted as an ordinary filter, so it shows as a chip and one click clears it. A sheet
+ * that opened having quietly hidden three hundred rows would be a bug to whoever
+ * opened it — the point is a head start, not a hidden state.
+ *
+ * And only when there is actually something left. A finished worklist used to open on a
+ * filter matching nothing: an empty grid over `0 of 468`, which reads as a lost sheet
+ * rather than as a job done.
+ */
+
+ function close() {
+ openId = null;
+ table = { columns: [], rows: [] };
+ meta = emptyMeta();
+ stamp = '';
+ conflict = false;
+ stale = null;
+ resetView();
+ }
+
+ function resetView() {
+ query = '';
+ queryInput = '';
+ filters = {};
+ cursor = { row: -1, column: -1 };
+ anchor = null;
+ editing = null;
+ picked = new Set();
+ lastTicked = null;
+ rowPanel = null;
+ columnPanel = null;
+ reading = null;
+ filling = null;
+ if (scroller) scroller.scrollTop = 0;
+ }
+
+ /**
+ * What is typed, applied a moment later.
+ *
+ * The pass over the table is cheap per row and there are twenty thousand of them, so a
+ * letter costing a full pass is a box that stutters. The term is also part of the reading,
+ * so it is written to the sidecar — through the same debounce, since a save per keystroke
+ * would be worse than the pass.
+ */
+ function onQuery(value) {
+ queryInput = value;
+ clearTimeout(queryTimer);
+ queryTimer = setTimeout(() => {
+ query = queryInput;
+ rememberView();
+ }, 180);
+ }
+
+ /**
+ * Write down what the analyst is looking at.
+ *
+ * The sidecar always carried half a reading — the sort, the hidden columns, the widths —
+ * and the half that decides which rows are on screen lived in this tab and died with it.
+ * So a sheet reopened showing all four hundred rows and the question had to be rebuilt
+ * every morning, on a tool whose stated answer to saved views is *the sheet is its own
+ * saved reading*.
+ *
+ * It is a **view** change: it never enters the undo stack, because Ctrl+Z is for what was
+ * written, not for what was asked, and it goes out through the sidecar-only route.
+ */
+ function rememberView() {
+ if (!openId) return;
+ const asked = serializeFilters(filters);
+ if (JSON.stringify(asked) === JSON.stringify(meta.filters ?? {}) && (meta.query ?? '') === query) {
+ return;
+ }
+ meta = { ...meta, filters: asked, query };
+ touch({ table: false });
+ }
+
+ /** Change one column's filter and remember it. Every funnel, chip and cell menu goes
+ * through here, so none of them can be the one that forgets. */
+ function ask(next) {
+ filters = next;
+ rememberView();
+ }
+
+ // -- saving ----------------------------------------------------------------
+ //
+ // A grid autosaves. Asking someone to press Save after every cell is asking them
+ // to lose work, and the file is the artifact — it should hold what is on screen.
+
+ function snapshot({ withTable = true } = {}) {
+ return JSON.stringify(withTable ? { table, meta } : { meta });
+ }
+
+ /** Mark the sheet unsaved and schedule the write. Nothing is scheduled while a
+ * conflict stands: the analyst has to say whether to reload or to overwrite, and
+ * retrying behind them would be a queue of refusals.
+ *
+ * `table: false` says the change is the sidecar's alone — a filter, a colour, a width —
+ * which is what lets the write go out without rewriting the CSV. Sticky until a full
+ * save lands: a table change still pending means the file does not hold the columns the
+ * sidecar talks about yet. */
+ function touch({ table: touchesTable = true } = {}) {
+ canUndo = history.canUndo;
+ canRedo = history.canRedo;
+ revision += 1;
+ if (touchesTable) pendingTable = true;
+ saveState = 'dirty';
+ clearTimeout(saveTimer);
+ if (!conflict) saveTimer = setTimeout(save, 900);
+ }
+
+ /** Record a run of cell edits and apply them. The common path, and the cheap one:
+ * what is kept is the cells, not the table. */
+ function editCells(edits) {
+ if (!edits?.length) return;
+ // A cell emptied loses what it pointed at. A blank cell still holding a link is a
+ // link nobody can see, reach or clear — and it would keep its `mentions` edge on
+ // every save, so the case would go on believing a row that says nothing.
+ const orphans = edits.filter(
+ (edit) => !String(edit.after ?? '').trim() && linkOf(edit.row, table.columns[edit.column]),
+ );
+ if (orphans.length) {
+ logEdits(edits);
+ // The sidecar moves too, so this is one whole-table step rather than a patch.
+ structural(() => {
+ table = applyEdits(table, edits, 'forward');
+ let next = meta;
+ for (const edit of orphans) {
+ const key = rowKey(table.columns, table.rows[edit.row]);
+ next = setLink(next, key, table.columns[edit.column], null);
+ }
+ meta = next;
+ });
+ return;
+ }
+ logEdits(edits);
+ table = applyEdits(table, edits, 'forward');
+ history.record(cellsEntry(edits));
+ touch();
+ }
+
+ /** Note what changed, before the table moves: the row's key is still the one the edit
+ * was aimed at, and it is filed against that key rather than the row's position — a
+ * sort between two edits would otherwise file the second against somebody else's row. */
+ function logEdits(edits) {
+ const log = new Map(rowLog);
+ for (const edit of edits) {
+ const key = rowKey(table.columns, table.rows[edit.row]);
+ if (!key) continue;
+ const entries = [...(log.get(key) ?? [])];
+ entries.push({ column: table.columns[edit.column], before: edit.before, after: edit.after });
+ log.set(key, entries.slice(-40));
+ }
+ rowLog = log;
+ }
+
+ /** Record a change no list of cells describes — a column added, moved or dropped,
+ * rows deleted, a paste that grew the sheet — by keeping the table on both sides.
+ * `withTable: false` is for a change that only touches the sidecar, which is
+ * kilobytes rather than megabytes on a long sheet. */
+ function structural(change, { withTable = true } = {}) {
+ const before = snapshot({ withTable });
+ change();
+ history.record(snapshotEntry(before, snapshot({ withTable })));
+ // The same flag answers both questions, because they are the same question: a step the
+ // undo stack can describe with the sidecar alone is a step the save can write with the
+ // sidecar alone.
+ touch({ table: withTable });
+ }
+
+ /**
+ * Write the sheet, one write at a time.
+ *
+ * Serialised rather than fired off, because every write presents the `stamp` it read
+ * the file at. Two in the air present the same one, the second is answered with the
+ * conflict banner, and the analyst is asked to arbitrate a race between their own
+ * keystrokes. Queueing behind the one in flight is what makes the stamp current
+ * again by the time the next write reads it.
+ */
+ async function save({ force = false } = {}) {
+ clearTimeout(saveTimer);
+ if (!openId || !caseId) return;
+ const mine = (inFlight = inFlight ? inFlight.then(() => write(force)) : write(force));
+ try {
+ await mine;
+ } finally {
+ if (inFlight === mine) inFlight = null;
+ }
+ }
+
+ /**
+ * One write, down whichever of the two roads the change needs.
+ *
+ * A sheet's state is two things and they are not written the same way. The **table** is
+ * the artifact: it goes with the stamp, and a save that would overwrite work the grid
+ * never saw is refused. The **sidecar** is the grid: widths, colours, the sort, the
+ * filters, the pinned row. Sending the sidecar through the table's route meant rewriting
+ * the CSV to record that a funnel had been clicked — which moved the modification time
+ * the stamp is made of, so the analyst's own next save answered a conflict nobody caused,
+ * and a spreadsheet open on the same file was told it had been overwritten.
+ */
+ async function write(force) {
+ const id = openId;
+ const sent = revision;
+ const tableToo = pendingTable;
+ saveState = 'saving';
+ try {
+ const saved = tableToo
+ ? await api.put(`/api/cases/${caseId}/sheets/${id}`, {
+ columns: table.columns,
+ rows: table.rows,
+ meta,
+ // Forcing is the analyst answering the banner: write over what is there.
+ ...(force ? {} : { stamp }),
+ })
+ : await api.put(`/api/cases/${caseId}/sheets/${id}/meta`, { meta });
+ if (openId !== id) return; // the analyst moved on while this was in flight
+ // Only the table's own route writes the file, so only it hands back a new stamp.
+ if (tableToo) stamp = saved.stamp ?? '';
+ conflict = false;
+ stale = null;
+ // Edits landed while this was in the air, so what came back describes the sheet
+ // as it was *before* them. Adopting it would flip the cell they just ticked back
+ // under their hand and then write that revert on the next pass. The sheet stays
+ // unsaved and the write `touch` already scheduled carries them instead — including
+ // the fact that the table is dirty, which is why the flag is cleared only here.
+ if (revision !== sent) {
+ saveState = 'dirty';
+ return;
+ }
+ if (tableToo) pendingTable = false;
+ // The server is the one that cleans the sidecar, so what comes back is what
+ // the case holds; adopting it is how a stale colour stops being drawn.
+ meta = { ...emptyMeta(), ...(saved.meta ?? {}) };
+ if (tableToo) {
+ table = { columns: saved.columns, rows: saved.rows };
+ assigned = false;
+ }
+ saveState = 'saved';
+ } catch (error) {
+ saveState = 'failed';
+ if (error?.status === 409) {
+ // Said by the banner, which offers the two ways out. A toast on top of it
+ // would say the same thing twice and then vanish.
+ conflict = true;
+ return;
+ }
+ toast(error.message || 'This sheet could not be saved.', 'error');
+ }
+ }
+
+ /**
+ * Whether the grid is holding work the file does not have yet.
+ *
+ * Which is exactly what `Reload` throws away, and what the banner had no word for: it
+ * dressed `Overwrite` as the dangerous one and left `Reload` looking like the safe
+ * default, when in a conflict it is the analyst's *own* unsaved edits that it drops —
+ * along with the undo stack, since a re-read resets it.
+ */
+ const unsaved = $derived(saveState === 'dirty' || saveState === 'failed' || conflict);
+
+ /** Re-read the file and lose the grid's version of it. */
+ async function reload() {
+ try {
+ adopt(await api.get(`/api/cases/${caseId}/sheets/${openId}`), { reset: true });
+ } catch (error) {
+ toast(error.message || 'This sheet could not be opened.', 'error');
+ }
+ }
+
+ /** Write anything pending before leaving the sheet, so switching never drops an edit. */
+ async function flush() {
+ if (saveState === 'dirty') await save();
+ }
+
+ $effect(() => () => {
+ clearTimeout(saveTimer);
+ clearTimeout(queryTimer);
+ });
+
+ /**
+ * Ask the file whether it is still the one this grid read, when the window comes back.
+ *
+ * The stamp was only ever checked by a save, which meant an analyst who edited the CSV in
+ * a spreadsheet went on working in a grid showing the old table — sometimes for an hour —
+ * and found out at the moment they were least able to choose: a refusal, with their own
+ * edits on one side and somebody's on the other.
+ *
+ * A stat is cheap enough to ask on every focus. It is deliberately **not** a conflict:
+ * nothing has been refused, so the banner says what is on disk and offers to read it.
+ */
+ async function checkStamp() {
+ if (!openId || !caseId || conflict || !stamp || uiState.tool !== 'sheet') return;
+ try {
+ const answer = await api.get(`/api/cases/${caseId}/sheets/${openId}/stamp`);
+ if (answer.stamp && answer.stamp !== stamp) stale = { diff: null };
+ } catch {
+ // Offline or the sheet is gone: the ordinary save will say so, in the place that can.
+ }
+ }
+
+ /**
+ * Read what the file holds and say how it differs, without taking it.
+ *
+ * The whole point of the banner having a third button. "Reload" and "Overwrite" are both
+ * irreversible in the direction that matters, and until now the analyst chose between them
+ * over one sentence saying the file had moved on — three rows a colleague added and one
+ * stray cell they fixed themselves were the same press.
+ */
+ async function compare() {
+ if (!openId || comparing) return;
+ comparing = true;
+ try {
+ const disk = await api.get(`/api/cases/${caseId}/sheets/${openId}`);
+ const diff = diffTables(table, { columns: disk.columns, rows: disk.rows });
+ // A spreadsheet that opened the file and saved it unchanged rewrote every byte of it,
+ // which moves the stamp and changes nothing. Saying so is the answer that ends it.
+ if (sameTable(diff)) {
+ stamp = disk.stamp ?? stamp;
+ stale = null;
+ conflict = false;
+ toast('The file holds the same table.');
+ return;
+ }
+ if (conflict) conflict = true;
+ stale = { diff };
+ } catch (error) {
+ toast(error.message || 'That file could not be read.', 'error');
+ } finally {
+ comparing = false;
+ }
+ }
+
+ // -- the sheet list --------------------------------------------------------
+
+ /**
+ * File a new sheet, or a pasted table as one.
+ *
+ * A **template** is columns and what the app should know about them: a verification
+ * worklist arrives with its status column already a state, a geolocation index with its
+ * coordinates already a point. Those are the four tables an analyst rebuilds by hand every
+ * case, ten minutes of naming columns before any work happens — and each one slightly
+ * different, which is why two of their sheets never compare.
+ *
+ * The roles are laid on afterwards rather than at creation: the browser owns reading a
+ * role, so a create route that also took a sidecar would be a second way to write one.
+ */
+ async function create() {
+ const name = (creating?.title ?? '').trim();
+ if (!name) return;
+ const pasted = creating.text !== undefined;
+ const template = pasted ? null : sheetTemplate(creating.template);
+ const body = pasted
+ ? { title: name, text: creating.text }
+ : { title: name, ...(template.columns ? { columns: template.columns } : {}) };
+ const route = pasted ? 'sheets/import' : 'sheets';
+ try {
+ const sheet = await api.post(`/api/cases/${caseId}/${route}`, body);
+ creating = null;
+ await list(caseId);
+ openId = null;
+ await open(sheet.id);
+ if (template && (Object.keys(template.roles).length || template.progress)) {
+ meta = templateMeta(meta, template);
+ await save();
+ }
+ } catch (error) {
+ toast(error.message || 'This sheet could not be created.', 'error');
+ }
+ }
+
+ async function rename() {
+ const name = title.trim();
+ const current = sheets.find((sheet) => sheet.id === openId);
+ if (!openId || !name || name === current?.title) return;
+ try {
+ await api.patch(`/api/cases/${caseId}/entities/${openId}`, { label: name });
+ await list(caseId);
+ } catch (error) {
+ toast(error.message || 'This sheet could not be renamed.', 'error');
+ title = current?.title ?? title;
+ }
+ }
+
+ async function remove() {
+ confirming = null;
+ try {
+ await api.del(`/api/cases/${caseId}/entities/${openId}`);
+ close();
+ await list(caseId);
+ } catch (error) {
+ toast(error.message || 'This sheet could not be deleted.', 'error');
+ }
+ }
+
+ /**
+ * Fork this sheet, sidecar and all.
+ *
+ * This app's answer to saved views has always been *another reading of these rows is
+ * another sheet* — and there was no button behind it: forking meant exporting the CSV and
+ * importing it back, which arrives stripped of every colour, role, note and link. So the
+ * copy carries the whole sidecar, and what is being forked is the work rather than the
+ * headings.
+ */
+ /**
+ * A second sheet from this one: the whole thing, or only its shape.
+ *
+ * Both are the same write with one flag between them, and both answer the same question
+ * — "another reading of these rows is another sheet", which is why this app has no named
+ * views. `empty` is the one a binder is actually built out of: an inbox, a worklist and
+ * a reference table at one schema, and the next floor up starts as this floor's columns
+ * with nothing under them.
+ */
+ async function duplicateSheet({ empty = false } = {}) {
+ picker = null;
+ if (!openId) return;
+ try {
+ await flush();
+ const made = await api.post(`/api/cases/${caseId}/sheets/${openId}/duplicate`, { empty });
+ await list(caseId);
+ openId = null;
+ await open(made.id);
+ await reloadCase();
+ toast(
+ empty
+ ? `“${made.label ?? 'Sheet'}” created, with the columns and no rows.`
+ : `“${made.label ?? 'Sheet'}” created, with the rows and everything the grid knows.`,
+ );
+ } catch (error) {
+ toast(error.message || 'This sheet could not be copied.', 'error');
+ }
+ }
+
+ /**
+ * Add a batch of rows to the sheet that is already open.
+ *
+ * Import files a new sheet, which is right the first time and wrong every time after it:
+ * the daily batch of links belongs in the worklist that already carries the statuses. The
+ * mapping is the analyst's (`SheetAppend`), and the rows land as one undoable step through
+ * the ordinary save — nothing here is a second write path.
+ */
+ function appendBatch(incoming, mapping) {
+ if (!room({ rows: incoming?.rows?.length ?? 0 })) return;
+ const grown = appendRows(table, incoming, mapping);
+ appending = false;
+ if (!grown.added) {
+ toast('No column of that table matches this sheet.', 'error');
+ return;
+ }
+ structural(() => {
+ table = grown.table;
+ });
+ toast(`${grown.added} ${grown.added === 1 ? 'row' : 'rows'} added.`);
+ }
+
+ /**
+ * Write the sheet out as a CSV the analyst hands to someone else.
+ *
+ * What travels is **what is on screen**: the columns drawn, in the order they are
+ * drawn, and the rows the filter and the sort left. The case folder already holds
+ * `sheets/<name>.csv`, so exporting the file would hand over a copy of something
+ * they have; the reading is what they do not have. The toast says how much of the
+ * sheet that was, because an export of twelve rows out of four hundred is worth
+ * hearing before it is mailed.
+ */
+ async function download({ ticked = false } = {}) {
+ if (!openId || exporting) return;
+ exporting = true;
+ exportOpen = false;
+ // The ticked rows in the order they are drawn, so an export of a selection reads the
+ // way the screen does rather than the way the file happens to hold it.
+ const rows = ticked ? shown.filter((index) => batchIndices.includes(index)) : shown;
+ try {
+ await flush();
+ const written = await exportCsv(caseId, openId, viewTable(table, drawn, rows));
+ const all = rows.length === table.rows.length && drawn.length === table.columns.length;
+ const how = all
+ ? `${rows.length} ${rows.length === 1 ? 'row' : 'rows'}`
+ : `${rows.length} of ${table.rows.length} rows, ${drawn.length} of ${table.columns.length} columns`;
+ // Where it landed **and a way to get there**, which is what every other export in the
+ // app offers: a sentence naming a folder is a folder the analyst then goes looking
+ // for, and a file nobody finds is a file exported twice.
+ toast(`${how} written to ${destinationLabel(written.path)}`, 'ok', 5200, {
+ label: 'Show',
+ onClick: () => showExports(),
+ });
+ } catch (error) {
+ toast(error.message || 'This sheet could not be exported.', 'error');
+ } finally {
+ exporting = false;
+ }
+ }
+
+ /** Open the folder those CSVs go to. Same offer the note PDFs and the plates make. */
+ async function showExports() {
+ exportOpen = false;
+ try {
+ await revealSheetExports(caseId);
+ } catch (error) {
+ toast(error.message || 'That folder could not be opened.', 'error');
+ }
+ }
+
+ /** Which folder the CSVs land in, read when the menu opens rather than on mount: it is a
+ * settings fetch, and a sheet that asked for it every time a case loaded would ask for
+ * nothing the analyst can see. */
+ function readDestination() {
+ if (destination !== null) return;
+ readDestinations()
+ .then((dirs) => {
+ destination = dirs.sheets;
+ })
+ .catch(() => {
+ destination = '';
+ });
+ }
+
+ /** A dropped or picked file becomes a new sheet, named after itself. The text goes
+ * to the import route: the delimiter is guessed on the side that writes the file
+ * back, so a semicolon export and a tab export both land. */
+ /**
+ * A file the analyst picked, whatever format it is in.
+ *
+ * A CSV is read here and filed as one sheet through the naming dialog. A **workbook**
+ * cannot be: it is a zip, it holds several tables, and reading it in the browser would
+ * be a second parser for the one artifact this app promises any spreadsheet can open.
+ * So it goes up whole and comes back as one sheet per tab, keeping the tabs' names —
+ * which is how a binder arrives, and what asking the analyst to export six tabs by hand
+ * was really asking.
+ */
+ function importFile(files) {
+ const file = files?.[0];
+ if (!file) return;
+ if (/\.xlsx$/i.test(file.name)) return importWorkbook(file);
+ const reader = new FileReader();
+ reader.onload = () => {
+ creating = { title: file.name.replace(/\.[^.]+$/, ''), text: String(reader.result ?? '') };
+ };
+ reader.readAsText(file);
+ }
+
+ async function importWorkbook(file) {
+ if (!caseId || building) return;
+ building = true;
+ try {
+ const body = new FormData();
+ body.append('file', file);
+ const made = await api.post(`/api/cases/${caseId}/sheets/import-xlsx`, body);
+ await list(caseId);
+ if (made.sheets?.length) {
+ openId = null;
+ await open(made.sheets[0].id);
+ }
+ await reloadCase();
+ const count = made.sheets?.length ?? 0;
+ // What did not land, named. Two tabs of a timeline binder hold nothing but pasted
+ // screenshots, and two empty sheets nobody asked for would be worse than the sentence.
+ const empty = made.empty?.length
+ ? ` ${made.empty.length === 1 ? 'One tab holds' : `${made.empty.length} tabs hold`} no cells: ${made.empty.join(', ')}.`
+ : '';
+ // And what the three ceilings left out. A thirty thousand row export arriving as
+ // twenty thousand under a toast reading "5 tabs filed" is a sheet that looks whole.
+ const dropped = made.dropped?.length ? ` Not read: ${made.dropped.join(', ')}.` : '';
+ const cut = (made.cut ?? [])
+ .map((tab) => {
+ const kept = [tab.rows && `${tab.rows} rows`, tab.columns && `${tab.columns} columns`]
+ .filter(Boolean)
+ .join(' and ');
+ return ` ${tab.title} was cut to ${kept}.`;
+ })
+ .join('');
+ toast(
+ `${count} ${count === 1 ? 'tab' : 'tabs'} filed as ${count === 1 ? 'a sheet' : 'sheets'}.${empty}${dropped}${cut}`,
+ dropped || cut ? 'warn' : 'info',
+ );
+ } catch (error) {
+ toast(error.message || 'This workbook could not be read.', 'error');
+ } finally {
+ building = false;
+ }
+ }
+
+ /**
+ * A file dropped on the grid: a table, or a picture for the row it landed on.
+ *
+ * An image dropped on a row is the gesture a geolocation index is worked with — the frame
+ * is on the desktop and the row is the lead — and it used to be read as an attempt to
+ * import a CSV. Now it goes into the case's own `media/`, the cell cites the file by its
+ * case-relative path so a collaborator opening the CSV can find it, and the cell points at
+ * the media entity so the graph knows the row rests on it.
+ */
+ function onDrop(event) {
+ event.preventDefault();
+ dropping = false;
+ const file = event.dataTransfer?.files?.[0];
+ if (!file) return;
+ if (file.type.startsWith('image/')) {
+ const cell = event.target?.closest?.('[data-row]');
+ const row = Number(cell?.dataset?.row ?? -1);
+ if (row >= 0) {
+ bringIn(file, row, Number(cell.dataset.column));
+ return;
+ }
+ }
+ importFile(event.dataTransfer.files);
+ }
+
+ /** Which column a dropped picture belongs in: the one it was dropped on when anything may
+ * be written there, the sheet's picture column otherwise. A drop on the row's handle is
+ * still a drop on the row. */
+ function pictureColumn(columnIndex) {
+ if (Number.isInteger(columnIndex) && writable(table.columns[columnIndex])) return columnIndex;
+ const declared = table.columns.findIndex((name) => roles[name]?.kind === 'picture');
+ return declared;
+ }
+
+ async function bringIn(file, rowIndex, columnIndex) {
+ const at = pictureColumn(columnIndex);
+ if (at === -1) {
+ toast('Declare a column a picture first, then drop the image on it.', 'error');
+ return;
+ }
+ try {
+ const body = new FormData();
+ body.append('file', file);
+ const made = await api.post(`/api/cases/${caseId}/media/upload`, body);
+ const path = made.item?.path;
+ if (!path) throw new Error('that file did not land in the case');
+ const key = rowKey(table.columns, table.rows[rowIndex]);
+ structural(() => {
+ table = setCells(table, [{ row: rowIndex, column: at, value: path }]);
+ // The link as well as the words: the CSV says where the file is and the graph says
+ // which media the row rests on, which is what makes the row reachable from it.
+ if (made.entity?.id) meta = setLink(meta, key, table.columns[at], made.entity.id);
+ });
+ await reloadCase();
+ toast(made.duplicate ? 'Already in the case. The cell now cites it.' : 'Picture added to the case.');
+ } catch (error) {
+ toast(error.message || 'That picture could not be brought in.', 'error');
+ }
+ }
+
+ // -- edits -----------------------------------------------------------------
+
+ /** Open the editor on a cell. Refused on the key column and on the two the app
+ * writes: an editor over a value the next save overwrites is a box that lies. */
+ function edit(row, column) {
+ cursor = { row, column };
+ anchor = { row, column };
+ if (isKeyColumn(column) || appFilled(table.columns[column])) return;
+ if (roles[table.columns[column]]?.kind === 'boolean') return flipCell(row, column);
+ editing = { row, column, value: table.rows[row]?.[column] ?? '' };
+ }
+
+ function commitEdit(move = null) {
+ if (!editing) return;
+ const { row, column, value } = editing;
+ editing = null;
+ const before = table.rows[row]?.[column];
+ if (before !== value) editCells([{ row, column, before, after: value }]);
+ // `newrow` is Tab off the end of the sheet: the row is grown rather than the cursor
+ // stopping dead, which is what typing a list into a grid actually feels like.
+ if (move === 'newrow') appendRow();
+ else if (move) step(move);
+ }
+
+ /** Whether the cursor is on the last cell of the last row on screen. What decides whether
+ * Tab steps across or grows the sheet. */
+ function atLastCell() {
+ const columns = drawn.map((column) => column.index);
+ return (
+ shown.indexOf(cursor.row) === shown.length - 1 &&
+ columns.indexOf(cursor.column) === columns.length - 1
+ );
+ }
+
+ /**
+ * Move the cursor, in display order rather than file order.
+ *
+ * One function for the arrows, Tab, Home, End and the page keys, because they are one
+ * gesture with different distances: a second walker would be a second answer to what
+ * "the next row" means under a filter.
+ */
+ function step(direction, { extend = false } = {}) {
+ const at = shown.indexOf(cursor.row);
+ const columns = drawn.map((column) => column.index);
+ const column = columns.indexOf(cursor.column);
+ const page = Math.max(1, Math.floor((scroller?.clientHeight ?? viewport) / rowH) - 1);
+ const rowAt = (index) => ({ ...cursor, row: shown[Math.max(0, Math.min(index, shown.length - 1))] });
+ const columnAt = (index) => ({
+ ...cursor,
+ column: columns[Math.max(0, Math.min(index, columns.length - 1))],
+ });
+ let next = cursor;
+ if (direction === 'down' && at < shown.length - 1) next = rowAt(at + 1);
+ if (direction === 'up' && at > 0) next = rowAt(at - 1);
+ if (direction === 'right' && column < columns.length - 1) next = columnAt(column + 1);
+ if (direction === 'left' && column > 0) next = columnAt(column - 1);
+ if (direction === 'pagedown') next = rowAt(at + page);
+ if (direction === 'pageup') next = rowAt(at - page);
+ if (direction === 'top') next = rowAt(0);
+ if (direction === 'bottom') next = rowAt(shown.length - 1);
+ if (direction === 'rowstart') next = columnAt(0);
+ if (direction === 'rowend') next = columnAt(columns.length - 1);
+ cursor = next;
+ if (!extend) anchor = { ...next };
+ scrollIntoView();
+ }
+
+ /**
+ * Bring the cursor into view, in **both** directions.
+ *
+ * Only the vertical half existed, which on a fourteen-column binder meant walking right
+ * with the arrow keys moved the cursor behind the frozen columns and off the edge: the
+ * grid stayed where it was and the analyst was typing into a cell they could not see. The
+ * sticky columns are subtracted from the left edge for the same reason — a cell scrolled
+ * flush to the viewport's edge is a cell underneath the row's handle.
+ */
+ function scrollIntoView() {
+ if (!scroller) return;
+ const at = shown.indexOf(cursor.row);
+ if (at !== -1) {
+ const top = headRoom + at * rowH;
+ if (top < scroller.scrollTop + headRoom) scroller.scrollTop = top - headRoom;
+ else if (top + rowH > scroller.scrollTop + scroller.clientHeight)
+ scroller.scrollTop = top + rowH - scroller.clientHeight;
+ }
+ const column = drawn.findIndex((entry) => entry.index === cursor.column);
+ if (column === -1) return;
+ // Where the column starts, walked rather than measured: the drawn widths are the only
+ // truth about that and the DOM node may not exist yet on a column just scrolled to.
+ let left = GUTTER_WIDTH;
+ for (const entry of drawn.slice(0, column)) {
+ left += meta.widths?.[entry.name] ?? DEFAULT_WIDTH;
+ }
+ const width = meta.widths?.[drawn[column].name] ?? DEFAULT_WIDTH;
+ if (offsets[drawn[column].name] !== undefined) return; // it never leaves the screen
+ if (left < scroller.scrollLeft + stickyWidth) scroller.scrollLeft = left - stickyWidth;
+ else if (left + width > scroller.scrollLeft + scroller.clientWidth)
+ scroller.scrollLeft = left + width - scroller.clientWidth;
+ measure();
+ }
+
+ /** Whether a pointer landed on something inside a cell that has its own job — a chip,
+ * the entity mark, the `@`. Those are not places to start a selection from. */
+ function onOwnControl(target) {
+ return Boolean(target?.closest?.('button, a, textarea, input'));
+ }
+
+ /**
+ * Press a cell: place the cursor, and start a drag that extends the selection.
+ *
+ * Pointer rather than click, because a spreadsheet's selection is a drag: press a cell,
+ * pull across the ones wanted, release. Shift keeps the anchor where it was, so
+ * shift-clicking a far corner still selects the rectangle between them.
+ */
+ function startCellDrag(event, row, column) {
+ if (onOwnControl(event.target)) return;
+ cursor = { row, column };
+ if (!event.shiftKey || !anchor) anchor = { row, column };
+ selecting = true;
+ const stop = () => {
+ selecting = false;
+ document.removeEventListener('pointerup', stop);
+ };
+ document.addEventListener('pointerup', stop);
+ }
+
+ /** Pull the selection over a cell the pointer is passing across, while held. */
+ function overCell(row, column) {
+ if (selecting) cursor = { row, column };
+ }
+
+ /** Whether the keystroke belongs to a box the analyst is typing in.
+ *
+ * Without this the search field was unusable: every letter typed into it also
+ * reached the grid and started editing whatever cell the cursor sat on. The cell
+ * editor is deliberately not excluded — it is a textarea, and its own branch in
+ * `onKey` is what gives Enter, Tab and Escape their meaning there. */
+ function inAField(target) {
+ if (!target || target.isContentEditable) return false;
+ const tag = target.tagName;
+ return (tag === 'INPUT' || tag === 'TEXTAREA') && !target.classList.contains('editor');
+ }
+
+ /** Everything the grid can have open over it, closed. One list, so a new popover
+ * is dismissable the day it is added rather than the day someone notices. */
+ function closePopovers() {
+ picker = null;
+ newOpen = false;
+ columnsOpen = false;
+ filterAt = null;
+ cellMenu = null;
+ headMenu = null;
+ rowMenu = null;
+ exportOpen = false;
+ legendOpen = false;
+ renaming = null;
+ filling = null;
+ fillValue = '';
+ rowPanel = null;
+ columnPanel = null;
+ }
+
+ const somethingOpen = $derived(
+ Boolean(picker) ||
+ newOpen ||
+ columnsOpen ||
+ filterAt !== null ||
+ cellMenu !== null ||
+ headMenu !== null ||
+ rowMenu !== null ||
+ exportOpen ||
+ legendOpen ||
+ renaming !== null ||
+ Boolean(filling) ||
+ rowPanel !== null ||
+ columnPanel !== null,
+ );
+
+ // A pointer outside a popover closes it. The bound element wraps the trigger too,
+ // so clicking the trigger stays a plain toggle.
+ $effect(() => (picker ? closeOnOutsidePointer(pickerAnchor, () => (picker = null)) : undefined));
+ $effect(() => (newOpen ? closeOnOutsidePointer(newAnchor, () => (newOpen = false)) : undefined));
+ $effect(() =>
+ columnsOpen ? closeOnOutsidePointer(columnsAnchor, () => (columnsOpen = false)) : undefined,
+ );
+ // Two elements for these two, because the menu is drawn away from the control that
+ // opens it: without the trigger in the list, its own click would close and reopen.
+ $effect(() =>
+ filterAt
+ ? closeOnOutsidePointer([filterMenu, funnels[table.columns[filterAt.index]]], () => (filterAt = null))
+ : undefined,
+ );
+ $effect(() =>
+ cellMenu ? closeOnOutsidePointer(cellMenuEl, () => (cellMenu = null)) : undefined,
+ );
+ $effect(() =>
+ headMenu ? closeOnOutsidePointer(headMenuEl, () => (headMenu = null)) : undefined,
+ );
+ $effect(() => (rowMenu ? closeOnOutsidePointer(rowMenuEl, () => (rowMenu = null)) : undefined));
+ $effect(() =>
+ exportOpen ? closeOnOutsidePointer(exportAnchor, () => (exportOpen = false)) : undefined,
+ );
+ $effect(() =>
+ legendOpen ? closeOnOutsidePointer(legendAnchor, () => (legendOpen = false)) : undefined,
+ );
+
+ /**
+ * Whether this grid is the tool on screen.
+ *
+ * Tools stay mounted once visited and are hidden with CSS, so every handler on `window`
+ * goes on firing behind whatever is in front. For most tools that is harmless; here it was
+ * data loss: with a cell cursor left somewhere, `Delete` pressed while the map was on
+ * screen emptied those cells and autosaved the CSV, a letter opened an editor nobody could
+ * see, and `Ctrl+C` quietly replaced the clipboard with a rectangle from a sheet.
+ */
+ function mine() {
+ return uiState.tool === 'sheet';
+ }
+
+ function onKey(event) {
+ if (!mine()) return;
+ if (creating || confirming || detailsId || linking || discarding || promoteOpen) return;
+ if (cleaning || fromCase || appending || geocoding || buildOpen) return;
+ if (helpOpen || destPicker) return;
+ // Escape backs out of whatever is over the grid, before the grid's own keys get
+ // a look: a menu left open by a stray click is the most common way to be stuck.
+ if (event.key === 'Escape' && !editing && somethingOpen) {
+ event.preventDefault();
+ closePopovers();
+ return;
+ }
+ const meta_ = event.ctrlKey || event.metaKey;
+ // The search is reachable from the grid, and only from the grid: pressing it
+ // inside a field would fight whatever that field does with the same keys.
+ if (meta_ && event.key.toLowerCase() === 'f' && !inAField(event.target)) {
+ event.preventDefault();
+ searchBox?.focus();
+ searchBox?.select();
+ return;
+ }
+ if (inAField(event.target)) return;
+ // The list of gestures, on the key every reader tries. Not behind a modifier: it is a
+ // question, and a question mark is how one is asked.
+ if (event.key === '?' && !editing) {
+ event.preventDefault();
+ helpOpen = true;
+ return;
+ }
+ if (meta_ && event.key.toLowerCase() === 's') {
+ event.preventDefault();
+ save();
+ return;
+ }
+ if (meta_ && event.key.toLowerCase() === 'z') {
+ event.preventDefault();
+ event.shiftKey ? redo() : undo();
+ return;
+ }
+ if (meta_ && event.key === 'Enter') {
+ event.preventDefault();
+ appendRow();
+ return;
+ }
+ if (editing) {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ editing = null;
+ }
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ commitEdit('down');
+ }
+ if (event.key === 'Tab') {
+ event.preventDefault();
+ // On the last cell of the last row, Tab is how a grid grows: the alternative is
+ // reaching for the mouse at the end of every line typed.
+ if (!event.shiftKey && atLastCell()) commitEdit('newrow');
+ else commitEdit(event.shiftKey ? 'left' : 'right');
+ }
+ // Reaching here means the editor is open and the textarea has **not** taken the
+ // focus yet: a field that has it exits this handler further up. Svelte mounts on
+ // the next tick, and a fast typist is inside that window — so the cell opened on
+ // `m` and swallowed the `ine` that followed. The characters are kept here and the
+ // editor mounts holding them.
+ if (event.key.length === 1 && !meta_) {
+ event.preventDefault();
+ editing = { ...editing, value: editing.value + event.key };
+ }
+ return;
+ }
+ // Every row on screen, ticked. The one selection gesture the grid was missing, and the
+ // header's own box is three hundred pixels away from the keyboard.
+ if (meta_ && event.key.toLowerCase() === 'a') {
+ event.preventDefault();
+ picked = new Set(shownKeys(table, shown));
+ lastTicked = null;
+ return;
+ }
+ // Escape with nothing open drops the selection, cursor and all: a rectangle left
+ // behind is what makes the next Delete act on more than the analyst has in mind.
+ if (event.key === 'Escape' && (picked.size || hasRange || cursor.row !== -1)) {
+ event.preventDefault();
+ dropSelection();
+ return;
+ }
+ if (cursor.row === -1) return;
+ if (meta_ && event.key.toLowerCase() === 'd') {
+ event.preventDefault();
+ fillDown();
+ return;
+ }
+ const moves = { ArrowDown: 'down', ArrowUp: 'up', ArrowRight: 'right', ArrowLeft: 'left' };
+ if (moves[event.key]) {
+ event.preventDefault();
+ step(moves[event.key], { extend: event.shiftKey });
+ return;
+ }
+ // The keys that cross a long sheet. Ctrl takes the whole column rather than a screen,
+ // which is what it does in every grid.
+ const jumps = {
+ PageDown: 'pagedown',
+ PageUp: 'pageup',
+ Home: meta_ ? 'top' : 'rowstart',
+ End: meta_ ? 'bottom' : 'rowend',
+ };
+ if (jumps[event.key]) {
+ event.preventDefault();
+ step(jumps[event.key], { extend: event.shiftKey });
+ return;
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ edit(cursor.row, cursor.column);
+ return;
+ }
+ if (event.key === 'Tab') {
+ event.preventDefault();
+ if (!event.shiftKey && atLastCell()) appendRow();
+ else step(event.shiftKey ? 'left' : 'right');
+ return;
+ }
+ if (event.key === 'Delete' || event.key === 'Backspace') {
+ event.preventDefault();
+ clearSelection();
+ return;
+ }
+ // Typing a printable character starts an edit on that character, the way a
+ // grid is expected to behave.
+ if (
+ event.key.length === 1 &&
+ !meta_ &&
+ !isKeyColumn(cursor.column) &&
+ !appFilled(table.columns[cursor.column])
+ ) {
+ event.preventDefault();
+ editing = { row: cursor.row, column: cursor.column, value: event.key };
+ }
+ }
+
+ /** Every part of a selection let go at once: the ticks, the dragged rectangle and the
+ * cursor itself. On Escape, and on the bar's own button, since anything left behind is
+ * what makes the next Delete act on more than the analyst has in mind. */
+ function dropSelection() {
+ picked = new Set();
+ lastTicked = null;
+ cursor = { row: -1, column: -1 };
+ anchor = null;
+ }
+
+ function isKeyColumn(index) {
+ return String(table.columns[index] ?? '').toLowerCase() === ID_COLUMN;
+ }
+
+ /** A cell as chips, or null when the column is not a set of values. Returned rather
+ * than a flag so the template asks once and draws from the answer. */
+ function chipsFor(rowIndex, column) {
+ const role = roles[column.name];
+ if (!isChipped(role)) return null;
+ const read = cellChips(table.rows[rowIndex][column.index], role);
+ if (!read.length) return null;
+ // A `row` column has no vocabulary: what makes one of its names *known* is that it
+ // reaches exactly one other row. Read from the words, so a name somebody renamed a row
+ // out from under is marked here rather than sitting in the cell looking answered.
+ if (role.kind !== 'row') return read;
+ const reached = rowPointers.find((entry) => entry.index === column.index);
+ const missing = new Set(
+ reached?.targets.get(rowKey(table.columns, table.rows[rowIndex]))?.missing ?? [],
+ );
+ return read.map((chip) => ({ ...chip, known: !missing.has(chip.value) }));
+ }
+
+ /**
+ * Press a chip in a cell.
+ *
+ * A yes/no column **flips**: two words is a toggle, and the tooltip said as much while
+ * the only way to do it was a double-click or Enter. Everything else **filters** on the
+ * value pressed — on the value and not on the cell's text, so `2x S-125` asks for
+ * `S-125` and finds the rows holding three of them too.
+ */
+ function onChipClick(rowIndex, column, chip) {
+ if (roles[column.name]?.kind === 'boolean') {
+ flipCell(rowIndex, column.index);
+ return;
+ }
+ toggleValue(column.name, chip.value);
+ }
+
+ /**
+ * A yes/no column answers a click rather than opening an editor: two words is not a
+ * menu, it is a toggle, and making the analyst pick from a list of two is a click too
+ * many on the column they will touch most.
+ *
+ * A column drawn as **tick boxes** cycles through three rather than flipping between
+ * two, because its box is drawn on an empty cell as well as a filled one: without
+ * the third state, *not answered yet* and *no* would look the same and there would
+ * be no way back. One function, so the box, the chip and Enter all agree.
+ */
+ function flipCell(rowIndex, columnIndex) {
+ const role = roles[table.columns[columnIndex]];
+ const before = table.rows[rowIndex][columnIndex];
+ const after = role?.tick ? cycleTick(role, before) : flipBoolean(role, before);
+ editCells([{ row: rowIndex, column: columnIndex, before, after }]);
+ }
+
+ /** Whether this column draws its cells as boxes. Asked once here so the grid's own
+ * branch and the cell's click read the same answer. */
+ function ticked(column) {
+ const role = roles[column.name];
+ return role?.kind === 'boolean' && Boolean(role.tick);
+ }
+
+ /**
+ * What each number column adds up to over the rows on screen.
+ *
+ * On screen, not in the sheet: filtering to the twelve rows left to check and then being
+ * told the total of all four hundred answers a question nobody asked. This is the one
+ * reading in the footer that follows the filter, and it follows it for that reason.
+ */
+ const numberFooters = $derived(
+ drawn
+ .filter((column) => roles[column.name]?.kind === 'number')
+ .map((column) => ({
+ name: column.name,
+ summary: roles[column.name].summary ?? 'sum',
+ unit: roles[column.name].unit ?? '',
+ ...numberTotals(table, column.index, shown),
+ }))
+ .filter((entry) => entry.summary !== 'none' && (entry.count || entry.unreadable)),
+ );
+
+ /** How each role reads in a heading: one glyph and one word. The word is the same one
+ * the role editor offers, so the heading and the panel cannot say two things. */
+ const ROLE_MARKS = {
+ state: { icon: 'chart', label: 'State' },
+ choice: { icon: 'stack', label: 'Values' },
+ boolean: { icon: 'check', label: 'Yes / no' },
+ number: { icon: 'hash', label: 'Number' },
+ latlon: { icon: 'pin', label: 'Point' },
+ when: { icon: 'clock', label: 'Date or time' },
+ picture: { icon: 'image', label: 'Picture' },
+ url: { icon: 'external', label: 'Source' },
+ row: { icon: 'link', label: 'Another row' },
+ offset: { icon: 'clock', label: 'Offset' },
+ stamped: { icon: 'save', label: 'Added on' },
+ computed: { icon: 'globe', label: 'On map' },
+ };
+
+ /** And what a computed column's heading says, now that there are three of them: a column
+ * answering "how complete" is not on a map, and one glyph for all three would be a
+ * heading that lies about two of them. */
+ const NATURE_MARKS = {
+ has_point: { icon: 'globe', label: 'On map' },
+ filled_of: { icon: 'chart', label: 'How complete' },
+ yes_of: { icon: 'check', label: 'Score' },
+ point: { icon: 'pin', label: 'Its point' },
+ relations: { icon: 'graph', label: 'What it is joined to' },
+ };
+
+ /** The mark a column's heading draws, or nothing. One place, so the heading, the columns
+ * list and the tooltip agree. */
+ function roleMark(name) {
+ const role = roles[name];
+ if (!role) return null;
+ if (role.kind === 'computed') return NATURE_MARKS[role.of ?? 'has_point'] ?? NATURE_MARKS.has_point;
+ return ROLE_MARKS[role.kind] ?? null;
+ }
+
+ /** Whether this cell is one its column's own type cannot read. Marked in the grid
+ * rather than refused, and the mark is the whole point: a permissive column that says
+ * nothing about the cells it skipped is a column whose total nobody can check. Only
+ * where nothing else already says it — a value outside a vocabulary is drawn as a
+ * dashed chip, which says it better than a badge would. */
+ function unreadable(rowIndex, column) {
+ const role = roles[column.name];
+ if (!role || isChipped(role) || appFilled(column.name)) {
+ return false;
+ }
+ return !readsCell(role, table.rows[rowIndex][column.index]);
+ }
+
+ /** The unit to write after this cell, or nothing. Only where the column asked for it
+ * in the cells, and never after an empty one: a blank means unknown, and `%` on its
+ * own would be a reading of a cell nobody has filled. */
+ function unitOf(rowIndex, column) {
+ const role = roles[column.name];
+ if (role?.kind !== 'number' || !role.unit || !role.unitInCells) return '';
+ return String(table.rows[rowIndex][column.index] ?? '').trim() ? role.unit : '';
+ }
+
+ /** A number written the way its column writes them. The unit is the whole of the
+ * formatting: a percentage and a currency differ by what follows the digits. */
+ function spellNumber(value, unit) {
+ if (value === null || value === undefined) return '—';
+ return unit ? `${value} ${unit}` : `${value}`;
+ }
+
+ /**
+ * Whether pointing this cell at an entity means anything.
+ *
+ * The `@` used to be drawn on every cell of every column, which read as an offer to point
+ * a *status* at a person: a yes/no cell, a date, a number and a vocabulary value are not
+ * things the case holds an entity for. So it is offered where a cell can plausibly name
+ * something — text, and a point, which names a place — and on any cell that already
+ * carries a link, because a link that cannot be seen or cleared is worse than one offered
+ * where it is not wanted.
+ */
+ function linkable(name) {
+ const kind = roles[name]?.kind;
+ // `locked` is here and no other written role is: its whole purpose is a cell that
+ // opens the entity the app filled it from. A stamped date and a computed count point
+ // at nothing, so offering the `@` on them would offer a link to nowhere.
+ return !kind || kind === 'latlon' || kind === 'picture' || kind === 'locked';
+ }
+
+ /** Whether the app writes this column rather than the analyst. None of the three is
+ * typed into: the editor would be a box whose value is overwritten on the next save,
+ * or on the next refresh for a column the case owns. */
+ function appFilled(name) {
+ const kind = roles[name]?.kind;
+ return kind === 'stamped' || kind === 'computed' || kind === 'locked';
+ }
+
+ /** Whether an edit may land in this column at all. The row's handle is the case's,
+ * and the two roles the app fills are rewritten on every save — a bulk fill into
+ * either writes a value that is gone before it is read. */
+ function writable(name) {
+ return String(name ?? '').toLowerCase() !== ID_COLUMN && !appFilled(name);
+ }
+
+ const fillable = $derived(table.columns.filter(writable));
+
+ // -- the cell bar ----------------------------------------------------------
+
+ /**
+ * The cell under the cursor, written in a box wide enough to read it.
+ *
+ * A grid cell is thirty pixels tall and as wide as its column, and the sentences an
+ * analyst writes into `Title` are neither. The bar is the same cell, at the top, with
+ * the whole value in one place: what a spreadsheet's formula bar is for.
+ *
+ * The draft carries **the cell it belongs to**, not just the text. The box loses the
+ * focus by the analyst clicking another cell, and the grid has already moved the cursor
+ * there by the time the blur lands — a draft that only knew its text would be committed
+ * into whichever cell was clicked next.
+ */
+ let barDraft = $state(null); // { row, column, value }
+ const barColumn = $derived(cursor.row === -1 ? null : (table.columns[cursor.column] ?? null));
+ /** What the bar shows when nothing is being typed in it. The open cell editor wins:
+ * two boxes on one cell that disagree is the worse of the two bugs. */
+ const barCell = $derived.by(() => {
+ if (cursor.row === -1) return '';
+ if (editing && editing.row === cursor.row && editing.column === cursor.column) {
+ return editing.value;
+ }
+ return table.rows[cursor.row]?.[cursor.column] ?? '';
+ });
+ const barValue = $derived(
+ barDraft?.row === cursor.row && barDraft?.column === cursor.column ? barDraft.value : barCell,
+ );
+ const barWritable = $derived(Boolean(barColumn) && writable(barColumn));
+ /** Why the box refuses, when it does. The two reasons are different ones: the key is the
+ * case's handle on the row, and the stamped columns are rewritten on every save. */
+ const barLocked = $derived.by(() => {
+ if (!barColumn || barWritable) return '';
+ return String(barColumn).toLowerCase() === ID_COLUMN
+ ? 'The row’s handle'
+ : 'Written by the app on every save';
+ });
+
+ /** Taking over from the cell's own editor. Closed rather than left open behind the
+ * bar, so the value being typed is only ever in one box. */
+ function barFocus() {
+ if (editing) commitEdit();
+ }
+
+ function commitBar({ down = false } = {}) {
+ const draft = barDraft;
+ barDraft = null;
+ if (!draft || !writable(table.columns[draft.column])) return;
+ const before = table.rows[draft.row]?.[draft.column];
+ if (before !== draft.value) {
+ editCells([{ row: draft.row, column: draft.column, before, after: draft.value }]);
+ }
+ if (down) step('down');
+ }
+
+ function onBarKey(event) {
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ commitBar({ down: true });
+ scroller?.focus();
+ return;
+ }
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ barDraft = null;
+ scroller?.focus();
+ }
+ }
+
+ // -- the clipboard ---------------------------------------------------------
+
+ /** Copy the selected rectangle as a block a spreadsheet will read back.
+ *
+ * A rectangle of empty cells is copied too, as empty. Bailing there left the
+ * keystroke to the browser, which has nothing to take from a grid that is not
+ * selectable text — so Ctrl+C looked like it worked and the next Ctrl+V pasted
+ * whatever had been on the clipboard before. */
+ function onCopy(event) {
+ if (!mine() || !openId || inAField(event.target) || editing || cursor.row === -1) return;
+ event.preventDefault();
+ event.clipboardData?.setData('text/plain', toBlock(rangeValues(table, range)));
+ }
+
+ /**
+ * Paste a block into the sheet, from the cursor.
+ *
+ * A wall of links with no tabs is the "to be sorted" inbox every field binder
+ * keeps, so it becomes one row per link rather than one cell holding forty. Any
+ * other block is a table, and lands as a rectangle from where the cursor is.
+ */
+ function onPaste(event) {
+ if (!mine() || !openId || inAField(event.target) || editing) return;
+ const text = event.clipboardData?.getData('text/plain') ?? '';
+ if (!text.trim()) return;
+ event.preventDefault();
+ const block = looksLikeLinks(text) ? linkRows(text) : parseBlock(text);
+ if (!block.length) return;
+ const at = {
+ row: cursor.row === -1 ? (shown[0] ?? 0) : cursor.row,
+ column: cursor.column === -1 ? firstWritableColumn() : cursor.column,
+ };
+ // The rows and the columns as they are drawn, because that is what was copied: a
+ // rectangle read off a filtered or re-sorted screen has to land on the rows the
+ // analyst is looking at, not on whatever sits at those places in the file.
+ const view = { rows: shown, columns: drawn.map((column) => column.index) };
+ // What the block would add past the last row on screen, which is the only way a
+ // paste grows the sheet: it never adds a column, it clips to the ones there are.
+ const from = view.rows.indexOf(at.row);
+ const wouldAdd =
+ from === -1
+ ? Math.max(0, at.row + block.length - table.rows.length)
+ : Math.max(0, from + block.length - view.rows.length);
+ if (!room({ rows: wouldAdd })) return;
+ let landed = null;
+ structural(() => {
+ landed = pasteBlock(table, block, at, view);
+ table = landed.table;
+ });
+ if (landed?.clipped) {
+ toast(`${landed.clipped} pasted ${landed.clipped === 1 ? 'column' : 'columns'} did not fit.`);
+ }
+ }
+
+ /** Where a paste goes when no cell has been clicked yet: the first column that is
+ * not the row's handle, because the handle is never written. */
+ function firstWritableColumn() {
+ return drawn.find((column) => String(column.name).toLowerCase() !== ID_COLUMN)?.index ?? 0;
+ }
+
+ /** Which column a bulk fill offers first: the first one an edit may land in, so the
+ * bar never opens on a column that would refuse or overwrite what is written. */
+ function firstFillable() {
+ return fillable[0] ?? '';
+ }
+
+ // -- filling ---------------------------------------------------------------
+
+ /** The selected rectangle with the columns nothing may write taken out, so a sweep
+ * over a selection that happens to include `Added on` leaves it alone. */
+ const writableRange = $derived({
+ rows: range.rows,
+ columns: range.columns.filter((index) => writable(table.columns[index])),
+ });
+
+ /** Empty every selected cell. One step in the undo stack, not one per cell. */
+ function clearSelection() {
+ editCells(
+ writableRange.columns.flatMap((column) => fillEdits(table, column, range.rows, '')),
+ );
+ }
+
+ function fillDown() {
+ editCells(fillDownEdits(table, writableRange));
+ }
+
+ /** Write one answer into one column for every row in the batch. The worklist gesture:
+ * forty rows checked in one pass, then all forty marked at once. */
+ function applyFill() {
+ const columnIndex = table.columns.indexOf(filling?.column);
+ if (columnIndex !== -1 && writable(filling.column)) {
+ editCells(fillEdits(table, columnIndex, batchIndices, fillValue));
+ }
+ filling = null;
+ fillValue = '';
+ }
+
+ /** What one set of promotion answers would do to the case, without doing it. Asked of
+ * the server rather than worked out here: the plan the analyst confirms and the plan
+ * the promotion executes have to be the same one. */
+ /**
+ * The three other roads out of a sheet, each planned before it is done.
+ *
+ * Same shape as the row promotion because it is the same promise: the analyst reads what
+ * would happen, presses, and the server executes exactly that plan. What differs is the
+ * grain — words for a column, statements for a column of hours, edges for a column of
+ * row names — and the answer each one gives back.
+ */
+ /** The moments this sheet times rows against. Sidecar only, so it goes through the
+ * meta-only save like every other thing the grid remembers. */
+ /** What this sheet is for, in the sidecar. Two lines, so it is written where it is
+ * read rather than in a dialog of its own. */
+ function commitDescription() {
+ if (!describing) return;
+ describing = false;
+ const text = describeText.trim().slice(0, MAX_DESCRIPTION);
+ if (text === (meta.description ?? '')) return;
+ structural(
+ () => {
+ meta = { ...meta, description: text };
+ },
+ { withTable: false },
+ );
+ }
+
+ function setAnchors(anchors) {
+ structural(
+ () => {
+ meta = { ...meta, anchors };
+ },
+ { withTable: false },
+ );
+ }
+
+ /**
+ * A case file the row carries, and the ones it already does.
+ *
+ * A reference and not a copy: the entity is already the case's, so nothing new is filed
+ * and no artifact is owned twice. What it buys is the thing the binders kept two whole
+ * tabs of pasted screenshots for — the proof of the hour, attached to the row it is the
+ * proof of instead of floating beside it.
+ */
+ const carried = $derived(meta.attachments ?? {});
+ const rowPieces = $derived(
+ rowPanel === null
+ ? []
+ : (carried[rowKey(table.columns, table.rows[rowPanel] ?? [])] ?? []).map((id) => ({
+ id,
+ label: pieces[id]?.label ?? '',
+ type: pieces[id]?.type ?? '',
+ })),
+ );
+
+ function setAttachments(key, ids) {
+ const next = { ...carried };
+ if (ids.length) next[key] = ids;
+ else delete next[key];
+ structural(
+ () => {
+ meta = { ...meta, attachments: next };
+ },
+ { withTable: false },
+ );
+ }
+
+ /** The picker hands back the **entity**, not its id: the sidecar stores ids only, and a
+ * whole object put there is dropped by the writer without a word — which is exactly how
+ * this read as "attaching does nothing". Its name is kept beside the read's own answer
+ * so the panel can say it before the next reload. */
+ function attachPiece(key, entity) {
+ attaching = null;
+ const entityId = entity?.id;
+ if (!entityId) return;
+ pieces = { ...pieces, [entityId]: { label: entity.label ?? '', type: entity.type ?? '' } };
+ const held = carried[key] ?? [];
+ if (held.includes(entityId)) return;
+ setAttachments(key, [...held, entityId]);
+ }
+
+ function detachPiece(key, entityId) {
+ setAttachments(key, (carried[key] ?? []).filter((id) => id !== entityId));
+ }
+
+ /**
+ * What the library already downloaded from this row's links.
+ *
+ * The two halves of one page: the analyst has the video and the row pointing at its post
+ * could not say so. Matched on the **source URL the download recorded**, never on a
+ * title resembling a filename — the same rule the whole bridge runs on.
+ */
+ async function findRowMedia(key) {
+ const index = table.rows.findIndex((row) => rowKey(table.columns, row) === key);
+ if (index === -1) return;
+ const urls = table.rows[index].flatMap((cell) => urlsIn(cell));
+ if (!urls.length) return;
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${openId}/media`, { urls });
+ const found = Object.values(answer.media ?? {});
+ if (!found.length) {
+ toast('Nothing in the library came from these links.');
+ return;
+ }
+ pieces = {
+ ...pieces,
+ ...Object.fromEntries(
+ found.map((entry) => [entry.id, { label: entry.label, type: entry.type }]),
+ ),
+ };
+ const held = carried[key] ?? [];
+ setAttachments(key, [
+ ...held,
+ ...found.map((entry) => entry.id).filter((id) => !held.includes(id)),
+ ]);
+ toast(`${found.length} ${found.length === 1 ? 'file' : 'files'} attached to this row.`);
+ } catch (error) {
+ toast(error.message || 'The library could not be searched.', 'error');
+ }
+ }
+
+ /**
+ * Which rows a `row` column reaches, and the other direction of it.
+ *
+ * Derived from the words on every read rather than stored, which is exactly what the
+ * binders could not do: theirs was a spreadsheet validation, it could not survive a row
+ * moving, and in the real file it had already decayed to `#REF!`. Here the same decay is
+ * a count of names that reach nothing.
+ */
+ const rowColumns = $derived(
+ table.columns
+ .map((name, index) => ({ name, index, role: roles[name] }))
+ .filter((entry) => entry.role?.kind === 'row'),
+ );
+ const rowPointers = $derived(
+ rowColumns.map((entry) => ({
+ ...entry,
+ targets: rowTargets(table, entry.index, entry.role),
+ })),
+ );
+ /** Who points at each row, across **every** row column: a registry may name its parent
+ * in one and its neighbours in another, and reading only the first would answer half. */
+ const pointedAt = $derived.by(() => {
+ const merged = new Map();
+ for (const entry of rowPointers) {
+ for (const [key, from] of backLinks(entry.targets)) {
+ const held = merged.get(key) ?? [];
+ merged.set(key, [...held, ...from.filter((one) => !held.includes(one))]);
+ }
+ }
+ return merged;
+ });
+ const rowPointedBy = $derived(
+ rowPanel === null || !rowPointers.length
+ ? []
+ : (pointedAt.get(rowKey(table.columns, table.rows[rowPanel] ?? [])) ?? []).map((key) =>
+ rowLabel(table, key, rowPointers[0].role),
+ ),
+ );
+
+ /**
+ * Move the chosen rows into another sheet, each column landing where the dialog said.
+ *
+ * Both sheets are written by one call, so there is no window in which a row is in both
+ * or in neither. What was dropped is said twice — once on the second screen before the
+ * press, once here — because a silent loss reads as a clean move.
+ */
+ async function moveRows(to, keys, mapping) {
+ if (!openId || promoting) return;
+ promoting = true;
+ clearTimeout(saveTimer);
+ await inFlight;
+ // The table as it stands, kept before the write: it *is* the undo, since a move drops
+ // the columns the destination does not have and replaying it backwards would hand the
+ // rows back with holes in them. Safe to hold by reference — every pass over the grid
+ // builds a new table rather than editing this one.
+ const before = { columns: table.columns, rows: table.rows, meta };
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${openId}/move`, {
+ columns: table.columns,
+ rows: table.rows,
+ meta,
+ stamp,
+ to,
+ keys,
+ mapping,
+ });
+ adopt({ ...answer, title });
+ moving = false;
+ picked = new Set();
+ await list(caseId);
+ const lost = answer.dropped?.length
+ ? ` ${answer.dropped.join(', ')} ${answer.dropped.length === 1 ? 'is' : 'are'} not in that sheet, so ${answer.dropped.length === 1 ? 'it was' : 'they were'} dropped.`
+ : '';
+ // The one write in this tool the grid's own undo cannot reach, and it is two files.
+ toast(`${answer.moved} moved to “${answer.to.title}”.${lost}`, 'ok', 9000, {
+ label: 'Undo',
+ onClick: () => undoMove(before, to, answer.landed ?? [], keys),
+ });
+ await reloadCase();
+ } catch (error) {
+ if (error?.status === 409) conflict = true;
+ else toast(error.message || 'Those rows could not be moved.', 'error');
+ } finally {
+ promoting = false;
+ }
+ }
+
+ /**
+ * Put a move back: this sheet as it stood, and the rows it sent taken out over there.
+ *
+ * The stamp presented is the current one rather than the one the snapshot was read at:
+ * the move itself moved the file on, and what has to be refused is an undo pressed after
+ * the analyst has typed into the sheet since.
+ */
+ async function undoMove(before, to, landed, mine) {
+ if (!openId || promoting || !landed.length) return;
+ promoting = true;
+ clearTimeout(saveTimer);
+ await inFlight;
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${openId}/move/undo`, {
+ columns: before.columns,
+ rows: before.rows,
+ meta: before.meta,
+ stamp,
+ to,
+ keys: landed,
+ });
+ adopt({ ...answer, title });
+ // Ticked again, because the rows are back and the analyst was in the middle of
+ // choosing where to send them. Their own keys, not the ones they landed under: a
+ // key already taken over there was minted fresh, and this sheet never saw that one.
+ picked = new Set(mine);
+ await list(caseId);
+ toast(`${answer.undone} put back.`, 'ok');
+ await reloadCase();
+ } catch (error) {
+ if (error?.status === 409) conflict = true;
+ else toast(error.message || 'That move could not be put back.', 'error');
+ } finally {
+ promoting = false;
+ }
+ }
+
+ function previewPass(declaration) {
+ return api.post(`/api/cases/${caseId}/sheets/${openId}/promote/preview`, {
+ columns: table.columns,
+ rows: table.rows,
+ meta,
+ keys: batchKeys,
+ ...declaration,
+ });
+ }
+
+ /**
+ * Send the ticked rows to the case: every column's mode, and the edges between them.
+ *
+ * One request, which is also a save: the analyst sends what is on screen, edits and all,
+ * and the links the pass earns are what makes a second press an update rather than a
+ * twin — so they have to land in the same write. The reply is the sheet, adopted as any
+ * save's is, plus what happened to the case.
+ */
+ async function sendToCase(declaration) {
+ if (!openId || promoting) return;
+ promoting = true;
+ clearTimeout(saveTimer);
+ // A write in the air holds the stamp this pass has to present. Going past it presents
+ // the one it replaced, and the case answers a conflict nobody caused.
+ await inFlight;
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${openId}/promote`, {
+ columns: table.columns,
+ rows: table.rows,
+ meta,
+ stamp,
+ keys: batchKeys,
+ ...declaration,
+ });
+ adopt({ ...answer, title });
+ promoteOpen = false;
+ toast(said(answer));
+ await reloadCase();
+ } catch (error) {
+ if (error?.status === 409) conflict = true;
+ else toast(error.message || 'These rows could not be sent to the case.', 'error');
+ } finally {
+ promoting = false;
+ }
+ }
+
+ /** Whether this sheet can feed a build at all: two columns of addresses and one of
+ * coordinates, which is what a geolocation index is. Offered on nothing else, because a
+ * button that answers "this sheet cannot do that" should not have been there. */
+ const buildable = $derived(canBuild(columnKinds(table, meta)));
+
+ /** Whether this sheet was built out of the case's proofs, and can therefore be brought
+ * back level with them. Read off the sidecar rather than off the column names: a sheet
+ * whose headings happen to spell `Title` is not this shape, and `built` is the record
+ * only the build writes. */
+ const refreshable = $derived(Object.keys(meta.built ?? {}).length > 0);
+ let refreshing = $state(false);
+
+ /**
+ * Bring a proofs sheet level with the case, on a press.
+ *
+ * Never on open. A sheet that rewrites itself when it is looked at is a sheet whose file
+ * moves under an analyst who only wanted to read it, and it would fight the stamp — which
+ * exists precisely so two readers of one file cannot silently overwrite each other.
+ *
+ * Nothing is ever removed here. A proof deleted since the build keeps its row and says NO
+ * in its `In case` column: the notes on that row are the analyst's, and throwing them away
+ * to tidy the table is not a decision this button gets to make.
+ */
+ async function refreshFromCase() {
+ if (refreshing || !openId) return;
+ refreshing = true;
+ try {
+ const answer = await api.post(`/api/cases/${caseId}/sheets/${openId}/refresh`, {
+ columns: table.columns,
+ rows: table.rows,
+ meta,
+ stamp,
+ });
+ adopt({ ...answer, title });
+ await reloadCase();
+ const said = [
+ answer.added ? `${answer.added} row${answer.added === 1 ? '' : 's'} added` : '',
+ answer.gone ? `${answer.gone} proof${answer.gone === 1 ? '' : 's'} no longer in the case` : '',
+ ].filter(Boolean);
+ toast(said.length ? `${said.join(', ')}.` : 'Already level with the case.');
+ } catch (error) {
+ toast(error.message || 'This sheet could not be refreshed.', 'error');
+ } finally {
+ refreshing = false;
+ }
+ }
+
+ function previewBuild(declaration) {
+ return api.post(`/api/cases/${caseId}/sheets/${openId}/proofs/preview`, {
+ columns: table.columns,
+ rows: table.rows,
+ keys: batchKeys,
+ ...declaration,
+ });
+ }
+
+ /**
+ * Build the ticked rows, and watch it happen.
+ *
+ * A job rather than a request, and the only sheet road that is one: a hundred downloads
+ * take minutes, and what an analyst watches for those minutes is the row count moving.
+ * Nothing is written to the sheet while it runs — the file is this tab's to save, and a
+ * job holding a stamp for two minutes would fight every autosave in the window.
+ */
+ async function startBuild(declaration) {
+ if (!openId || buildJob) return;
+ buildReport = null;
+ try {
+ const { job_id } = await api.post(`/api/cases/${caseId}/sheets/${openId}/proofs`, {
+ columns: table.columns,
+ rows: table.rows,
+ keys: batchKeys,
+ ...declaration,
+ });
+ buildJob = { id: job_id, progress: {} };
+ await watchBuild(job_id);
+ } catch (error) {
+ buildJob = null;
+ toast(error.message || 'That build could not be started.', 'error');
+ }
+ }
+
+ async function watchBuild(jobId) {
+ for (;;) {
+ const status = await api.get(`/api/jobs/${jobId}`);
+ if (status.status === 'running') {
+ buildJob = { id: jobId, progress: status.progress ?? {} };
+ await new Promise((resolve) => setTimeout(resolve, 700));
+ continue;
+ }
+ buildJob = null;
+ if (status.status !== 'done') {
+ toast(status.error || 'That build stopped.', 'error');
+ return;
+ }
+ buildReport = status.result ?? null;
+ built(buildReport);
+ return;
+ }
+ }
+
+ async function stopBuild() {
+ if (!buildJob) return;
+ await api.post(`/api/jobs/${buildJob.id}/cancel`, {});
+ }
+
+ /**
+ * What a finished build leaves on the sheet: a chip per cell, and a line in the log.
+ *
+ * The sidecar is written here rather than by the job, because the file is this tab's to
+ * save. Losing it costs the chips and never a duplicate — a second press finds the proof
+ * by the name it was saved under, so the case is what remembers.
+ */
+ function built(report) {
+ if (!report) return;
+ const links = report.links ?? {};
+ if (Object.keys(links).length) {
+ structural(
+ () => {
+ let next = meta;
+ for (const [key, cells] of Object.entries(links)) {
+ for (const [column, entityId] of Object.entries(cells)) {
+ next = setLink(next, key, column, entityId);
+ }
+ }
+ meta = next;
+ },
+ { withTable: false },
+ );
+ }
+ const log = new Map(rowLog);
+ for (const row of report.rows ?? []) {
+ const entries = [...(log.get(row.key) ?? [])];
+ entries.push({
+ column: 'Build',
+ before: '',
+ after: row.outcome === 'failed' ? row.reason : row.outcome,
+ });
+ log.set(row.key, entries.slice(-40));
+ }
+ rowLog = log;
+ const counts = report.counts ?? {};
+ const words = [
+ counts.built && `${counts.built} built`,
+ counts.restated && `${counts.restated} refreshed`,
+ counts.failed && `${counts.failed} failed`,
+ report.stopped && 'stopped',
+ ].filter(Boolean);
+ toast(words.length ? words.join(' · ') : 'Nothing was built.');
+ reloadCase();
+ }
+
+ /**
+ * What a pass did, in the words that distinguish it.
+ *
+ * Counted apart rather than summed: "forty sent" hides whether the case gained forty
+ * subjects or recognised thirty-nine it already had, and it hides the two rows nothing
+ * could be read out of. The edges are counted apart again, because they are the half the
+ * older roads could not draw at all.
+ */
+ function said(answer) {
+ const tally = { make: 0, join: 0, update: 0, skip: 0, error: 0 };
+ for (const layer of answer.entities ?? []) {
+ for (const word of Object.keys(tally)) tally[word] += layer[word] ?? 0;
+ }
+ const drawn = (answer.joins ?? []).reduce((total, join) => total + (join.drawn ?? 0), 0);
+ const words = [
+ tally.make && `${tally.make} added`,
+ tally.join && `${tally.join} joined`,
+ tally.update && `${tally.update} updated`,
+ drawn && `${drawn} ${drawn === 1 ? 'edge' : 'edges'}`,
+ tally.skip && `${tally.skip} left out`,
+ tally.error && `${tally.error} could not be read`,
+ ].filter(Boolean);
+ return words.length ? words.join(' · ') : 'Nothing to send in those rows.';
+ }
+
+ function undo() {
+ apply(history.undo());
+ }
+
+ function redo() {
+ apply(history.redo());
+ }
+
+ function apply(step_) {
+ if (!step_) return;
+ const { entry, direction } = step_;
+ if (entry.kind === 'cells') {
+ table = applyEdits(table, entry.edits, direction);
+ } else {
+ const parsed = JSON.parse(direction === 'backward' ? entry.before : entry.after);
+ if (parsed.table) table = parsed.table;
+ meta = { ...emptyMeta(), ...parsed.meta };
+ }
+ editing = null;
+ touch();
+ }
+
+ // -- rows and columns ------------------------------------------------------
+
+ /**
+ * Grow the sheet by one row, and make sure the analyst can see it.
+ *
+ * A blank row does not answer most filters, so under an active question the row was
+ * written to the file and vanished from the screen in the same breath — which reads as
+ * the press having done nothing, and the row is then found by somebody else a week later.
+ * The filter is the analyst's, so it is not cleared behind them; what happens is that the
+ * grid says the row is there and offers to show it.
+ */
+ function appendRow() {
+ if (!room({ rows: 1 })) return false;
+ structural(() => {
+ table = addRow(table);
+ });
+ const at = table.rows.length - 1;
+ cursor = { row: at, column: firstWritableColumn() };
+ anchor = { ...cursor };
+ if (!shown.includes(at)) {
+ toast('That row is hidden by the current filter.', 'ok', 6000, {
+ label: 'Show it',
+ onClick: showEverything,
+ });
+ return false;
+ }
+ scrollIntoView();
+ return true;
+ }
+
+ /** Every question dropped at once — the chips and the search together, since a row the
+ * one hides is hidden by the other in exactly the same way. */
+ function showEverything() {
+ clearTimeout(queryTimer);
+ queryInput = '';
+ query = '';
+ ask(clearFilters());
+ }
+
+ /**
+ * The empty line at the end of the grid, made real by being typed in.
+ *
+ * What every spreadsheet does, and what a `+ Row` button in the footer was standing in
+ * for: the most ordinary thing a grid does cost a trip to the bottom of the screen and
+ * then a second one back to the column being filled. The editor opens where the click
+ * landed, so the gesture ends where the typing starts — on the column the app writes,
+ * the first one that takes an edit instead.
+ */
+ function startGhost(columnIndex) {
+ // Only where the row actually landed on screen: an editor opened on a row the filter
+ // has already taken away is a box nothing draws and a state nothing can leave.
+ if (!appendRow()) return;
+ const name = table.columns[columnIndex];
+ edit(table.rows.length - 1, writable(name) ? columnIndex : firstWritableColumn());
+ }
+
+ /** A row where the analyst is reading rather than four hundred rows below it. The cursor
+ * follows it, because a line inserted to be filled in is a line to type in. */
+ function addRowAt(index, where) {
+ if (!room({ rows: 1 })) return;
+ const at = where === 'above' ? index : index + 1;
+ structural(() => {
+ table = insertRow(table, at);
+ });
+ cursor = { row: at, column: firstWritableColumn() };
+ anchor = { ...cursor };
+ scrollIntoView();
+ }
+
+ /**
+ * Refuse a gesture that would grow the sheet past what the file can hold, and say why.
+ *
+ * Asked **before** the edit. The bounds are the server's and they were only the
+ * server's, so the grid took the eight hundredth row over the limit and then answered
+ * 422 on every autosave from that moment on: the work was on screen, unsaved, and the
+ * only way out was to guess how much to delete. Refusing the press costs the analyst
+ * one paste; refusing the save cost them the afternoon.
+ */
+ function room(growth) {
+ const full = tooBigBy(table, growth);
+ if (full) toast(full, 'error');
+ return !full;
+ }
+
+ /** The rows a gesture made *on one row* is about: the batch when that row is part of it,
+ * and that row alone otherwise. One rule, so painting, duplicating and deleting from the
+ * gutter cannot disagree about what "these" means. */
+ function rowsAround(index) {
+ return batchIndices.includes(index) && batchIndices.length ? batchIndices : [index];
+ }
+
+ /** Copy the rows this menu is about, each under its own. The gesture is a candidate that
+ * turns out to be two — one address, two hypotheses — and the copies come back ticked so
+ * the next thing done to them is done to the copies. */
+ function duplicateBatch(index) {
+ const wanted = rowsAround(index);
+ if (!room({ rows: wanted.length })) return;
+ let made = [];
+ structural(() => {
+ const grown = duplicateRows(table, wanted);
+ table = grown.table;
+ made = grown.keys;
+ });
+ picked = new Set(made);
+ lastTicked = null;
+ toast(`${made.length} ${made.length === 1 ? 'row' : 'rows'} duplicated.`);
+ }
+
+ /** Ask before the rows go. The count is the whole reason: the batch is whatever was
+ * ticked or dragged over, and "40 rows" that turn out to be the wrong forty is
+ * exactly what a confirmation is for. */
+ function askDeleteBatch() {
+ if (batchIndices.length) confirming = { kind: 'rows', count: batchIndices.length };
+ }
+
+ /** The same ask, from the gutter. The rows travel with it: the batch can change between
+ * the question and the answer, and a delete that acted on a different set than the one
+ * counted would be the exact failure the ask exists to prevent. */
+ function askDeleteRows(index) {
+ const rows = rowsAround(index);
+ if (rows.length) confirming = { kind: 'rows', count: rows.length, rows };
+ }
+
+ function deleteBatch() {
+ const indices = confirming?.rows ?? batchIndices;
+ confirming = null;
+ if (!indices.length) return;
+ structural(() => {
+ table = removeRows(table, indices);
+ });
+ picked = new Set();
+ lastTicked = null;
+ rowPanel = null;
+ cursor = { row: -1, column: -1 };
+ anchor = null;
+ }
+
+ /** Tick a row, or — held with shift — everything between it and the last one
+ * ticked, in the order the grid draws rather than the order the file holds. */
+ function togglePicked(key, extend = false) {
+ const next = new Set(picked);
+ if (extend && lastTicked && lastTicked !== key) {
+ for (const between of keysBetween(table, shown, lastTicked, key)) next.add(between);
+ } else if (!next.delete(key)) next.add(key);
+ picked = next;
+ lastTicked = key;
+ }
+
+ function toggleAllShown() {
+ const keys = shownKeys(table, shown);
+ picked = allShownTicked ? new Set() : new Set(keys);
+ lastTicked = null;
+ }
+
+ /** Paint from the gutter, on the batch or on the one row pressed. */
+ function paintRows(index, colour) {
+ const keys = rowsAround(index).map((at) => rowKey(table.columns, table.rows[at]));
+ structural(
+ () => {
+ let next = meta;
+ for (const key of keys) next = setColour(next, key, colour);
+ meta = next;
+ },
+ { withTable: false },
+ );
+ }
+
+ function paint(colour) {
+ structural(
+ () => {
+ let next = meta;
+ for (const key of batchKeys) next = setColour(next, key, colour);
+ meta = next;
+ },
+ { withTable: false },
+ );
+ }
+
+ function appendColumn() {
+ if (!room({ columns: 1 })) return;
+ structural(() => {
+ table = addColumn(table, 'Column');
+ });
+ showColumn(table.columns.length - 1);
+ }
+
+ /** A column beside the one being worked on. The `+` at the far right is still there for
+ * a column appended to the end; this is the one that was missing, and dragging a new
+ * heading back across twelve columns was the workaround. */
+ function addColumnAt(index, side) {
+ if (!room({ columns: 1 })) return;
+ const at = side === 'left' ? index : index + 1;
+ let name = null;
+ structural(() => {
+ table = insertColumn(table, at, 'Column');
+ name = table.columns[at];
+ });
+ columnPanel = null;
+ renameColumnAt(at, name);
+ }
+
+ function copyColumn(index) {
+ if (!room({ columns: 1 })) return;
+ let made = null;
+ structural(() => {
+ const grown = duplicateColumn(table, meta, index);
+ table = grown.table;
+ meta = grown.meta;
+ made = grown.name;
+ });
+ if (made) toast(`“${made}” written.`);
+ }
+
+ /** Rename in the heading itself. Double-click, or the row in the heading menu: the panel
+ * can still do it, and going two screens away to fix a spelling is not a rename. */
+ function renameColumnAt(index, name = null) {
+ renaming = index;
+ renameText = name ?? table.columns[index] ?? '';
+ }
+
+ function commitHeadingRename() {
+ if (renaming === null) return;
+ const index = renaming;
+ const name = renameText;
+ renaming = null;
+ applyRename(index, name);
+ }
+
+ function applyRename(index, name) {
+ const previous = table.columns[index];
+ if (String(name ?? '').trim() === previous) return;
+ structural(() => {
+ const moved = renameColumn(table, meta, index, name);
+ table = moved.table;
+ meta = moved.meta;
+ // The sidecar's half is moved by `renameColumn`; this is the grid's own copy of the
+ // question, which is held as sets while it is being matched against. Without it the
+ // rows on screen changed because a heading was spelled again.
+ filters = renameFilterColumn(filters, previous, table.columns[index]);
+ });
+ }
+
+ /** Ask before a column goes, and say what goes with it. A column carries cells the
+ * file holds, and a role, a note and a width nothing else remembers — none of which
+ * a heading shows, so the count is how the click stops being a guess. */
+ function askDropColumn(index) {
+ const name = table.columns[index];
+ if (name === undefined) return;
+ confirming = {
+ kind: 'column',
+ index,
+ name,
+ filled: table.rows.filter((row) => String(row[index] ?? '').trim()).length,
+ role: Boolean(roles[name]),
+ };
+ }
+
+ /** Delete a column, and close the panel that was showing it.
+ *
+ * The index is read from the argument rather than from the panel, and the panel is
+ * closed **after** the table moves. Closing it first read `column.index` off a
+ * derived that had just lost its column, which threw before the delete ever ran —
+ * the column stayed, and the only sign was a line in the console. */
+ function dropColumn(index) {
+ confirming = null;
+ if (index < 0 || index >= table.columns.length) return;
+ structural(() => {
+ const moved = removeColumn(table, meta, index);
+ table = moved.table;
+ meta = moved.meta;
+ });
+ columnPanel = null;
+ filterAt = null;
+ cursor = { row: -1, column: -1 };
+ anchor = null;
+ editing = null;
+ }
+
+ /** A pass that rewrote cells: one undoable step, and a word about what it did. */
+ function cleanCells(edits, said) {
+ editCells(edits);
+ toast(said);
+ }
+
+ /** A pass that grew or shrank the table: whole-table step, because the columns moved.
+ *
+ * The bound is checked on the table the pass **produced** rather than on what it was
+ * about to do: splitting one column into six is the pass that reaches the ceiling, and
+ * only the pass itself knows how many it made. */
+ function cleanTable(next, said) {
+ const full = tooBigBy(next.table);
+ if (full) {
+ toast(full, 'error');
+ return;
+ }
+ structural(() => {
+ table = next.table;
+ meta = { ...emptyMeta(), ...next.meta };
+ });
+ columnPanel = null;
+ toast(said);
+ }
+
+ /**
+ * Fold the rows this gesture is about into the first of them.
+ *
+ * The other half of "this value is said twice". Finding the duplicates and painting them
+ * was already here; what followed was retyping one row out of three by hand, which on an
+ * imported inbox where the same address arrives from three channels is the whole job. The
+ * fullest answer per column wins (`lib/sheet.mergeRows`), and the surviving row keeps its
+ * key, so its colour, its links and its promotion record survive with it.
+ */
+ function mergeBatch(index) {
+ const wanted = rowsAround(index);
+ if (wanted.length < 2) return;
+ let folded = 0;
+ let kept = null;
+ structural(() => {
+ const merged = mergeRows(table, wanted);
+ table = merged.table;
+ folded = merged.folded;
+ kept = merged.key;
+ });
+ picked = kept ? new Set([kept]) : new Set();
+ lastTicked = null;
+ cursor = { row: -1, column: -1 };
+ anchor = null;
+ toast(`${folded + 1} rows folded into one. Undo puts them back.`);
+ }
+
+ /**
+ * One cell's values as one row each.
+ *
+ * The shape every "to be sorted" inbox arrives in: a row holding five links, or a cell
+ * reading `Buk-M2E, ZU23-2, S-300` in a worklist that wants a line per system. Splitting a
+ * column into *columns* answers a different question and already existed.
+ */
+ function explodeCell(rowIndex, columnIndex) {
+ const role = roles[table.columns[columnIndex]];
+ const cell = String(table.rows[rowIndex]?.[columnIndex] ?? '');
+ // What the values are written between: the column's own separator where it declares one,
+ // a line per link where the cell holds several, and commas as the last resort — which is
+ // what a pasted list holds.
+ const separator = role?.multi ?? (urlsIn(cell).length > 1 || cell.includes('\n') ? '\n' : ',');
+ // One row is already there, so only the values after the first are new rows.
+ const parts = cell.split(separator).map((part) => part.trim()).filter(Boolean);
+ if (parts.length > 1 && !room({ rows: parts.length - 1 })) return;
+ let made = [];
+ structural(() => {
+ const grown = explodeRow(table, rowIndex, columnIndex, separator);
+ table = grown.table;
+ made = grown.keys;
+ });
+ if (!made.length) {
+ toast('That cell holds one value.');
+ return;
+ }
+ toast(`${made.length + 1} rows out of one.`);
+ }
+
+ /** Keep one row under the heading, or let it go. */
+ function pinRow(index) {
+ const key = rowKey(table.columns, table.rows[index]);
+ structural(
+ () => {
+ meta = setPinned(meta, key);
+ },
+ { withTable: false },
+ );
+ }
+
+ /** Say what a colour means in this sheet. */
+ function nameColour(colour, label) {
+ if ((meta.legend?.[colour] ?? '') === String(label ?? '').trim()) return;
+ structural(
+ () => {
+ meta = setLegend(meta, colour, label);
+ },
+ { withTable: false },
+ );
+ }
+
+ /** One line per row, or the four a note needs. */
+ function toggleTall() {
+ structural(
+ () => {
+ meta = setTall(meta, !meta.tall);
+ },
+ { withTable: false },
+ );
+ }
+
+ /**
+ * Ask whether a column of sources still answers.
+ *
+ * The only reading that reaches the network, and it goes on this press. Walked in batches
+ * so the count moves and a long column can be left half done — and over the rows on
+ * screen, like every other pass here.
+ */
+ async function checkColumnLinks(name) {
+ const at = table.columns.indexOf(name);
+ if (at === -1 || checking) return;
+ const entries = urlsInColumn(table, at, shown);
+ if (!entries.length) {
+ toast('No links in this column, over the rows on screen.');
+ return;
+ }
+ checking = { column: name, done: 0, total: entries.length };
+ const verdicts = {};
+ try {
+ for (const batch of chunk(entries.map((entry) => entry.url))) {
+ Object.assign(verdicts, await checkLinks(caseId, openId, batch));
+ checking = { ...checking, done: Math.min(checking.total, checking.done + batch.length) };
+ }
+ reading = { kind: 'links', column: name, ...readVerdicts(entries, verdicts) };
+ } catch (error) {
+ toast(error.message || 'Those links could not be checked.', 'error');
+ } finally {
+ checking = null;
+ }
+ }
+
+ /**
+ * Build a sheet out of the entities the case holds.
+ *
+ * The other direction of the promotion road, and the server owns all of it: the rows, the
+ * links back and the `mentions` edges land in one write, so a worklist made from forty
+ * places is connected to them before it is opened.
+ */
+ async function buildFromCase(choice) {
+ if (building) return;
+ building = true;
+ try {
+ const sheet = await api.post(`/api/cases/${caseId}/sheets/from-case`, choice);
+ fromCase = false;
+ await list(caseId);
+ openId = null;
+ await open(sheet.id);
+ await reloadCase();
+ toast(
+ sheet.taken < sheet.total
+ ? `${sheet.taken} of ${sheet.total} taken into the sheet.`
+ : `${sheet.taken} ${sheet.taken === 1 ? 'row' : 'rows'} taken into the sheet.`,
+ );
+ } catch (error) {
+ toast(error.message || 'This sheet could not be built.', 'error');
+ } finally {
+ building = false;
+ }
+ }
+
+ /** The reading as a Markdown table, on the clipboard. What goes into a note, a ticket or
+ * a message — retyping twelve rows into the Notebook is where citing the sheet stops. */
+ /**
+ * The reading as a Markdown table, with the provenance that makes it citable.
+ *
+ * The header is what this app kept from the idea of a sheet plate and the only part of
+ * it worth keeping: twelve rows pasted into a ticket with no case, no filter and no
+ * timestamp are twelve rows nobody can check a week later, and `12 of 468` read without
+ * seeing that a filter was on is a sample presented as a set.
+ */
+ async function copyMarkdown() {
+ exportOpen = false;
+ const text = toMarkdown(
+ viewTable(table, drawn, shown),
+ provenance({
+ caseName: caseState.current?.name ?? '',
+ sheet: title,
+ filter: chips.map((chip) => chip.label).join(' · '),
+ sort: meta.sort ? `${meta.sort.column}${meta.sort.desc ? ', descending' : ''}` : '',
+ shown: shown.length,
+ total: table.rows.length,
+ at: new Date().toISOString(),
+ }),
+ );
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(`${shown.length} ${shown.length === 1 ? 'row' : 'rows'} copied as a table.`);
+ } catch {
+ toast('Copying failed. Export the CSV instead.', 'error');
+ }
+ }
+
+ function sortBy(name) {
+ structural(
+ () => {
+ meta = { ...meta, sort: nextSort(meta.sort, name) };
+ },
+ { withTable: false },
+ );
+ }
+
+ /** Sorted the way the menu names it, and pressing the same row again turns it off — the
+ * heading's own click still cycles, which is what a heading does. A second key already in
+ * place travels with it: it is a tiebreak on this sort, not a sort of its own. */
+ function sortDirection(name, desc) {
+ const same = meta.sort?.column === name && meta.sort.desc === desc;
+ structural(
+ () => {
+ const then = meta.sort?.then && meta.sort.then.column !== name ? { then: meta.sort.then } : {};
+ meta = { ...meta, sort: same ? null : { column: name, desc, ...then } };
+ },
+ { withTable: false },
+ );
+ }
+
+ /** Break the first key's ties with this column: ascending, descending, off. */
+ function secondSort(name) {
+ structural(
+ () => {
+ meta = { ...meta, sort: nextSecondSort(meta.sort, name) };
+ },
+ { withTable: false },
+ );
+ }
+
+ function hideColumn(name) {
+ structural(
+ () => {
+ meta = toggleHidden(meta, name);
+ },
+ { withTable: false },
+ );
+ }
+
+ function freezeColumn(name) {
+ structural(
+ () => {
+ meta = setFrozen(meta, name);
+ },
+ { withTable: false },
+ );
+ }
+
+ // -- what a column knows ---------------------------------------------------
+ //
+ // Every one of these writes the sidecar and nothing else. A role is a lens: it changes
+ // what the grid shows and how it sorts, never what the file says. The two exceptions
+ // are declared as such — `stamped` and `computed` are written into the CSV by the
+ // server, and normalising is an edit the analyst asks for by name.
+
+ /**
+ * Declare, change or clear a column's role.
+ *
+ * Almost every role is sidecar-only, so the step it records is the sidecar alone —
+ * kilobytes rather than the whole table. The two exceptions are the roles the **server
+ * writes into the CSV** on the next save: undoing one of those has to put the cells
+ * back as well, or the column keeps its `YES`/`NO` after the role that produced them is
+ * gone, and the undo reads as having done nothing at all.
+ */
+ function setRole(name, role) {
+ const touchesFile = appFilled(name) || ['stamped', 'computed', 'locked'].includes(role?.kind);
+ structural(
+ () => {
+ const next = { ...(meta.roles ?? {}) };
+ if (role) next[name] = role;
+ else delete next[name];
+ meta = { ...meta, roles: next };
+ },
+ { withTable: touchesFile },
+ );
+ }
+
+ /** Take a word the cell holds into the column's own vocabulary, from the cell.
+ *
+ * The column panel could always do this, and that is two screens away from the moment
+ * it is wanted: the analyst is typing `OK en cours` into a status column *now*, and
+ * the choice is between adopting it here or leaving it outside the words for good. */
+ function addValue(name, word) {
+ const role = roles[name];
+ if (!role || !word) return;
+ setRole(name, { ...role, values: [...(role.values ?? []), word] });
+ }
+
+ function setNote(name, text) {
+ const clean = String(text ?? '').trim();
+ if ((meta.notes?.[name] ?? '') === clean) return;
+ structural(
+ () => {
+ const next = { ...(meta.notes ?? {}) };
+ if (clean) next[name] = clean;
+ else delete next[name];
+ meta = { ...meta, notes: next };
+ },
+ { withTable: false },
+ );
+ }
+
+ function setProgress(name) {
+ structural(
+ () => {
+ meta = { ...meta, progress: meta.progress === name ? null : name };
+ },
+ { withTable: false },
+ );
+ }
+
+ /** Offer the column the sheet is plainly being worked through, once, and only when
+ * nobody has said. A suggestion in the footer rather than a setting applied behind
+ * the analyst: the whole point is that they choose it. */
+ const suggestedProgress = $derived(
+ meta.progress ? null : suggestProgressColumn(table, roles, ID_COLUMN),
+ );
+
+ /**
+ * Hand a column of coordinates to the map, as a session layer.
+ *
+ * The points travel rather than the sheet: the map is shown what this column says
+ * right now, and nothing is written anywhere. Same shape as the window Timeline hands
+ * over — `uiState` carries it, the map consumes it and clears it.
+ */
+ function toMap(name, rows = shown) {
+ const at = table.columns.indexOf(name);
+ const points = rows.map((index) => pointOf(index, at)).filter(Boolean);
+ if (!points.length) {
+ toast('No coordinates could be read in this column.', 'error');
+ return;
+ }
+ uiState.mapSheetPoints = { points, sheet: title, column: name };
+ uiState.tool = 'satellite';
+ }
+
+ /** The first column of a kind, or nothing: which column the batch handoffs read without
+ * asking, since a sheet holds one column of coordinates and one of dates far more often
+ * than it holds two. */
+ function firstOfKind(kind) {
+ return table.columns.find((name) => roles[name]?.kind === kind) ?? null;
+ }
+
+ /**
+ * The rows that are ticked, on the map or on the Timeline.
+ *
+ * The column handoffs sent everything on screen, which is the wrong question as often as
+ * it is the right one: an analyst who has just ticked eleven candidates out of four hundred
+ * wants those eleven drawn, not the field. The selection is what they said.
+ */
+ function batchToMap() {
+ const name = firstOfKind('latlon');
+ if (!name) {
+ toast('No column is set to coordinates.', 'error');
+ return;
+ }
+ toMap(name, batchIndices);
+ }
+
+ function batchToTimeline() {
+ const name = firstOfKind('when');
+ if (!name) {
+ toast('No column is set to dates.', 'error');
+ return;
+ }
+ toTimeline(name, batchIndices);
+ }
+
+ /**
+ * One cell's point, on the map, on its own.
+ *
+ * The column's handoff one point wide, because that is the question a worklist asks
+ * most: not *where are all four hundred* but *where is this one*. Through the same
+ * layer, so the pin carries the same circle when the cell was written to a kilometre
+ * — a row sent over alone deserves that warning more than a field of pins does.
+ */
+ function cellToMap(rowIndex, columnIndex) {
+ const point = pointOf(rowIndex, columnIndex);
+ if (!point) return;
+ uiState.mapSheetPoints = {
+ points: [point],
+ sheet: title,
+ column: table.columns[columnIndex],
+ };
+ uiState.tool = 'satellite';
+ }
+
+ /** A cell as a point the map can take, or null where it cannot be read. The label is
+ * how the row will name itself once it is a pin: the first column that is neither the
+ * coordinates being drawn nor the handle, and the handle when there is nothing else. */
+ function pointOf(rowIndex, columnIndex) {
+ const point = parseLatLon(table.rows[rowIndex][columnIndex]);
+ if (!point || point.outOfBounds) return null;
+ const name = table.columns[columnIndex];
+ const label = table.columns.find((column) => column !== name && column !== ID_COLUMN);
+ const labelAt = label ? table.columns.indexOf(label) : -1;
+ return {
+ lat: point.lat,
+ lon: point.lon,
+ label:
+ (labelAt !== -1 ? table.rows[rowIndex][labelAt] : '') ||
+ table.rows[rowIndex][keyIndex(table.columns)],
+ decimals: point.decimals,
+ };
+ }
+
+ /**
+ * Hand a column of dates to the Timeline, as a session layer.
+ *
+ * What travels is the window the column covers, which is what the Timeline is built to
+ * take: it already knows how to draw a period of the case. A bare clock is left behind
+ * — a time with no date cannot be put on an axis, and inventing the date would be
+ * inventing evidence.
+ */
+ function toTimeline(name, rows = shown) {
+ const at = table.columns.indexOf(name);
+ const role = roles[name];
+ const moments = rows
+ .map((index) => parseWhen(table.rows[index][at], role))
+ .filter((read) => read?.shape === 'moment')
+ .map((read) => read.key);
+ if (!moments.length) {
+ toast('No date in this column could be read.', 'error');
+ return;
+ }
+ const day = 86_400_000;
+ uiState.timelineRange = {
+ from: new Date(Math.min(...moments)).toISOString(),
+ to: new Date(Math.max(...moments) + day).toISOString(),
+ };
+ uiState.tool = 'timeline';
+ }
+
+ /** Rewrite every point of a column in one form. The one action here that touches the
+ * file, asked for by name, in one undoable step — because a role by itself never
+ * improves the file, and the binders hold three formats in one column. */
+ function normalise(name) {
+ const at = table.columns.indexOf(name);
+ const edits = [];
+ table.rows.forEach((row, index) => {
+ const point = parseLatLon(row[at]);
+ if (!point) return;
+ const after = formatLatLon(point);
+ if (after !== row[at]) edits.push({ row: index, column: at, before: row[at], after });
+ });
+ if (!edits.length) {
+ toast('Every point is already written the same way.');
+ return;
+ }
+ editCells(edits);
+ toast(`${edits.length} ${edits.length === 1 ? 'point' : 'points'} rewritten.`);
+ }
+
+ function showDuplicates(name) {
+ const at = table.columns.indexOf(name);
+ const groups = duplicateGroups(table, at, roles[name]);
+ reading = { kind: 'duplicates', column: name, groups };
+ }
+
+ function showNearby(name) {
+ const at = table.columns.indexOf(name);
+ reading = { kind: 'nearby', column: name, ...nearbyPairs(table, at, NEARBY_M) };
+ }
+
+ /** How close two points have to be before the grid calls them one place. Wide enough
+ * that two readings of the same building match, tight enough that two ends of a
+ * street do not. */
+ const NEARBY_M = 150;
+
+ /** Paint the rows a reading points at, so the answer lands in the table itself rather
+ * than staying a list beside it. */
+ function paintReading(rowIndices, colour = 'yellow') {
+ const keys = rowIndices.map((index) => rowKey(table.columns, table.rows[index]));
+ structural(
+ () => {
+ let next = meta;
+ for (const key of keys) next = setColour(next, key, colour);
+ meta = next;
+ },
+ { withTable: false },
+ );
+ picked = new Set(keys);
+ }
+
+ // -- dragging a column into place ------------------------------------------
+ //
+ // Pointer events rather than HTML drag and drop: the grid already owns the pointer
+ // for resizing and for its own scrollbars, and mixing the two gesture models on
+ // one heading is how a resize starts a reorder.
+
+ function grabColumn(event, index) {
+ event.preventDefault();
+ event.stopPropagation();
+ dragColumn = { from: index, over: index };
+ const up = () => {
+ const move = dragColumn;
+ dragColumn = null;
+ document.removeEventListener('pointerup', up);
+ if (!move || move.over === move.from) return;
+ structural(() => {
+ table = moveColumn(table, move.from, move.over);
+ });
+ };
+ document.addEventListener('pointerup', up);
+ }
+
+ function dragOver(index) {
+ if (dragColumn && dragColumn.over !== index) dragColumn = { ...dragColumn, over: index };
+ }
+
+ // -- filtering -------------------------------------------------------------
+ //
+ // A heading has two doors, and they are split by how often each is wanted. The
+ // funnel asks something of the column, which is the gesture of the day; the `...`
+ // sets the column up, which is done once and then left alone. One door for both
+ // made the constant thing cost what the rare thing costs — and it was the rare
+ // thing the door was named after.
+
+ function toggleValue(column, value) {
+ ask(toggleFilterValue(filters, column, value));
+ }
+
+ /** Open the filter on the heading under the pointer, or close it if it is that
+ * heading's that is open. Placed from the funnel's own rectangle. */
+ function openFilter(event, column) {
+ const box = event.currentTarget.getBoundingClientRect();
+ const same = filterAt?.index === column.index;
+ cellMenu = null;
+ filterAt = same ? null : { index: column.index, x: box.left, y: box.bottom + 4 };
+ }
+
+ /**
+ * Filter a column the analyst cannot see.
+ *
+ * The columns list is the map of a sheet too wide to read at once, so asking
+ * something of a column from there has to bring its heading over first — a menu
+ * placed on a funnel that is off screen is a menu off screen. Unhides it too: being
+ * asked about is a reason to be visible.
+ */
+ async function filterColumn(name) {
+ columnsOpen = false;
+ if ((meta.hidden ?? []).includes(name)) hideColumn(name);
+ await tick();
+ scrollColumnIntoView(name);
+ await tick();
+ const funnel = funnels[name];
+ if (!funnel?.isConnected) return;
+ const box = funnel.getBoundingClientRect();
+ filterAt = { index: table.columns.indexOf(name), x: box.left, y: box.bottom + 4 };
+ }
+
+ /** How wide the columns that stay put are, together. Where a column brought into
+ * view has to land, or it arrives underneath the frozen ones. */
+ const stickyWidth = $derived(
+ Object.entries(offsets).reduce(
+ (edge, [name, left]) => Math.max(edge, left + (meta.widths?.[name] ?? DEFAULT_WIDTH)),
+ GUTTER_WIDTH,
+ ),
+ );
+
+ /**
+ * Keep an open filter menu on the heading it belongs to while the grid scrolls.
+ *
+ * Followed rather than closed, because the scroll is often the analyst's own doing on
+ * the way to reading the rows the filter just left. It closes when the heading has
+ * gone behind the frozen columns or off the far edge, which is the point at which a
+ * menu is no longer attached to anything.
+ */
+ function followFilter() {
+ if (!filterAt) return;
+ const funnel = funnels[table.columns[filterAt.index]];
+ const grid = scroller?.getBoundingClientRect();
+ if (!funnel?.isConnected || !grid) {
+ filterAt = null;
+ return;
+ }
+ const box = funnel.getBoundingClientRect();
+ if (box.right < grid.left + stickyWidth || box.left > grid.right) {
+ filterAt = null;
+ return;
+ }
+ filterAt = { ...filterAt, x: box.left, y: box.bottom + 4 };
+ }
+
+ function scrollColumnIntoView(name) {
+ if (!scroller) return;
+ let left = GUTTER_WIDTH;
+ for (const column of drawn) {
+ if (column.name === name) break;
+ left += meta.widths?.[column.name] ?? DEFAULT_WIDTH;
+ }
+ scroller.scrollLeft = Math.max(0, left - stickyWidth - 8);
+ measure();
+ }
+
+ /**
+ * The heading's short menu, from the `...` and from a right-click on the heading.
+ *
+ * Placed from the pointer where there is one and from the button's own rectangle
+ * otherwise, so both gestures land somewhere sensible. Everything else over the grid
+ * closes: two menus open at once is two answers to one press.
+ */
+ function openHeadMenu(event, column) {
+ event.preventDefault();
+ event.stopPropagation();
+ const same = headMenu?.index === column.index;
+ filterAt = null;
+ cellMenu = null;
+ rowMenu = null;
+ if (same) {
+ headMenu = null;
+ return;
+ }
+ const box = event.currentTarget?.getBoundingClientRect?.();
+ headMenu = {
+ index: column.index,
+ x: event.clientX || box?.left || 0,
+ y: event.clientY || (box ? box.bottom + 4 : 0),
+ };
+ }
+
+ /** The gutter's menu. It acts on the batch when the row pressed is part of it, which is
+ * what "these forty" means when forty are ticked. */
+ function openRowMenu(event, rowIndex) {
+ event.preventDefault();
+ event.stopPropagation();
+ filterAt = null;
+ cellMenu = null;
+ headMenu = null;
+ rowMenu = { row: rowIndex, x: event.clientX, y: event.clientY };
+ }
+
+ /** How many rows a row menu is about: the batch when this row is in it, or this one. */
+ const rowMenuCount = $derived(
+ rowMenu && batchIndices.includes(rowMenu.row) ? batchIndices.length : 1,
+ );
+
+ /**
+ * A cell's own menu.
+ *
+ * The fastest filter there is, because the answer is already under the pointer: the
+ * analyst reads `Kherson` in a row and wants the other rows saying it, and walking
+ * up to the heading of a column they can see is the step that was in the way. A
+ * blank cell asks the one question a blank cell can: which others are blank too.
+ */
+ function openCellMenu(event, rowIndex, column) {
+ event.preventDefault();
+ filterAt = null;
+ cursor = { row: rowIndex, column: column.index };
+ anchor = { ...cursor };
+ cellMenu = {
+ row: rowIndex,
+ column: column.name,
+ index: column.index,
+ value: String(table.rows[rowIndex]?.[column.index] ?? '').trim(),
+ x: event.clientX,
+ y: event.clientY,
+ };
+ }
+
+ /** The value a cell menu filters on. On a column drawn as chips it is the chip, not
+ * the cell: `Buk-M2E, ZU23-2` is two answers, and asking for the pair would ask for
+ * something no second row holds. */
+ function menuValues(entry) {
+ const role = roles[entry.column];
+ if (!isChipped(role)) return entry.value ? [entry.value] : [];
+ // Distinct: a cell holding one word twice asks one question, and a menu offering
+ // “Only “S-125”” twice is the same filter drawn twice.
+ return [...new Set(cellChips(entry.value, role).map((chip) => chip.value))];
+ }
+
+ // -- the grid's own scrollbars ---------------------------------------------
+
+ /**
+ * What a scroll changes, and only that.
+ *
+ * `measure()` also reads `scrollWidth` and `clientHeight`, and asking a scroller for
+ * those in the middle of a scroll forces the layout it is halfway through — on a wide
+ * grid with sticky columns, a reflow per tick. The four sizes cannot change under a
+ * scroll anyway: a column resized, one hidden or rows filtered away all go through the
+ * effect below, and the panel changing shape goes through the ResizeObserver.
+ */
+ function trackScroll() {
+ if (!scroller) return;
+ extent = { ...extent, left: scroller.scrollLeft, top: scroller.scrollTop };
+ }
+
+ function measure() {
+ if (!scroller) return;
+ extent = {
+ scrollW: scroller.scrollWidth,
+ clientW: scroller.clientWidth,
+ scrollH: scroller.scrollHeight,
+ clientH: scroller.clientHeight,
+ left: scroller.scrollLeft,
+ top: scroller.scrollTop,
+ };
+ }
+
+ // Re-measured when the scroller appears and whenever what it holds changes
+ // shape: a column resized, one hidden, rows filtered away.
+ $effect(() => {
+ const node = scroller;
+ void [template, shown.length, drawn.length];
+ if (!node) return;
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(node);
+ return () => observer.disconnect();
+ });
+
+ /** Drag a thumb. The pointer is captured, so leaving the bar keeps the grab. */
+ function grabThumb(event, axis) {
+ event.preventDefault();
+ event.stopPropagation();
+ dragging = axis;
+ const thumb = axis === 'x' ? hThumb : vThumb;
+ const start = axis === 'x' ? event.clientX : event.clientY;
+ const from = thumb?.position ?? 0;
+ const move = (moved) => {
+ const at = axis === 'x' ? moved.clientX : moved.clientY;
+ const offset = scrollFromThumb(thumb, from + at - start);
+ if (axis === 'x') scroller.scrollLeft = offset;
+ else scroller.scrollTop = offset;
+ measure();
+ };
+ const up = () => {
+ dragging = null;
+ document.removeEventListener('pointermove', move);
+ document.removeEventListener('pointerup', up);
+ };
+ document.addEventListener('pointermove', move);
+ document.addEventListener('pointerup', up);
+ }
+
+ /** Click the empty part of a bar: jump one panel that way, as a scrollbar does. */
+ function pageBy(event, axis) {
+ const thumb = axis === 'x' ? hThumb : vThumb;
+ if (!thumb) return;
+ const box = event.currentTarget.getBoundingClientRect();
+ const at = axis === 'x' ? event.clientX - box.left : event.clientY - box.top;
+ const forward = at > thumb.position + thumb.size / 2;
+ const page = axis === 'x' ? extent.clientW : extent.clientH;
+ if (axis === 'x') scroller.scrollLeft += forward ? page : -page;
+ else scroller.scrollTop += forward ? page : -page;
+ measure();
+ }
+
+ // -- resizing --------------------------------------------------------------
+
+ function startResize(event, name) {
+ event.preventDefault();
+ event.stopPropagation();
+ const startX = event.clientX;
+ const startW = meta.widths?.[name] ?? DEFAULT_WIDTH;
+ const before = snapshot({ withTable: false });
+ const move = (moved) => {
+ meta = setWidth(meta, name, startW + moved.clientX - startX);
+ };
+ const up = () => {
+ document.removeEventListener('pointermove', move);
+ document.removeEventListener('pointerup', up);
+ history.record(snapshotEntry(before, snapshot({ withTable: false })));
+ touch();
+ };
+ document.addEventListener('pointermove', move);
+ document.addEventListener('pointerup', up);
+ }
+
+ // -- entity links ----------------------------------------------------------
+
+ function openLinkPicker(row, column) {
+ linking = { row, column };
+ }
+
+ function attach(entity) {
+ const { row, column } = linking;
+ const key = rowKey(table.columns, table.rows[row]);
+ linking = null;
+ structural(() => {
+ meta = setLink(meta, key, table.columns[column], entity.id);
+ // An empty cell takes the entity's name: the file has to say in words what
+ // the link says in the graph, or the CSV reads as a blank where the work was
+ // done.
+ if (!String(table.rows[row][column] ?? '').trim()) {
+ table = setCells(table, [{ row, column, value: entity.label ?? '' }]);
+ }
+ });
+ }
+
+ function detach(row, column) {
+ const key = rowKey(table.columns, table.rows[row]);
+ linking = null;
+ structural(
+ () => {
+ meta = setLink(meta, key, table.columns[column], null);
+ },
+ { withTable: false },
+ );
+ }
+
+ /**
+ * Let go of what the case has deleted.
+ *
+ * A link is an id in the sidecar rather than an edge, so a delete on another screen
+ * cannot reach the copy this grid is holding: the cell went on showing a link to a row
+ * the case no longer had, and the next save would have written the dead id back over
+ * the file that the delete had just cleared (`engine/sheets.forget_entities`).
+ *
+ * Asked once per case change, and only about the ids this sheet actually points at.
+ * The screen is brought to where the file already is, so nothing is marked unsaved and
+ * nothing the analyst is typing is touched.
+ */
+ let sweptRev = null;
+ $effect(() => {
+ const rev = caseState.rev;
+ const id = caseId;
+ if (!id || !openId) return;
+ if (sweptRev === null || sweptRev === rev) {
+ sweptRev = rev; // the read that opened the sheet is already current
+ return;
+ }
+ sweptRev = rev;
+ untrack(() => void forgetDeleted(id));
+ });
+
+ async function forgetDeleted(id) {
+ const ids = linkedEntityIds(meta);
+ if (!ids.length) return;
+ let missing = [];
+ try {
+ ({ missing = [] } = await api.post(`/api/cases/${id}/entities/missing`, { ids }));
+ } catch {
+ return; // the file is already clear; the next read of the sheet settles the screen
+ }
+ if (!missing.length || id !== caseId) return;
+ const next = withoutEntities(meta, new Set(missing));
+ if (next === meta) return;
+ meta = next;
+ toast(`Dropped ${missing.length} link${missing.length > 1 ? 's' : ''} to deleted items`, 'info');
+ }
+
+ function linkOf(rowIndex, columnName) {
+ return linkAt(meta, rowKey(table.columns, table.rows[rowIndex]), columnName);
+ }
+
+ /**
+ * Whether this cell has been rewritten since the case took what it said.
+ *
+ * The link alone cannot answer it: it is the same link after the label is edited, so a
+ * promoted row and a promoted row that has moved on looked identical. The sidecar keeps
+ * the words the promotion read, and the difference is what the mark says. Promotion
+ * runs one way — nothing here writes the cell back from the graph — so the answer is
+ * "this row and the case no longer agree", which is the analyst's to settle.
+ */
+ function editedSincePromotion(rowIndex, column) {
+ const key = rowKey(table.columns, table.rows[rowIndex]);
+ const said = meta.promoted?.[key]?.[column.name];
+ if (said === undefined) return false;
+ return said !== String(table.rows[rowIndex][column.index] ?? '').trim();
+ }
+
+ /** Escape and the backdrop both close a modal, and the Details panel's fields wait
+ * for its own Save: closing over half-typed edits threw them away without a word.
+ * The ask is only raised when there is something to lose. */
+ function closeDetails() {
+ if (detailsDirty) discarding = true;
+ else detailsId = null;
+ }
+
+ /**
+ * The two right-hand panels, which share one slot.
+ *
+ * Exclusive in the state rather than only in the template: a slot showing one of them
+ * while the other is still set is a panel that comes back on its own when the first is
+ * closed. Opening either puts the other away, which is the whole rule.
+ */
+ function showColumn(index) {
+ rowPanel = null;
+ columnPanel = index;
+ }
+
+ function showRow(index) {
+ columnPanel = null;
+ rowPanel = index;
+ }
+
+ /** The row panel walks the rows the analyst can see, not the file's own order. */
+ function stepPanel(by) {
+ const at = shown.indexOf(rowPanel);
+ if (at === -1) return;
+ const next = shown[at + by];
+ if (next !== undefined) showRow(next);
+ }
+
+ const saveWord = $derived(
+ { idle: '', dirty: 'Unsaved', saving: 'Saving', saved: 'Saved', failed: 'Not saved' }[saveState],
+ );
+</script>
+
+<!-- The focus listener is what turns "the file moved on" from a refusal into a warning:
+ the stamp is a stat, so asking on every return is cheap, and hearing it now beats
+ hearing it at the save. -->
+<svelte:window onkeydown={onKey} oncopy={onCopy} onpaste={onPaste} onfocus={checkStamp} />
+
+<div class="tool">
+ <header class="tool-header">
+ <Icon name="table" size={17} />
+ <h2>Sheet</h2>
+ {#if openId}
+ <input
+ class="input title-input"
+ bind:value={title}
+ onblur={rename}
+ onkeydown={(event) => event.key === 'Enter' && event.currentTarget.blur()}
+ aria-label="Sheet name"
+ />
+ <!-- What the table is for, beside its name, because that is what it is: a subtitle.
+ The binders carried a whole "How to use" tab of annotated screenshots; most of
+ what it said belongs on the columns it was about, which is a column's note, and
+ this is the sentence left over. One line, quiet, and the only door it needs. -->
+ {#if describing}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input describe-input" autofocus maxlength={MAX_DESCRIPTION}
+ placeholder="what this sheet is for"
+ aria-label="What this sheet is for" bind:value={describeText}
+ onkeydown={(event) => {
+ if (event.key === 'Enter') commitDescription();
+ if (event.key === 'Escape') describing = false;
+ }}
+ onblur={commitDescription} />
+ {:else if meta.description}
+ <button class="describe-text" title="Edit this description"
+ onclick={() => { describeText = meta.description; describing = true; }}>
+ {meta.description}
+ </button>
+ {:else}
+ <!-- A pencil and not an `i`: the `i` in this header is the help, the way it is in
+ every other tool, and two of them side by side asked the same question twice. -->
+ <button class="btn btn-ghost btn-sm" title="Add a description"
+ aria-label="Add a description"
+ onclick={() => { describeText = ''; describing = true; }}>
+ <Icon name="edit" size={13} />
+ </button>
+ {/if}
+ <div class="anchor" bind:this={pickerAnchor}>
+ <button class="btn btn-ghost btn-sm" aria-expanded={Boolean(picker)}
+ onclick={() => (picker = picker ? null : 'list')}>
+ {sheets.length} {sheets.length === 1 ? 'sheet' : 'sheets'}
+ <Icon name="chevronDown" size={13} />
+ </button>
+ {#if picker}
+ <div class="sheet-menu">
+ {#if sheets.length > 8}
+ <!-- A case that has grown nine worklists is a case where the picker is a list
+ to be searched rather than read. -->
+ <!-- svelte-ignore a11y_autofocus -->
+ <div class="sheet-search-row">
+ <input class="input" autofocus bind:value={sheetTerm}
+ placeholder="Find a sheet" aria-label="Find a sheet" />
+ </div>
+ {/if}
+ <!-- Only the list scrolls. The two actions below make a sheet **out of this
+ one**, so a case holding fourteen of them must not scroll them out of
+ reach — the same shape the case switcher uses for the same reason. -->
+ <div class="sheet-list">
+ {#each sheetsShown as sheet (sheet.id)}
+ <button class="sheet-row" class:active={sheet.id === openId}
+ onclick={() => open(sheet.id)}>
+ <Icon name="table" size={13} />
+ <span>{sheet.title}</span>
+ <small>{sheet.rows} rows · {sheet.columns} columns</small>
+ </button>
+ {:else}
+ <p class="menu-note">No match.</p>
+ {/each}
+ </div>
+ {#if openId}
+ <div class="sheet-foot">
+ <!-- The app's answer to saved views is "another reading is another sheet". -->
+ <button class="menu-row" onclick={() => duplicateSheet()}>
+ <Icon name="copy" size={12} /><span>Duplicate this sheet</span>
+ </button>
+ <!-- And the fork a binder is actually built out of: an inbox, a worklist
+ and a reference table at one schema, the next starting as this one's
+ columns with nothing under them. -->
+ <button class="menu-row" onclick={() => duplicateSheet({ empty: true })}>
+ <Icon name="table" size={12} /><span>New sheet with these columns</span>
+ </button>
+ </div>
+ {/if}
+ </div>
+ {/if}
+ </div>
+ {/if}
+ <div class="spacer"></div>
+ {#if saveWord}<span class="save-state {saveState}">{saveWord}</span>{/if}
+ <!-- Five ways of getting rows in, under one button. As five buttons they were five
+ sixths of a header that had to fit a title, a subtitle, the sheet list, an export
+ and a delete: on a laptop the last of them ran off the edge. They are also asked
+ once per sheet, where the grid's own controls are asked all day. -->
+ <div class="anchor" bind:this={newAnchor}>
+ <button class="btn btn-sm" aria-expanded={newOpen} onclick={() => (newOpen = !newOpen)}>
+ <Icon name="plus" size={13} /> New <Icon name="chevronDown" size={12} />
+ </button>
+ {#if newOpen}
+ <div class="new-menu">
+ <button class="menu-row" onclick={() => { newOpen = false; creating = { title: '' }; }}>
+ <Icon name="table" size={12} /><span>Blank sheet</span>
+ </button>
+ <!-- One row for both, because the analyst has a file and not a format: a CSV
+ lands as one sheet, a workbook as one sheet per tab under the tabs' names. -->
+ <label class="menu-row">
+ <Icon name="upload" size={12} /><span>Import a file</span>
+ <input type="file" accept=".csv,.tsv,.xlsx,text/csv,text/plain" hidden
+ onchange={(event) => {
+ newOpen = false;
+ importFile(event.currentTarget.files);
+ event.currentTarget.value = '';
+ }} />
+ </label>
+ <button class="menu-row"
+ onclick={() => { newOpen = false; creating = { title: '', text: '' }; }}>
+ <Icon name="copy" size={12} /><span>Paste a table</span>
+ </button>
+ <!-- The other direction of the promotion road: what the case believes, as rows
+ to work through. -->
+ <button class="menu-row" onclick={() => { newOpen = false; fromCase = true; }}>
+ <Icon name="graph" size={12} /><span>From the case</span>
+ </button>
+ {#if openId}
+ <div class="menu-rule"></div>
+ <!-- The daily batch belongs in the worklist that already carries the statuses,
+ not in a thirteenth sheet nobody compares. -->
+ <button class="menu-row" onclick={() => { newOpen = false; appending = true; }}>
+ <Icon name="plus" size={12} /><span>Add rows to this sheet</span>
+ </button>
+ {/if}
+ </div>
+ {/if}
+ </div>
+ {#if openId}
+ <!-- What is on screen, as a file to hand over. Named for what it produces
+ rather than for the machinery: the sheet is already a CSV in the case. -->
+ <div class="anchor" bind:this={exportAnchor}>
+ <button class="btn btn-sm" disabled={exporting} aria-expanded={exportOpen}
+ onclick={() => { exportOpen = !exportOpen; if (exportOpen) readDestination(); }}>
+ <Icon name="download" size={13} /> Export <Icon name="chevronDown" size={12} />
+ </button>
+ {#if exportOpen}
+ <div class="export-menu">
+ <button class="menu-row" onclick={() => download()}>
+ <Icon name="download" size={12} />
+ <span>Save {shown.length} rows on screen as CSV</span>
+ </button>
+ <button class="menu-row" disabled={!batchKeys.length}
+ onclick={() => download({ ticked: true })}>
+ <Icon name="check" size={12} />
+ <span>{batchKeys.length ? `Save ${batchKeys.length} selected rows as CSV` : 'No rows selected'}</span>
+ </button>
+ <!-- What goes into a note, a ticket or a message. Retyping twelve rows into
+ the Notebook is where citing the sheet stops. -->
+ <button class="menu-row" onclick={copyMarkdown}>
+ <Icon name="copy" size={12} /><span>Copy as a Markdown table</span>
+ </button>
+ <div class="menu-rule"></div>
+ <!-- Where it lands, named and changeable **here** — the same offer the plates
+ and the note PDFs make. Sending the analyst to Settings to file a table
+ somewhere else was the one export in the app that did that. -->
+ <div class="dest">
+ <span>Folder</span>
+ <span class="dest-path" title={destination || CASE_FOLDER_LABEL}>
+ {destination === null ? 'reading…' : destinationLabel(destination)}
+ </span>
+ <button class="link" onclick={() => { exportOpen = false; destPicker = true; }}>
+ Change
+ </button>
+ </div>
+ <button class="menu-row" onclick={showExports}>
+ <Icon name="folderOpen" size={12} /><span>Open this folder</span>
+ </button>
+ </div>
+ {/if}
+ </div>
+ <button class="btn btn-sm btn-danger" title="Delete this sheet"
+ onclick={() => (confirming = { kind: 'sheet' })}>
+ <Icon name="trash" size={13} />
+ </button>
+ {/if}
+ <!-- The grid keeps its power under a right-click, which is right — and a right-click
+ nobody tries is a feature nobody has. So one door says what there is. -->
+ <button class="btn btn-ghost btn-sm" title="Keys and gestures (?)" aria-label="Keys and gestures"
+ onclick={() => (helpOpen = true)}>
+ <Icon name="info" size={14} />
+ </button>
+ </header>
+
+ {#if !openId}
+ <div class="empty">
+ {#if loading}
+ <p>Opening.</p>
+ {:else}
+ <Icon name="table" size={30} />
+ <p>No sheet in this case.</p>
+ <small>A sheet is a CSV in the case folder.</small>
+ <!-- What the grid is *for*, in an empty state that used to say only that it was
+ empty. A worklist, a comparison grid and the half-facts are the three things no
+ other tool here covers, and an analyst who does not know that files a
+ spreadsheet somewhere else instead. -->
+ <ul class="empty-what">
+ <li>A worklist that counts what is left</li>
+ <li>A comparison grid: candidates down, criteria across</li>
+ <li>Notes too rough for the graph</li>
+ </ul>
+ <div class="row-actions">
+ <button class="btn btn-primary btn-sm" onclick={() => (creating = { title: '' })}>
+ New sheet
+ </button>
+ <!-- The same file kinds the header takes, workbooks included: an empty state that
+ refused an `.xlsx` the menu accepts is the app disagreeing with itself. -->
+ <label class="btn btn-sm">
+ Import a file
+ <input type="file" accept=".csv,.tsv,.xlsx,text/csv,text/plain" hidden
+ onchange={(event) => { importFile(event.currentTarget.files); event.currentTarget.value = ''; }} />
+ </label>
+ <button class="btn btn-sm" onclick={() => (creating = { title: '', text: '' })}>
+ Paste a table
+ </button>
+ <button class="btn btn-sm" onclick={() => (fromCase = true)}>
+ From the case
+ </button>
+ </div>
+ {/if}
+ </div>
+ {:else}
+ <div class="question">
+ {#if refreshable}
+ <!-- Beside the search rather than up in the header: it acts on the rows, and this
+ bar is the one that does. Pressed, never automatic — refreshing on open would
+ rewrite a file somebody opened to read. It adds and never removes. -->
+ <button class="btn btn-ghost btn-sm" disabled={refreshing} onclick={refreshFromCase}
+ title="File the proofs added since, and restate the columns the case owns">
+ <Icon name="reset" size={13} /> {refreshing ? 'Refreshing' : 'Refresh'}
+ </button>
+ {/if}
+ <div class="search">
+ <Icon name="search" size={13} />
+ <!-- Written by hand rather than bound: the box echoes the keystroke and the grid
+ narrows a moment later, and one binding cannot hold both clocks. -->
+ <input class="input" placeholder="Search these rows" bind:this={searchBox}
+ value={queryInput} oninput={(event) => onQuery(event.currentTarget.value)} />
+ </div>
+ {#each chips as chip (chip.column + chip.part + chip.value)}
+ <button class="chip" onclick={() => ask(dropChip(filters, chip))}>
+ <span class="chip-key">{chip.column}</span>
+ {chip.label}
+ <Icon name="x" size={11} />
+ </button>
+ {/each}
+ {#if chips.length > 1}
+ <!-- Taking six chips off one at a time is six presses to ask the sheet the question
+ it opened on. -->
+ <button class="link" onclick={() => ask(clearFilters())}>Clear all</button>
+ {/if}
+ <span class="count">
+ <strong>{shown.length}</strong> of {table.rows.length}
+ </span>
+ <div class="spacer"></div>
+ <button class="btn btn-ghost btn-sm" title="Undo (Ctrl+Z)" disabled={!canUndo} onclick={undo}>
+ <Icon name="undo" size={13} />
+ </button>
+ <button class="btn btn-ghost btn-sm" title="Redo (Ctrl+Shift+Z)" disabled={!canRedo} onclick={redo}>
+ <Icon name="redo" size={13} />
+ </button>
+ <!-- Thirty pixels is right for a worklist and wrong for the column the reasoning is
+ written in, so the sheet says which it is. Named rather than drawn: a lone glyph
+ whose meaning arrives on hover is a button nobody presses. -->
+ <button class="btn btn-ghost btn-sm" class:active={Boolean(meta.tall)}
+ aria-pressed={Boolean(meta.tall)} onclick={toggleTall}>
+ <Icon name="text" size={13} /> {meta.tall ? 'Short rows' : 'Tall rows'}
+ </button>
+ {#if legendUsed.length}
+ <!-- Six colours and no legend is six colours whose meaning lives in one analyst's
+ head, on a case that gets handed over. -->
+ <div class="anchor" bind:this={legendAnchor}>
+ <button class="btn btn-ghost btn-sm" class:active={legendOpen} aria-expanded={legendOpen}
+ title="What the colours mean"
+ onclick={() => (legendOpen = !legendOpen)}>
+ <Icon name="square" size={13} /> Colours
+ </button>
+ {#if legendOpen}
+ <SheetLegend {meta} counts={colourCounts} onlabel={nameColour} />
+ {/if}
+ </div>
+ {/if}
+ <div class="anchor" bind:this={columnsAnchor}>
+ <button class="btn btn-ghost btn-sm" class:active={columnsOpen}
+ aria-expanded={columnsOpen} onclick={() => (columnsOpen = !columnsOpen)}>
+ <Icon name="layers" size={13} /> Columns
+ </button>
+ {#if columnsOpen}
+ <!-- The map of the sheet, not a list of checkboxes. On a fourteen-column
+ binder the column being asked about is usually off screen, so this says
+ what each one is and what is being asked of it, and its funnel brings it
+ over and opens its filter there. -->
+ <div class="columns-menu">
+ {#each table.columns as name (name)}
+ {@const hidden = meta.hidden?.includes(name)}
+ {@const mark = roleMark(name)}
+ {#if String(name).toLowerCase() !== ID_COLUMN}
+ <div class="column-row" class:off={hidden}>
+ <input type="checkbox" checked={!hidden} aria-label="Show {name}"
+ title={hidden ? 'Show this column' : 'Hide this column'}
+ onchange={() => hideColumn(name)} />
+ <span class="column-name">{name}</span>
+ {#if meta.sort?.column === name}
+ <Icon name={meta.sort.desc ? 'chevronDown' : 'chevronUp'} size={11} />
+ {/if}
+ {#if mark}
+ <span class="column-kind" title={mark.label}>
+ <Icon name={mark.icon} size={11} />
+ </span>
+ {/if}
+ <button class="column-ask" class:on={isFilterActive(filters[name])}
+ title={isFilterActive(filters[name])
+ ? `Filtered: ${filterSummary(filters[name])}`
+ : `Filter ${name}`}
+ aria-label="Filter {name}"
+ onclick={() => filterColumn(name)}>
+ <Icon name="filter" size={12} />
+ </button>
+ </div>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ </div>
+ </div>
+
+ {#if filling}
+ <!-- Buttons rather than a dropdown: on a fourteen-column binder, the column
+ being written is worth reading at a glance, and a closed menu hides which
+ one is about to be overwritten. -->
+ <div class="fill-bar">
+ <span class="label">Set</span>
+ <!-- The two columns the app fills are not on offer: a value written into
+ `Added on` or `On map` is rewritten by the next save, so a bar that took it
+ would be a bar that appeared to work. -->
+ {#if fillable.length > 10}
+ <!-- Past a dozen columns the chips wrap into three rows and push the box that is
+ about to be typed in off the bar. A binder is exactly that wide. -->
+ <select class="input fill-pick" aria-label="Which column to fill"
+ value={filling.column}
+ onchange={(event) => (filling = { column: event.currentTarget.value })}>
+ {#each fillable as name (name)}
+ <option value={name}>{name}</option>
+ {/each}
+ </select>
+ {:else}
+ <div class="fill-columns">
+ {#each fillable as name (name)}
+ <button class="chip" class:on={filling.column === name}
+ onclick={() => (filling = { column: name })}>{name}</button>
+ {/each}
+ </div>
+ {/if}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input" autofocus aria-label="What to write into {filling.column}"
+ placeholder="Value" bind:value={fillValue}
+ onkeydown={(event) => event.key === 'Enter' && applyFill()} />
+ <span class="label">on {batchKeys.length} {batchKeys.length === 1 ? 'row' : 'rows'}</span>
+ <button class="btn btn-sm" onclick={() => (filling = null)}>Cancel</button>
+ <button class="btn btn-primary btn-sm" onclick={applyFill}>Fill</button>
+ </div>
+ {/if}
+
+ {#if droppedRoles.length}
+ <p class="notice" role="alert">
+ {droppedRoles.length === 1
+ ? `“${droppedRoles[0]}” is no longer in the file, so its type, its words and its note are gone.`
+ : `${droppedRoles.length} columns are no longer in the file, so their types, words and notes are gone: ${droppedRoles.join(', ')}.`}
+ Renaming a column outside the app does this.
+ <button class="btn btn-sm" onclick={() => (droppedRoles = [])}>OK</button>
+ </p>
+ {/if}
+
+ {#if checking}
+ <!-- The one reading here that leaves the machine, so it says how far it has got.
+ Nominatim's pacing and a rotting host are both slow for honest reasons. -->
+ <p class="notice" role="status">
+ Checking the links in “{checking.column}”: {checking.done} of {checking.total}.
+ </p>
+ {/if}
+
+ {#if reading}
+ <div class="reading">
+ {#if reading.kind === 'duplicates'}
+ <strong>{reading.groups.length}</strong>
+ {reading.groups.length === 1 ? 'value appears' : 'values appear'} more than once in
+ <em>{reading.column}</em>
+ {#if reading.groups.length}
+ <div class="found">
+ {#each reading.groups.slice(0, 12) as group (group.value)}
+ <button class="chip" onclick={() => paintReading(group.rows)}>
+ {group.value} <small>×{group.rows.length}</small>
+ </button>
+ {/each}
+ {#if reading.groups.length > 12}
+ <span class="foot-note">and {reading.groups.length - 12} more</span>
+ {/if}
+ </div>
+ {/if}
+ {:else if reading.kind === 'links'}
+ <!-- Counted apart, because they are different facts: a 403 behind a login says
+ nothing about whether the page is there, and folding it into "dead" is how a
+ source gets thrown away for having a paywall. -->
+ <strong>{reading.bad.length}</strong>
+ {reading.bad.length === 1 ? 'link' : 'links'} did not answer in
+ <em>{reading.column}</em>
+ <span class="foot-note">
+ {reading.ok} answered{reading.refused ? `, ${reading.refused} blocked` : ''}{reading.skipped
+ ? `, ${reading.skipped} not tried`
+ : ''}
+ </span>
+ {#if reading.bad.length}
+ <div class="found">
+ {#each reading.bad.slice(0, 12) as entry (entry.url)}
+ <button class="chip" title="{entry.url} — {entry.state}{entry.code ? ` (${entry.code})` : ''}"
+ onclick={() => paintReading(entry.rows, 'red')}>
+ {linkLabel(entry.url)} <small>×{entry.rows.length}</small>
+ </button>
+ {/each}
+ {#if reading.bad.length > 12}
+ <span class="foot-note">and {reading.bad.length - 12} more</span>
+ {/if}
+ <button class="chip" onclick={() => paintReading(reading.rows, 'red')}>
+ Paint all {reading.rows.length}
+ </button>
+ </div>
+ {/if}
+ {:else}
+ <strong>{reading.pairs.length}</strong>
+ {reading.pairs.length === 1 ? 'pair' : 'pairs'} within {NEARBY_M} m in
+ <em>{reading.column}</em>
+ {#if reading.capped}<span class="foot-note">(list cut short)</span>{/if}
+ {#if reading.pairs.length}
+ <div class="found">
+ {#each reading.pairs.slice(0, 12) as pair (pair.rows.join(':'))}
+ <button class="chip" onclick={() => paintReading(pair.rows, 'orange')}>
+ {rowKey(table.columns, table.rows[pair.rows[0]])} ·
+ {rowKey(table.columns, table.rows[pair.rows[1]])}
+ <small>{pair.metres} m</small>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ {/if}
+ <div class="spacer"></div>
+ <button class="btn btn-ghost btn-sm" aria-label="Close"
+ onclick={() => (reading = null)}>
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {/if}
+
+ {#if conflict || stale}
+ <!-- Two banners' worth of news in one place, because it is one fact told at two
+ volumes. The soft one comes from the stamp checked on focus: nothing has been
+ refused, so it says what happened and waits. The hard one is a save that was
+ refused, and until it is answered nothing more is written.
+
+ Both offer to **read the file first**. Reload and Overwrite are each
+ irreversible in the direction that matters, and choosing between them over one
+ sentence made three rows a colleague added and one stray cell the same press. -->
+ <div class="notice stacked" class:danger={conflict} role="alert">
+ <p>
+ {conflict
+ ? 'This file changed on disk. Nothing is being saved until you answer.'
+ : 'This file changed on disk after it was opened. Nothing is lost.'}
+ {#if stale?.diff}<span class="diff-said">{describeDiff(stale.diff)}</span>{/if}
+ </p>
+ {#if stale?.diff?.changed.length}
+ <!-- The sample that makes the count believable. -->
+ <ul class="diff-rows">
+ {#each stale.diff.changed as change (change.key + change.column)}
+ <li>
+ <code>{change.key}</code>
+ <em>{change.column}</em>
+ <span class="was">{change.mine || '—'}</span>
+ <Icon name="arrowRight" size={11} />
+ <span>{change.theirs || '—'}</span>
+ </li>
+ {/each}
+ {#if stale.diff.cellsChanged > stale.diff.changed.length}
+ <li class="foot-note">
+ and {stale.diff.cellsChanged - stale.diff.changed.length} more
+ </li>
+ {/if}
+ </ul>
+ {/if}
+ <div class="notice-row">
+ {#if !stale?.diff}
+ <button class="btn btn-sm" disabled={comparing} onclick={compare}>
+ {comparing ? 'Reading…' : 'See what changed'}
+ </button>
+ {/if}
+ <!-- Both are destructive and each destroys the other side's work, so both say
+ so. Reload is the one that used to look free. -->
+ <button class="btn btn-sm" class:btn-danger={unsaved}
+ onclick={() => (unsaved ? (confirming = { kind: 'reload' }) : reload())}>
+ Reload
+ </button>
+ <button class="btn btn-sm btn-danger" onclick={() => (confirming = { kind: 'overwrite' })}>
+ Overwrite
+ </button>
+ {#if !conflict}
+ <button class="btn btn-ghost btn-sm" onclick={() => (stale = null)}>Later</button>
+ {/if}
+ </div>
+ </div>
+ {:else if assigned}
+ <p class="notice">
+ This file has no <code>id</code> column. Saving adds one, so colours and links
+ keep their rows.
+ </p>
+ {/if}
+
+ <!-- The cell under the cursor, in a box the width of the tool. A cell thirty pixels
+ tall is where a value is read; this is where a long one is written.
+
+ Always drawn, empty and all, rather than appearing with the cursor: a bar that
+ arrives on the first click pushes the grid down under the pointer, and the drag
+ that click started then paints a selection across cells nobody aimed at.
+
+ A textarea rather than a box one line tall, because the cells hold paragraphs and
+ the corner pulls the bar as far open as the value needs. Enter commits it — a
+ newline is Shift+Enter, as it is in the cell's own editor. -->
+ <div class="cell-bar" class:idle={!barColumn}>
+ {#if barColumn}
+ <span class="cell-bar-where">
+ <strong>{shown.indexOf(cursor.row) + 1}</strong>{barColumn}
+ </span>
+ {/if}
+ <textarea class="input cell-bar-box" rows="1" spellcheck="false"
+ aria-label="The cell under the cursor"
+ placeholder={barColumn ? '' : 'Click a cell'}
+ disabled={!barColumn}
+ readonly={Boolean(barColumn) && !barWritable}
+ title={barLocked}
+ value={barValue}
+ onfocus={barFocus}
+ oninput={(event) => (barDraft = {
+ row: cursor.row, column: cursor.column, value: event.currentTarget.value,
+ })}
+ onkeydown={onBarKey}
+ onblur={() => commitBar()}></textarea>
+ </div>
+
+ <div class="grid-panel">
+ <div class="grid-wrap" class:dropping
+ ondragover={(event) => { event.preventDefault(); dropping = true; }}
+ ondragleave={() => (dropping = false)}
+ ondrop={onDrop}
+ role="presentation">
+ <!-- The grid takes the focus itself and says which cell the cursor is on, because the
+ keyboard is answered on `window` and the cells are never focused: without this a
+ screen reader followed none of it. -->
+ <div class="grid" class:tall={meta.tall} id="sheet-grid" role="grid" aria-label="Sheet rows"
+ tabindex="0"
+ aria-activedescendant={cursor.row === -1
+ ? undefined
+ : `sheet-cell-${cursor.row}-${cursor.column}`}
+ bind:this={scroller}
+ onscroll={(event) => {
+ scrollTop = event.currentTarget.scrollTop;
+ trackScroll();
+ followFilter();
+ cellMenu = null;
+ }}
+ bind:clientHeight={viewport}>
+ <div class="head" role="row" style="grid-template-columns: {headTemplate}">
+ <div class="cell gutter">
+ <input type="checkbox" checked={allShownTicked} onchange={toggleAllShown}
+ aria-label="Tick every row shown"
+ title={allShownTicked ? 'Untick these rows' : 'Tick every row shown'} />
+ </div>
+ {#each drawn as column (column.name)}
+ {@const sticky = offsets[column.name]}
+ {@const mark = roleMark(column.name)}
+ <div class="cell heading" class:sorted={meta.sort?.column === column.name}
+ class:asked={isFilterActive(filters[column.name])}
+ class:sticky={sticky !== undefined}
+ class:dragged={dragColumn?.from === column.index}
+ class:target={dragColumn && dragColumn.over === column.index && dragColumn.from !== column.index}
+ style={sticky !== undefined ? `left: ${sticky}px` : ''}
+ role="columnheader" tabindex="-1"
+ aria-sort={meta.sort?.column === column.name
+ ? (meta.sort.desc ? 'descending' : 'ascending')
+ : 'none'}
+ oncontextmenu={(event) => openHeadMenu(event, column)}
+ onpointerenter={() => dragOver(column.index)}>
+ <button class="grip" aria-label="Move {column.name}" title="Drag to move this column"
+ onpointerdown={(event) => grabColumn(event, column.index)}>
+ <Icon name="grip" size={11} />
+ </button>
+ <!-- What the column is, in the heading rather than two clicks away in the
+ panel. A grid where the type is invisible is a grid where a sort that
+ reads dates and a sort that reads words look identical. -->
+ {#if mark}
+ <span class="role-mark" title="{mark.label}: {column.name}">
+ <Icon name={mark.icon} size={11} />
+ </span>
+ {/if}
+ {#if renaming === column.index}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input class="input heading-rename" autofocus bind:value={renameText}
+ aria-label="Rename {column.name}"
+ onkeydown={(event) => {
+ if (event.key === 'Enter') event.currentTarget.blur();
+ if (event.key === 'Escape') renaming = null;
+ }}
+ onblur={commitHeadingRename} />
+ {:else}
+ <button class="heading-name" onclick={() => sortBy(column.name)}
+ ondblclick={() => !isKeyColumn(column.index) && renameColumnAt(column.index)}
+ title="Sort by {column.name} · double-click to rename">
+ <span>{column.name}</span>
+ <!-- The unit where a spreadsheet writes it: beside the name, once. It
+ belongs to every cell of the column, and the file holds the digits
+ alone — repeating it down four hundred rows would be four hundred
+ copies of one fact, in cells thirty pixels tall. -->
+ {#if roles[column.name]?.unit}
+ <small class="unit">{roles[column.name].unit}</small>
+ {/if}
+ {#if meta.sort?.column === column.name}
+ <Icon name={meta.sort.desc ? 'chevronDown' : 'chevronUp'} size={12} />
+ {:else if meta.sort?.then?.column === column.name}
+ <!-- Smaller and quieter than the first key, because it is a tiebreak on
+ that key rather than a sort of its own. -->
+ <span class="then-mark" title="Breaks ties on {meta.sort.column}">
+ <Icon name={meta.sort.then.desc ? 'chevronDown' : 'chevronUp'} size={10} />
+ </span>
+ {/if}
+ </button>
+ {/if}
+ <!-- The heading's two visible doors. The funnel stays lit whether or not the
+ heading is hovered: hiding the one gesture made a hundred times a day
+ behind a hover is how an analyst concludes a grid cannot filter. -->
+ {#if String(column.name).toLowerCase() !== ID_COLUMN}
+ <button class="heading-filter" class:asking={isFilterActive(filters[column.name])}
+ bind:this={funnels[column.name]}
+ title={isFilterActive(filters[column.name])
+ ? `Filtered: ${filterSummary(filters[column.name])}`
+ : `Filter ${column.name}`}
+ aria-label="Filter {column.name}"
+ aria-expanded={filterAt?.index === column.index}
+ onclick={(event) => openFilter(event, column)}>
+ <Icon name="filter" size={12} />
+ </button>
+ {/if}
+ <!-- What this used to open was the setup panel: 340px of grid, for a role and
+ a note that are declared once. What an analyst wants from a heading all
+ day — insert one beside it, copy it, rename it, split it — had no door at
+ all. So it opens the short list, and that list's last row is the panel. -->
+ <button class="heading-menu" title="Column menu"
+ aria-label="What to do with {column.name}"
+ aria-expanded={headMenu?.index === column.index}
+ onclick={(event) => openHeadMenu(event, column)}>
+ <Icon name="more" size={15} stroke={2.6} />
+ </button>
+ <button class="resize" aria-label="Resize {column.name}"
+ onpointerdown={(event) => startResize(event, column.name)}></button>
+ </div>
+ {/each}
+ <button class="cell add-column" title="Add a column" onclick={appendColumn}>
+ <Icon name="plus" size={13} />
+ </button>
+ </div>
+
+ <!-- One row, written once and drawn twice: down the virtualised list, and again
+ pinned under the heading. A second copy of a hundred lines of cell reading is
+ two grids that disagree by the next change, so it is a snippet. -->
+ <!-- `copy` is the pinned drawing of a row that is also down the list. It carries no
+ cell ids, because two elements answering to one id is a grid whose cursor a
+ screen reader reads twice. -->
+ {#snippet bodyRow(rowIndex, number, copy = false)}
+ {@const key = rowKey(table.columns, table.rows[rowIndex])}
+ <div class="row c-{meta.colours?.[key] ?? 'none'}" class:ticked={picked.has(key)}
+ role="row" style="grid-template-columns: {template}; height: {rowH}px">
+ <!-- The number, and the tick box in its place on hover or once anything is
+ ticked. A gutter that only ever held a checkbox left the analyst with no
+ way to say which row they mean out loud, and the key is a handle
+ (`r7a3f…`) rather than a position. -->
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div class="cell gutter" class:ticking={picked.size > 0} data-row={rowIndex}
+ oncontextmenu={(event) => openRowMenu(event, rowIndex)}>
+ <span class="row-number">{number}</span>
+ <input type="checkbox" checked={picked.has(key)} aria-label="Tick this row"
+ onclick={(event) => togglePicked(key, event.shiftKey)} />
+ </div>
+ {#each drawn as column (column.name)}
+ {@const linked = linkOf(rowIndex, column.name)}
+ {@const sticky = offsets[column.name]}
+ {@const links = urlsIn(table.rows[rowIndex][column.index])}
+ <!-- Read once and held, rather than once to choose the branch and again inside
+ it: at forty rows by fourteen columns, twice is five hundred readings of a
+ role per frame of scrolling. -->
+ {@const chips = chipsFor(rowIndex, column)}
+ {@const unit = unitOf(rowIndex, column)}
+ <!-- The grid owns the keyboard: arrows move the cursor, Enter opens
+ the editor, and typing a character starts one (`onKey`). A
+ handler per cell would be a second, divergent model. -->
+ <!-- svelte-ignore a11y_click_events_have_key_events -->
+ <div class="cell"
+ id={copy ? undefined : `sheet-cell-${rowIndex}-${column.index}`}
+ class:cursor={cursor.row === rowIndex && cursor.column === column.index}
+ class:picked={hasRange && selectedRows.has(rowIndex) && selectedColumns.has(column.index)}
+ class:sticky={sticky !== undefined}
+ class:key-cell={String(column.name).toLowerCase() === ID_COLUMN}
+ style={sticky !== undefined ? `left: ${sticky}px` : ''}
+ role="gridcell" tabindex="-1"
+ data-row={rowIndex} data-column={column.index}
+ onpointerdown={(event) => startCellDrag(event, rowIndex, column.index)}
+ onpointerenter={() => overCell(rowIndex, column.index)}
+ oncontextmenu={(event) => openCellMenu(event, rowIndex, column)}
+ ondblclick={() => edit(rowIndex, column.index)}>
+ {#if editing && editing.row === rowIndex && editing.column === column.index}
+ <!-- Read and written by hand rather than bound: committing
+ clears `editing`, and a two-way binding writes back into
+ it on the way out. -->
+ <SheetCellEditor
+ value={editing.value}
+ role={roles[column.name]}
+ {column} {table}
+ oninput={(next) => (editing = { ...editing, value: next })}
+ onaddvalue={(word) => addValue(column.name, word)}
+ oncommit={() => commitEdit()} />
+ {:else}
+ {#if linked}
+ {@const moved = editedSincePromotion(rowIndex, column)}
+ <button class="link-mark" class:moved
+ title={moved ? 'Edited since the case took it' : 'Open this entity'}
+ aria-label="Open the linked entity"
+ onclick={(event) => { event.stopPropagation(); detailsId = linked; }}>
+ <Icon name={moved ? 'alert' : 'link'} size={11} />
+ </button>
+ {/if}
+ {#if ticked(column)}
+ <!-- A yes/no column drawn as a box, and read the way a box is read:
+ ticked is yes, an empty box is no. The file still holds the two
+ words — a tick is how the cell is *drawn*, not what it is — and
+ the box has a third state because it is drawn on an empty cell
+ too: no answer yet is not the same as no, so it is the same
+ empty box gone faint. -->
+ {@const held = tickState(roles[column.name], table.rows[rowIndex][column.index])}
+ <button class="cell-tick" data-state={held}
+ title="{roles[column.name].values?.[0]} / {roles[column.name].values?.[1]}"
+ aria-label="{column.name}: {held === 'blank' ? 'not answered' : table.rows[rowIndex][column.index]}"
+ onclick={(event) => { event.stopPropagation(); flipCell(rowIndex, column.index); }}>
+ {#if held === 'yes'}<Icon name="check" size={11} stroke={3} />{/if}
+ </button>
+ {#if held === 'other'}
+ <span class="value">{table.rows[rowIndex][column.index]}</span>
+ {/if}
+ {:else if chips}
+ <span class="value chips">
+ <!-- Keyed on the position, not the value: a cell may hold the same
+ word twice, and a cell is drawn as what it says. -->
+ {#each chips as chip, at (at)}
+ <button class="cell-chip c-{chip.colour ?? 'none'}"
+ class:unknown={!chip.known} class:tinted={chip.colour}
+ title={chip.known ? chip.value : `${chip.value}, outside this column's words`}
+ onclick={(event) => { event.stopPropagation(); onChipClick(rowIndex, column, chip); }}>
+ {#if chip.count > 1}<b>{chip.count}×</b>{/if}{chip.value}
+ </button>
+ {/each}
+ </span>
+ {:else if roles[column.name]?.kind === 'latlon'}
+ {@const point = parseLatLon(table.rows[rowIndex][column.index])}
+ <span class="value">{table.rows[rowIndex][column.index]}</span>
+ {#if point?.outOfBounds}
+ <span class="badge bad" title="Outside the globe">!</span>
+ {:else if !point && table.rows[rowIndex][column.index]}
+ <span class="badge bad" title="Not read as a point">?</span>
+ {:else if point && point.decimals <= 2}
+ <span class="badge" title="About {precisionMetres(point.decimals)} m at {point.decimals} decimals">
+ ±{precisionMetres(point.decimals)}m
+ </span>
+ {/if}
+ {#if point && !point.outOfBounds}
+ <!-- The column's handoff, from the row being read. A worklist is
+ worked row by row, and walking up to the heading to send the
+ whole column over is not what "where is this one" asks. -->
+ <button class="cell-map" title="Show on the map"
+ aria-label="Show this point on the map"
+ onclick={(event) => { event.stopPropagation(); cellToMap(rowIndex, column.index); }}>
+ <Icon name="satellite" size={11} />
+ </button>
+ {/if}
+ {:else if roles[column.name]?.kind === 'picture'}
+ {@const shot = pictureRef(table.rows[rowIndex][column.index])}
+ {@const url = shot?.kind === 'case' ? fileUrl(caseId, shot.value) : shot?.value}
+ <!-- A picture the case holds, or an address. The case's own files are why
+ a frame can be dropped on a row: a geolocation index is worked on the
+ images in the case folder, and only a `case` cell stays on the
+ machine. -->
+ {#if url}
+ <a class="cell-shot" href={url} target="_blank" rel="noreferrer noopener"
+ title={shot.value} onclick={(event) => event.stopPropagation()}>
+ <img src={url} alt="" loading="lazy" />
+ </a>
+ <span class="value">
+ {shot.kind === 'case' ? shot.value : linkLabel(shot.value)}
+ </span>
+ {:else}
+ <span class="value">{table.rows[rowIndex][column.index]}</span>
+ {#if table.rows[rowIndex][column.index]}
+ <span class="badge bad" title="Not a case file or an address">?</span>
+ {/if}
+ {/if}
+ {:else if unreadable(rowIndex, column)}
+ <!-- Shown as it is, and marked. The value stays — the file keeps the
+ words — but a number column that quietly skipped this cell would
+ be a total the analyst cannot check. -->
+ <span class="value">{table.rows[rowIndex][column.index]}</span>
+ <span class="badge bad"
+ title="Not read as {ROLE_MARKS[roles[column.name].kind].label.toLowerCase()}">?</span>
+ {:else if links.length}
+ <!-- A URL is worth opening, and worth reading as its host: a
+ hundred and twenty characters of query string in a cell
+ thirty pixels tall says nothing at all. -->
+ <span class="value">
+ {#each links as url, at (at)}
+ <a class="cell-url" href={url} target="_blank" rel="noreferrer noopener"
+ title={url} onclick={(event) => event.stopPropagation()}>
+ {linkLabel(url)}
+ </a>
+ {/each}
+ </span>
+ {:else if unit}
+ <!-- The unit after the number, when the column asked for it there.
+ Beside the value and not in it: the cell holds the digits the
+ file holds, and what is copied out of the grid is the file. -->
+ <span class="value">{table.rows[rowIndex][column.index]}</span>
+ <span class="cell-unit">{unit}</span>
+ {:else if query.trim()}
+ <!-- Marked, because a grid that narrows to 23 rows out of 1 204 and
+ leaves the analyst to find the word in each of them has done half
+ the job — often in a column that is off screen. -->
+ <span class="value" class:linked>
+ {#each highlightParts(table.rows[rowIndex][column.index], query) as part, piece (piece)}
+ {#if part.hit}<mark>{part.text}</mark>{:else}{part.text}{/if}
+ {/each}
+ </span>
+ {:else}
+ <span class="value" class:linked>{table.rows[rowIndex][column.index]}</span>
+ {/if}
+ {#if String(column.name).toLowerCase() === ID_COLUMN}
+ <button class="cell-open" title="Open this row"
+ aria-label="Open this row field by field"
+ onclick={(event) => { event.stopPropagation(); showRow(rowIndex); }}>
+ <Icon name="panelRight" size={11} />
+ </button>
+ {:else if linkable(column.name) || linked}
+ <!-- Not on every column: a yes/no cell, a date, a number and a value
+ out of a vocabulary are not things the case holds an entity for,
+ and an `@` on them read as an offer to point a status at a
+ person. A cell that already carries a link keeps it either way. -->
+ <button class="cell-link" title={linked ? 'Change the link' : 'Link to an entity'}
+ aria-label="Point this cell at an entity"
+ onclick={(event) => { event.stopPropagation(); openLinkPicker(rowIndex, column.index); }}>@</button>
+ {/if}
+ {/if}
+ </div>
+ {/each}
+ </div>
+ {/snippet}
+
+ <!-- The row the others are read against — the confirmed case, the sample that sets
+ the standard — kept under the heading instead of scrolling away at the moment it
+ is being compared to. Drawn only while the filter leaves it: a reference the
+ count says is not on screen would be the grid disagreeing with itself. -->
+ {#if pinnedAt !== -1}
+ <div class="pinned" role="presentation" style="top: {HEAD_H}px; height: {rowH}px">
+ {@render bodyRow(pinnedAt, matching.indexOf(pinnedAt) + 1, true)}
+ </div>
+ {/if}
+
+ <!-- One row taller than the sheet, because the last line is a ghost. -->
+ <!-- The three wrappers hold the virtual list up and say nothing: without
+ `presentation` they sit between the grid and its rows in the accessibility tree,
+ which is a grid a screen reader reads as having no rows at all. -->
+ <div class="body" role="presentation" style="height: {(shown.length + 1) * rowH}px">
+ <div class="rows" role="presentation" style="transform: translateY({first * rowH}px)">
+ {#each window_ as rowIndex, at (rowKey(table.columns, table.rows[rowIndex]))}
+ {@render bodyRow(rowIndex, first + at + 1)}
+ {/each}
+ </div>
+ <!-- The empty line every spreadsheet ends on: click it or type in it and the row
+ exists. Adding a row used to be a trip to a button in the footer, for the most
+ ordinary thing a grid does. -->
+ <div class="rows ghost" role="presentation"
+ style="transform: translateY({shown.length * rowH}px)">
+ <div class="row" role="row" style="grid-template-columns: {template}; height: {rowH}px">
+ <div class="cell gutter"><Icon name="plus" size={12} /></div>
+ {#each drawn as column (column.name)}
+ {@const sticky = offsets[column.name]}
+ <button class="cell ghost-cell" class:sticky={sticky !== undefined}
+ style={sticky !== undefined ? `left: ${sticky}px` : ''}
+ aria-label="Add a row and write in {column.name}"
+ onclick={() => startGhost(column.index)}></button>
+ {/each}
+ </div>
+ </div>
+ </div>
+
+ </div>
+
+ <!-- What can be done to the rows that are chosen, over the grid rather than above it.
+ In the question bar these ten controls doubled its width, so ticking a row wrapped
+ the bar onto a second line and pushed the table down a row height — under the
+ pointer that had just done the ticking. Here nothing moves: the bar is drawn on top
+ of the last rows, the way it is wherever a table has a selection. -->
+ {#if batchKeys.length}
+ <div class="selection" role="toolbar" aria-label="What to do with the chosen rows">
+ <!-- One selection, said out loud. Ticking wins where both exist, and the word says
+ which of the two these rows came from. -->
+ <span class="count">{batchKeys.length} {picked.size ? 'ticked' : 'selected'}</span>
+ <div class="selection-rule"></div>
+ <button class="btn btn-ghost btn-sm" class:active={Boolean(filling)}
+ onclick={() => (filling = filling ? null : { column: firstFillable() })}>
+ <Icon name="edit" size={13} /> Fill a column
+ </button>
+ <!-- One road into the case, where there were four. Each column says what it is —
+ a subject, a set of words, a point, addresses, an hour, a name of other rows —
+ and the vocabulary says what may join them. -->
+ <button class="btn btn-ghost btn-sm" onclick={() => (promoteOpen = true)}>
+ <Icon name="graph" size={13} /> To the case
+ </button>
+ <!-- The one road that fetches bytes, so it is a button of its own and only on a
+ sheet that can feed it: two columns of addresses and one of coordinates. -->
+ {#if buildable}
+ <button class="btn btn-ghost btn-sm" title="Download what these rows point at and compose the proofs"
+ onclick={() => (buildOpen = true)}>
+ <Icon name="download" size={13} /> Build proofs
+ </button>
+ {/if}
+ <!-- Up a floor. An inbox, a worklist and a reference table at one schema is what a
+ binder is, and copying a row across by hand loses its colour and its links. -->
+ <button class="btn btn-ghost btn-sm" onclick={() => (moving = true)}>
+ <Icon name="arrowRight" size={13} /> Move
+ </button>
+ <!-- The handoffs, on the rows that were chosen. A column's own buttons send
+ everything on screen, which is the wrong question for an analyst who has just
+ ticked eleven candidates out of four hundred. Named like the rest of the bar:
+ two lone glyphs among six labels read as a different kind of control. -->
+ <button class="btn btn-ghost btn-sm" title="Show these rows on the map"
+ onclick={batchToMap}>
+ <Icon name="satellite" size={13} /> Map
+ </button>
+ <button class="btn btn-ghost btn-sm" title="Show these rows on the Timeline"
+ onclick={batchToTimeline}>
+ <Icon name="clock" size={13} /> Timeline
+ </button>
+ <div class="swatches">
+ {#each ROW_COLOURS as colour (colour)}
+ <button class="swatch c-{colour}" title="Paint these rows {colour}"
+ aria-label="Paint these rows {colour}" onclick={() => paint(colour)}></button>
+ {/each}
+ <button class="swatch none" title="Clear the colour" aria-label="Clear the colour"
+ onclick={() => paint(null)}></button>
+ </div>
+ <button class="btn btn-sm btn-danger" onclick={askDeleteBatch}>
+ <Icon name="trash" size={12} /> Delete
+ </button>
+ <div class="selection-rule"></div>
+ <!-- Escape does this too, and Escape is not on the screen. -->
+ <button class="btn btn-ghost btn-sm" title="Drop the selection"
+ aria-label="Drop the selection" onclick={dropSelection}>
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {/if}
+
+ <!-- The grid draws its own bars: the app's chrome is thin everywhere, and on
+ Linux the native ones are overlays that fade. Here they are the control. -->
+ {#if vThumb}
+ <div class="bar vertical" class:held={dragging === 'y'} role="presentation"
+ onpointerdown={(event) => pageBy(event, 'y')}>
+ <div class="thumb" role="scrollbar" tabindex="-1" aria-label="Scroll the rows"
+ aria-controls="sheet-grid" aria-orientation="vertical"
+ aria-valuenow={Math.round((extent.top / Math.max(1, vThumb.maxScroll)) * 100)}
+ style="top: {vThumb.position}px; height: {vThumb.size}px"
+ onpointerdown={(event) => grabThumb(event, 'y')}></div>
+ </div>
+ {/if}
+ {#if hThumb}
+ <div class="bar horizontal" class:held={dragging === 'x'} role="presentation"
+ onpointerdown={(event) => pageBy(event, 'x')}>
+ <div class="thumb" role="scrollbar" tabindex="-1" aria-label="Scroll the columns"
+ aria-controls="sheet-grid" aria-orientation="horizontal"
+ aria-valuenow={Math.round((extent.left / Math.max(1, hThumb.maxScroll)) * 100)}
+ style="left: {hThumb.position}px; width: {hThumb.size}px"
+ onpointerdown={(event) => grabThumb(event, 'x')}></div>
+ </div>
+ {/if}
+
+ <div class="foot">
+ <span class="foot-note">{table.columns.length} columns</span>
+ {#if hasRange}
+ <span class="foot-note">
+ {range.rows.length} × {range.columns.length} selected
+ </span>
+ {/if}
+ <!-- What the colours mean, under the rows they are painted on rather than in one
+ analyst's head. Only the ones the sheet actually uses: a colour nothing carries
+ is not worth naming, and the count is what says so. -->
+ {#each legendUsed as entry (entry.colour)}
+ <button class="legend-chip" title="Rename the colours"
+ onclick={() => (legendOpen = true)}>
+ <span class="swatch c-{entry.colour}"></span>
+ {entry.label || 'unnamed'}
+ </button>
+ {/each}
+ <div class="spacer"></div>
+ <!-- How far along the work is, off whichever column carries it. `23 of 969`
+ answers a question nobody asked; the real one is how many are left. -->
+ <!-- One answer per number column, the one the column was told to give. `Count 20
+ over 2 8–12` was four numbers in a strip nobody could parse, and the reading
+ that mattered — that it had only read two cells of fifteen — was the smallest
+ of them. Now the answer is chosen and the cells it could not read are a
+ button that shows them. -->
+ {#each numberFooters as total (total.name)}
+ <span class="progress">
+ <span class="progress-key">{total.name}</span>
+ <!-- Which reading this is, in the strip itself. A bare `52 km over 3` was a
+ number whose meaning lived in a panel two clicks away, and a total and an
+ average look identical from the footer. -->
+ {#if total.summary === 'count'}
+ <strong>{total.count}</strong><span>read</span>
+ {:else if total.summary === 'mean'}
+ <span>average</span>
+ <strong>{spellNumber(total.mean, total.unit)}</strong>
+ <span>over {total.count}</span>
+ {:else if total.summary === 'range'}
+ <span>from</span>
+ <strong>{spellNumber(total.min, total.unit)}</strong>
+ <span>to</span>
+ <strong>{spellNumber(total.max, total.unit)}</strong>
+ {:else}
+ <span>total</span>
+ <strong>{spellNumber(total.sum, total.unit)}</strong>
+ <span>over {total.count}</span>
+ {/if}
+ {#if total.unreadable}
+ <button class="progress-left"
+ title="Cells that are not numbers"
+ onclick={() => ask(toggleFilterFill(filters, total.name, 'unreadable'))}>
+ {total.unreadable} to check
+ </button>
+ {/if}
+ </span>
+ {/each}
+ {#if progress}
+ <span class="progress">
+ <span class="progress-key">{meta.progress}</span>
+ {#if progress.kind === 'fill'}
+ <strong>{progress.filled}</strong> filled ·
+ <button class="progress-left" onclick={() => ask(toggleFilterFill(filters, meta.progress, 'blank'))}>
+ {progress.empty} left
+ </button>
+ {:else}
+ {#each progress.buckets.filter((bucket) => bucket.count) as bucket (bucket.value)}
+ <span><strong>{bucket.count}</strong> {bucket.value}</span>
+ {/each}
+ {#if progress.other}<span>{progress.other} other</span>{/if}
+ {#if progress.empty}
+ <button class="progress-left" onclick={() => ask(toggleFilterFill(filters, meta.progress, 'blank'))}>
+ {progress.empty} empty
+ </button>
+ {/if}
+ {/if}
+ </span>
+ {:else if suggestedProgress}
+ <button class="suggest-progress" onclick={() => setProgress(suggestedProgress)}>
+ <Icon name="chart" size={12} /> Count progress on “{suggestedProgress}”
+ </button>
+ {/if}
+ </div>
+ </div>
+
+ <!-- One slot on the right, and the two panels take turns in it: you are either reading
+ a row across its fields or working on a column down the rows. Opening one puts the
+ other away (`showColumn` / `showRow`), so the slot never has two claims on it —
+ and the column panel stays open as the next heading is clicked, which is what
+ makes declaring six roles six clicks rather than six trips. -->
+ {#if columnPanel !== null && table.columns[columnPanel] !== undefined}
+ {@const column = { name: table.columns[columnPanel], index: columnPanel }}
+ <SheetColumnPanel
+ {table} {meta} {column} filter={filters[column.name]}
+ onrename={(name) => applyRename(column.index, name)}
+ onfreeze={freezeColumn}
+ onclearfilter={() => ask(clearFilter(filters, column.name))}
+ onrole={(role) => setRole(column.name, role)}
+ onnote={(text) => setNote(column.name, text)}
+ onprogress={setProgress}
+ onmap={toMap}
+ ontimeline={toTimeline}
+ onnormalise={normalise}
+ onduplicates={showDuplicates}
+ onnearby={showNearby}
+ onvalue={(value) => ask(onlyFilterValue(filters, column.name, value))}
+ ongeocode={(mode) => (geocoding = { index: column.index, mode })}
+ oncheck={checkColumnLinks}
+ onanchors={() => { columnPanel = null; anchorsOpen = true; }}
+ onclose={() => (columnPanel = null)} />
+ {:else if rowPanel !== null && table.rows[rowPanel]}
+ <SheetRowPanel {table} rowIndex={rowPanel} {linkOf} {roles}
+ rowKey={rowKey(table.columns, table.rows[rowPanel])}
+ attached={rowPieces}
+ pointedBy={rowPointedBy}
+ changes={rowLog.get(rowKey(table.columns, table.rows[rowPanel])) ?? []}
+ onedit={(row, column, value) => {
+ const before = table.rows[row]?.[column];
+ if (before !== value) editCells([{ row, column, before, after: value }]);
+ }}
+ onlink={openLinkPicker}
+ onattach={(key) => (attaching = key)}
+ ondetach={(id) =>
+ detachPiece(rowKey(table.columns, table.rows[rowPanel]), id)}
+ onfindmedia={findRowMedia}
+ onopenentity={(id) => (detailsId = id)}
+ onstep={stepPanel}
+ onclose={() => (rowPanel = null)} />
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<!-- Both menus are drawn out here, outside the scroller: inside it, `overflow: auto`
+ clips them and the grid's own scrollbars grow to account for a menu. -->
+{#if filterAt !== null && table.columns[filterAt.index] !== undefined}
+ {@const name = table.columns[filterAt.index]}
+ <div bind:this={filterMenu}>
+ <SheetFilterMenu
+ {table} column={{ name, index: filterAt.index }} role={roles[name]}
+ filter={filters[name]} at={filterAt}
+ onvalue={(value) => toggleValue(name, value)}
+ onfill={(fill) => ask(toggleFilterFill(filters, name, fill))}
+ oncontains={(term) => ask(setFilterContains(filters, name, term))}
+ onwithout={(term) => ask(setFilterWithout(filters, name, term))}
+ onrange={(bounds) => ask(setFilterRange(filters, name, bounds))}
+ onclear={() => ask(clearFilter(filters, name))}
+ onclose={() => (filterAt = null)} />
+ </div>
+{/if}
+
+{#if headMenu !== null && table.columns[headMenu.index] !== undefined}
+ <!-- The index is read here and not inside the handlers: every row of the menu closes it
+ before it acts — a menu left open over the change it made hides it — so a handler
+ reaching back for `headMenu.index` would be reading what it has just cleared. -->
+ {@const at = headMenu?.index ?? -1}
+ {@const name = table.columns[at]}
+ <div bind:this={headMenuEl}>
+ <SheetHeadingMenu
+ column={{ name, index: at }} {meta} at={headMenu}
+ onsort={(desc) => sortDirection(name, desc)}
+ onsecondsort={() => secondSort(name)}
+ onfilter={() => filterColumn(name)}
+ oninsert={(side) => addColumnAt(at, side)}
+ onduplicate={() => copyColumn(at)}
+ onrename={() => renameColumnAt(at)}
+ onclean={() => (cleaning = { index: at, mode: 'replace' })}
+ onsplit={() => (cleaning = { index: at, mode: 'split' })}
+ onfreeze={() => freezeColumn(name)}
+ onhide={() => hideColumn(name)}
+ ondrop={() => askDropColumn(at)}
+ onsetup={() => showColumn(at)}
+ onclose={() => (headMenu = null)} />
+ </div>
+{/if}
+
+{#if rowMenu !== null && table.rows[rowMenu.row]}
+ {@const row = rowMenu?.row ?? -1}
+ <div bind:this={rowMenuEl}>
+ <SheetRowMenu
+ at={rowMenu} count={rowMenuCount}
+ pinned={meta.pinned === rowKey(table.columns, table.rows[row])}
+ onread={() => showRow(row)}
+ oninsert={(where) => addRowAt(row, where)}
+ onduplicate={() => duplicateBatch(row)}
+ onpaint={(colour) => paintRows(row, colour)}
+ onpin={() => pinRow(row)}
+ onmerge={() => mergeBatch(row)}
+ ondelete={() => askDeleteRows(row)}
+ onclose={() => (rowMenu = null)} />
+ </div>
+{/if}
+
+{#if cellMenu}
+ {@const values = menuValues(cellMenu)}
+ <div class="cell-menu" bind:this={cellMenuEl} role="menu"
+ style="left: {cellMenu.x}px; top: {cellMenu.y}px">
+ <p class="cell-menu-head">{cellMenu.column}</p>
+ {#if values.length}
+ {#each values as value (value)}
+ <button class="menu-row" role="menuitem"
+ onclick={() => { ask(onlyFilterValue(filters, cellMenu.column, value)); cellMenu = null; }}>
+ <Icon name="filter" size={12} /><span>Only “{value}”</span>
+ </button>
+ {/each}
+ {#if isFilterActive(filters[cellMenu.column])}
+ {#each values as value (value)}
+ <button class="menu-row" role="menuitem"
+ onclick={() => { ask(toggleFilterValue(filters, cellMenu.column, value)); cellMenu = null; }}>
+ <Icon name="plus" size={12} /><span>Also “{value}”</span>
+ </button>
+ {/each}
+ {/if}
+ {:else}
+ <button class="menu-row" role="menuitem"
+ onclick={() => { ask(toggleFilterFill(filters, cellMenu.column, 'blank')); cellMenu = null; }}>
+ <Icon name="filter" size={12} /><span>Only the empty ones</span>
+ </button>
+ {/if}
+ {#if isFilterActive(filters[cellMenu.column])}
+ <button class="menu-row" role="menuitem"
+ onclick={() => { ask(clearFilter(filters, cellMenu.column)); cellMenu = null; }}>
+ <Icon name="x" size={12} /><span>Clear this filter</span>
+ </button>
+ {/if}
+ {#if cellMenu.value}
+ <div class="menu-rule"></div>
+ <!-- The shape every "to be sorted" inbox arrives in: one row holding five links, or a
+ cell reading `Buk-M2E, ZU23-2, S-300` in a worklist that wants a line each. -->
+ <button class="menu-row" role="menuitem"
+ onclick={() => { const at = cellMenu; cellMenu = null; explodeCell(at.row, at.index); }}>
+ <Icon name="stack" size={12} /><span>Split into rows</span>
+ </button>
+ {/if}
+ <button class="menu-row" role="menuitem"
+ onclick={() => { const column = cellMenu.column; cellMenu = null; filterColumn(column); }}>
+ <Icon name="sliders" size={12} /><span>Filter this column…</span>
+ </button>
+ </div>
+{/if}
+
+{#if creating}
+ <Modal title={creating.text === undefined ? 'New sheet' : 'A table as a new sheet'}
+ onclose={() => (creating = null)} width="520px">
+ <label class="label" for="sheet-title">Name</label>
+ <!-- svelte-ignore a11y_autofocus -->
+ <input id="sheet-title" class="input" autofocus bind:value={creating.title}
+ placeholder="Candidates"
+ onkeydown={(event) => event.key === 'Enter' && creating.text === undefined && create()} />
+ {#if creating.text === undefined}
+ <!-- Columns and what the app should know about them. The four tables an analyst
+ rebuilds by hand every case, each one slightly different — which is why two of
+ their sheets never compare. Renamed and dropped like any others afterwards. -->
+ <p class="label">Start from</p>
+ <div class="templates">
+ {#each SHEET_TEMPLATES as entry (entry.id)}
+ <button class="template" class:on={(creating.template ?? 'blank') === entry.id}
+ onclick={() => (creating = { ...creating, template: entry.id })}>
+ <strong>{entry.label}</strong>
+ <small>{entry.hint}</small>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ {#if creating.text !== undefined}
+ <label class="label" for="sheet-text">The table</label>
+ <textarea id="sheet-text" class="input paste-box" rows="8" bind:value={creating.text}
+ placeholder="Paste rows here, or drop a CSV on the grid"></textarea>
+ <p class="hint">The delimiter is guessed, and every row is keyed on import.</p>
+ {/if}
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={() => (creating = null)}>Cancel</button>
+ <button class="btn btn-primary"
+ disabled={!creating.title.trim() || (creating.text !== undefined && !creating.text.trim())}
+ onclick={create}>
+ {creating.text === undefined ? 'Create' : 'Import'}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+{#if geocoding !== null && table.columns[geocoding.index] !== undefined}
+ {@const column = { name: table.columns[geocoding.index], index: geocoding.index }}
+ <Modal
+ title={geocoding.mode === 'forward'
+ ? `Read “${column.name}” into coordinates`
+ : `Read “${column.name}” into place names`}
+ onclose={() => (geocoding = null)} width="720px">
+ <SheetGeocode
+ {caseId} sheetId={openId} {table} {meta} {column} mode={geocoding.mode} rows={shown}
+ writable={table.columns
+ .map((name, index) => ({ name, index }))
+ .filter((entry) => writable(entry.name))}
+ onedits={(edits, said) => { geocoding = null; cleanCells(edits, said); }}
+ onclose={() => (geocoding = null)} />
+ </Modal>
+{/if}
+
+{#if appending}
+ <Modal title="Add rows to this sheet" onclose={() => (appending = false)} width="720px">
+ <SheetAppend {caseId} {table} onappend={appendBatch} onclose={() => (appending = false)} />
+ </Modal>
+{/if}
+
+{#if helpOpen}
+ <Modal title="Keys and gestures" onclose={() => (helpOpen = false)} width="760px">
+ <SheetHelp onclose={() => (helpOpen = false)} />
+ </Modal>
+{/if}
+
+{#if destPicker}
+ <ExportFolderPicker kind="sheets" current={destination ?? ''}
+ onclose={() => (destPicker = false)}
+ onchosen={(path) => (destination = path)} />
+{/if}
+
+{#if cleaning !== null && table.columns[cleaning.index] !== undefined}
+ {@const column = { name: table.columns[cleaning.index], index: cleaning.index }}
+ <Modal title="Clean up “{column.name}”" onclose={() => (cleaning = null)} width="760px">
+ <SheetClean
+ {table} {meta} {column} mode={cleaning.mode}
+ writable={table.columns
+ .map((name, index) => ({ name, index }))
+ .filter((entry) => writable(entry.name))}
+ rows={shown}
+ onedits={cleanCells}
+ ontable={cleanTable}
+ onclose={() => (cleaning = null)} />
+ </Modal>
+{/if}
+
+{#if fromCase}
+ <Modal title="A sheet out of this case" onclose={() => (fromCase = false)} width="560px">
+ <SheetFromCase {caseId} busy={building} onmake={buildFromCase}
+ onclose={() => (fromCase = false)} />
+ </Modal>
+{/if}
+
+{#if promoteOpen}
+ <Modal title="Send these rows to the case" onclose={() => (promoteOpen = false)} width="700px">
+ <!-- The word the selection bar uses, carried across: forty rows that turn out to be the
+ wrong forty is the one thing this must not do, and "ticked" over a drag is that. -->
+ <!-- The sync points open *over* this rather than instead of it: the declaration on
+ screen is what sent the analyst there, and an undated shot is the only thing
+ standing between its offsets and real hours. -->
+ <SheetToCase {table} {meta} count={batchKeys.length} scope={picked.size ? 'ticked' : 'selected'}
+ busy={promoting} onpreview={previewPass} onpass={sendToCase}
+ onanchors={() => (anchorsOpen = true)}
+ onclose={() => (promoteOpen = false)} />
+ </Modal>
+{/if}
+
+{#if buildOpen}
+ <!-- Closing does not abandon the press. The downloads are already happening and what
+ they produce still has to reach the sidecar, so the watcher runs on and the screen
+ reopens onto the same progress. -->
+ <Modal title="Build proofs from these rows" width="700px"
+ onclose={() => { buildOpen = false; buildReport = null; }}>
+ <SheetBuildProofs {table} {meta} count={batchKeys.length}
+ scope={picked.size ? 'ticked' : 'selected'}
+ busy={Boolean(buildJob)} progress={buildJob?.progress ?? null}
+ report={buildReport}
+ onpreview={previewBuild} onbuild={startBuild} oncancel={stopBuild}
+ onclose={() => { buildOpen = false; buildReport = null; }} />
+ </Modal>
+{/if}
+
+{#if moving}
+ <Modal title="Move these rows" onclose={() => (moving = false)} width="520px">
+ <!-- The word the selection bar uses, carried across: the lot is whatever the grid was
+ holding, and "ticked" over a drag would be the dialog lying about which. -->
+ <SheetMove {sheets} sheetId={openId} columns={table.columns} rows={batchRows}
+ scope={picked.size ? 'ticked' : 'selected'}
+ busy={promoting} onmove={moveRows} onclose={() => (moving = false)} />
+ </Modal>
+{/if}
+
+{#if anchorsOpen}
+ <Modal title="Sync points" onclose={() => (anchorsOpen = false)} width="560px">
+ <SheetAnchors {table} {meta} onchange={setAnchors} onclose={() => (anchorsOpen = false)} />
+ </Modal>
+{/if}
+
+{#if attaching}
+ <Modal title="Attach a case file to this row" onclose={() => (attaching = null)} width="580px">
+ <SheetEntityPicker
+ {caseId}
+ cellText=""
+ current={null}
+ onpick={(entity) => attachPiece(attaching, entity)}
+ onclose={() => (attaching = null)} />
+ </Modal>
+{/if}
+
+{#if linking}
+ <Modal title="Point this cell at an entity" onclose={() => (linking = null)} width="580px">
+ <SheetEntityPicker
+ {caseId}
+ cellText={table.rows[linking.row]?.[linking.column] ?? ''}
+ current={linkOf(linking.row, table.columns[linking.column])}
+ onpick={attach}
+ onclear={() => detach(linking.row, linking.column)}
+ onclose={() => (linking = null)} />
+ </Modal>
+{/if}
+
+{#if confirming?.kind === 'sheet'}
+ <ConfirmDialog
+ title="Delete this sheet"
+ message="The CSV and everything the grid remembers about it go to the trash."
+ confirmLabel="Delete"
+ onconfirm={remove}
+ oncancel={() => (confirming = null)} />
+{:else if confirming?.kind === 'column'}
+ <!-- What a heading does not show is what the ask is for: the cells go, and so does
+ the role, the note and the width, none of which is written in the file. -->
+ <ConfirmDialog
+ title="Delete “{confirming.name}”"
+ message={confirming.filled
+ ? `${confirming.filled} ${confirming.filled === 1 ? 'cell has' : 'cells have'} a value.`
+ : 'This column is empty.'}
+ detail={confirming.role
+ ? 'Its type, its words and its note go with it.'
+ : ''}
+ confirmLabel="Delete the column"
+ restorable="Undo puts it back until the sheet is closed."
+ onconfirm={() => dropColumn(confirming.index)}
+ oncancel={() => (confirming = null)} />
+{:else if confirming?.kind === 'reload'}
+ <!-- The press that reads as "go back to normal" and is the one that costs the analyst
+ their afternoon: it is their own unsaved edits that go, not the file's. -->
+ <ConfirmDialog
+ title="Read the file and lose your edits"
+ message="This grid is holding changes that were never written. Reading the file replaces them with what is on disk."
+ detail="Undo cannot bring them back afterwards."
+ confirmLabel="Reload"
+ onconfirm={() => { confirming = null; reload(); }}
+ oncancel={() => (confirming = null)} />
+{:else if confirming?.kind === 'overwrite'}
+ <ConfirmDialog
+ title="Write over the file"
+ message="What is on disk was changed outside this grid. Saving replaces it with what is on screen."
+ detail="Whoever made those changes loses them."
+ confirmLabel="Overwrite"
+ onconfirm={() => { confirming = null; save({ force: true }); }}
+ oncancel={() => (confirming = null)} />
+{:else if confirming?.kind === 'rows'}
+ <ConfirmDialog
+ title="Delete {confirming.count} {confirming.count === 1 ? 'row' : 'rows'}"
+ message="They leave the file, with their colours and their links."
+ confirmLabel="Delete"
+ restorable="Undo puts them back until the sheet is closed."
+ onconfirm={deleteBatch}
+ oncancel={() => (confirming = null)} />
+{/if}
+
+{#if detailsId}
+ <!-- EntityDetails is panel content, not a dialog: it draws no chrome of its own, so
+ hosting it bare rendered it into nowhere. Board and Timeline both wrap it. -->
+ <Modal title="Details" onclose={closeDetails} width="640px">
+ <EntityDetails
+ entityId={detailsId}
+ bind:dirty={detailsDirty}
+ onclose={() => (detailsId = null)}
+ ondeleted={() => { detailsId = null; save(); }} />
+ </Modal>
+{/if}
+
+{#if discarding}
+ <ConfirmDialog
+ title="Close without saving?"
+ message="This entity has unsaved edits."
+ confirmLabel="Discard them"
+ onconfirm={() => { discarding = false; detailsDirty = false; detailsId = null; }}
+ oncancel={() => (discarding = false)} />
+{/if}
+
+<style>
+ .tool { display: flex; flex-direction: column; height: 100%; min-height: 0; }
+ .spacer { flex: 1; }
+ /* Held at a width, because the four words it cycles through are four lengths: without
+ it the whole row of buttons stepped sideways on every save. */
+ .save-state {
+ flex: none; min-width: 54px; text-align: right;
+ font-size: var(--fs-xs); color: var(--text-3);
+ }
+ .save-state.failed { color: var(--danger); }
+ .save-state.saved { color: var(--ok); }
+
+ /* -- popovers ------------------------------------------------------------ */
+ /* Each one hangs off a wrapper that also holds its trigger. That is what lets a
+ pointer landing outside close it while a pointer on the trigger stays a plain
+ toggle — closing on the press and reopening on the click leaves it open. */
+ .anchor { position: relative; display: flex; }
+ /* A column, so only the list scrolls: the search stays reachable at the top and the
+ two actions stay reachable at the bottom however long the list gets. */
+ .sheet-menu {
+ position: absolute; z-index: 8; top: calc(100% + 4px); left: 0; width: 320px;
+ max-height: min(420px, calc(100vh - 140px));
+ display: flex; flex-direction: column; overflow: hidden;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0004;
+ }
+ .sheet-search-row { padding: 6px 6px 2px; }
+ .sheet-search-row .input { width: 100%; }
+ .sheet-list { flex: 1; min-height: 0; overflow: auto; padding: 6px; }
+ .sheet-foot { padding: 5px 6px; border-top: 1px solid var(--border); }
+ .sheet-row {
+ display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center;
+ gap: 8px; width: 100%; padding: 7px; border-radius: var(--r-sm);
+ color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .sheet-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .sheet-row.active { color: var(--accent); }
+ .sheet-row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .sheet-row small { color: var(--text-3); font-size: var(--fs-xs); }
+
+ /* -- empty state --------------------------------------------------------- */
+ .empty {
+ flex: 1; display: flex; flex-direction: column; align-items: center;
+ justify-content: center; gap: 8px; color: var(--text-3);
+ }
+ .empty p { color: var(--text-2); font-size: var(--fs-md); }
+ .empty small { font-size: var(--fs-sm); }
+ /* What the grid is for, in the state that has nothing to show. A list without
+ bullets: three short lines read as three answers, and the browser's own discs
+ and indent read as prose in a panel that is centred. */
+ .empty-what {
+ display: flex; flex-direction: column; gap: 3px;
+ margin: 4px 0 2px; padding: 0; list-style: none; text-align: center;
+ color: var(--text-3); font-size: var(--fs-sm);
+ }
+ .row-actions { display: flex; gap: 8px; margin-top: 6px; }
+
+ /* -- the question bar ---------------------------------------------------- */
+ .question {
+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
+ padding: 7px 16px; border-bottom: 1px solid var(--border);
+ }
+ .search { display: flex; align-items: center; gap: 6px; color: var(--text-3); }
+ .search .input { width: 220px; }
+ .count { font-size: var(--fs-sm); color: var(--text-3); }
+ .count strong { color: var(--text-1); font-weight: 600; }
+ /* The cell under the cursor. Flat against the grid it belongs to — a bar of its own
+ chrome above a grid of chrome is two headers — and as short as one line of text,
+ since it is drawn whether or not anything is being written in it. */
+ .cell-bar {
+ display: flex; align-items: flex-start; gap: 8px;
+ padding: 3px 16px; border-bottom: 1px solid var(--border); background: var(--bg-1);
+ }
+ .cell-bar-where {
+ display: inline-flex; align-items: baseline; gap: 6px; flex: none;
+ min-width: 96px; max-width: 220px; padding-top: 5px;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ font-size: var(--fs-xs); color: var(--text-3);
+ }
+ .cell-bar-where strong {
+ color: var(--text-2); font-weight: 600; font-variant-numeric: tabular-nums;
+ }
+ /* One line tall until the corner is pulled, and it stays where it is pulled to: the
+ value the analyst is reading is the reason they opened it that far. */
+ .cell-bar-box {
+ flex: 1; min-width: 0; height: 26px; min-height: 26px; max-height: 40vh;
+ padding: 3px 8px; resize: vertical; line-height: 1.5;
+ font-family: inherit; white-space: pre-wrap; overflow-y: auto;
+ }
+ .cell-bar-box[readonly] { color: var(--text-3); }
+ /* Nothing picked yet: a line of text at the margin rather than an empty field. A box
+ drawn around nothing, with a grab handle on the far end of it, is furniture. */
+ .cell-bar-box:disabled {
+ background: none; border-color: transparent; resize: none; padding-left: 0;
+ }
+ .chip {
+ display: inline-flex; align-items: center; gap: 6px; padding: 2px 7px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-1); font-size: var(--fs-xs);
+ }
+ .chip:hover { border-color: var(--border-strong); }
+ .chip-key { color: var(--text-3); }
+ .swatches { display: flex; gap: 4px; }
+ .swatch {
+ width: 16px; height: 16px; border-radius: var(--r-sm);
+ border: 1px solid var(--border-strong); background: var(--mark, var(--bg-3));
+ }
+ .swatch.none { background: repeating-linear-gradient(45deg, var(--bg-2) 0 3px, var(--bg-3) 3px 6px); }
+ /* The same answer to a pointer the gutter menu's swatches give: a colour that does
+ not light up under the cursor reads as a legend rather than a button. */
+ .swatch:hover { outline: 2px solid var(--accent); outline-offset: 1px; }
+
+ /* The ways a sheet is started. Same drawer the export uses, because they are the same
+ kind of thing: a short list of rare presses hanging off one button. */
+ .new-menu {
+ position: absolute; right: 0; top: calc(100% + 4px); z-index: 20; width: 240px;
+ display: flex; flex-direction: column; gap: 1px;
+ padding: 5px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ .new-menu label.menu-row { cursor: pointer; }
+
+ .export-menu {
+ position: absolute; right: 0; top: calc(100% + 4px); z-index: 20; width: 260px;
+ display: flex; flex-direction: column; gap: 1px;
+ padding: 5px; border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ .export-menu .menu-row {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .export-menu .menu-row:hover:not(:disabled) { background: var(--bg-2); color: var(--text-1); }
+ .export-menu .menu-row:disabled { color: var(--text-3); }
+ .export-menu .menu-row span {
+ flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .export-menu .menu-note {
+ padding: 6px 7px 3px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.5;
+ }
+ /* Where the file lands, and the way to send it elsewhere. The path is the one thing
+ here that can be arbitrarily long, so it is the part that gives: a folder name that
+ overran pushed Change out of a 260px menu. */
+ .dest {
+ display: flex; align-items: baseline; gap: 6px; padding: 4px 7px;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .dest-path {
+ flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-2); font-family: var(--font-mono);
+ }
+
+ /* One per table an analyst rebuilds by hand every case. */
+ .templates { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px; }
+ .template {
+ display: flex; flex-direction: column; gap: 2px; padding: 7px 9px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); text-align: left;
+ }
+ .template:hover { border-color: var(--border-strong); }
+ .template.on { border-color: var(--accent); background: var(--accent-soft); }
+ .template strong { color: var(--text-1); font-size: var(--fs-sm); font-weight: 500; }
+ .template small { color: var(--text-3); font-size: var(--fs-xs); }
+
+ .fill-bar {
+ display: flex; align-items: center; gap: 8px; padding: 7px 16px;
+ border-bottom: 1px solid var(--border); background: var(--bg-1);
+ }
+ .fill-bar .label { margin: 0; color: var(--text-3); font-size: var(--fs-sm); }
+ .fill-bar input { flex: 1; min-width: 160px; }
+ .fill-columns { display: flex; flex-wrap: wrap; gap: 4px; }
+ .fill-columns .chip.on { border-color: var(--accent); color: var(--accent); }
+ /* Past a dozen columns the chips wrap into three rows and push the box that is about to
+ be typed in off the bar. A binder is exactly that wide. */
+ .fill-pick { flex: none; max-width: 220px; }
+
+ .columns-menu {
+ position: absolute; z-index: 8; top: calc(100% + 4px); right: 0; width: 240px;
+ max-height: min(380px, calc(100vh - 140px)); overflow: auto;
+ display: flex; flex-direction: column; gap: 2px; padding: 6px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0004;
+ }
+ .column-row {
+ display: flex; align-items: center; gap: 7px; padding: 4px 6px;
+ border-radius: var(--r-sm); font-size: var(--fs-sm); color: var(--text-2);
+ }
+ .column-row:hover { background: var(--bg-2); color: var(--text-1); }
+ /* A hidden column is still listed — that is the point of the list — but reads as
+ put away rather than as one of the columns on screen. */
+ .column-row.off .column-name { color: var(--text-3); }
+ .column-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .column-kind { display: flex; color: var(--text-3); }
+ .column-ask { flex: none; display: flex; padding: 3px; border-radius: var(--r-sm); color: var(--text-3); }
+ .column-ask:hover { background: var(--bg-3); color: var(--text-1); }
+ .column-ask.on { color: var(--accent); }
+
+ /* -- a cell's own menu --------------------------------------------------- */
+ /* At the pointer, outside the scroller, and narrow: it asks one question about the
+ value that was right-clicked. */
+ .cell-menu {
+ position: fixed; z-index: 20; min-width: 200px; max-width: 300px;
+ display: flex; flex-direction: column; gap: 1px; padding: 5px;
+ border: 1px solid var(--border-strong); border-radius: var(--r-sm);
+ background: var(--bg-1); box-shadow: 0 12px 30px #0005;
+ }
+ .cell-menu-head {
+ padding: 2px 7px 5px; color: var(--text-3); font-size: var(--fs-xs);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .menu-row {
+ display: flex; align-items: center; gap: 8px; width: 100%; padding: 5px 7px;
+ border-radius: var(--r-sm); color: var(--text-2); text-align: left; font-size: var(--fs-sm);
+ }
+ .menu-row:hover { background: var(--bg-2); color: var(--text-1); }
+ .menu-row span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ /* The line between two kinds of row in a menu. Same rule the heading and gutter menus
+ draw, so a separator means the same thing wherever one is. */
+ .menu-rule { height: 1px; margin: 4px 2px; background: var(--border); }
+
+ .notice {
+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
+ padding: 6px 16px; font-size: var(--fs-sm); color: var(--text-2);
+ background: var(--info-soft); border-bottom: 1px solid var(--border);
+ }
+ .notice.danger { background: var(--danger-soft); color: var(--text-1); }
+
+ /* What this sheet is for, beside its name. Quiet on purpose: it is read once by
+ whoever inherits the case and then it is furniture, so it takes a line and not a
+ band. Bounded, because the header carries seven other controls. */
+ .describe-input { width: 280px; font-size: var(--fs-sm); }
+ .describe-text {
+ max-width: 320px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ color: var(--text-3); text-align: left; font-size: var(--fs-sm);
+ }
+ .describe-text:hover { color: var(--text-1); }
+
+ /* A column of row names read as edges. Its own small screen rather than a component,
+ because there is one question on it and the answer is a list. */
+ .edges { display: flex; flex-direction: column; min-height: 0; }
+ .edges-lead { color: var(--text-2); font-size: var(--fs-sm); line-height: 1.5; }
+ .edges-plan {
+ max-height: 300px; overflow: auto; margin-top: 12px;
+ border: 1px solid var(--border); border-radius: var(--r-sm);
+ }
+ .edges-row {
+ display: flex; align-items: center; gap: 8px; padding: 4px 7px;
+ border-bottom: 1px solid var(--border); font-size: var(--fs-xs);
+ }
+ .edges-row:last-child { border-bottom: 0; }
+ .edges-mark { flex: none; width: 44px; color: var(--text-3); }
+ .edges-row.make .edges-mark { color: var(--ok); }
+ .edges-row.error .edges-mark { color: var(--danger); }
+ .edges-name { color: var(--text-1); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .edges-says { color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .edges-tally { color: var(--text-3); font-size: var(--fs-xs); }
+ .notice code { font-family: var(--font-mono); font-size: 0.92em; }
+ /* The file-moved banner is a sentence, a sample of what differs and a row of answers,
+ so it stacks instead of running along one line like the other notices. */
+ .notice.stacked { flex-direction: column; align-items: flex-start; gap: 6px; padding: 8px 16px; }
+ .diff-said { color: var(--text-3); }
+ .diff-rows {
+ display: flex; flex-direction: column; gap: 2px; max-width: 100%;
+ font-size: var(--fs-xs); color: var(--text-2);
+ }
+ .diff-rows li { display: flex; align-items: center; gap: 6px; min-width: 0; }
+ .diff-rows li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .diff-rows em { color: var(--text-3); font-style: italic; }
+ /* What the grid holds, struck through: the file's answer is the one being offered. */
+ .diff-rows .was { color: var(--text-3); text-decoration: line-through; }
+ .notice-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+ .link { color: var(--accent); font-size: var(--fs-xs); }
+ .link:hover { text-decoration: underline; }
+
+ /* -- the grid ------------------------------------------------------------ */
+ /* Scrolls both ways. The header, the body and every row are `max-content`
+ wide so a table wider than the panel actually scrolls sideways instead of
+ squeezing its columns; `min-width: 100%` keeps a narrow one filling the
+ panel. Both bars are drawn heavier than the app's default thin ones,
+ because here they are how the analyst navigates rather than a hint that
+ there is more below. */
+ /* The panel is a two-by-two: the scroller, then a strip per bar. A bar that is
+ not needed is not rendered and its `auto` track collapses, so a sheet that
+ fits gives back the space. */
+ .grid-panel { flex: 1; min-height: 0; display: flex; }
+ .grid-wrap {
+ flex: 1; min-width: 0; min-height: 0; display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ grid-template-rows: minmax(0, 1fr) auto auto;
+ }
+ .grid-wrap.dropping { outline: 2px dashed var(--accent); outline-offset: -3px; }
+ .grid {
+ grid-area: 1 / 1; position: relative; min-height: 0; overflow: auto;
+ /* The native bars are hidden because the tool draws its own just outside. */
+ scrollbar-width: none;
+ /* Dragging across cells is how a rectangle is chosen, so the press must not also
+ start a text highlight: it painted the headings, the row numbers and whatever
+ sat past the table blue, and left that highlight behind as the thing Ctrl+C
+ would have taken. Typing gets it back below. */
+ user-select: none;
+ }
+ .grid::-webkit-scrollbar { width: 0; height: 0; }
+ /* Where text is being written rather than picked: the cell editor and the boxes the
+ grid's own popovers hold. */
+ .grid :global(textarea),
+ .grid :global(input) { user-select: text; }
+
+ /* Over the last rows, in the scroller's own cell of the panel rather than inside it, so
+ it neither scrolls with the table nor pushes it. Centred, because it belongs to the
+ rows rather than to either edge. */
+ .selection {
+ grid-area: 1 / 1; z-index: 6; align-self: end; justify-self: center;
+ max-width: calc(100% - 24px); margin-bottom: 12px;
+ display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
+ padding: 5px 8px; border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); box-shadow: 0 10px 26px #0006;
+ }
+ .selection .count { flex: none; padding: 0 3px; }
+ .selection-rule { flex: none; width: 1px; height: 18px; background: var(--border); }
+
+ .bar { position: relative; background: var(--bg-0); }
+ .bar.vertical { grid-area: 1 / 2; width: 13px; border-left: 1px solid var(--border); }
+ .bar.horizontal { grid-area: 2 / 1; height: 13px; border-top: 1px solid var(--border); }
+ .bar .thumb { position: absolute; border-radius: 5px; background: var(--border-strong); }
+ .bar.vertical .thumb { left: 2px; right: 2px; }
+ .bar.horizontal .thumb { top: 2px; bottom: 2px; }
+ .bar .thumb:hover { background: var(--border-strong); }
+ .bar.held .thumb { background: var(--accent); }
+ .head, .row { display: grid; align-items: stretch; width: max-content; min-width: 100%; }
+ .head {
+ position: sticky; top: 0; z-index: 3; height: 32px;
+ background: var(--bg-1); border-bottom: 1px solid var(--border-strong);
+ }
+ .cell {
+ position: relative; display: flex; align-items: center; gap: 4px;
+ min-width: 0; padding: 0 8px; border-right: 1px solid var(--border);
+ font-size: var(--fs-sm);
+ }
+ /* The tick box and the columns the analyst kept stay put while the table scrolls
+ sideways: on a wide comparison grid, losing which row you are on is losing the
+ grid. The offsets are computed (`stickyOffsets`), not written here, because a
+ column moved by dragging changes them. */
+ .cell.gutter {
+ position: sticky; left: 0; z-index: 2;
+ justify-content: center; padding: 0; background: var(--bg-1);
+ }
+ /* The row's place on screen, swapped for its tick box on hover or once anything is
+ ticked. Two controls in 34 pixels would be neither, and a number is what an analyst
+ says out loud — the key is a handle, not a position. */
+ .row .cell.gutter .row-number {
+ color: var(--text-3); font-size: var(--fs-xs); font-variant-numeric: tabular-nums;
+ }
+ .row .cell.gutter input[type='checkbox'] { display: none; }
+ .row:hover .cell.gutter .row-number,
+ .cell.gutter.ticking .row-number { display: none; }
+ .row:hover .cell.gutter input[type='checkbox'],
+ .cell.gutter.ticking input[type='checkbox'] { display: inline-block; }
+ /* Opaque underneath, tinted on top: a sticky cell has to hide the cells sliding
+ under it, and a translucent row colour cannot do that on its own. */
+ .cell.sticky {
+ position: sticky; z-index: 2; background-color: var(--bg-1);
+ background-image: linear-gradient(var(--row-tint, transparent), var(--row-tint, transparent));
+ }
+ .head .cell.heading { padding: 0 2px 0 4px; color: var(--text-2); font-weight: 500; }
+ .head .cell.heading.sorted { color: var(--accent); }
+ .head .cell.heading.asked { box-shadow: inset 0 -2px 0 var(--accent); }
+ .head .cell.heading.dragged { opacity: 0.45; }
+ .head .cell.heading.target { box-shadow: inset 2px 0 0 var(--accent); }
+ /* The handle is a hover affordance and the settings are not: three controls always
+ lit on every heading is a header nobody can read, and the one that has to be
+ found without hunting is the menu. */
+ .grip {
+ display: flex; color: var(--text-3); cursor: grab; padding: 0 1px;
+ opacity: 0; transition: opacity 90ms;
+ }
+ .head .cell.heading:hover .grip { opacity: 1; }
+ .grip:hover { color: var(--text-1); }
+ /* What the column is, beside its name. Quiet: the type is read once when a column
+ is set up and glanced at afterwards, so it sits at the weight of the grip. */
+ .role-mark { display: flex; flex: none; color: var(--text-3); }
+ .head .cell.heading:hover .role-mark { color: var(--text-2); }
+ .heading-name {
+ display: flex; align-items: center; gap: 5px; flex: 1; min-width: 0;
+ height: 100%; color: inherit; font-size: inherit; font-weight: inherit;
+ }
+ .heading-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ /* The second sort key, marked smaller and fainter than the first: it breaks that key's
+ ties, and two chevrons at the same weight would read as two sorts. */
+ .then-mark { display: flex; flex: none; color: var(--text-3); }
+ /* Quieter than the name: the unit qualifies the column, it does not name it. */
+ .heading-name .unit {
+ flex: none; color: var(--text-3); font-size: var(--fs-xs); font-weight: 400;
+ }
+ /* The funnel is quiet at rest and loud when it holds something. Quiet because three
+ controls always lit on fourteen headings is a header nobody reads; loud when the
+ column is filtered because then it is not decoration — it is where the filter is
+ read and taken off, and it says the rows on screen are not all of them. */
+ /* Lit at all times, faintly. It used to appear on hover, which meant the one gesture an
+ analyst makes a hundred times a day was invisible until the pointer happened to cross
+ the heading — and a grid that looks like it cannot filter is a grid nobody filters. */
+ .heading-filter {
+ display: flex; align-items: center; color: var(--text-3);
+ padding: 0 2px; border-radius: var(--r-sm);
+ opacity: 0.55; transition: opacity 90ms, color 90ms;
+ }
+ .head .cell.heading:hover .heading-filter { opacity: 1; }
+ .heading-filter:hover { color: var(--accent); background: var(--bg-2); }
+ .heading-filter.asking,
+ .heading-filter[aria-expanded='true'] { opacity: 1; color: var(--accent); }
+ .heading-rename {
+ flex: 1; min-width: 0; height: 22px; padding: 0 5px;
+ font-size: var(--fs-sm); font-weight: 500;
+ }
+ .heading-menu {
+ display: flex; align-items: center; color: var(--text-2);
+ padding: 0 2px; border-radius: var(--r-sm);
+ }
+ .heading-menu:hover { color: var(--accent); background: var(--bg-2); }
+ .heading-menu[aria-expanded='true'] { color: var(--accent); background: var(--bg-2); }
+ .resize {
+ position: absolute; right: -3px; top: 0; width: 7px; height: 100%;
+ cursor: col-resize; background: transparent;
+ }
+ .resize:hover { background: var(--accent-soft); }
+ .add-column {
+ display: flex; align-items: center; justify-content: center; width: 34px;
+ color: var(--text-3); border-right: 1px solid var(--border);
+ }
+ .add-column:hover { color: var(--accent); background: var(--bg-2); }
+
+ .body { position: relative; width: max-content; min-width: 100%; }
+ /* Both lists are moved with a transform, and a transform is a stacking context: without
+ these two, the ghost simply painted last and sat on top of anything a row put over it.
+ The list a cell editor's offers belong to has to win — the menu opens downwards, so on
+ the last rows of a short sheet it lands right across the empty line, and a click meant
+ for a word added a row instead. */
+ .rows { position: absolute; top: 0; left: 0; width: 100%; z-index: 1; }
+ .rows.ghost { z-index: 0; }
+ /* The height is written inline, from the sheet's own answer: a worklist wants thirty
+ pixels and the column the reasoning is written in cannot live in one line. */
+ /* The colour is a layer over the background rather than the background itself, the way
+ a sticky cell already paints. As the background it was replaced by the hover, so
+ running the pointer down a painted worklist rubbed out the colour under it — the one
+ thing the analyst was reading. */
+ .row {
+ border-bottom: 1px solid var(--border);
+ background-image: linear-gradient(var(--row-tint, transparent), var(--row-tint, transparent));
+ }
+ .row:hover { background-color: var(--bg-2); }
+ /* A tall row is a row with room to read, so its cells stop being one clipped line and
+ sit at the top of the space rather than floating in the middle of it. */
+ .grid.tall .cell { align-items: flex-start; padding-top: 5px; }
+ .grid.tall .cell .value {
+ display: -webkit-box; -webkit-box-orient: vertical;
+ -webkit-line-clamp: 4; line-clamp: 4;
+ white-space: pre-wrap; overflow: hidden; text-overflow: clip; line-height: 1.4;
+ }
+ /* The reference row, held under the heading. Opaque and shadowed because the rows it is
+ being compared to slide underneath it. */
+ .pinned {
+ position: sticky; z-index: 2; width: max-content; min-width: 100%;
+ background: var(--bg-1); box-shadow: 0 3px 8px #0003;
+ }
+ .pinned .row { border-bottom: 1px solid var(--border-strong); }
+ /* The empty line the grid always ends on. Faint, because it is an offer rather than a
+ row: it holds nothing and counts for nothing until it is typed in. */
+ .ghost .row { border-bottom: 1px dashed var(--border); background: none; }
+ .ghost .cell.gutter { color: var(--text-3); background: var(--bg-1); }
+ .ghost-cell { background: none; }
+ .ghost .row:hover .cell.gutter { color: var(--accent); }
+ .ghost-cell:hover { background: var(--bg-2); }
+ /* Ticking marks the gutter, not the whole row: a row washed in amber hid the
+ colour that had just been painted on it, which is the one thing the analyst
+ was looking at. The checkbox and the edge say it instead. */
+ .row.ticked .cell.gutter { background: var(--accent-soft); box-shadow: inset 2px 0 0 var(--accent); }
+ .row .cell.gutter { border-left: 3px solid var(--mark, transparent); }
+ .row .cell.key-cell { color: var(--text-3); font-family: var(--font-mono); font-size: var(--fs-xs); }
+ .cell .value { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .cell .value.linked { color: var(--accent); }
+ /* A cell of a column that is a set of values, one chip per value. Clicking one filters
+ on it: the chip is the answer and the way to ask for more of it. */
+ .value.chips { display: flex; align-items: center; gap: 3px; }
+ .cell-chip {
+ flex: none; max-width: 100%; padding: 1px 6px; border-radius: 9px;
+ border: 1px solid var(--border-strong); background: var(--bg-2);
+ color: var(--text-1); font-size: var(--fs-xs);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .cell-chip:hover { border-color: var(--accent); color: var(--accent); }
+ .cell-chip b { color: var(--text-3); font-weight: 600; margin-right: 2px; }
+ /* Outside the column's own words. Shown, never hidden: the binders write outside
+ their vocabulary on every page, and a lens that hid that would hide the work. */
+ .cell-chip.unknown { border-style: dashed; color: var(--text-2); }
+ /* A value given a colour in the column's own vocabulary wears it. The `.c-*` classes
+ below set `--mark`, so the chip reads in the same palette a row is painted with. */
+ .cell-chip.tinted {
+ border-color: var(--mark); color: var(--mark);
+ background: color-mix(in srgb, var(--mark) 12%, transparent);
+ }
+ /* A yes/no column drawn as a box, in three states the eye tells apart from a screen
+ away: answered yes is ticked, answered no is the empty box, and a cell nobody has
+ been through yet is that box faded back. Without that third drawing, four hundred
+ unopened rows and four hundred noes look the same. The border is drawn off the
+ text ramp rather than off `--border-strong`: an outline the grid's own rules can
+ out-shout is an outline the analyst has to hunt for. */
+ .cell-tick {
+ flex: none; display: flex; align-items: center; justify-content: center;
+ width: 16px; height: 16px; border-radius: 3px;
+ border: 1.5px solid var(--text-3); background: var(--bg-2); color: var(--text-2);
+ }
+ .cell-tick:hover { border-color: var(--accent); }
+ .cell-tick[data-state='yes'] { border-color: var(--ok); background: var(--ok); color: var(--bg-0); }
+ .cell-tick[data-state='blank'] { border-width: 1px; border-color: var(--border-strong); background: none; }
+ /* A word the column's pair does not hold. Kept and shown beside the box: the file
+ keeps the words, and a cell reading `maybe` is a finding, not a mistake. */
+ .cell-tick[data-state='other'] { border-style: dashed; border-color: var(--danger); }
+ .badge {
+ flex: none; padding: 0 4px; border-radius: var(--r-sm);
+ background: var(--bg-3); color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .badge.bad { background: var(--danger-soft); color: var(--danger); font-weight: 600; }
+ /* Quieter than the number it follows, in the grid as in the heading: the unit is the
+ same word on every row, and reading it at full weight four hundred times is reading
+ the column rather than the values. */
+ .cell-unit { flex: none; color: var(--text-3); font-size: var(--fs-xs); }
+ .cell-url { color: var(--accent); text-decoration: none; margin-right: 8px; }
+ .cell-url:hover { text-decoration: underline; }
+ .cell.cursor { outline: 2px solid var(--accent); outline-offset: -2px; }
+ .cell.picked { background-color: var(--accent-soft); }
+ .cell-link, .cell-open, .cell-map {
+ opacity: 0; color: var(--text-3); font-weight: 600; padding: 0 2px;
+ font-family: var(--font-mono);
+ }
+ .cell-open, .cell-map { display: flex; flex: none; font-weight: 400; }
+ /* Shown on hover, and on the cell under the cursor: reaching a cell by keyboard
+ should not hide the things that can be done to it. */
+ .cell:hover .cell-link, .cell:hover .cell-open, .cell:hover .cell-map,
+ .cell.cursor .cell-link, .cell.cursor .cell-open, .cell.cursor .cell-map { opacity: 1; }
+ .cell-link:hover, .cell-open:hover, .cell-map:hover { color: var(--accent); }
+ .link-mark { display: flex; color: var(--accent); }
+ /* A thumbnail inside a 30px row: enough to tell two photographs apart, and the link is
+ the full-size one. Fetched from wherever the cell points, which is why the role says
+ so before it is chosen. */
+ .cell-shot {
+ flex: none; display: flex; width: 34px; height: 22px; overflow: hidden;
+ border-radius: 2px; background: var(--bg-3);
+ }
+ .cell-shot img { width: 100%; height: 100%; object-fit: cover; }
+ .cell .value mark {
+ background: var(--accent-soft); color: var(--accent); border-radius: 2px;
+ }
+ /* The row and the case no longer say the same thing. Amber rather than red: it is a
+ divergence to settle, not an error. */
+ .link-mark.moved { color: var(--warn); }
+ /* A strip under the grid rather than a button floating inside it: pinned inside
+ the scroller it sat on top of whichever row happened to be at the bottom. */
+ .foot {
+ grid-area: 3 / 1 / 4 / 3; display: flex; align-items: center; gap: 12px;
+ padding: 0 12px; height: 30px;
+ background: var(--bg-1); border-top: 1px solid var(--border);
+ }
+ .foot-note { color: var(--text-3); font-size: var(--fs-xs); }
+ /* What a colour means, under the rows carrying it. Pressing one opens the panel that
+ names them, so the strip is both the reading and the way to write it. */
+ .legend-chip {
+ display: flex; align-items: center; gap: 5px;
+ color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .legend-chip:hover { color: var(--text-1); }
+ .legend-chip .swatch {
+ width: 9px; height: 9px; border-radius: 2px;
+ border: 1px solid var(--border-strong); background: var(--mark, var(--bg-3));
+ }
+ .progress { display: flex; align-items: center; gap: 8px; font-size: var(--fs-xs); color: var(--text-3); }
+ .progress strong { color: var(--text-1); font-weight: 600; }
+ .progress-key { color: var(--text-3); font-style: italic; }
+ .progress-left { color: var(--accent); font-size: inherit; }
+ .progress-left:hover { text-decoration: underline; }
+ .suggest-progress {
+ display: flex; align-items: center; gap: 5px; padding: 2px 7px;
+ border-radius: var(--r-sm); color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .suggest-progress:hover { color: var(--accent); background: var(--bg-2); }
+
+ /* A reading over one column — what it repeats, which of its points overlap — as a
+ strip under the question rather than a dialog: the answer is meant to be compared
+ against the table it came from, which a modal would cover. */
+ .reading {
+ display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
+ padding: 6px 16px; font-size: var(--fs-sm); color: var(--text-2);
+ background: var(--bg-1); border-bottom: 1px solid var(--border);
+ }
+ .reading strong { color: var(--text-1); }
+ .reading em { color: var(--text-3); font-style: italic; }
+ .found { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
+ .found .chip small { color: var(--text-3); }
+
+ .modal-row { display: flex; align-items: center; gap: 8px; margin-top: 14px; }
+ .paste-box { width: 100%; font-family: var(--font-mono); font-size: var(--fs-xs); resize: vertical; }
+ .hint { color: var(--text-3); font-size: var(--fs-sm); margin-top: 8px; }
+
+ /* The `.c-*` marks live in `app.css`: the grid, the cell editor and the column
+ panel all paint with them, and a scoped copy each is three lists that drift. */
+</style>
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
index bdb9d31..436da6c 100644
--- a/frontend/src/tools/Timeline.svelte
+++ b/frontend/src/tools/Timeline.svelte
@@ -63,7 +63,10 @@
trackPresets,
trackTint,
} from '../lib/timelineTracks.js';
+ import { plateFilename } from '../lib/plate.js';
+ import { PLATE_PLOT, timelinePlate } from '../lib/timelinePlate.js';
import AnalysisViews from '../components/AnalysisViews.svelte';
+ import PlateExport from '../components/PlateExport.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
import Icon from '../components/Icon.svelte';
@@ -203,8 +206,16 @@
});
const unplaced = $derived(pageItems.filter((item) => !item.earliest && item.raw));
const undated = $derived(pageItems.filter((item) => !item.earliest && !item.raw));
- const tracks = $derived(
- groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {
+ /**
+ * The tracks as they are drawn, laid out against a given axis width.
+ *
+ * The width is a parameter rather than the measured one, because `layoutTimelineItems`
+ * packs lanes by the room a label takes in pixels: it is the width that decides which
+ * entries collide, how many lanes a track needs and what ends up in a `+n`. The screen
+ * asks at the width it measured, the export at the plate's own.
+ */
+ function buildTracks(axisWidth) {
+ return groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {
const baseId = track.parentId ?? track.id;
const expanded = Boolean(expandedTracks[baseId]);
return {
@@ -212,12 +223,13 @@
expanded,
total: groupBy === 'none' ? (trackPages[baseId]?.total ?? track.items.length) : track.items.length,
layout: layoutTimelineItems(
- track.items.filter((item) => item.earliest), from, to, plotWidth,
+ track.items.filter((item) => item.earliest), from, to, axisWidth,
expanded ? PAGE : 6
),
};
- })
- );
+ });
+ }
+ const tracks = $derived(buildTracks(plotWidth));
const density = $derived(layoutDensityBuckets(overview, extent));
const overviewUnit = $derived(
{ 13: 'Hour', 10: 'Day', 7: 'Month' }[overview[0]?.start?.length] ?? 'Year'
@@ -541,6 +553,48 @@
};
}
+ /**
+ * The axis as a page, for the export dialog.
+ *
+ * The window, the tracks and the clock are the ones on screen — the plate reads what the
+ * analyst is on, never a second answer about it. The *geometry* is the plate's own: the
+ * ruler and the lanes are laid out at `PLATE_PLOT`, because both are packed in pixels
+ * and reusing the browser's width would make the page depend on the size of the window
+ * it was exported from.
+ */
+ function capturePlate() {
+ if (!axisWindow) return null;
+ const view = timelineViews.activeView?.name ?? '';
+ const at = new Date().toISOString();
+ const page = timelinePlate({
+ meta: {
+ caseName: caseState.current?.name ?? '',
+ surface: 'Timeline',
+ view,
+ title: 'Timeline',
+ question: entityFilter ? `Scoped to ${entityFilter.label}` : '',
+ window: windowWords(from, to, zone),
+ clock: zoneWord,
+ // What the axis cannot hold is stated rather than left out silently.
+ aside: undatedTotal
+ ? `${undatedTotal} undated entr${undatedTotal === 1 ? 'y' : 'ies'} are not on this axis`
+ : '',
+ at,
+ },
+ tracks: buildTracks(PLATE_PLOT),
+ ticks: axisTicks(from, to, PLATE_PLOT, zone),
+ minorTicks: axisMinorTicks(from, to, PLATE_PLOT, zone),
+ bands: axisBands(from, to, PLATE_PLOT, zone),
+ nowLeft,
+ scaleWord: axisScale(from, to, PLATE_PLOT),
+ clock: zoneWord,
+ });
+ return {
+ ...page,
+ filename: plateFilename({ surface: 'timeline', view, lens: windowWords(from, to, 'UTC'), at }),
+ };
+ }
+
function openRangeIn(tool) {
if (!caseState.current?.id || !axisWindow) return;
const period = { from, to, categories: activeCategories };
@@ -1354,6 +1408,7 @@
onopen={openAnalysisView}
onleave={leaveAnalysisReading}
/>
+ <PlateExport surface="timeline" plate={capturePlate} disabled={!caseState.current} />
<button class="btn btn-ghost fullscreen-btn" aria-pressed={fullscreen} onclick={toggleFullscreen}>{fullscreen ? 'Exit full screen' : 'Full screen'}</button>
<button class="btn btn-primary add-event" disabled={snapshotReading} onclick={() => openEditor()}><Icon name="plus" size={13} />Add assessment</button>
</div>
@@ -2041,7 +2096,12 @@
.range-handoffs button:disabled { opacity: .4; cursor: default; }
.range-spans button:hover { border-color: var(--border-strong); color: var(--text-1); }
.range-spans button:disabled { opacity: .4; cursor: default; }
- .head-actions { justify-self: end; display: flex; gap: 5px; }
+ .head-actions { justify-self: end; display: flex; align-items: center; gap: 5px; }
+ /* One height across the row. Views and Export come from shared components and are
+ `btn-sm`, the tool's own two are not, and four buttons of two heights read as a
+ mistake. Stated from the same tokens a plain `.btn` is built from — its text plus
+ its padding and rule — rather than as a number that would drift from them. */
+ .head-actions :global(.btn) { min-height: calc(var(--fs-sm) * 1.5 + 12px); }
.add-event { justify-self: end; }
.timeline-tool:fullscreen { width: 100vw; height: 100vh; }
.filter-row { min-height: 42px; display: flex; align-items: center; gap: 8px; padding: 0 24px 10px; border-bottom: 1px solid color-mix(in srgb, var(--border) 75%, transparent); }
diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.js
index 1a84b1e..2e45685 100644
--- a/frontend/src/tools/Timeline.test.js
+++ b/frontend/src/tools/Timeline.test.js
@@ -304,3 +304,35 @@ describe('measuring between two entries', () => {
expect(source).toContain('selected = item;\n against = null;');
});
});
+
+describe('exporting the axis', () => {
+ it('serialises the tracks the tool laid out, never a canvas', () => {
+ expect(source).toContain('timelinePlate({');
+ expect(source).toContain('const tracks = $derived(buildTracks(plotWidth));');
+ });
+
+ it('lays the page out at the plate’s width, not the browser’s', () => {
+ // `layoutTimelineItems` packs lanes by the pixels a label takes, so the width it is
+ // given decides what collides and what ends up in a `+n`. Replaying the screen's
+ // answer on a fixed page would put the gaps in the wrong places, and the same saved
+ // view would export differently from a laptop and from a wide monitor.
+ expect(source).toContain('tracks: buildTracks(PLATE_PLOT)');
+ expect(source).toContain('ticks: axisTicks(from, to, PLATE_PLOT, zone)');
+ expect(source).toContain('minorTicks: axisMinorTicks(from, to, PLATE_PLOT, zone)');
+ expect(source).toContain('bands: axisBands(from, to, PLATE_PLOT, zone)');
+ expect(source).toContain('scaleWord: axisScale(from, to, PLATE_PLOT)');
+ });
+
+ it('exports the window and the clock the reading was made on', () => {
+ expect(source).toContain('window: windowWords(from, to, zone)');
+ expect(source).toContain('clock: zoneWord');
+ });
+
+ it('states the entries the axis cannot hold', () => {
+ expect(source).toContain('undated entr${undatedTotal === 1');
+ });
+
+ it('offers the export beside the saved views', () => {
+ expect(source).toContain('<PlateExport surface="timeline" plate={capturePlate}');
+ });
+});
diff --git a/frontend/src/tools/inspect/CollageMenu.svelte b/frontend/src/tools/inspect/CollageMenu.svelte
index 8677f50..40a0d5c 100644
--- a/frontend/src/tools/inspect/CollageMenu.svelte
+++ b/frontend/src/tools/inspect/CollageMenu.svelte
@@ -20,7 +20,14 @@
session.collages.find((c) => c.id === session.activeCollageId) ?? session.collages[0]
);
- const onCanvas = (id) => active?.nodes.some((n) => n.frameId === id);
+ // How many pieces on this collage came from that tray frame — a tile can be
+ // added several times, and with a long tray that count is the only way to see
+ // what is already placed.
+ const usedCount = (id) => active?.nodes.filter((n) => n.frameId === id).length ?? 0;
+
+ // Same wording as the Frame tab tray, so a frame keeps one name across tabs.
+ const frameLabel = (fr, i) =>
+ fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`;
// These controls act on one piece; a multi-piece block is transformed as a
// whole on the canvas, so the section simply steps aside for it.
const selected = $derived(
@@ -250,19 +257,29 @@
<div class="section">
<div class="section-head"><span>Frames</span></div>
- <div class="grid">
- {#each session.frames as fr (fr.id)}
+ <div class="tray">
+ {#each session.frames as fr, i (fr.id)}
{@const look = previewStyle(filters, fr.adjust)}
- <button class="tile" class:used={onCanvas(fr.id)} onclick={() => addToCollage(fr)} title={onCanvas(fr.id) ? 'Add again (fresh snapshot)' : 'Add to canvas'}>
+ {@const used = usedCount(fr.id)}
+ <button
+ class="thumb"
+ class:used={used > 0}
+ onclick={() => addToCollage(fr)}
+ title={used ? `${frameLabel(fr, i)} · added ${used}×` : frameLabel(fr, i)}
+ >
<img
- class:cropped={fr.crop}
src={fr.url}
- alt="frame"
+ alt={frameLabel(fr, i)}
style={styleText(cropImgStyle(fr.crop))}
style:filter={look.filter}
style:transform={look.transform}
/>
- <span class="add"><Icon name="plus" size={12} /></span>
+ <span class="num">{i + 1}</span>
+ {#if used}
+ <span class="tag count">×{used}</span>
+ {:else}
+ <span class="tag"><Icon name="plus" size={11} /></span>
+ {/if}
</button>
{/each}
</div>
@@ -447,40 +464,60 @@
color: var(--text-2);
cursor: pointer;
}
- .grid {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
+ .tray {
+ display: flex;
+ flex-wrap: wrap;
gap: 6px;
- max-height: 200px;
- overflow: auto;
}
- .tile {
+ .thumb {
position: relative;
- aspect-ratio: 1;
+ width: 60px;
+ height: 60px;
border-radius: var(--r-sm);
overflow: hidden;
border: 2px solid transparent;
padding: 0;
}
- .tile.used {
+ .thumb.used {
border-color: var(--border-strong);
}
- .tile img {
+ .thumb img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
- .tile .add {
+ .num {
position: absolute;
- bottom: 3px;
- right: 3px;
+ top: 2px;
+ left: 2px;
+ min-width: 15px;
+ height: 15px;
+ padding: 0 3px;
+ border-radius: 4px;
+ background: rgba(10, 10, 10, 0.7);
+ color: #fff;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 15px;
+ text-align: center;
+ }
+ .tag {
+ position: absolute;
+ bottom: 2px;
+ right: 2px;
background: var(--accent);
color: var(--accent-text);
border-radius: 4px;
display: flex;
padding: 1px;
}
+ .tag.count {
+ padding: 0 4px;
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 15px;
+ }
.modes {
display: flex;
gap: 0;
diff --git a/frontend/src/tools/inspect/CollageMenu.test.js b/frontend/src/tools/inspect/CollageMenu.test.js
index 0c324ba..89d3f21 100644
--- a/frontend/src/tools/inspect/CollageMenu.test.js
+++ b/frontend/src/tools/inspect/CollageMenu.test.js
@@ -35,3 +35,23 @@ describe('CollageMenu renaming', () => {
expect(source).toContain('maxlength="200"');
});
});
+
+describe('CollageMenu frame tray', () => {
+ it('numbers the tiles and names them like the Frame tab', () => {
+ expect(source).toContain(
+ "fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`"
+ );
+ expect(source).toContain('<span class="num">{i + 1}</span>');
+ });
+
+ it('counts how many pieces a frame already has on the collage', () => {
+ expect(source).toContain(
+ 'const usedCount = (id) => active?.nodes.filter((n) => n.frameId === id).length ?? 0;'
+ );
+ expect(source).toContain('<span class="tag count">×{used}</span>');
+ });
+
+ it('lets the panel scroll instead of boxing the tray in its own window', () => {
+ expect(source).not.toContain('max-height: 200px');
+ });
+});
diff --git a/frontend/src/tools/inspect/FrameMenu.svelte b/frontend/src/tools/inspect/FrameMenu.svelte
index e2654bf..bce45c6 100644
--- a/frontend/src/tools/inspect/FrameMenu.svelte
+++ b/frontend/src/tools/inspect/FrameMenu.svelte
@@ -88,7 +88,6 @@
<div class="thumb" class:active={fr.id === session.activeFrameId}>
<button class="pick" onclick={() => setActive(fr.id)} title={fr.time != null ? `Image ${i + 1} · t=${fr.time.toFixed(2)}s` : `Image ${i + 1}`}>
<img
- class:cropped={fr.crop}
src={fr.url}
alt={`Image ${i + 1}`}
style={styleText(cropImgStyle(fr.crop))}
diff --git a/frontend/src/tools/proof/ImportProofDialog.render.test.js b/frontend/src/tools/proof/ImportProofDialog.render.test.js
new file mode 100644
index 0000000..5c6885e
--- /dev/null
+++ b/frontend/src/tools/proof/ImportProofDialog.render.test.js
@@ -0,0 +1,798 @@
+// @vitest-environment happy-dom
+/**
+ * The import dialog, actually mounted.
+ *
+ * The engine suite next door proves what gets written; this one drives the
+ * screen, because the two promises that matter here are about the screen:
+ *
+ * - **the prefill never decides.** A position read out of a post lands in the
+ * field with a note saying where it came from, and the analyst's approval is
+ * what confirms it;
+ * - **nothing is created without the preview.** Create appears only once the
+ * preview has come back ready, and closing the dialog discards what was held.
+ */
+import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+const post = vi.fn();
+const put = vi.fn();
+const del = vi.fn();
+vi.mock('../../lib/api.js', () => ({ api: { get, post, put, del } }));
+vi.mock('../../lib/state.svelte.js', () => ({ toast: vi.fn() }));
+
+const { default: ImportProofDialog } = await import('./ImportProofDialog.svelte');
+
+const POST_TEXT = {
+ url: 'https://x.com/a/1',
+ title: 'Hoyo de la Puerta',
+ text: 'Point of view — 10.393313, -66.892504 — Source: https://instagram.com/reels/D1',
+ coords: [
+ { lat: 10.393313, lon: -66.892504, text: '10.393313, -66.892504', format: 'decimal' },
+ { lat: 48.8584, lon: 2.2945, text: '48.8584, 2.2945', format: 'decimal' },
+ ],
+ urls: ['https://instagram.com/reels/D1'],
+};
+
+const STAGED = { filename: 'panel.png', kind: 'image', size: 12345, sha256: 'a'.repeat(64) };
+
+const READY_PREVIEW = {
+ ready: true,
+ blocking: [],
+ entities: [
+ { slot: 'place', type: 'place', label: '10°23′N', state: 'new', detail: '' },
+ { slot: 'source', type: 'media', label: 'reel.mp4', state: 'new', detail: 'video · 2.4 MB' },
+ { slot: 'panel', type: 'media', label: 'panel.png', state: 'new', detail: 'image · 0.4 MB' },
+ { slot: 'proof', type: 'proof', label: 'Hoyo de la Puerta', state: 'new', detail: '' },
+ ],
+ links: [
+ { from: 'source', to: 'place', type: 'located-at', label: 'was recorded at' },
+ { from: 'proof', to: 'place', type: 'depicts', label: 'shows' },
+ ],
+ warnings: [],
+};
+
+let live = null;
+
+/** The modal portals itself out of the mount point, so the screen under test is
+ * the document, not the element it was mounted into. */
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(ImportProofDialog, {
+ target,
+ props: { caseId: 'c1', onclose: vi.fn(), oncreated: vi.fn(), ...props },
+ });
+ flushSync();
+ return document.body;
+}
+
+async function settle() {
+ for (let i = 0; i < 8; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+ flushSync();
+}
+
+function buttons(target) {
+ return [...target.querySelectorAll('button')].map((node) => node.textContent.trim());
+}
+
+function press(target, label) {
+ const node = [...target.querySelectorAll('button')].find(
+ (button) => button.textContent.trim() === label,
+ );
+ if (!node) throw new Error(`no button labelled '${label}' (have: ${buttons(target)})`);
+ node.click();
+ flushSync();
+}
+
+function field(target, label) {
+ // Source is a set of boxes rather than one, so its wrapper is a div; the rest are
+ // still labels around a single input.
+ const wrapper = [...target.querySelectorAll('label, .import-field')].find((node) =>
+ node.querySelector('span')?.textContent.trim().startsWith(label),
+ );
+ return wrapper?.querySelector('input');
+}
+
+function type(input, value) {
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+/** The fetch is a job: a token, a start, then polls until it is done. */
+function fetchAnswers(result) {
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview')) return Promise.resolve(READY_PREVIEW);
+ if (path.endsWith('/commit')) return Promise.resolve({ proof: { name: 'Hoyo de la Puerta' } });
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({ status: 'done', progress: {}, result });
+}
+
+beforeEach(() => {
+ get.mockReset();
+ post.mockReset();
+ put.mockReset();
+ del.mockReset();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('fetching a post', () => {
+ it('opens on the address, and asks for nothing else first', () => {
+ const target = open();
+ expect(target.textContent).toContain('Post address');
+ expect(buttons(target)).toContain('Fetch');
+ expect(post).not.toHaveBeenCalled();
+ });
+
+ it('holds the picture in a staging directory rather than the case', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ expect(post).toHaveBeenCalledWith('/api/cases/c1/proof-imports/0123456789ab/fetch', {
+ url: 'https://x.com/a/1',
+ slot: 'panel',
+ index: null,
+ indexes: [],
+ use_cookies: false,
+ });
+ const image = target.querySelector('img');
+ expect(image.getAttribute('src')).toContain('media/.dl/0123456789ab/panel.png');
+ });
+});
+
+describe('what the post prefilled', () => {
+ async function fetched() {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ return target;
+ }
+
+ it('fills the position and says which words it was read from', async () => {
+ const target = await fetched();
+ expect(field(target, 'Coordinates').value).toBe('10.393313, -66.892504');
+ expect(target.textContent).toContain('Read from the post: 10.393313, -66.892504');
+ });
+
+ it('offers the other positions it found instead of choosing between them', async () => {
+ const target = await fetched();
+ expect(buttons(target)).toContain('48.8584, 2.2945');
+ press(target, '48.8584, 2.2945');
+ expect(field(target, 'Coordinates').value).toBe('48.8584, 2.2945');
+ });
+
+ it('proposes the link the post points at as the source', async () => {
+ const target = await fetched();
+ expect(field(target, 'Source').value).toBe('https://instagram.com/reels/D1');
+ });
+
+ it('drops the note about where a position came from once it is edited', async () => {
+ const target = await fetched();
+ type(field(target, 'Coordinates'), '1.0, 2.0');
+ expect(target.textContent).not.toContain('Read from the post');
+ });
+});
+
+describe('a proof read from a thread', () => {
+ async function fetched(urls = ['https://instagram.com/reels/D1']) {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: { ...POST_TEXT, urls } });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ return target;
+ }
+
+ function sourceBoxes(target) {
+ return [...target.querySelectorAll('.import-source-row input')].map((one) => one.value);
+ }
+
+ it('offers a box for every address the post pointed at, not just the first', async () => {
+ // A thread naming the photos and the clip names its material. Picking the first
+ // would be the dialog choosing for the analyst.
+ const target = await fetched([
+ 'https://x.com/a/2', 'https://x.com/a/3', 'https://x.com/a/4',
+ ]);
+ expect(sourceBoxes(target)).toEqual([
+ 'https://x.com/a/2', 'https://x.com/a/3', 'https://x.com/a/4',
+ ]);
+ });
+
+ it('adds a box, and fetches each address on its own', async () => {
+ const target = await fetched();
+ press(target, 'Add a source');
+ const boxes = [...target.querySelectorAll('.import-source-row input')];
+ expect(boxes).toHaveLength(2);
+
+ type(boxes[1], 'https://x.com/a/2');
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: { slot: 'source', staged: STAGED, held: [STAGED] },
+ });
+ press(target, 'Preview');
+ await settle();
+
+ const asked = post.mock.calls
+ .filter(([path, body]) => path.endsWith('/fetch') && body.slot === 'source')
+ .map(([, body]) => body.url);
+ expect(asked).toEqual(['https://instagram.com/reels/D1', 'https://x.com/a/2']);
+ // And the form states both, in the order the boxes hold them.
+ const asked_preview = post.mock.calls.find(([path]) => path.endsWith('/preview'))[1];
+ expect(asked_preview.source_urls).toEqual([
+ 'https://instagram.com/reels/D1', 'https://x.com/a/2',
+ ]);
+ });
+
+ it('drops a box without touching what the others hold', async () => {
+ const target = await fetched(['https://x.com/a/2', 'https://x.com/a/3']);
+ const drops = [...target.querySelectorAll('.import-source-drop')];
+ expect(drops).toHaveLength(2);
+ drops[0].click();
+ flushSync();
+ expect(sourceBoxes(target)).toEqual(['https://x.com/a/3']);
+ });
+});
+
+describe('a post that states nothing', () => {
+ it('leaves every field empty and offers no chips', async () => {
+ fetchAnswers({
+ slot: 'panel',
+ staged: STAGED,
+ post: { url: 'https://x.com/a/1', title: '', text: 'Look at this', coords: [], urls: [] },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ expect(field(target, 'Coordinates').value).toBe('');
+ expect(field(target, 'Source').value).toBe('');
+ expect(target.textContent).not.toContain('Read from the post');
+ });
+});
+
+describe('the preview gate', () => {
+ async function filled() {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ return target;
+ }
+
+ it('offers a preview, never a create, before anything has been checked', async () => {
+ const target = await filled();
+ expect(buttons(target)).toContain('Preview');
+ expect(buttons(target)).not.toContain('Create');
+ });
+
+ it('will not preview without a name and a position', async () => {
+ const target = await filled();
+ type(field(target, 'Coordinates'), '');
+ const preview = [...target.querySelectorAll('button')].find(
+ (node) => node.textContent.trim() === 'Preview',
+ );
+ expect(preview.disabled).toBe(true);
+ });
+
+ it('downloads the source before previewing, so the preview reads real bytes', async () => {
+ const target = await filled();
+ press(target, 'Preview');
+ await settle();
+
+ const fetches = post.mock.calls.filter(([path]) => path.endsWith('/fetch'));
+ expect(fetches.map(([, body]) => body.slot)).toEqual(['panel', 'source']);
+ expect(fetches[1][1].url).toBe('https://instagram.com/reels/D1');
+ });
+
+ it('lists the entities and the edges, then offers Create', async () => {
+ const target = await filled();
+ press(target, 'Preview');
+ await settle();
+
+ expect(target.textContent).toContain('To be created');
+ expect(target.textContent).toContain('was recorded at');
+ expect(target.textContent).toContain('Hoyo de la Puerta');
+ expect(buttons(target)).toContain('Create');
+ });
+
+ it('does not claim the camera was on site until it is ticked', async () => {
+ const target = await filled();
+ press(target, 'Preview');
+ await settle();
+ const [, body] = post.mock.calls.find(([path]) => path.endsWith('/preview'));
+ expect(body.pov).toBe(false);
+ });
+
+ it('sends the camera answer once it is given', async () => {
+ const target = await filled();
+ const box = target.querySelector('input[type="checkbox"]');
+ box.click();
+ flushSync();
+ press(target, 'Preview');
+ await settle();
+ const [, body] = post.mock.calls.find(([path]) => path.endsWith('/preview'));
+ expect(body.pov).toBe(true);
+ });
+
+ it('withdraws Create the moment a field changes again', async () => {
+ const target = await filled();
+ press(target, 'Preview');
+ await settle();
+ type(field(target, 'Name'), 'Another name');
+ expect(buttons(target)).not.toContain('Create');
+ expect(buttons(target)).toContain('Preview');
+ });
+
+ it('refuses to create and says why when the preview is not ready', async () => {
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview')) {
+ return Promise.resolve({
+ ready: false,
+ blocking: ['A source is required.'],
+ entities: [],
+ links: [],
+ warnings: [],
+ });
+ }
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: { slot: 'panel', staged: STAGED, post: { ...POST_TEXT, urls: [] } },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+
+ expect(target.textContent).toContain('A source is required.');
+ expect(buttons(target)).not.toContain('Create');
+ });
+
+ it('shows a warning without blocking the create', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview')) {
+ return Promise.resolve({
+ ...READY_PREVIEW,
+ warnings: [{ code: 'gps-conflict', text: 'The file states 10.4, -66.9 — 800 m away.' }],
+ });
+ }
+ return Promise.resolve({});
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+
+ expect(target.textContent).toContain('800 m away');
+ expect(buttons(target)).toContain('Create');
+ });
+});
+
+describe('the two files the import is holding', () => {
+ async function withBoth() {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ // pressing Preview is what downloads the footage, so the viewer gains it there
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ slot: 'source',
+ staged: { filename: 'reel.mp4', kind: 'video', size: 2400000, sha256: 'b'.repeat(64) },
+ },
+ });
+ press(target, 'Preview');
+ await settle();
+ return target;
+ }
+
+ it('shows the proof picture on its own until the footage lands', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ expect(target.textContent).toContain('Proof:');
+ expect(target.querySelector('[aria-label="Next file"]')).toBeNull();
+ });
+
+ it('offers both files once the footage has been downloaded', async () => {
+ const target = await withBoth();
+ expect(target.textContent).toContain('Proof:');
+ expect(target.textContent).toContain('1/2');
+ expect(target.querySelector('[aria-label="Next file"]')).not.toBeNull();
+ });
+
+ it('steps to the footage and plays it from the staging directory', async () => {
+ const target = await withBoth();
+ target.querySelector('[aria-label="Next file"]').click();
+ flushSync();
+
+ expect(target.textContent).toContain('Source media:');
+ expect(target.textContent).toContain('reel.mp4');
+ const video = target.querySelector('video');
+ expect(video.getAttribute('src')).toContain('media/.dl/0123456789ab/reel.mp4');
+ expect(target.querySelector('img')).toBeNull();
+ });
+
+ it('wraps back round to the proof', async () => {
+ const target = await withBoth();
+ target.querySelector('[aria-label="Next file"]').click();
+ flushSync();
+ target.querySelector('[aria-label="Next file"]').click();
+ flushSync();
+ expect(target.textContent).toContain('Proof:');
+ });
+});
+
+describe('what a slot can hold', () => {
+ it('refuses a clip for the picture slot where it is chosen, not two screens later', async () => {
+ // A proof is composed of pictures: the composer lays panels out on a canvas and a
+ // video has nothing to lay out. Ticking one used to download it, fill the picture
+ // slot with it, and say so only at the preview.
+ fetchAnswers({
+ multi: true,
+ items: [
+ { index: 1, title: 'the published picture', thumbnail: null, kind: 'image', own: true },
+ { index: 2, title: 'the clip', thumbnail: null, kind: 'video', own: true },
+ ],
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ const rows = [...target.querySelectorAll('.import-pick')];
+ expect(rows[0].disabled).toBe(false);
+ expect(rows[0].getAttribute('aria-pressed')).toBe('true');
+ // Shown, so "this post also carries a clip" is legible, and refused.
+ expect(rows[1].disabled).toBe(true);
+ expect(rows[1].getAttribute('aria-pressed')).toBe('false');
+
+ rows[1].click();
+ flushSync();
+ expect(
+ [...target.querySelectorAll('.import-pick')][1].getAttribute('aria-pressed'),
+ ).toBe('false');
+ });
+});
+
+describe('a question nobody has answered yet', () => {
+ it('reports nothing while a picker is open, and nothing once it is cancelled', async () => {
+ // Preview downloads the material first, so an address holding several files raises
+ // the picker mid-press. Reading the case behind that question reported on a state
+ // nobody had agreed to: the picker cancelled, the preview still said "ready", and
+ // Create filed a proof whose source had never been downloaded.
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ multi: true,
+ items: [
+ { index: 1, title: 'the clip', thumbnail: null, kind: 'video', own: true },
+ { index: 2, title: 'the quoted clip', thumbnail: null, kind: 'video', own: false },
+ ],
+ },
+ });
+ press(target, 'Preview');
+ await settle();
+
+ expect(post.mock.calls.some(([path]) => path.endsWith('/preview'))).toBe(false);
+ expect(target.textContent).toContain('Choose the footage');
+ expect(buttons(target)).not.toContain('Create');
+
+ // the picker's own Cancel, not the dialog's
+ [...target.querySelectorAll('button')].filter((one) => one.textContent.trim() === 'Cancel')
+ .at(-1).click();
+ flushSync();
+ expect(target.textContent).not.toContain('Choose the footage');
+ expect(buttons(target)).not.toContain('Create');
+ });
+});
+
+describe('a post with several attachments', () => {
+ async function picking() {
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview')) return Promise.resolve(READY_PREVIEW);
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ multi: true,
+ items: [
+ { index: 1, title: 'first photo', thumbnail: 'https://cdn/a.jpg', kind: 'image' },
+ { index: 2, title: 'the clip', thumbnail: null, kind: 'video' },
+ ],
+ },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ return target;
+ }
+
+ it('previews each attachment with the poster frame the extractor gave', async () => {
+ const target = await picking();
+ const thumbs = [...target.querySelectorAll('.import-pick-thumb img')];
+ expect(thumbs.map((node) => node.getAttribute('src'))).toEqual(['https://cdn/a.jpg']);
+ expect(target.textContent).toContain('first photo');
+ expect(target.textContent).toContain('This link has 2 attachments');
+ });
+
+ it('falls back to the kind for an attachment with no poster frame', async () => {
+ const target = await picking();
+ const rows = [...target.querySelectorAll('.import-pick')];
+ expect(rows[1].querySelector('img')).toBeNull();
+ expect(rows[1].querySelector('svg')).not.toBeNull();
+ expect(rows[1].textContent).toContain('video');
+ });
+
+ /** Answer the picker: tick what is wanted, then take it. The confirm button says how
+ * many panels it is composing, so it is found by its role rather than its words. */
+ async function take(target, ...ticks) {
+ for (const at of ticks) {
+ [...target.querySelectorAll('.import-pick')][at].click();
+ flushSync();
+ }
+ [...target.querySelectorAll('.modal-row .btn-primary')].at(-1).click();
+ flushSync();
+ await settle();
+ }
+
+ it('arrives with the pictures ticked, because that is what a post published', async () => {
+ const target = await picking();
+ const rows = [...target.querySelectorAll('.import-pick')];
+ // The picture is the point of the post; the clip beside it is the footage, and which
+ // clip is the source is not something a rule knows.
+ expect(rows[0].getAttribute('aria-pressed')).toBe('true');
+ expect(rows[1].getAttribute('aria-pressed')).toBe('false');
+ expect(target.textContent).toContain('become the panels of one proof');
+ });
+
+ it('counts a picked source as tried, so the preview does not fetch it twice', async () => {
+ const target = await picking();
+ // the picker was opened for the picture; answer it, then drive to a preview
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: { slot: 'panel', staged: STAGED, post: { ...POST_TEXT, urls: [] } },
+ });
+ await take(target);
+ type(field(target, 'Source'), 'https://instagram.com/reels/D1');
+ press(target, 'Preview');
+ await settle();
+
+ const sources = post.mock.calls.filter(
+ ([path, body]) => path.endsWith('/fetch') && body.slot === 'source',
+ );
+ expect(sources).toHaveLength(1);
+ });
+
+ it('downloads only what was ticked', async () => {
+ // Two pictures, both of use to the slot: unticking the first and keeping the second
+ // is a choice the analyst is allowed to make. (A clip is not — see the slot's own
+ // kinds — so it cannot stand in for the second picture here.)
+ fetchAnswers({
+ multi: true,
+ items: [
+ { index: 1, title: 'the overhead', thumbnail: null, kind: 'image', own: true },
+ { index: 2, title: 'the ground shot', thumbnail: null, kind: 'image', own: true },
+ ],
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ await take(target, 0); // untick the first; the second stays
+
+ const fetches = post.mock.calls.filter(([path]) => path.endsWith('/fetch'));
+ expect(fetches.at(-1)[1].index).toBe(2);
+ expect(fetches.at(-1)[1].indexes).toEqual([2]);
+ });
+
+ it('renders a report about several panels rather than blanking on it', async () => {
+ // The report is keyed by slot. Three pictures all called `panel` are a duplicate key,
+ // Svelte throws on those, and the whole reading disappears — the loudest failure for
+ // the quietest fault, and indistinguishable from a preview that never answered.
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview'))
+ return Promise.resolve({
+ ready: true,
+ blocking: [],
+ warnings: [],
+ entities: [
+ { slot: 'panel', type: 'media', label: 'overhead', state: 'new', detail: '' },
+ { slot: 'panel 2', type: 'media', label: 'ground', state: 'new', detail: '' },
+ { slot: 'panel 3', type: 'media', label: 'match', state: 'new', detail: '' },
+ ],
+ links: [
+ { from: 'proof', to: 'panel', type: 'derived-from', label: 'derived from' },
+ { from: 'proof', to: 'panel 2', type: 'derived-from', label: 'derived from' },
+ { from: 'proof', to: 'panel 3', type: 'derived-from', label: 'derived from' },
+ ],
+ });
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ slot: 'panel',
+ staged: STAGED,
+ held: [STAGED, { ...STAGED, filename: 'p2.png' }, { ...STAGED, filename: 'p3.png' }],
+ post: { ...POST_TEXT, urls: [] },
+ },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ type(field(target, 'Source'), 'https://instagram.com/reels/D1');
+ press(target, 'Preview');
+ await settle();
+
+ expect(target.querySelectorAll('.import-links li')).toHaveLength(3);
+ expect(target.textContent).toContain('panel 3');
+ });
+
+ it('shows the set it will compose, not one picture of it', async () => {
+ // "Where are my three images?" is the question the stepper alone could not answer:
+ // it counted the footage as if it were part of the proof and showed one at a time.
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ slot: 'panel',
+ staged: STAGED,
+ held: [STAGED, { ...STAGED, filename: 'panel-2.png' }, { ...STAGED, filename: 'panel-3.png' }],
+ post: POST_TEXT,
+ },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ const strip = target.querySelector('.import-strip');
+ expect(strip.querySelectorAll('.import-strip-one')).toHaveLength(3);
+ expect(target.textContent).toContain('One proof of 3 panels');
+ // And each is reachable on its own, which is what the stepper was for.
+ expect(target.textContent).toContain('Panel 1');
+ });
+
+ it('composes several ticked pictures as the panels of one proof', async () => {
+ // A published geolocation is often a set — the overhead, the ground shot, the match.
+ // Keeping the first of three keeps a third of what was published.
+ post.mockImplementation((path) => {
+ if (path.endsWith('/proof-imports')) return Promise.resolve({ token: '0123456789ab' });
+ if (path.endsWith('/fetch')) return Promise.resolve({ job_id: 'j1' });
+ if (path.endsWith('/preview')) return Promise.resolve(READY_PREVIEW);
+ return Promise.resolve({});
+ });
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: {
+ multi: true,
+ items: [
+ { index: 1, title: 'overhead', thumbnail: 'https://cdn/a.jpg', kind: 'image' },
+ { index: 2, title: 'ground', thumbnail: 'https://cdn/b.jpg', kind: 'image' },
+ { index: 3, title: 'the clip', thumbnail: null, kind: 'video' },
+ ],
+ },
+ });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+
+ expect(target.textContent).toContain('Compose 2 panels');
+ get.mockResolvedValue({
+ status: 'done',
+ progress: {},
+ result: { slot: 'panel', staged: STAGED, post: POST_TEXT },
+ });
+ await take(target);
+
+ const fetches = post.mock.calls.filter(([path]) => path.endsWith('/fetch'));
+ expect(fetches.at(-1)[1].indexes).toEqual([1, 2]);
+ });
+});
+
+describe('creating and cancelling', () => {
+ it('commits the form the preview approved, then hands the proof back', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const oncreated = vi.fn();
+ const target = open({ oncreated });
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+ press(target, 'Create');
+ await settle();
+
+ const [path, body] = post.mock.calls.find(([p]) => p.endsWith('/commit'));
+ expect(path).toBe('/api/cases/c1/proof-imports/0123456789ab/commit');
+ expect(body.coords).toBe('10.393313, -66.892504');
+ expect(oncreated).toHaveBeenCalledWith({ proof: { name: 'Hoyo de la Puerta' } });
+ });
+
+ it('discards what it held when the dialog is closed', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const onclose = vi.fn();
+ const target = open({ onclose });
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ press(target, 'Cancel');
+ await settle();
+
+ expect(del).toHaveBeenCalledWith('/api/cases/c1/proof-imports/0123456789ab');
+ expect(onclose).toHaveBeenCalled();
+ });
+
+ it('does not discard after a commit, which already cleaned up', async () => {
+ fetchAnswers({ slot: 'panel', staged: STAGED, post: POST_TEXT });
+ const target = open();
+ type(target.querySelector('input.input'), 'https://x.com/a/1');
+ press(target, 'Fetch');
+ await settle();
+ press(target, 'Preview');
+ await settle();
+ press(target, 'Create');
+ await settle();
+
+ expect(del).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/tools/proof/ImportProofDialog.svelte b/frontend/src/tools/proof/ImportProofDialog.svelte
new file mode 100644
index 0000000..3c9b704
--- /dev/null
+++ b/frontend/src/tools/proof/ImportProofDialog.svelte
@@ -0,0 +1,1021 @@
+<script>
+ /**
+ * Import a geolocated post as a proof.
+ *
+ * One screen with three states, because they are the same work at different
+ * stages: a link to fetch, a form to check, an approval to give. Nothing this
+ * dialog does reaches the case until the last one — the downloads land in a
+ * staging directory the server sweeps, and closing the dialog discards it.
+ *
+ * The prefill never decides. A position read out of the post's text fills the
+ * field and says where it came from; the analyst's save is what confirms it,
+ * exactly as it is for coordinates they typed themselves.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import Modal from '../../components/Modal.svelte';
+ import { api } from '../../lib/api.js';
+ import { fileUrl } from '../../lib/fileUrl.js';
+ import { thisBrowser } from '../../lib/thisBrowser.js';
+ import { toast } from '../../lib/state.svelte.js';
+
+ let { caseId, onclose, oncreated } = $props();
+
+ // Same table the Media Library picker falls back to when an extractor hands
+ // back no poster frame.
+ const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };
+
+ // 'link' → nothing held yet; 'form' → a picture is staged and the fields are open.
+ let stage = $state('link');
+ let token = $state(null);
+ let postUrl = $state('');
+ let busy = $state(false);
+ let job = $state(null); // { slot, progress }
+ let picker = $state(null); // several attachments: pick before anything downloads
+ let authPrompt = $state(null); // a login wall, with the same answer Media offers
+
+ /** The pictures the proof composes, in the order they were published. A list because a
+ * post publishing a set published one proof of several panels. */
+ let panels = $state([]);
+ const panel = $derived(panels[0] ?? null);
+ /** The staged material, each entry stamped with the address it was fetched for. A
+ * thread states one point and hangs the photos and the clips it rests on off several
+ * posts, so this is a list and every row of the form owns its share of it. */
+ let sourceFiles = $state([]);
+ let post = $state(null); // what the platform said, and what its text states
+
+ // `pov` decides the verb the footage takes: ticked, it was recorded at the
+ // point; unticked, it shows it. The stronger of the two is a claim, so it is
+ // never pre-made — a post that says "point of view" still needs the click.
+ let form = $state({ title: '', coords: '', source_urls: [''], note: '', pov: false });
+ let coordsFrom = $state(''); // the substring a prefilled position was read from
+ let report = $state(null); // the preview, once asked for
+ /** Which of the two waits behind the Preview button is running: '' | 'source' |
+ * 'checking'. They differ by two orders of magnitude, so one word for both is a
+ * progress bar that lies. */
+ let phase = $state('');
+ /** One http(s) address and nothing else, which is what the Source field holds.
+ *
+ * Only decides whether to attempt the download: the reading that counts is the
+ * server's, and the preview blocks on it. Two addresses pasted with a space
+ * between them used to be posted to /fetch as one, refused there, and reported as
+ * a source that "was not downloaded" — a proof filed with no material. */
+ const ONE_ADDRESS = /^https?:\/\/\S+$/i;
+
+ /** The addresses a download has been attempted for, held or failed.
+ *
+ * Addresses rather than a flag, because the question is not "was something tried" but
+ * "was *this* tried". As a flag, retyping the address that had just been downloaded —
+ * or pressing the chip that already filled the box — threw away a held video and made
+ * the next Preview fetch it all over again. */
+ let sourceTried = $state([]);
+
+ /** What one row of the form holds: its files, and whether it was ever asked for. */
+ function sourceState(url) {
+ const address = url.trim();
+ const files = address ? sourceFiles.filter((one) => one.for_url === address) : [];
+ return { address, files, tried: !!address && sourceTried.includes(address) };
+ }
+
+ /** What the import is holding, in the order it is written: the picture the
+ * proof is composed of, then the footage it rests on. Both are on disk in the
+ * staging directory, so both can be looked at before anything is created —
+ * which is the point of downloading the source before the preview. */
+ const held = $derived(
+ [
+ ...panels.map((staged, at) => ({
+ slot: 'panel',
+ label: panels.length > 1 ? `Panel ${at + 1}` : 'Proof',
+ staged,
+ })),
+ ...sourceFiles.map((staged, at) => ({
+ slot: 'source',
+ label: sourceFiles.length > 1 ? `Source ${at + 1}` : 'Source media',
+ staged,
+ })),
+ ]
+ .filter((entry) => entry.staged)
+ .map((entry) => ({
+ ...entry,
+ url: token ? fileUrl(caseId, `media/.dl/${token}/${entry.staged.filename}`) : null,
+ }))
+ );
+ let shownIndex = $state(0);
+ // The footage arrives mid-dialog, so the index has to survive the list growing
+ // and shrinking rather than pointing past the end of it.
+ const shownAt = $derived(Math.min(shownIndex, Math.max(held.length - 1, 0)));
+ const shown = $derived(held[shownAt] ?? null);
+
+ function step(by) {
+ if (!held.length) return;
+ shownIndex = (shownAt + by + held.length) % held.length;
+ }
+
+ async function ensureToken() {
+ if (token) return token;
+ const started = await api.post(`/api/cases/${caseId}/proof-imports`);
+ token = started.token;
+ return token;
+ }
+
+ /** Poll one staging download to its end. Same shape as the Media Library's,
+ * and the same three answers: a picker, a login wall, or a held file. */
+ async function runJob(jobId, slot) {
+ job = { slot, progress: {} };
+ for (;;) {
+ const status = await api.get(`/api/jobs/${jobId}`);
+ job = { slot, progress: status.progress ?? {} };
+ if (status.status === 'running') {
+ await new Promise((resolve) => setTimeout(resolve, 700));
+ continue;
+ }
+ job = null;
+ if (status.status !== 'done') throw new Error(status.error || 'the download failed');
+ return status.result ?? {};
+ }
+ }
+
+ async function fetchInto(slot, url, { index = null, indexes = [], useCookies = false } = {}) {
+ const id = await ensureToken();
+ const { job_id } = await api.post(`/api/cases/${caseId}/proof-imports/${id}/fetch`, {
+ url,
+ slot,
+ index,
+ indexes,
+ use_cookies: useCookies,
+ });
+ const result = await runJob(job_id, slot);
+ if (result.multi) {
+ // What the slot can use arrives ticked, and unticking is the exception. The
+ // published picture is usually the whole point of the post; and an address typed
+ // into a source box was typed as material, so what hangs off it is material —
+ // a picture, a clip or a recording alike.
+ //
+ // `own` is the one thing that holds a file back from arriving ticked: the video
+ // extractor reads a post's media and the media of the post it quotes into one
+ // list, so past the first it cannot say whose a clip is. Everything is still
+ // listed — a quoted clip is sometimes exactly what is wanted — it is just not
+ // ticked by a rule. A picker that hides is a picker that lies.
+ const items = result.items ?? [];
+ picker = {
+ slot,
+ url,
+ items,
+ picked: items
+ .filter((item) => usable(slot, item.kind) && item.own !== false)
+ .map((item) => item.index),
+ };
+ return null;
+ }
+ if (result.needs_auth) {
+ // The tab this is running in *is* the analyst's browser, so it is the session
+ // being asked for. A guess, filling a select they can change.
+ authPrompt = { slot, url, browser: thisBrowser(), busy: false };
+ return null;
+ }
+ return result;
+ }
+
+ async function fetchPost() {
+ const url = postUrl.trim();
+ if (!url || busy) return;
+ busy = true;
+ try {
+ const result = await fetchInto('panel', url);
+ if (result) applyPost(result);
+ } catch (e) {
+ toast(e.message, 'danger', 6000);
+ } finally {
+ busy = false;
+ }
+ }
+
+ /** One place the footage lands, whatever route reached it: a plain download, a
+ * pick out of several attachments, or a retry behind a login. Each of those
+ * counts as the attempt the preview must not make a second time. */
+ function applySource(result, url) {
+ const address = url.trim();
+ const landed = (result.held ?? (result.staged ? [result.staged] : []))
+ .map((staged) => ({ ...staged, for_url: address }));
+ // Stamped here rather than read back off the answer: what a slot holds is keyed by
+ // address on the server, and a hand-attached file has no metadata to read it from.
+ sourceFiles = [...sourceFiles.filter((one) => one.for_url !== address), ...landed];
+ if (!sourceTried.includes(address)) sourceTried = [...sourceTried, address];
+ report = null;
+ }
+
+ /** An address that answered with nothing. Tried is what the preview must not repeat. */
+ function sourceFailed(url) {
+ const address = url.trim();
+ sourceFiles = sourceFiles.filter((one) => one.for_url !== address);
+ if (!sourceTried.includes(address)) sourceTried = [...sourceTried, address];
+ }
+
+ function setSource(at, value) {
+ form.source_urls = form.source_urls.map((one, i) => (i === at ? value : one));
+ report = null;
+ }
+
+ /** A box of its own per address, rather than a space between two of them: each one is
+ * fetched on its own, fails on its own and is attached by hand on its own, and one
+ * field could never show four states at once. */
+ function addSource(url = '') {
+ if (url && form.source_urls.some((one) => one.trim() === url)) return;
+ const rows = form.source_urls.filter((one) => one.trim());
+ form.source_urls = [...rows, url];
+ report = null;
+ }
+
+ function dropSource(at) {
+ const rows = form.source_urls.filter((_, i) => i !== at);
+ form.source_urls = rows.length ? rows : [''];
+ report = null;
+ }
+
+ function applyPost(result) {
+ panels = result.held ?? (result.staged ? [result.staged] : []);
+ post = result.post ?? null;
+ report = null;
+ const first = post?.coords?.[0];
+ if (first) {
+ form.coords = `${first.lat}, ${first.lon}`;
+ coordsFrom = first.text;
+ }
+ // The addresses the post's own text points at, all of them: a thread naming the
+ // photos and the clip names its material, and picking the first would be this
+ // dialog choosing for the analyst.
+ if (!form.source_urls.some((one) => one.trim())) {
+ form.source_urls = post?.urls?.length ? [...post.urls] : [''];
+ }
+ if (!form.title) form.title = (post?.title || '').slice(0, 60).trim();
+ stage = 'form';
+ }
+
+ async function attach(slot, file, sourceUrl = '') {
+ const id = await ensureToken();
+ const body = new FormData();
+ body.append('file', file);
+ body.append('slot', slot);
+ if (sourceUrl) body.append('source_url', sourceUrl);
+ return api.post(`/api/cases/${caseId}/proof-imports/${id}/attach`, body);
+ }
+
+ async function attachPicture(file) {
+ if (!file || busy) return;
+ busy = true;
+ try {
+ // Attaching replaces: "here is my picture instead" is what this route means, and a
+ // set built from a post is not something a hand-attached file adds to.
+ const result = await attach('panel', file, postUrl.trim());
+ panels = [result.staged];
+ report = null;
+ if (!form.title) form.title = file.name.replace(/\.[^.]+$/, '');
+ stage = 'form';
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function attachSourceFile(url, file) {
+ if (!file || busy) return;
+ busy = true;
+ try {
+ // For this address and no other: what the other rows hold stays where it is.
+ applySource(await attach('source', file, url.trim()), url);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ /** Download the footage the post points at.
+ *
+ * A failure here is information, not a stop: the address stays on the proof
+ * and the preview says the material is missing, which is the honest reading
+ * of a link that has been taken down.
+ */
+ async function downloadSource(url) {
+ const address = url.trim();
+ if (!address) return;
+ try {
+ const result = await fetchInto('source', address);
+ if (result) applySource(result, address);
+ } catch (e) {
+ toast(`${address} could not be downloaded: ${e.message}`, 'warn', 6000);
+ sourceFailed(address); // it was tried and it did not answer, which is the point
+ }
+ }
+
+ /** The source lands before the preview runs, so the preview reads bytes that
+ * are on disk instead of promising a download that has not happened. */
+ async function preview() {
+ if (busy) return;
+ busy = true;
+ try {
+ // Two different waits behind one button, and only one of them is short. Fetching
+ // the footage is a video off a platform — a walled one costs two refused attempts
+ // and a cookie store read before a single byte arrives — where the check itself is
+ // a tenth of a second. Saying "Checking…" through the first was the app claiming to
+ // be nearly done for minutes.
+ const pending = form.source_urls
+ .map((one) => one.trim())
+ .filter((one) => ONE_ADDRESS.test(one) && !sourceTried.includes(one));
+ if (pending.length) {
+ phase = 'source';
+ for (const url of pending) await downloadSource(url);
+ }
+ // A fetch that answered with a picker or a login wall settled nothing: the question
+ // is on screen and the slot is about to change under it. Reading the case behind it
+ // reported on a state nobody had agreed to yet — a picker cancelled left a preview
+ // standing that said "ready", and Create filed a proof whose source had never been
+ // downloaded. No report is the honest answer to an unanswered question.
+ if (picker || authPrompt) {
+ report = null;
+ return;
+ }
+ phase = 'checking';
+ report = await api.post(`/api/cases/${caseId}/proof-imports/${token}/preview`, { ...form });
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ phase = '';
+ busy = false;
+ }
+ }
+
+ async function create() {
+ if (busy || !report?.ready) return;
+ busy = true;
+ try {
+ const created = await api.post(
+ `/api/cases/${caseId}/proof-imports/${token}/commit`,
+ { ...form }
+ );
+ token = null; // the server dropped the staging directory
+ toast(`Imported as '${created.proof.name}'`, 'ok');
+ oncreated?.(created);
+ onclose?.();
+ } catch (e) {
+ toast(e.message, 'danger', 6000);
+ report = null;
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function retryWithBrowser() {
+ authPrompt.busy = true;
+ const { slot, url, browser } = authPrompt;
+ try {
+ await api.put('/api/settings/prefs', {
+ download_cookies: { source: 'browser', browser },
+ });
+ authPrompt = null;
+ busy = true;
+ const result = await fetchInto(slot, url, { useCookies: true });
+ if (result && slot === 'panel') applyPost(result);
+ else if (result) applySource(result, url);
+ } catch (e) {
+ toast(e.message, 'danger');
+ if (authPrompt) authPrompt.busy = false;
+ } finally {
+ busy = false;
+ }
+ }
+
+ //: What each slot has somewhere to put. A proof is composed of **pictures**: the
+ //: composer lays panels out on a canvas and a video has nothing to lay out, so a clip
+ //: ticked for the picture slot was a refusal waiting two screens away at the preview.
+ //: The material takes anything that was recorded — a still photographed on the spot is
+ //: material as much as the clip beside it.
+ const SLOT_KINDS = { panel: ['image'], source: ['image', 'video', 'audio'] };
+
+ function usable(slot, kind) {
+ return (SLOT_KINDS[slot] ?? []).includes(kind);
+ }
+
+ /**
+ * Take what was ticked, in the order it was ticked.
+ *
+ * **Both slots compose a set.** A post publishing a geolocation as three images
+ * published one proof, and keeping the first keeps a third of it; a post carrying two
+ * photos of the scene and the clip under them holds three things that were shot there,
+ * and keeping one leaves the rest of the case's own evidence outside it.
+ */
+ function tick(index) {
+ const item = picker.items.find((one) => one.index === index);
+ if (!item || !usable(picker.slot, item.kind)) return;
+ const held = picker.picked ?? [];
+ picker = {
+ ...picker,
+ picked: held.includes(index) ? held.filter((one) => one !== index) : [...held, index],
+ };
+ }
+
+ async function pick() {
+ const { slot, url, picked } = picker;
+ if (!picked?.length) return;
+ picker = null;
+ busy = true;
+ try {
+ const result = await fetchInto(slot, url, { index: picked[0], indexes: picked });
+ if (result && slot === 'panel') applyPost(result);
+ else if (result) applySource(result, url);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ /** Closing is cancelling: the held files go with it. */
+ async function close() {
+ if (busy) return;
+ const id = token;
+ token = null;
+ onclose?.();
+ if (id) {
+ try {
+ await api.del(`/api/cases/${caseId}/proof-imports/${id}`);
+ } catch {
+ /* the sweep will take it */
+ }
+ }
+ }
+
+ function onFormInput() {
+ report = null;
+ }
+
+ const canPreview = $derived(Boolean(panel && form.title.trim() && form.coords.trim()));
+</script>
+
+<Modal title="Import a proof" onclose={close} width={stage === 'link' ? '520px' : '860px'}>
+ {#if stage === 'link'}
+ <div class="import-start">
+ <label class="import-field">
+ <span>Post address</span>
+ <input
+ class="input"
+ bind:value={postUrl}
+ placeholder="https://…"
+ onkeydown={(e) => e.key === 'Enter' && fetchPost()}
+ />
+ <small>The picture is downloaded and the text is read for a position and a source.</small>
+ </label>
+ <div class="import-actions">
+ <button class="btn btn-primary" onclick={fetchPost} disabled={busy || !postUrl.trim()}>
+ <Icon name="download" size={14} />
+ {busy ? 'Fetching…' : 'Fetch'}
+ </button>
+ <label class="btn" class:disabled={busy}>
+ <Icon name="image" size={14} /> Use an image
+ <input
+ type="file"
+ accept="image/*"
+ hidden
+ onchange={(e) => attachPicture(e.currentTarget.files?.[0])}
+ />
+ </label>
+ </div>
+ {#if job}
+ <p class="import-progress">
+ Downloading{job.progress?.percent != null ? ` — ${job.progress.percent}%` : '…'}
+ </p>
+ {/if}
+ </div>
+ {:else}
+ <div class="import-body">
+ <div class="import-picture">
+ {#if shown}
+ <div class="import-view">
+ {#if shown.staged.kind === 'video'}
+ <!-- svelte-ignore a11y_media_has_caption -->
+ <video src={shown.url} controls preload="metadata"></video>
+ {:else if shown.staged.kind === 'image'}
+ <img src={shown.url} alt={shown.label} />
+ {:else}
+ <div class="import-view-plain">
+ <Icon name={KIND_ICONS[shown.staged.kind] ?? 'file'} size={28} />
+ <span>{shown.staged.kind}</span>
+ </div>
+ {/if}
+ </div>
+ {#if panels.length > 1}
+ <!-- What the proof will compose, in the order it will compose it. Not the
+ render — laying panels out is the composer's canvas — but the set, which
+ is the part an analyst is checking before they press Create. -->
+ <div class="import-strip" aria-label="The pictures this proof composes">
+ {#each held.filter((entry) => entry.slot === 'panel') as entry, at (entry.staged.filename)}
+ <button class="import-strip-one" class:on={held[shownAt] === entry}
+ title={entry.staged.filename} onclick={() => (shownIndex = at)}>
+ <img src={entry.url} alt={entry.label} />
+ </button>
+ {/each}
+ </div>
+ <p class="import-note">
+ One proof of {panels.length} panels, in this order.
+ </p>
+ {/if}
+ <div class="import-view-bar">
+ {#if held.length > 1}
+ <button class="btn btn-sm" onclick={() => step(-1)} aria-label="Previous file">
+ <Icon name="chevronLeft" size={14} />
+ </button>
+ {/if}
+ <p class="import-note">
+ <b>{shown.label}:</b>
+ {shown.staged.filename}
+ {#if held.length > 1}<span class="import-count">
+ {shownAt + 1}/{held.length}
+ </span>{/if}
+ </p>
+ {#if held.length > 1}
+ <button class="btn btn-sm" onclick={() => step(1)} aria-label="Next file">
+ <Icon name="chevronRight" size={14} />
+ </button>
+ {/if}
+ </div>
+ {/if}
+ </div>
+
+ <div class="import-form">
+ <label class="import-field">
+ <span>Name <b aria-hidden="true">*</b></span>
+ <input class="input" bind:value={form.title} oninput={onFormInput} maxlength="68" />
+ </label>
+
+ <label class="import-field">
+ <span>Coordinates <b aria-hidden="true">*</b></span>
+ <input
+ class="input"
+ bind:value={form.coords}
+ oninput={() => { coordsFrom = ''; onFormInput(); }}
+ placeholder="10.393313, -66.892504"
+ />
+ {#if coordsFrom}
+ <small class="import-read">Read from the post: {coordsFrom}</small>
+ {/if}
+ </label>
+
+ {#if post?.coords?.length > 1}
+ <div class="import-chips">
+ {#each post.coords as candidate (candidate.text)}
+ <button
+ class="btn btn-sm"
+ onclick={() => {
+ form.coords = `${candidate.lat}, ${candidate.lon}`;
+ coordsFrom = candidate.text;
+ report = null;
+ }}
+ >{candidate.text}</button>
+ {/each}
+ </div>
+ {/if}
+
+ <!-- One box per address, each with its own outcome underneath it. A proof read
+ from a thread rests on the post that published it, the photos beside it and
+ the clip under those, and every one of them is fetched on its own. -->
+ <div class="import-field">
+ <span>Source <b aria-hidden="true">*</b></span>
+ {#each form.source_urls as url, at (at)}
+ {@const state = sourceState(url)}
+ <div class="import-source-row">
+ <input
+ class="input"
+ value={url}
+ oninput={(e) => setSource(at, e.target.value)}
+ placeholder="https://…"
+ />
+ {#if form.source_urls.length > 1}
+ <button
+ class="import-source-drop"
+ title="Remove this source"
+ onclick={() => dropSource(at)}
+ >
+ <Icon name="x" size={13} />
+ </button>
+ {/if}
+ </div>
+ {#if state.files.length}
+ <div class="import-source-state">
+ <span class="badge ok">
+ {state.files.length > 1
+ ? `${state.files.length} files held`
+ : `Held: ${state.files[0].filename}`}
+ </span>
+ </div>
+ {:else if state.tried}
+ <div class="import-source-state">
+ <span class="badge danger">Not downloaded</span>
+ <label class="btn btn-sm">
+ Attach it
+ <input
+ type="file"
+ hidden
+ onchange={(e) => attachSourceFile(url, e.currentTarget.files?.[0])}
+ />
+ </label>
+ </div>
+ {/if}
+ {/each}
+ <button class="btn btn-sm import-source-add" onclick={() => addSource()}>
+ <Icon name="plus" size={12} />
+ Add a source
+ </button>
+ </div>
+
+ {#if post?.urls?.length}
+ <div class="import-chips">
+ {#each post.urls as url (url)}
+ <button class="btn btn-sm" onclick={() => addSource(url)}>{url}</button>
+ {/each}
+ </div>
+ {/if}
+
+ <label class="import-field">
+ <span>Note</span>
+ <input class="input" bind:value={form.note} oninput={onFormInput} maxlength="500" />
+ </label>
+
+ <label class="import-check">
+ <input type="checkbox" bind:checked={form.pov} onchange={onFormInput} />
+ <span>The camera was at this point</span>
+ </label>
+
+ {#if report}
+ <div class="import-report">
+ <h4>To be created</h4>
+ <ul>
+ <!-- Keyed on the position as well as the name: a duplicate key makes
+ Svelte throw, which blanks the whole report rather than showing a row
+ twice — the loudest possible failure for the quietest possible fault. -->
+ {#each report.entities as entity, at (entity.slot + at)}
+ <li>
+ <span class="import-kind">{entity.type}</span>
+ <span class="import-label">{entity.label}</span>
+ <span class="badge" class:info={entity.state === 'existing'}>
+ {entity.state === 'existing' ? 'reused' : 'new'}
+ </span>
+ {#if entity.detail}<small>{entity.detail}</small>{/if}
+ </li>
+ {/each}
+ </ul>
+ {#if report.links.length}
+ <h4>Links</h4>
+ <ul class="import-links">
+ {#each report.links as link, at (link.from + link.type + link.to + at)}
+ <li>{link.from} <b>{link.label}</b> {link.to}</li>
+ {/each}
+ </ul>
+ {/if}
+ {#each report.warnings as warning (warning.code + warning.text)}
+ <p class="import-warning">{warning.text}</p>
+ {/each}
+ {#each report.blocking as line (line)}
+ <p class="import-blocking">{line}</p>
+ {/each}
+ </div>
+ {/if}
+
+ <!-- Above the buttons, not under them: a wait of minutes rendered past the last
+ row of a modal is a wait nobody is told about. -->
+ {#if phase === 'source'}
+ <p class="import-progress">
+ {job?.progress?.percent != null
+ ? `Downloading the footage — ${job.progress.percent}%`
+ : 'Reaching the footage…'}
+ </p>
+ {/if}
+ <div class="import-actions">
+ <button class="btn" onclick={close} disabled={busy}>Cancel</button>
+ {#if report?.ready}
+ <button class="btn btn-primary" onclick={create} disabled={busy}>
+ {busy ? 'Creating…' : 'Create'}
+ </button>
+ {:else}
+ <button class="btn btn-primary" onclick={preview} disabled={busy || !canPreview}>
+ {phase === 'source' ? 'Downloading…' : phase ? 'Checking…' : 'Preview'}
+ </button>
+ {/if}
+ </div>
+ </div>
+ </div>
+ {/if}
+</Modal>
+
+<!-- Several attachments, nothing downloaded yet. Both slots take the ones ticked: a
+ post publishing a geolocation as a set publishes one proof, and a post carrying two
+ photos of the scene holds two things that were shot there. The extractor's own
+ poster frame is what makes the choice possible without fetching first. -->
+{#if picker}
+ <Modal
+ title={picker.slot === 'source' ? 'Choose the footage' : 'Choose the picture'}
+ onclose={() => (picker = null)}
+ width="600px"
+ >
+ <p class="import-note">
+ This link has {picker.items.length} attachments.
+ {#if picker.slot === 'panel'}
+ Ticked ones become the panels of one proof.
+ {:else}
+ Ticked ones become the material it rests on.
+ {/if}
+ {#if picker.items.some((item) => item.own === false)}
+ The video extractor also reports what a post quotes, so only the first is ticked.
+ {/if}
+ </p>
+ <ul class="import-picker">
+ {#each picker.items as item (item.index)}
+ <li>
+ <button class="import-pick" class:picked={picker.picked?.includes(item.index)}
+ class:unusable={!usable(picker.slot, item.kind)}
+ disabled={!usable(picker.slot, item.kind)}
+ title={usable(picker.slot, item.kind)
+ ? undefined
+ : 'A proof is composed of pictures'}
+ aria-pressed={picker.picked?.includes(item.index)}
+ onclick={() => tick(item.index)}>
+ <span class="import-pick-thumb">
+ {#if item.thumbnail}
+ <img src={item.thumbnail} alt="" loading="lazy" />
+ {:else}
+ <Icon name={KIND_ICONS[item.kind] ?? 'file'} size={22} />
+ {/if}
+ </span>
+ <span class="import-pick-title">{item.title}</span>
+ <span class="badge">{item.kind}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ <div class="modal-row">
+ <div class="spacer"></div>
+ <button class="btn" onclick={() => (picker = null)}>Cancel</button>
+ <button class="btn btn-primary" disabled={!picker.picked?.length} onclick={pick}>
+ {#if picker.picked?.length > 1}
+ {picker.slot === 'panel'
+ ? `Compose ${picker.picked.length} panels`
+ : `Take ${picker.picked.length} files`}
+ {:else}
+ Take it
+ {/if}
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+{#if authPrompt}
+ <Modal title="This link asks for a login" onclose={() => (authPrompt = null)} width="440px">
+ <p class="import-note">Retry with a browser session Azimut can read.</p>
+ <select class="input" bind:value={authPrompt.browser}>
+ {#each ['firefox', 'chrome', 'chromium', 'edge', 'brave'] as browser (browser)}
+ <option value={browser}>{browser}</option>
+ {/each}
+ </select>
+ <div class="import-actions">
+ <button class="btn" onclick={() => (authPrompt = null)}>Cancel</button>
+ <button class="btn btn-primary" onclick={retryWithBrowser} disabled={authPrompt.busy}>
+ Download signed in
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .import-start,
+ .import-form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .import-body {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ gap: 18px;
+ }
+ .import-view img,
+ .import-view video {
+ display: block;
+ width: 100%;
+ max-height: 420px;
+ object-fit: contain;
+ border-radius: 6px;
+ background: var(--bg-0);
+ }
+ .import-view-plain {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: 160px;
+ border-radius: 6px;
+ background: var(--bg-0);
+ color: var(--text-3);
+ font-size: 12px;
+ }
+ .import-view-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 6px;
+ }
+ .import-view-bar .import-note {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .import-count {
+ color: var(--text-3);
+ }
+ .import-field {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .import-field > span {
+ font-size: 12px;
+ color: var(--text-2);
+ }
+ .import-field b {
+ color: var(--danger);
+ }
+ .import-read {
+ color: var(--warn);
+ }
+ .import-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .import-chips .btn {
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .import-check {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 13px;
+ }
+ .import-source-state {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 22px;
+ }
+ .import-source-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .import-source-row .input { flex: 1; min-width: 0; }
+ .import-source-drop {
+ display: inline-flex;
+ color: var(--text-3);
+ padding: 3px;
+ border-radius: var(--r-sm);
+ }
+ .import-source-drop:hover { color: var(--danger); background: var(--bg-2); }
+ /* Discreet on purpose: one source is the ordinary case and the button must not read
+ as a step somebody skipped. */
+ .import-source-add {
+ align-self: flex-start;
+ gap: 5px;
+ color: var(--text-3);
+ background: none;
+ border: none;
+ padding: 2px 0;
+ }
+ .import-source-add:hover { color: var(--text-1); background: none; }
+ .import-report {
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ padding: 10px 12px;
+ }
+ .import-report h4 {
+ margin: 0 0 6px;
+ font-size: 12px;
+ color: var(--text-2);
+ }
+ .import-report ul {
+ list-style: none;
+ margin: 0 0 10px;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ font-size: 13px;
+ }
+ .import-report li {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ }
+ .import-kind {
+ color: var(--text-2);
+ min-width: 46px;
+ }
+ .import-label {
+ font-weight: 600;
+ }
+ .import-links b {
+ color: var(--accent);
+ font-weight: 600;
+ }
+ .import-warning {
+ margin: 6px 0 0;
+ color: var(--warn);
+ font-size: 13px;
+ }
+ .import-blocking {
+ margin: 6px 0 0;
+ color: var(--danger);
+ font-size: 13px;
+ }
+ .import-actions {
+ display: flex;
+ gap: 8px;
+ justify-content: flex-end;
+ }
+ .import-note,
+ .import-progress {
+ margin: 0;
+ font-size: 12px;
+ color: var(--text-2);
+ }
+ /* What is going in, told apart from what is merely there — a picker whose ticks are
+ invisible is a picker nobody can check before pressing. */
+ .import-pick.picked {
+ border-color: var(--accent);
+ background: color-mix(in srgb, var(--accent) 12%, transparent);
+ }
+ /* The set the proof composes, laid the way one row of panels is laid. A preview and
+ never the render: it says what is going in, not what it will look like. */
+ .import-strip { display: flex; gap: 6px; overflow-x: auto; padding: 6px 0 2px; }
+ .import-strip-one {
+ flex: none; height: 54px; padding: 0; border: 1px solid var(--border);
+ border-radius: var(--r-sm); overflow: hidden; background: none; cursor: pointer;
+ }
+ .import-strip-one.on { border-color: var(--accent); }
+ .import-strip-one img { height: 100%; width: auto; display: block; }
+ .import-picker {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .import-pick {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .import-pick:hover:not(:disabled) {
+ background: var(--bg-3);
+ border-color: var(--border-strong);
+ }
+ /* Shown and refused rather than hidden: a picker that hides is a picker that lies,
+ and "this post also carries a clip" is worth knowing while choosing. */
+ .import-pick.unusable { opacity: 0.45; cursor: not-allowed; }
+ .import-pick-thumb {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: 0 0 84px;
+ height: 56px;
+ overflow: hidden;
+ border-radius: 4px;
+ background: var(--bg-0);
+ color: var(--text-3);
+ }
+ .import-pick-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .import-pick-title {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 13px;
+ }
+</style>
diff --git a/frontend/src/tools/proof/NewProofDialog.svelte b/frontend/src/tools/proof/NewProofDialog.svelte
index 237fec0..13fb04a 100644
--- a/frontend/src/tools/proof/NewProofDialog.svelte
+++ b/frontend/src/tools/proof/NewProofDialog.svelte
@@ -19,6 +19,7 @@
caseId,
togglePanel,
requestCreation,
+ startImport,
close,
} = $props();
@@ -136,6 +137,16 @@
</fieldset>
<div class="new-proof-actions">
+ <!-- The third way into the tool, beside composing one and opening a saved
+ one: a proof somebody already published, brought in whole. -->
+ <button
+ type="button"
+ class="btn new-proof-import"
+ disabled={creating}
+ onclick={startImport}
+ >
+ <Icon name="download" size={15} /> Import a published proof
+ </button>
<button type="button" class="btn" disabled={creating} onclick={close}>Cancel</button>
<button type="submit" class="btn btn-primary" disabled={creating}>
<Icon name="plus" size={15} /> {creating ? 'Creating…' : 'Create proof'}
@@ -268,4 +279,5 @@
font-size: var(--fs-sm);
}
.new-proof-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
+ .new-proof-import { margin-right: auto; }
</style>
diff --git a/frontend/src/tools/proof/NewProofDialog.test.js b/frontend/src/tools/proof/NewProofDialog.test.js
index 7996b20..54a08f1 100644
--- a/frontend/src/tools/proof/NewProofDialog.test.js
+++ b/frontend/src/tools/proof/NewProofDialog.test.js
@@ -27,12 +27,21 @@ function props(overrides = {}) {
caseId: 'case-1',
togglePanel: vi.fn(),
requestCreation: vi.fn(),
+ startImport: vi.fn(),
close: vi.fn(),
...overrides,
};
}
describe('Create proof dialog', () => {
+ it('offers importing a published proof beside composing one', () => {
+ // The toolbar has no room for a seventh button, so this dialog is the door.
+ const { body } = render(NewProofDialog, { props: props() });
+
+ expect(body).toContain('Import a published proof');
+ expect(source).toContain('onclick={startImport}');
+ });
+
it('offers the same category chips as the Add-a-panel picker', () => {
const { body } = render(NewProofDialog, { props: props() });
diff --git a/frontend/src/tools/proof/ProofCanvas.svelte b/frontend/src/tools/proof/ProofCanvas.svelte
index 53e2f7e..a195741 100644
--- a/frontend/src/tools/proof/ProofCanvas.svelte
+++ b/frontend/src/tools/proof/ProofCanvas.svelte
@@ -17,8 +17,11 @@
<div class="canvas-wrap" class:drawing={tool !== 'select'}>
<div class="konva" bind:this={containerEl}></div>
{#if textEdit}
- <input
+ <!-- A textarea, because a label can be two lines: Konva draws the newline,
+ so the editor has to be able to hold one. -->
+ <textarea
class="text-edit"
+ rows={textEdit.value.split('\n').length}
style:left={`${textEdit.left}px`}
style:top={`${textEdit.top}px`}
style:font-size={`${textEdit.size}px`}
@@ -28,10 +31,14 @@
onblur={() => commitTextEdit(true)}
onkeydown={(event) => {
event.stopPropagation();
- if (event.key === 'Enter') commitTextEdit(true);
- else if (event.key === 'Escape') commitTextEdit(false);
+ // Shift+Enter opens a second line. Enter on its own still ends the edit,
+ // the way it did when this held one line only.
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ commitTextEdit(true);
+ } else if (event.key === 'Escape') commitTextEdit(false);
}}
- />
+ ></textarea>
{/if}
{#if !proofHasContent}
<div class="empty overlay-empty">
@@ -71,10 +78,17 @@
padding: 0 2px;
font-family: system-ui, sans-serif;
font-weight: 700;
+ line-height: 1.2;
background: rgba(14, 14, 14, 0.85);
border: 1px dashed var(--accent);
border-radius: 2px;
outline: none;
+ /* Grows with its lines instead of scrolling, and stays the size the label
+ will be: a drag handle in the corner would resize the editor, not the
+ text. */
+ resize: none;
+ overflow: hidden;
+ white-space: pre;
}
.overlay-empty {
position: absolute;
diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelte
index ebadb04..40edde2 100644
--- a/frontend/src/tools/proof/ProofLayersPanel.svelte
+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte
@@ -1,14 +1,23 @@
<script>
import Icon from '../../components/Icon.svelte';
+ import ProofGlyph from '../../components/ProofGlyph.svelte';
+ import { iconByName } from '../../lib/proofIcons.js';
import { fileUrl } from '../../lib/fileUrl.js';
let {
proof,
collapsed,
gonePanels,
- selectedPanelId = $bindable(),
- selectedPasteId = $bindable(),
- selectedId = $bindable(),
+ selectedPanelId,
+ selectedPasteId,
+ selectedIds,
+ // A drawing tool holds the handles back on the canvas, so the rows stop
+ // lighting up too: a pick shown in one column and absent from the other is
+ // a selection the analyst cannot act on.
+ selectionLive,
+ selectShape,
+ selectPanelRow,
+ selectPasteRow,
activeColor,
caseId,
scaleMin,
@@ -36,6 +45,11 @@
deleteShape,
markDirty,
} = $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];
</script>
<!-- Coloured border for a panel or a pasted image. Picking a colour adds one,
@@ -101,13 +115,13 @@
{#each proof.panels as panel, index (panel.id)}
<div
class="panel-row card"
- class:selected={selectedPanelId === panel.id}
+ class:selected={selectionLive && selectedPanelId === panel.id}
class:gone={gonePanels.includes(panel)}
>
<button
class="panel-thumb"
title="Select this panel on the canvas"
- onclick={() => (selectedPanelId = selectedPanelId === panel.id ? null : panel.id)}
+ onclick={() => selectPanelRow(panel.id)}
>
<img src={fileUrl(caseId, panel.src)} alt="" />
{#if proof.layout === 'free'}
@@ -181,11 +195,11 @@
<div class="none">Paste a screenshot with Ctrl+V. It stays in this proof only.</div>
{/if}
{#each proof.pastes as paste, index (paste.id)}
- <div class="panel-row paste-row card" class:selected={selectedPasteId === paste.id}>
+ <div class="panel-row paste-row card" class:selected={selectionLive && selectedPasteId === paste.id}>
<button
class="panel-thumb"
title="Select this overlay on the canvas"
- onclick={() => (selectedPasteId = selectedPasteId === paste.id ? null : paste.id)}
+ onclick={() => selectPasteRow(paste.id)}
>
<img src={paste.img?.src} alt="" />
<span class="row-badge" title="Z1 is the foreground">Z{index + 1}</span>
@@ -263,11 +277,11 @@
{#each proof.shapes as shape, index (shape.id)}
<div
class="shape-row"
- class:selected={selectedId === shape.id}
- onclick={() => (selectedId = shape.id)}
+ class:selected={selectionLive && selectedIds.includes(shape.id)}
+ onclick={(event) => selectShape(shape.id, event.shiftKey)}
role="button"
tabindex="0"
- onkeydown={(event) => event.key === 'Enter' && (selectedId = shape.id)}
+ onkeydown={(event) => event.key === 'Enter' && selectShape(shape.id, event.shiftKey)}
>
<div class="reorder">
<button
@@ -284,7 +298,11 @@
><Icon name="chevronDown" size={11} /></button>
</div>
<span class="chip" style:background={shape.color}></span>
- <Icon name={kindIcon[shape.kind]} size={13} />
+ {#if shape.kind === 'icon'}
+ <ProofGlyph name={shape.name} size={13} />
+ {:else}
+ <Icon name={kindIcon[shape.kind]} size={13} />
+ {/if}
{#if shape.kind === 'text'}
<input
class="input comment-input"
@@ -326,7 +344,7 @@
><Icon name="x" size={11} /></button>
{/if}
{:else}
- <span class="el-label">{kindLabel[shape.kind]} <span class="el-id">#{index + 1}</span></span>
+ <span class="el-label">{rowLabel(shape)} <span class="el-id">#{index + 1}</span></span>
{/if}
<button
class="btn btn-ghost btn-sm"
diff --git a/frontend/src/tools/proof/ProofLayersPanel.test.js b/frontend/src/tools/proof/ProofLayersPanel.test.js
index 80a3470..569985f 100644
--- a/frontend/src/tools/proof/ProofLayersPanel.test.js
+++ b/frontend/src/tools/proof/ProofLayersPanel.test.js
@@ -23,3 +23,22 @@ describe('Proof Layers panel hierarchy', () => {
expect(source).not.toContain('btn-primary btn-sm side-add');
});
});
+
+describe('the rows and the canvas agree about what is picked', () => {
+ it('lights a row only while the pick can be acted on', () => {
+ // With a drawing tool in hand the canvas shows no handles and Delete reaches
+ // nothing, so a row lit orange was a selection visible in one column and
+ // absent from the other.
+ expect(source).toContain('class:selected={selectionLive && selectedPanelId === panel.id}');
+ expect(source).toContain('class:selected={selectionLive && selectedPasteId === paste.id}');
+ expect(source).toContain('class:selected={selectionLive && selectedIds.includes(shape.id)}');
+ });
+
+ it('hands a pick back to the composer instead of writing it in place', () => {
+ // Writing selectedPanelId straight through the binding skipped the switch
+ // back to Select that makes the pick answer to anything.
+ expect(source).toContain('onclick={() => selectPanelRow(panel.id)}');
+ expect(source).toContain('onclick={() => selectPasteRow(paste.id)}');
+ expect(source).not.toContain('$bindable');
+ });
+});
diff --git a/frontend/src/tools/proof/ProofToolbar.svelte b/frontend/src/tools/proof/ProofToolbar.svelte
index 62723a2..240509d 100644
--- a/frontend/src/tools/proof/ProofToolbar.svelte
+++ b/frontend/src/tools/proof/ProofToolbar.svelte
@@ -1,5 +1,8 @@
<script>
import Icon from '../../components/Icon.svelte';
+ import ProofGlyph from '../../components/ProofGlyph.svelte';
+ import { PROOF_ICONS } from '../../lib/proofIcons.js';
+ import { canFill, fillPaint } from '../../lib/proofEdits.js';
let {
canUndo,
@@ -10,10 +13,19 @@
tool = $bindable(),
palette,
activeColor,
+ activeFill,
selectedShape,
+ selectedCount,
+ fillableSelection,
+ // A silhouette has no outline, so the width control is hidden for it. Any
+ // caller that says nothing gets the control.
+ showStroke = true,
+ iconName = PROOF_ICONS[0].name,
+ setIconName = () => {},
strokeW,
setColor,
setStroke,
+ setFill,
fit,
layout,
setLayoutMode,
@@ -23,36 +35,51 @@
applyMagic,
} = $props();
- // Colour + size only matter while drawing or when a shape is selected. When
+ // Colour + size only matter while drawing or when something is selected. When
// the analyst is just panning with Select, they stay hidden so the column
// packs short enough to fit small screens without spilling controls off the
- // bottom.
- const showContextTools = $derived(tool !== 'select' || !!selectedShape);
+ // bottom. `selectedShape` is the one picked annotation and is null for a
+ // family of them, so what is on screen answers to the count.
+ const showContextTools = $derived(tool !== 'select' || selectedCount > 0);
const sizeValue = $derived(
selectedShape?.kind === 'text'
? (selectedShape.fontSize ?? 28)
: (selectedShape?.strokeWidth ?? strokeW),
);
+ // Only the closed kinds hold a fill, so the control follows the box/ellipse
+ // tool — or the box/ellipse in hand.
+ const showFill = $derived(selectedCount > 0 ? fillableSelection : canFill(tool));
+ const fillPercent = $derived(Math.round((activeFill ?? 0) * 100));
// Flyouts: one open at a time. Content stays in the DOM (hidden via CSS) so
// it renders on the server and can be tested; opening just reveals it.
let colorOpen = $state(false);
let sizeOpen = $state(false);
+ let fillOpen = $state(false);
+ let iconOpen = $state(false);
let overflowOpen = $state(false);
// Wrapper refs feed outside-click detection; button refs anchor the flyout.
let colorEl = $state();
let sizeEl = $state();
+ let fillEl = $state();
+ let iconEl = $state();
let overflowEl = $state();
let colorBtn = $state();
let sizeBtn = $state();
+ let fillBtn = $state();
+ let iconBtn = $state();
let overflowBtn = $state();
let colorPos = $state({});
let sizePos = $state({});
+ let fillPos = $state({});
+ let iconPos = $state({});
let overflowPos = $state({});
function toggle(which) {
colorOpen = which === 'color' ? !colorOpen : false;
sizeOpen = which === 'size' ? !sizeOpen : false;
+ fillOpen = which === 'fill' ? !fillOpen : false;
+ iconOpen = which === 'icon' ? !iconOpen : false;
overflowOpen = which === 'overflow' ? !overflowOpen : false;
}
@@ -63,6 +90,7 @@
colorOpen = false;
sizeOpen = false;
}
+ if (!showFill) fillOpen = false;
});
// Flyouts are position:fixed so the toolbar can scroll (overflow-y) without
@@ -83,21 +111,29 @@
$effect(() => {
if (sizeOpen && sizeBtn) sizePos = anchor(sizeBtn);
});
+ $effect(() => {
+ if (fillOpen && fillBtn) fillPos = anchor(fillBtn);
+ });
+ $effect(() => {
+ if (iconOpen && iconBtn) iconPos = anchor(iconBtn);
+ });
$effect(() => {
if (overflowOpen && overflowBtn) overflowPos = anchor(overflowBtn);
});
// Close on outside click (mousedown capture, like Satellite.svelte) or Escape.
$effect(() => {
- if (!colorOpen && !sizeOpen && !overflowOpen) return;
+ if (!colorOpen && !sizeOpen && !fillOpen && !iconOpen && !overflowOpen) return;
const onDown = (e) => {
if (colorOpen && colorEl && !colorEl.contains(e.target)) colorOpen = false;
if (sizeOpen && sizeEl && !sizeEl.contains(e.target)) sizeOpen = false;
+ if (fillOpen && fillEl && !fillEl.contains(e.target)) fillOpen = false;
+ if (iconOpen && iconEl && !iconEl.contains(e.target)) iconOpen = false;
if (overflowOpen && overflowEl && !overflowEl.contains(e.target)) overflowOpen = false;
};
const onKey = (e) => {
if (e.key === 'Escape') {
- colorOpen = sizeOpen = overflowOpen = false;
+ colorOpen = sizeOpen = fillOpen = iconOpen = overflowOpen = false;
}
};
document.addEventListener('mousedown', onDown, true);
@@ -127,6 +163,40 @@
<Icon name={entry.icon} size={18} />
</button>
{/each}
+ <!-- Symbols: a grid of stamps. The button takes the tool like every other
+ button on this rail — and like the `s` its own tooltip promises — then
+ opens the grid, so re-picking a glyph already chosen is never the price of
+ coming back to the stamp. Lit by the tool in hand, not by the open grid. -->
+ <div class="tb-group" bind:this={iconEl}>
+ <button
+ class="tb-btn"
+ class:active={tool === 'icon'}
+ title="Symbol (s)"
+ onclick={() => { tool = 'icon'; toggle('icon'); }}
+ bind:this={iconBtn}
+ >
+ <ProofGlyph name={iconName} size={18} />
+ </button>
+ <div
+ class="flyout flyout-icons"
+ class:open={iconOpen}
+ style:left={iconPos.left}
+ style:top={iconPos.top}
+ style:bottom={iconPos.bottom}
+ >
+ {#each PROOF_ICONS as entry (entry.name)}
+ <button
+ class="icon-btn"
+ class:active={iconName === entry.name}
+ title={entry.label}
+ aria-label={entry.label}
+ onclick={() => { setIconName(entry.name); iconOpen = false; }}
+ >
+ <ProofGlyph name={entry.name} size={20} />
+ </button>
+ {/each}
+ </div>
+ </div>
<div class="tb-sep"></div>
<button class="tb-btn" title="Fit view (f)" onclick={fit}>
<Icon name="eye" size={18} />
@@ -181,6 +251,7 @@
</div>
<!-- Size: a horizontal slider for stroke width / font size. -->
+ {#if showStroke}
<div class="tb-group" bind:this={sizeEl}>
<button
class="tb-btn tb-size"
@@ -209,14 +280,47 @@
? (selectedShape.fontSize ?? 28)
: (selectedShape?.strokeWidth ?? strokeW)}
oninput={(event) => setStroke(+event.target.value)}
- title={selectedShape?.kind === 'text'
- ? 'Font size'
- : selectedShape
- ? 'Stroke width (selected)'
- : 'Stroke width'}
+ aria-label={selectedShape?.kind === 'text' ? 'font size' : 'stroke width'}
/>
</div>
</div>
+ {/if}
+
+ <!-- Fill: how much of the shape's own colour lands inside it. -->
+ {#if showFill}
+ <div class="tb-group" bind:this={fillEl}>
+ <button
+ class="tb-btn tb-size"
+ class:active={fillOpen}
+ title="Fill"
+ onclick={() => toggle('fill')}
+ bind:this={fillBtn}
+ >
+ <span class="tb-fill" style:background={fillPaint(activeColor, activeFill) ?? 'transparent'}
+ ></span>
+ <span class="tb-size-val">{fillPercent}</span>
+ </button>
+ <div
+ class="flyout flyout-size"
+ class:open={fillOpen}
+ style:left={fillPos.left}
+ style:top={fillPos.top}
+ style:bottom={fillPos.bottom}
+ >
+ <input
+ class="fill-slider"
+ type="range"
+ min="0"
+ max="100"
+ step="5"
+ value={fillPercent}
+ oninput={(event) => setFill(+event.target.value / 100)}
+ title="Fill opacity"
+ aria-label="fill opacity"
+ />
+ </div>
+ </div>
+ {/if}
{/if}
<div class="tb-sep"></div>
@@ -332,6 +436,14 @@
border-radius: 50%;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.25);
}
+ /* A hollow square that fills up as the opacity rises, so the button shows
+ the state it sets. Empty at 0, which is where every shape starts. */
+ .tb-fill {
+ width: 18px;
+ height: 18px;
+ border-radius: 3px;
+ box-shadow: inset 0 0 0 1.5px var(--text-3);
+ }
.tb-group { display: contents; }
@@ -353,6 +465,35 @@
align-items: center;
}
.flyout-size { align-items: center; }
+ .flyout-icons {
+ flex-wrap: wrap;
+ gap: 4px;
+ width: 168px;
+ align-items: center;
+ }
+
+ .icon-btn {
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid transparent;
+ border-radius: var(--r-sm, 5px);
+ color: var(--text-2);
+ background: transparent;
+ cursor: pointer;
+ transition: border-color 0.12s var(--ease), color 0.12s var(--ease);
+ }
+ .icon-btn:hover { border-color: var(--border); color: var(--text-1); }
+ .icon-btn.active {
+ border-color: var(--accent);
+ /* --accent-text is ink for sitting ON the accent, not a foreground: on a
+ transparent button it is near-black, which in the dark theme is invisible.
+ Active follows .tb-btn.active instead — full-strength text, raised back. */
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
.flyout-overflow { flex-direction: column; gap: 6px; }
.flyout-row { display: flex; gap: 6px; }
@@ -384,7 +525,8 @@
opacity: 0;
cursor: pointer;
}
- .stroke-slider {
+ .stroke-slider,
+ .fill-slider {
width: 140px;
accent-color: var(--accent);
}
diff --git a/frontend/src/tools/proof/ProofToolbar.test.js b/frontend/src/tools/proof/ProofToolbar.test.js
index a577645..fabdb49 100644
--- a/frontend/src/tools/proof/ProofToolbar.test.js
+++ b/frontend/src/tools/proof/ProofToolbar.test.js
@@ -1,15 +1,23 @@
import { describe, expect, it, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
import { render } from 'svelte/server';
import ProofToolbar from './ProofToolbar.svelte';
+import { PROOF_ICONS, iconByName } from '../../lib/proofIcons.js';
const DRAW_TOOLS = [
- { id: 'select', icon: 'hand', label: 'Select / move', shortcut: 'v' },
+ { id: 'select', icon: 'cursor', label: 'Select / move', shortcut: 'v' },
{ id: 'rect', icon: 'square', label: 'Box', shortcut: 'r' },
{ id: 'text', icon: 'text', label: 'Text', shortcut: 't' },
];
+// The composer hands the toolbar a count and a fill-ability read off the whole
+// picked family; `selectedShape` is only the one when exactly one is picked.
+// Mirror that here so a test naming a shape does not have to spell out both.
function props(overrides = {}) {
+ const shape = 'selectedShape' in overrides ? overrides.selectedShape : null;
return {
+ selectedCount: shape ? 1 : 0,
+ fillableSelection: ['rect', 'ellipse'].includes(shape?.kind),
canUndo: true,
canRedo: true,
undo: vi.fn(),
@@ -18,10 +26,12 @@ function props(overrides = {}) {
tool: 'rect',
palette: ['#ff5252', '#40c4ff'],
activeColor: '#ff5252',
+ activeFill: 0,
selectedShape: null,
strokeW: 4,
setColor: vi.fn(),
setStroke: vi.fn(),
+ setFill: vi.fn(),
fit: vi.fn(),
layout: 'grid',
setLayoutMode: vi.fn(),
@@ -77,6 +87,49 @@ describe('ProofToolbar context controls (colour + size)', () => {
});
});
+describe('ProofToolbar fill control', () => {
+ it('follows the box tool, and stays out for the kinds that cannot hold a fill', () => {
+ expect(render(ProofToolbar, { props: props({ tool: 'rect' }) }).body)
+ .toContain('aria-label="fill opacity"');
+ expect(render(ProofToolbar, { props: props({ tool: 'line' }) }).body)
+ .not.toContain('aria-label="fill opacity"');
+ expect(render(ProofToolbar, { props: props({ tool: 'text' }) }).body)
+ .not.toContain('aria-label="fill opacity"');
+ });
+
+ it('follows the selected shape under Select rather than the tool', () => {
+ const { body } = render(ProofToolbar, {
+ props: props({ tool: 'select', selectedShape: { kind: 'ellipse', fillOpacity: 0.4 } }),
+ });
+ expect(body).toContain('aria-label="fill opacity"');
+ });
+
+ it('reads zero until a fill is asked for, and shows the share once it is', () => {
+ expect(render(ProofToolbar, { props: props({ tool: 'rect', activeFill: 0 }) }).body)
+ .toMatch(/tb-size-val[^"]*">0</);
+ const filled = render(ProofToolbar, { props: props({ tool: 'rect', activeFill: 0.35 }) }).body;
+ expect(filled).toMatch(/tb-size-val[^"]*">35</);
+ expect(filled).toContain('rgba(255, 82, 82, 0.35)');
+ });
+});
+
+describe('ProofToolbar with a family of shapes picked', () => {
+ const family = { tool: 'select', selectedShape: null, selectedCount: 3 };
+
+ it('keeps colour and size on show, though no single shape answers for them', () => {
+ const { body } = render(ProofToolbar, { props: props({ ...family }) });
+ expect(body).toContain('aria-label="color #ff5252"');
+ expect(body).toContain('stroke-slider');
+ });
+
+ it('offers the fill when any of them can hold one, and not otherwise', () => {
+ expect(render(ProofToolbar, { props: props({ ...family, fillableSelection: true }) }).body)
+ .toContain('aria-label="fill opacity"');
+ expect(render(ProofToolbar, { props: props({ ...family, fillableSelection: false }) }).body)
+ .not.toContain('aria-label="fill opacity"');
+ });
+});
+
describe('ProofToolbar document controls (overflow flyout)', () => {
it('carries layout modes, tweet guides and the magic repack action', () => {
const { body } = render(ProofToolbar, { props: props() });
@@ -92,3 +145,72 @@ describe('ProofToolbar document controls (overflow flyout)', () => {
expect(body).toMatch(/title="Repack panels[^"]*"[^>]*disabled/);
});
});
+
+describe('the symbol picker', () => {
+ it('offers every symbol in the set, each named', () => {
+ const { body } = render(ProofToolbar, { props: props() });
+
+ for (const entry of PROOF_ICONS) expect(body).toContain(`aria-label="${entry.label}"`);
+ expect(body).toContain('flyout-icons');
+ });
+
+ it('shows the symbol in hand on the button that opens the grid', () => {
+ const { body } = render(ProofToolbar, { props: props({ iconName: 'tank' }) });
+ const button = body.slice(body.indexOf('title="Symbol (s)"'));
+
+ expect(button).toContain(iconByName('tank').path);
+ });
+
+ it('lights the button while the stamp is the active tool', () => {
+ const idle = render(ProofToolbar, { props: props({ tool: 'rect' }) }).body;
+ const armed = render(ProofToolbar, { props: props({ tool: 'icon' }) }).body;
+ const buttonOf = (body) => body.slice(body.indexOf('title="Symbol (s)"') - 120, body.indexOf('title="Symbol (s)"'));
+
+ expect(buttonOf(idle)).not.toContain('active');
+ expect(buttonOf(armed)).toContain('active');
+ });
+
+ it('keeps the stroke control away from a symbol that has no outline', () => {
+ // a solid silhouette takes a colour and nothing else — a width slider that
+ // moved nothing would be a control lying about what it does
+ expect(render(ProofToolbar, { props: props({ showStroke: false }) }).body)
+ .not.toContain('stroke-slider');
+ expect(render(ProofToolbar, { props: props() }).body).toContain('stroke-slider');
+ });
+
+ it('offers the fill that becomes a symbol’s badge while stamping', () => {
+ expect(render(ProofToolbar, { props: props({ tool: 'icon' }) }).body)
+ .toContain('fill-slider');
+ });
+});
+
+describe('the symbol picker reads in both themes', () => {
+ const css = readFileSync(new URL('./ProofToolbar.svelte', import.meta.url), 'utf8');
+
+ it('never paints a glyph with the ink meant for sitting on the accent', () => {
+ // --accent-text is near-black in both themes: as a foreground on a
+ // transparent button it disappears the moment the theme goes dark
+ const rule = css
+ .slice(css.indexOf('.icon-btn.active'), css.indexOf('}', css.indexOf('.icon-btn.active')))
+ .replace(/\/\*[\s\S]*?\*\//g, ''); // the declarations, not the note explaining them
+
+ expect(rule).not.toContain('--accent-text');
+ expect(rule).toContain('var(--text-1)');
+ });
+});
+
+describe('the symbol button', () => {
+ const src = readFileSync(new URL('./ProofToolbar.svelte', import.meta.url), 'utf8');
+
+ 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
+ });
+
+ it('is lit by the tool in hand, not by the grid being open', () => {
+ expect(src).toContain("class:active={tool === 'icon'}");
+ expect(src).not.toContain("class:active={tool === 'icon' || iconOpen}");
+ });
+});
diff --git a/frontend/src/tools/proof/canvasLifecycle.js b/frontend/src/tools/proof/canvasLifecycle.js
index 54cb2f4..0465375 100644
--- a/frontend/src/tools/proof/canvasLifecycle.js
+++ b/frontend/src/tools/proof/canvasLifecycle.js
@@ -73,3 +73,17 @@ export function createCanvasRenderGate(schedule, cancel, { rebuild, refreshUi })
},
};
}
+
+/**
+ * Drop a draft that is still in hand.
+ *
+ * A tool can change under an unreleased pointer — Escape, a letter shortcut —
+ * and the release then belongs to whichever tool is current, which may well
+ * return before reaching the code that settles the draft. What is left is a
+ * Konva node still tracking the pointer that nothing can commit or destroy.
+ * Callers assign the result back: it is always null.
+ */
+export function discardDraft(draft) {
+ draft?.node?.destroy?.();
+ return null;
+}
diff --git a/frontend/src/tools/proof/canvasLifecycle.test.js b/frontend/src/tools/proof/canvasLifecycle.test.js
new file mode 100644
index 0000000..c911dde
--- /dev/null
+++ b/frontend/src/tools/proof/canvasLifecycle.test.js
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import { createCanvasRenderGate } from './canvasLifecycle.js';
+
+describe('createCanvasRenderGate', () => {
+ /** Runs the scheduled callback by hand, standing in for the frame. */
+ function gateHarness() {
+ const calls = { rebuild: 0, refreshUi: 0 };
+ let pending = null;
+ const gate = createCanvasRenderGate(
+ (fn) => {
+ pending = fn;
+ return 1;
+ },
+ () => {
+ pending = null;
+ },
+ {
+ rebuild: () => { calls.rebuild += 1; },
+ refreshUi: () => { calls.refreshUi += 1; },
+ },
+ );
+ return { gate, calls, frame: () => { const fn = pending; pending = null; fn?.(); } };
+ }
+
+ it('holds a rebuild until the gesture settles', () => {
+ const { gate, calls, frame } = gateHarness();
+ gate.beginPointer();
+ gate.requestRebuild();
+ frame();
+ expect(calls.rebuild).toBe(0);
+
+ gate.endPointer();
+ frame();
+ expect(calls.rebuild).toBe(1);
+ });
+
+ it('folds a pending ui refresh into the rebuild that supersedes it', () => {
+ const { gate, calls, frame } = gateHarness();
+ gate.requestUi();
+ gate.requestRebuild();
+ frame();
+ expect(calls).toEqual({ rebuild: 1, refreshUi: 0 });
+ });
+
+ it('refreshes the ui on its own when no rebuild is due', () => {
+ const { gate, calls, frame } = gateHarness();
+ gate.requestUi();
+ frame();
+ expect(calls).toEqual({ rebuild: 0, refreshUi: 1 });
+ });
+
+ it('keeps a request made during a gesture that its frame arrived inside of', () => {
+ const { gate, calls, frame } = gateHarness();
+ gate.requestRebuild();
+ gate.beginPointer(); // the press lands before the frame does
+ frame();
+ expect(calls.rebuild).toBe(0);
+
+ gate.endPointer();
+ frame();
+ expect(calls.rebuild).toBe(1);
+ });
+});
diff --git a/frontend/src/tools/satellite/PlaceSearch.svelte b/frontend/src/tools/satellite/PlaceSearch.svelte
new file mode 100644
index 0000000..5c1aedc
--- /dev/null
+++ b/frontend/src/tools/satellite/PlaceSearch.svelte
@@ -0,0 +1,284 @@
+<script>
+ /**
+ * The Satellite search bar: type, and the matches come to you.
+ *
+ * Three of the four sources answer on the keystroke — saved work already in
+ * memory, and one localhost call that parses coordinates and reads the
+ * bundled city gazetteer. The fourth is the geocoder, which forbids being
+ * asked on every letter, so it is asked once typing stops and its matches
+ * arrive underneath the rest.
+ *
+ * Pressing Enter without choosing a row still does exactly what the plain box
+ * did before this list existed: hand the text over to be parsed or geocoded.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import { api } from '../../lib/api.js';
+ import {
+ REMOTE_MIN_CHARS,
+ buildGroups,
+ flatten,
+ matchSaved,
+ pushRecent,
+ readRecents,
+ step,
+ } from '../../lib/satSuggest.js';
+
+ let {
+ value = $bindable(''),
+ savedRows = [],
+ centre = null,
+ units = 'metric',
+ searching = false,
+ onpick,
+ onsubmit,
+ } = $props();
+
+ // Long enough that a fast typist makes one call per word, short enough that a
+ // pause between words already shows the list.
+ const LOCAL_DELAY = 120;
+ // The geocoder's floor is one request a second; this keeps a typist under it
+ // without a fixed queue, and the server drops what it cannot pace anyway.
+ const REMOTE_DELAY = 650;
+
+ let open = $state(false);
+ let at = $state(-1); // highlighted row, -1 for none
+ let coords = $state(null);
+ let cities = $state([]);
+ let places = $state([]);
+ let recents = $state(readRecents());
+ let boxEl = $state(null);
+ let localTimer;
+ let remoteTimer;
+ // Every request carries the query it was made for; a late answer to an older
+ // query is dropped rather than shown under a newer one.
+ let localFor = '';
+ let remoteFor = '';
+
+ const groups = $derived(
+ buildGroups({
+ query: value,
+ coords,
+ saved: matchSaved(savedRows, value),
+ cities,
+ places,
+ recents,
+ centre,
+ units,
+ })
+ );
+ const rows = $derived(flatten(groups));
+
+ function schedule(text) {
+ clearTimeout(localTimer);
+ clearTimeout(remoteTimer);
+ const query = text.trim();
+ if (!query) {
+ coords = null;
+ cities = [];
+ places = [];
+ localFor = remoteFor = '';
+ return;
+ }
+ // A query that grows keeps the previous places on screen until better ones
+ // land — a list that empties itself on every letter is unreadable.
+ localTimer = setTimeout(() => askLocal(query), LOCAL_DELAY);
+ if (query.length >= REMOTE_MIN_CHARS) {
+ remoteTimer = setTimeout(() => askRemote(query), REMOTE_DELAY);
+ } else {
+ places = [];
+ }
+ }
+
+ async function askLocal(query) {
+ localFor = query;
+ try {
+ const body = await api.get(`/api/geo/suggest?q=${encodeURIComponent(query)}`);
+ if (localFor !== query) return;
+ coords = body.coords;
+ cities = body.cities ?? [];
+ } catch {
+ /* the bar still works without suggestions */
+ }
+ }
+
+ async function askRemote(query) {
+ remoteFor = query;
+ try {
+ const body = await api.get(`/api/geo/places?q=${encodeURIComponent(query)}&limit=5`);
+ if (remoteFor !== query) return;
+ // `busy` means the request was dropped rather than queued: keep whatever
+ // is on screen instead of blanking the group.
+ if (!body.busy) places = body.places ?? [];
+ } catch {
+ /* offline, or nothing there — the local groups stand on their own */
+ }
+ }
+
+ function oninput(event) {
+ value = event.currentTarget.value;
+ at = -1;
+ open = true;
+ schedule(value);
+ }
+
+ function choose(item) {
+ open = false;
+ at = -1;
+ recents = pushRecent(item);
+ onpick(item);
+ }
+
+ function onkeydown(event) {
+ if (event.key === 'Escape') {
+ open = false;
+ at = -1;
+ return;
+ }
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ if (!open) open = true;
+ event.preventDefault();
+ at = step(at, event.key === 'ArrowDown' ? 1 : -1, rows.length);
+ return;
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ if (at >= 0 && rows[at]) choose(rows[at]);
+ else {
+ open = false;
+ onsubmit(value);
+ }
+ }
+ }
+
+ function onWindowPointerDown(event) {
+ if (open && !boxEl?.contains(event.target)) open = false;
+ }
+</script>
+
+<svelte:window onpointerdown={onWindowPointerDown} />
+
+<div class="place-search" bind:this={boxEl}>
+ <div class="field">
+ <input
+ class="input"
+ role="combobox"
+ aria-expanded={open && rows.length > 0}
+ aria-controls="sat-suggestions"
+ aria-autocomplete="list"
+ aria-activedescendant={at >= 0 && rows[at] ? `sat-suggestion-${at}` : undefined}
+ autocomplete="off"
+ aria-label="Search a place or coordinates"
+ placeholder={'A place, or 50.4501, 30.5234'}
+ title="A place name, or coordinates (decimal, DMS, MGRS, plus code)"
+ {value}
+ {oninput}
+ {onkeydown}
+ onfocus={() => (open = true)}
+ onclick={() => (open = true)}
+ />
+ <button
+ type="button"
+ class="btn"
+ disabled={!value.trim() || searching}
+ onclick={() => onsubmit(value)}
+ >
+ <Icon name="search" size={15} /> {searching ? '…' : 'Go'}
+ </button>
+ </div>
+
+ {#if open && groups.length}
+ <div class="menu card" id="sat-suggestions" role="listbox" aria-label="Matches">
+ {#each groups as group (group.id)}
+ <p class="head">{group.label}</p>
+ {#each group.items as item (item.key)}
+ {@const index = rows.indexOf(item)}
+ <button
+ type="button"
+ class="row"
+ class:on={index === at}
+ id={`sat-suggestion-${index}`}
+ role="option"
+ aria-selected={index === at}
+ onmouseenter={() => (at = index)}
+ onclick={() => choose(item)}
+ >
+ <span class="name">{item.label}</span>
+ {#if item.detail}<span class="detail">{item.detail}</span>{/if}
+ {#if item.away}<span class="away">{item.away}</span>{/if}
+ </button>
+ {/each}
+ {/each}
+ {#if groups.some((group) => group.id === 'cities')}
+ <p class="credit">Cities from GeoNames, CC BY 4.0</p>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .place-search {
+ position: relative;
+ width: min(420px, 36vw);
+ }
+ .field {
+ display: flex;
+ gap: 8px;
+ }
+ .menu {
+ position: absolute;
+ z-index: 1200;
+ top: calc(100% + 4px);
+ left: 0;
+ right: 0;
+ max-height: min(52vh, 420px);
+ overflow-y: auto;
+ padding: 4px;
+ }
+ .head {
+ padding: 6px 8px 3px;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-3);
+ }
+ .row {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ width: 100%;
+ padding: 5px 8px;
+ border-radius: var(--r-sm);
+ text-align: left;
+ cursor: pointer;
+ }
+ .row.on {
+ background: var(--bg-3);
+ }
+ /* not `.label`: the global one is a form label, uppercase and block */
+ .name {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ white-space: nowrap;
+ }
+ .detail {
+ flex: 1;
+ min-width: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .credit {
+ padding: 6px 8px 3px;
+ border-top: 1px solid var(--border);
+ margin-top: 4px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .away {
+ flex-shrink: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ font-variant-numeric: tabular-nums;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/PlaceSearch.test.js b/frontend/src/tools/satellite/PlaceSearch.test.js
new file mode 100644
index 0000000..9ac3f09
--- /dev/null
+++ b/frontend/src/tools/satellite/PlaceSearch.test.js
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import { render } from 'svelte/server';
+import { readFileSync } from 'node:fs';
+import PlaceSearch from './PlaceSearch.svelte';
+
+const source = readFileSync(new URL('./PlaceSearch.svelte', import.meta.url), 'utf8');
+
+const props = { value: '', savedRows: [], centre: { lat: 50, lon: 30 }, onpick() {}, onsubmit() {} };
+
+describe('the bar itself', () => {
+ it('renders a combobox with the Go button beside it', () => {
+ const { body } = render(PlaceSearch, { props });
+ expect(body).toContain('role="combobox"');
+ expect(body).toContain('aria-autocomplete="list"');
+ expect(body).toContain('Go');
+ });
+
+ it('still names both things it accepts', () => {
+ const { body } = render(PlaceSearch, { props });
+ expect(body).toContain('A place, or 50.4501, 30.5234');
+ expect(body).toContain('decimal, DMS, MGRS, plus code');
+ });
+
+ it('shows no list until there is something to list', () => {
+ const { body } = render(PlaceSearch, { props });
+ expect(body).not.toContain('role="listbox"');
+ });
+});
+
+describe('what typing costs', () => {
+ it('asks the offline route on the keystroke and the geocoder only after a pause', () => {
+ expect(source).toContain('const LOCAL_DELAY = 120');
+ expect(source).toContain('const REMOTE_DELAY = 650');
+ expect(source).toContain('setTimeout(() => askLocal(query), LOCAL_DELAY)');
+ expect(source).toContain('setTimeout(() => askRemote(query), REMOTE_DELAY)');
+ });
+
+ it('keeps the geocoder out of short queries entirely', () => {
+ expect(source).toContain('query.length >= REMOTE_MIN_CHARS');
+ });
+
+ it('cancels the pending calls on every keystroke', () => {
+ expect(source).toContain('clearTimeout(localTimer)');
+ expect(source).toContain('clearTimeout(remoteTimer)');
+ });
+
+ it('drops an answer to a query that is no longer what is typed', () => {
+ expect(source).toContain('if (localFor !== query) return');
+ expect(source).toContain('if (remoteFor !== query) return');
+ });
+
+ it('leaves the list alone when the geocoder request was dropped rather than answered', () => {
+ expect(source).toContain('if (!body.busy) places = body.places ?? []');
+ });
+
+ it('survives a failed suggestion without breaking the bar', () => {
+ expect(source).toContain('/* the bar still works without suggestions */');
+ });
+});
+
+describe('choosing', () => {
+ it('walks the list with the arrows and closes on Escape', () => {
+ expect(source).toContain("event.key === 'ArrowDown'");
+ expect(source).toContain("event.key === 'ArrowUp'");
+ expect(source).toContain("event.key === 'Escape'");
+ });
+
+ it('falls back to the old behaviour when Enter is pressed with nothing highlighted', () => {
+ expect(source).toContain('if (at >= 0 && rows[at]) choose(rows[at]);');
+ expect(source).toContain('onsubmit(value)');
+ });
+
+ it('remembers what was picked', () => {
+ expect(source).toContain('recents = pushRecent(item)');
+ });
+});
diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelte
index 717cd6f..f1ba2ff 100644
--- a/frontend/src/tools/satellite/SavedPopup.svelte
+++ b/frontend/src/tools/satellite/SavedPopup.svelte
@@ -157,7 +157,9 @@
</button>
<div class="body">
<button type="button" class="title" onclick={() => onopen(row)}>
- {row.title || 'Untitled'}
+ <!-- one proof, several points: the name is what tells this mark from
+ the others under the same title -->
+ {row.label ? `${row.title || 'Untitled'} · ${row.label}` : (row.title || 'Untitled')}
</button>
<p class="meta">
<span class="kind"><Icon name={GLYPH[row.kind] ?? 'pin'} size={10} /> {KIND[row.kind]}</span>
diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelte
index e527cab..fb33523 100644
--- a/frontend/src/tools/satellite/SavedRow.svelte
+++ b/frontend/src/tools/satellite/SavedRow.svelte
@@ -88,7 +88,9 @@
{#if worked}<span class="worked" role="img" aria-label={worked} title={worked}></span>{/if}
</span>
<span class="text">
- <span class="title">{row.title || 'Untitled'}</span>
+ <!-- A proof arguing three points is three rows under one title. What the
+ analyst called each point is what tells them apart. -->
+ <span class="title">{row.title || 'Untitled'}{#if row.label}<span class="point">· {row.label}</span>{/if}</span>
<span class="sub">
<!-- a screenshot filed from a URL that carried no position has none:
say so rather than printing 0°, 0° -->
@@ -248,6 +250,7 @@
text-overflow: ellipsis;
white-space: nowrap;
}
+ .title .point { margin-left: 5px; color: var(--text-3); }
.open:hover:not(:disabled) .title {
color: var(--accent);
}
diff --git a/frontend/src/tools/satellite/SheetPointsOverlay.svelte b/frontend/src/tools/satellite/SheetPointsOverlay.svelte
new file mode 100644
index 0000000..f8d6ea8
--- /dev/null
+++ b/frontend/src/tools/satellite/SheetPointsOverlay.svelte
@@ -0,0 +1,97 @@
+<script>
+ /**
+ * A sheet's column of coordinates, on the map, for as long as the tab is open.
+ *
+ * Drawn with the saved index's geometry — the same teardrop, the same badge, the lift
+ * on hover — because it is the same gesture on the same map, in this layer's own tint.
+ *
+ * The one thing it says that no other layer does: **how precisely each point was
+ * written.** A cell holding `48.85, 2.35` is a claim about a kilometre, not about a
+ * building, and a worklist full of two-decimal coordinates looks exactly like a
+ * worklist of addresses until the circles are drawn. So the imprecision is the shape,
+ * and the pin sits on top of it.
+ */
+ import L from 'leaflet';
+ import { paths } from '../../components/Icon.svelte';
+ import { precisionMetres } from '../../lib/sheetRoles.js';
+
+ let { map = null, points = [] } = $props();
+ let group = null;
+
+ const TINT = '#c58af9';
+
+ /** Past this the cell says a neighbourhood, not a place, and the circle is worth
+ * drawing. Three decimals is about a hundred metres, which a building fits in. */
+ const COARSE_DECIMALS = 2;
+
+ function glyph(size) {
+ return (
+ `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor"` +
+ ` stroke-width="2" stroke-linecap="round" stroke-linejoin="round">` +
+ `<path d="${paths.table}"/></svg>`
+ );
+ }
+
+ function icon(point) {
+ const coarse = point.decimals <= COARSE_DECIMALS ? ' sheet-mark-coarse' : '';
+ return L.divIcon({
+ className: 'sheet-mark-wrap',
+ html: `<span class="sheet-mark${coarse}">${glyph(12)}</span>`,
+ iconSize: [24, 24],
+ iconAnchor: [12, 12],
+ });
+ }
+
+ $effect(() => {
+ if (!map) return;
+ group?.remove();
+ group = L.layerGroup(
+ points.flatMap((point) => {
+ const metres = precisionMetres(point.decimals);
+ const marker = L.marker([point.lat, point.lon], {
+ icon: icon(point),
+ keyboard: true,
+ title:
+ point.decimals <= COARSE_DECIMALS
+ ? `${point.label} — written to ${point.decimals} decimals, about ${metres} m`
+ : point.label,
+ });
+ marker.bindTooltip(point.label, { direction: 'top', offset: [0, -12] });
+ if (point.decimals > COARSE_DECIMALS) return [marker];
+ const circle = L.circle([point.lat, point.lon], {
+ radius: metres,
+ color: TINT,
+ weight: 1,
+ opacity: 0.75,
+ fillColor: TINT,
+ fillOpacity: 0.08,
+ interactive: false,
+ });
+ return [circle, marker];
+ }),
+ ).addTo(map);
+ });
+
+ $effect(() => () => {
+ group?.remove();
+ group = null;
+ });
+</script>
+
+<style>
+ /* Leaflet builds these outside this component's markup, so they have to be global.
+ The saved layer's geometry in this layer's tint. */
+ :global(.sheet-mark-wrap) { border: 0; background: none; }
+ :global(.sheet-mark) {
+ position: relative; display: grid; width: 24px; height: 24px; place-items: center;
+ border-radius: 50% 50% 50% 2px; transform: rotate(-45deg);
+ background: rgba(20, 20, 20, 0.82);
+ box-shadow: 0 0 0 1.5px #c58af9, 0 2px 5px rgba(0, 0, 0, 0.45);
+ color: #c58af9; transition: transform 0.12s var(--ease);
+ }
+ /* A point written to a kilometre is drawn as one: dashed, so the pin reads as the
+ centre of a guess rather than as an answer. */
+ :global(.sheet-mark-coarse) { box-shadow: 0 0 0 1.5px #c58af9, 0 0 0 3px rgba(197, 138, 249, 0.25); }
+ :global(.sheet-mark > svg) { transform: rotate(45deg); }
+ :global(.sheet-mark-wrap:hover .sheet-mark) { z-index: 500; transform: rotate(-45deg) scale(1.25); }
+</style>
diff --git a/packaging/icons/render_icons.py b/packaging/icons/render_icons.py
index e7f1673..8eee2e6 100644
--- a/packaging/icons/render_icons.py
+++ b/packaging/icons/render_icons.py
@@ -68,7 +68,7 @@ def _draw(size: int) -> Image.Image:
)
draw.polygon([px(TIP), px(BASE_W), px(WAIST)], fill=INK)
draw.polygon([px(TIP), px(BASE_E), px(WAIST)], fill=AMBER)
- return img.resize((size, size), Image.LANCZOS)
+ return img.resize((size, size), Image.Resampling.LANCZOS)
def main() -> None:
diff --git a/pyproject.toml b/pyproject.toml
index 162c0b4..f8ed916 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -45,6 +45,13 @@ dependencies = [
# correctly in one document (see docs, and the shaping note below).
"fpdf2>=2.8,<3",
"markdown-it-py>=4.0,<5",
+ # Reading a multi-tab workbook into one sheet per tab (engine/sheetxlsx.py). The
+ # binders this tool replaces arrive as .xlsx with five or six tabs, and asking the
+ # analyst to export each one to CSV by hand is asking them not to bother. Pure
+ # Python with its one pure-Python dependency (et-xmlfile), so the three binaries
+ # get the same reader and no build step. Reading only: the case's own table is a
+ # CSV, and writing xlsx would be a second artifact format to keep honest.
+ "openpyxl>=3.1,<4",
# Text shaping, and not optional: without it Arabic comes out unjoined and
# Burmese mis-stacked — text that looks like text and is wrong, which is
# worse than text that is missing. fpdf2 uses it when it is importable,
@@ -91,6 +98,13 @@ dev = [
# Reads an exported note back, so the PDF tests assert what is on the page
# rather than that bytes were written. Test-only: nothing ships it.
"pypdf>=6,<7",
+ # Runs the suite across the machine's cores, which CI asks for with `-n auto`.
+ # The tests were already isolated from each other — every one builds its case
+ # under `tmp_path`, and nothing is scoped wider than a test — so the only
+ # thing serial execution bought was a quarter of an hour per CI run. Not in
+ # `addopts` on purpose: a local run stays serial, because parallel output
+ # interleaves and `-x` and pdb stop being useful the moment it does.
+ "pytest-xdist>=3.6,<4",
# Static analysis, run in CI (see .github/workflows/ci.yml). ruff is 0.x and
# ships rule changes between minors, so it's pinned to one minor; mypy to the
# next major. Both bounds are raised deliberately, after the suite is green.
@@ -155,7 +169,11 @@ line-length = 100
target-version = "py311"
[tool.mypy]
-files = ["src/azimut"]
+# Every Python file the repo ships or runs, not only the package: `packaging/entry.py`
+# is the script PyInstaller analyses, so it is *inside* all three binaries, and it was
+# checked by nothing. `scripts/` is the release and development tooling. Tests stay out
+# — they are checked by running them.
+files = ["src/azimut", "scripts", "packaging"]
# yt-dlp, gallery-dl and cv2 ship no type stubs; don't fail on their absence.
# No python_version pin: mypy runs under the CI interpreter (3.12+), and numpy's
# 2.x stubs use 3.12 syntax that a 3.11 target can't parse. The 3.11 floor stays
diff --git a/scripts/build_cities.py b/scripts/build_cities.py
new file mode 100644
index 0000000..8941092
--- /dev/null
+++ b/scripts/build_cities.py
@@ -0,0 +1,139 @@
+"""Rebuild the offline city gazetteer shipped in engine/data/cities.tsv.gz.
+
+The Satellite search bar proposes matches while the analyst types, and the
+geocoder it would otherwise ask (Nominatim) forbids exactly that. So the cities
+travel with the app: a trimmed GeoNames extract, gzipped, read straight off disk.
+
+GeoNames publishes a fresh dump daily, so nothing here is SHA-pinned — the
+guards are size bounds and a shape check on every row instead. The source is
+CC BY 4.0; the attribution rides in the file header and in what the API returns.
+
+Run it from the repo root when the gazetteer needs refreshing:
+
+ python scripts/build_cities.py
+
+It writes src/azimut/engine/data/cities.tsv.gz and prints what changed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import gzip
+import io
+import urllib.request
+import zipfile
+from datetime import date
+from pathlib import Path
+
+CITIES_URL = "https://download.geonames.org/export/dump/cities15000.zip"
+ADMIN1_URL = "https://download.geonames.org/export/dump/admin1CodesASCII.txt"
+#: Both dumps are a few MB; anything an order of magnitude past that is not the
+#: file we asked for.
+MAX_ARCHIVE_BYTES = 32 * 1024 * 1024
+MAX_MEMBER_BYTES = 96 * 1024 * 1024
+MEMBER = "cities15000.txt"
+
+#: Columns of the GeoNames dump this reads (the file has 19).
+NAME, ASCII, LAT, LON, COUNTRY, ADMIN1, POPULATION = 1, 2, 4, 5, 8, 10, 14
+
+OUT = Path(__file__).resolve().parents[1] / "src" / "azimut" / "engine" / "data" / "cities.tsv.gz"
+
+
+def _fetch(url: str) -> bytes:
+ with urllib.request.urlopen(url, timeout=120) as response: # noqa: S310 (fixed https URL)
+ data = response.read(MAX_ARCHIVE_BYTES + 1)
+ if len(data) > MAX_ARCHIVE_BYTES:
+ raise SystemExit(f"{url} is larger than {MAX_ARCHIVE_BYTES} bytes — refusing it")
+ return data
+
+
+def _regions(text: str) -> dict[str, str]:
+ """``"ua.12"`` → ``"Kyiv Oblast"``, from the admin1 code table."""
+ table: dict[str, str] = {}
+ for line in text.splitlines():
+ fields = line.split("\t")
+ if len(fields) >= 2 and fields[0]:
+ table[fields[0].lower()] = fields[1]
+ return table
+
+
+def _rows(dump: str, regions: dict[str, str]) -> list[tuple[str, ...]]:
+ rows: list[tuple[str, ...]] = []
+ for line in dump.splitlines():
+ fields = line.split("\t")
+ if len(fields) <= POPULATION:
+ continue
+ name = fields[NAME].strip()
+ country = fields[COUNTRY].strip().lower()
+ if not name or len(country) != 2:
+ continue
+ try:
+ lat, lon = float(fields[LAT]), float(fields[LON])
+ population = int(fields[POPULATION] or 0)
+ except ValueError:
+ continue
+ if not (-90 <= lat <= 90 and -180 <= lon <= 180):
+ continue
+ ascii_name = fields[ASCII].strip()
+ region = regions.get(f"{country}.{fields[ADMIN1].strip().lower()}", "")
+ rows.append(
+ (
+ name,
+ # only when it says something the name doesn't
+ "" if ascii_name == name else ascii_name,
+ country,
+ "" if region == name else region,
+ _trim(lat),
+ _trim(lon),
+ str(population),
+ )
+ )
+ # Biggest first, so a row's position in the file *is* its rank and the
+ # reader needs no second sort.
+ rows.sort(key=lambda row: -int(row[6]))
+ return rows
+
+
+def _trim(value: float) -> str:
+ """Four decimals is ~11 m — a city centre, not a survey mark."""
+ return f"{value:.4f}".rstrip("0").rstrip(".") or "0"
+
+
+def build(cities_zip: bytes, admin1: bytes) -> bytes:
+ with zipfile.ZipFile(io.BytesIO(cities_zip)) as archive:
+ info = archive.getinfo(MEMBER)
+ if info.file_size > MAX_MEMBER_BYTES:
+ raise SystemExit(f"{MEMBER} unpacks to {info.file_size} bytes — refusing it")
+ dump = archive.read(MEMBER).decode("utf-8")
+ rows = _rows(dump, _regions(admin1.decode("utf-8")))
+ if len(rows) < 10_000: # the dump has ~34k; a tenth of that means a bad fetch
+ raise SystemExit(f"only {len(rows)} cities parsed — the dump looks wrong")
+ header = (
+ f"# GeoNames cities15000, trimmed {date.today().isoformat()} — "
+ "© GeoNames (CC BY 4.0), https://www.geonames.org/\n"
+ "# name\tascii\tcountry\tregion\tlat\tlon\tpopulation\n"
+ )
+ body = "\n".join("\t".join(row) for row in rows)
+ return gzip.compress((header + body + "\n").encode("utf-8"), 9)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--out", type=Path, default=OUT)
+ args = parser.parse_args()
+
+ print(f"fetching {CITIES_URL}")
+ cities_zip = _fetch(CITIES_URL)
+ print(f"fetching {ADMIN1_URL}")
+ admin1 = _fetch(ADMIN1_URL)
+
+ packed = build(cities_zip, admin1)
+ before = args.out.stat().st_size if args.out.exists() else 0
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_bytes(packed)
+ lines = gzip.decompress(packed).decode("utf-8").splitlines()
+ print(f"{args.out}: {len(lines) - 2} cities, {len(packed) / 1024:.0f} KiB (was {before / 1024:.0f} KiB)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/relaunch.py b/scripts/relaunch.py
index d641cef..619bd0a 100755
--- a/scripts/relaunch.py
+++ b/scripts/relaunch.py
@@ -267,7 +267,10 @@ def _spawn(command: list[str], cwd: Path) -> subprocess.Popen[bytes]:
return subprocess.Popen(
command,
cwd=cwd,
- creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
+ # Read by name: the constant is Windows-only, so a type-checker running on
+ # Linux does not know the attribute exists. Zero is what Windows means by
+ # "no extra creation flags", and this branch never runs anywhere else.
+ creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
)
return subprocess.Popen(command, cwd=cwd, start_new_session=True)
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index 108d409..5ca6d9a 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -13,7 +13,7 @@ from PIL import Image as _Image
# The capture extension is versioned separately, on purpose — it carries the
# release that last changed it (tests/test_updates.py). Don't move the two
# together.
-__version__ = "0.2.8"
+__version__ = "0.2.9"
# Cap the pixels Pillow will decode from a file, process-wide. A tiny,
# highly-compressed image can otherwise expand to gigabytes in memory and take
diff --git a/src/azimut/api/analysis_views.py b/src/azimut/api/analysis_views.py
index ab4b6cd..a21e24a 100644
--- a/src/azimut/api/analysis_views.py
+++ b/src/azimut/api/analysis_views.py
@@ -34,6 +34,10 @@ class AnalysisViewDuplicateIn(BaseModel):
name: str = Field(min_length=1, max_length=80)
+class AnalysisViewRenameIn(BaseModel):
+ name: str = Field(min_length=1, max_length=80)
+
+
def _unique(case, name: str, surface: str, *, ignore: str | None = None) -> None:
"""A name is claimed inside its own family, not across the app: the Timeline's
views and the catalog's are separate lists, and refusing a name the user cannot
@@ -126,6 +130,31 @@ def duplicate_analysis_view(
)
[email protected]("/{view_id}")
+def rename_analysis_view(
+ case_id: str, view_id: str, body: AnalysisViewRenameIn
+) -> dict[str, Any]:
+ """Rename one reading, whatever it holds.
+
+ A snapshot refuses `PUT` because its capture is evidence, but its label is not:
+ renaming is the one edit both modes accept, and it leaves the spec untouched. The
+ answer is the menu row rather than the whole view, so relabelling a large capture
+ does not ship it back.
+ """
+ case = get_case(case_id)
+ current = case.get_analysis_view(view_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ name = body.name.strip()
+ if not name:
+ raise HTTPException(status_code=400, detail="an analysis view needs a name")
+ _unique(case, name, current["surface"], ignore=view_id)
+ renamed = case.rename_analysis_view(view_id, name, _now())
+ if renamed is None: # pragma: no cover - the read above is the invariant
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ return view_engine.summary(renamed)
+
+
@router.put("/{view_id}")
def update_analysis_view(
case_id: str, view_id: str, body: AnalysisViewIn
diff --git a/src/azimut/api/cases/common.py b/src/azimut/api/cases/common.py
index 31ff2fc..b4d63b1 100644
--- a/src/azimut/api/cases/common.py
+++ b/src/azimut/api/cases/common.py
@@ -18,6 +18,7 @@ from fastapi import HTTPException
from ...engine import entities as entity_engine
from ...engine import links as link_engine
+from ...engine import sheets as sheet_engine
from ...engine import timeline as timeline_engine
from ...engine import trash as trash_engine
from ...engine.temporal import TemporalError, window_bound
@@ -89,6 +90,18 @@ def delete_entities_deep(case: Case, entity_ids: list[str]) -> dict[str, Any]:
trash_engine.rollback(case, group["id"])
raise
+ # A sheet points at the case through ids in a sidecar rather than through edges,
+ # so nothing above reaches them: a cell would stay marked as linked to a row the
+ # case no longer holds, and the next save would write the dead id back. Cleared
+ # here, which is the one door every delete comes through.
+ #
+ # **After the commit, and outside the rollback.** A sidecar is a file and the
+ # rollback restores the graph and the trash, so clearing them inside it meant a
+ # refused delete gave the entities back with the sheets' links, vocabularies and
+ # attached pieces already gone for good. Past the commit there is nothing left to
+ # roll back, which is what makes this the safe side of the line.
+ sheet_engine.forget_entities(case, set(going_by_id))
+
return {
"status": "deleted",
"deleted": [e["id"] for e in going],
diff --git a/src/azimut/api/cases/entities.py b/src/azimut/api/cases/entities.py
index 899e2df..b7d08ef 100644
--- a/src/azimut/api/cases/entities.py
+++ b/src/azimut/api/cases/entities.py
@@ -43,6 +43,11 @@ class EntityPatch(BaseModel):
class EntityDeleteIn(BaseModel):
ids: list[str] = Field(min_length=1, max_length=200)
+class EntityIdsIn(BaseModel):
+ #: A sheet may point at one entity per cell, so the bound is the sidecar's, not a
+ #: selection's.
+ ids: list[str] = Field(min_length=1, max_length=2000)
+
@router.get("/{case_id}/entities/lookup")
def lookup_entity(case_id: str, attr: str, value: str) -> dict[str, Any]:
"""One entity by an ``attrs`` value (``path``, ``spec``, ``draft``), or null.
@@ -203,3 +208,16 @@ def remove_entities(case_id: str, body: EntityDeleteIn) -> dict[str, Any]:
return delete_entities_deep(case, body.ids)
except CaseError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
+
[email protected]("/{case_id}/entities/missing")
+def missing_entities(case_id: str, body: EntityIdsIn) -> dict[str, list[str]]:
+ """Which of these ids the case no longer holds.
+
+ A sidecar keeps ids and only ids — a sheet cell's link, the files a row carries —
+ so a delete on another screen leaves a tool holding pointers at nothing. This is
+ how it finds out in one bounded lookup: there is no route that reads one entity,
+ and asking per id would be a request per cell.
+ """
+ case = get_case(case_id)
+ held = {str(entity["id"]) for entity in case.entities_by_ids(body.ids)}
+ return {"missing": [row for row in dict.fromkeys(body.ids) if row not in held]}
diff --git a/src/azimut/api/cases/entity_images.py b/src/azimut/api/cases/entity_images.py
index 4c96b5c..cdc076d 100644
--- a/src/azimut/api/cases/entity_images.py
+++ b/src/azimut/api/cases/entity_images.py
@@ -55,8 +55,9 @@ async def upload_entity_image(
) -> dict[str, Any]:
"""Store one private presentation photo outside the Media Library.
- Bounded at the edge like the two other surfaces that swallow an image, and
- against the same limit: a portrait is a portrait wherever it came from. The
+ Bounded at the edge like every other surface that swallows an image, and against
+ the same limit — ``MAX_IMAGE_BYTES``, whose users are the list: a portrait is a
+ portrait wherever it came from. The
pixel clamp further in answers a decompression bomb, not a file that is simply
enormous, and refusing early is what keeps a mistaken drag from filling the
disk with a temporary nobody asked for.
diff --git a/src/azimut/api/cases/registry.py b/src/azimut/api/cases/registry.py
index a8d8191..5d90b4c 100644
--- a/src/azimut/api/cases/registry.py
+++ b/src/azimut/api/cases/registry.py
@@ -15,6 +15,7 @@ from fastapi import APIRouter
from ...engine import entities as entity_engine
from ...engine import graph as graph_engine
from ...engine import links as link_engine
+from ...engine import sheetpromote as promote_engine
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -125,6 +126,13 @@ def entity_types() -> list[dict[str, Any]]:
"family_reads": entity_engine.FAMILY_READS.get(entry.family, ""),
"icon": entry.icon,
"manual": entry.manual,
+ # Whether a sheet row may become one. Not the same question as ``manual``
+ # and it drifted the moment it was assumed to be: a ``place`` is never
+ # created by hand because it is born from the map, yet a column of
+ # coordinates is the other honest way to have one; a ``claim`` is created
+ # by hand and a bare row cannot make one, since a statement carries what it
+ # is about, when it applies and what it rests on.
+ "promotable": entry.type in promote_engine.promotable_types(),
"image_gallery": entry.image_gallery,
# ``entity.label`` is the primary value, but "Name" is not an honest
# reading for an IP address, a phone number or a claim. The generated
diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.py
index 5076811..a483844 100644
--- a/src/azimut/api/drafts.py
+++ b/src/azimut/api/drafts.py
@@ -220,7 +220,8 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:
@router.delete("/cases/{case_id}/drafts/{name}")
def delete_draft(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
- rel = layout.draft_rel(name)
+ # Named the way the save named it — see `api/satellite.delete_search_grid`.
+ rel = layout.draft_rel(slugify(name, "draft"))
try:
case.resolve_inside(rel)
except CaseError as exc:
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 13ce560..6fbb7b7 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -1,9 +1,10 @@
"""REST API for the capture browser extension (extension/ at the repo root).
-The extension screenshots a map the user is looking at — an external site
-(Google Earth, Google Maps, Bing, Yandex, OSM) or this app's own Maps JS
-widget basemap — and files it here as a ``capture`` entity, riding the same
-media pipeline as a satellite crop so it lists, opens and exports like one.
+The extension screenshots a map the user is looking at — any site
+``engine/mapsites.SITES`` declares, or this app's own Maps JS widget basemap — and
+files it here as a ``capture`` entity, riding the same media pipeline as a satellite
+crop so it lists, opens and exports like one. The list lives there and only there:
+copied into this sentence it went stale at four of the nine sites.
Trust model: the server already binds localhost only, so the pairing token
(``config.ingest_token``, shown in Settings, pasted once into the extension)
@@ -65,9 +66,19 @@ ATTRIBUTIONS = {
def require_token(x_azimut_token: str = Header(default="")) -> None:
"""401 unless the request carries the pairing token. Constant-time compare;
- an unminted token ("") matches nothing."""
+ an unminted token ("") matches nothing.
+
+ Compared as **bytes**, which is what makes this a refusal rather than a crash. Starlette
+ decodes a header as latin-1, so any octet above 0x7f arrives as a non-ASCII string and
+ `compare_digest` raises `TypeError` on one — a 500 on the authentication edge, from a
+ value the caller chooses entirely, with a traceback into the log that
+ `engine/diagnostics.py` keeps for "Report an issue". The same guard exists in
+ `scripts/relaunch.py`, which decodes its token as ASCII and catches the failure.
+ """
expected = config.load_settings().get("ingest_token") or ""
- if not expected or not secrets.compare_digest(x_azimut_token, expected):
+ if not expected or not secrets.compare_digest(
+ x_azimut_token.encode("latin-1", "replace"), expected.encode("utf-8")
+ ):
raise HTTPException(status_code=401, detail="missing or invalid pairing token")
diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.py
index 3af54eb..ab21b2e 100644
--- a/src/azimut/api/inspect.py
+++ b/src/azimut/api/inspect.py
@@ -386,7 +386,8 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:
@router.delete("/cases/{case_id}/inspect/sessions/{name}")
def delete_session(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
- rel = layout.session_rel(name)
+ # Named the way the save named it — see `api/satellite.delete_search_grid`.
+ rel = layout.session_rel(slugify(name, "session"))
try:
case.resolve_inside(rel)
except CaseError as exc:
diff --git a/src/azimut/api/media.py b/src/azimut/api/media.py
index fe666ca..c753e08 100644
--- a/src/azimut/api/media.py
+++ b/src/azimut/api/media.py
@@ -6,7 +6,6 @@ from __future__ import annotations
import io
import warnings
from typing import Any
-from urllib.parse import urlsplit
from fastapi import APIRouter, Form, HTTPException, UploadFile
from PIL import Image
@@ -50,6 +49,9 @@ class UpdateIn(BaseModel):
notes: str | None = None
folder: str | None = None
title: str | None = None
+ # Where the analyst says a collected file came from. Empty drops the claim;
+ # a download refuses it (engine/media.py).
+ source_url: str | None = Field(default=None, max_length=4000)
class ThumbRegenIn(BaseModel):
@@ -64,6 +66,21 @@ class MediaMetadataIn(BaseModel):
paths: list[str] = Field(max_length=500)
+def stated_source(source_url: str) -> str:
+ """A hand-typed origin, or a refusal.
+
+ One reading of "source" for every surface that lets one be stated — the paste
+ dialog, an import, a later correction. Links only: the field feeds the entity's
+ ``source_url``, the proof plate's source line and the lineage a lost file leaves
+ behind, all of which are addresses. An origin that is not one (a hand-off, a
+ disk) is a note, and Notes is where it goes.
+ """
+ source_url = source_url.strip()
+ if source_url and not media_engine.is_address(source_url):
+ raise HTTPException(status_code=422, detail="the source must be an http(s) URL")
+ return source_url
+
+
def with_thumb_state(case: Case, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Tag each media item with the background states the UI polls.
@@ -247,10 +264,21 @@ def enrich_media(case_id: str, body: EnrichIn) -> dict[str, int]:
@router.post("/cases/{case_id}/media/upload")
-async def upload(case_id: str, file: UploadFile) -> dict[str, Any]:
+async def upload(
+ case_id: str,
+ file: UploadFile,
+ source_url: str = Form(default="", max_length=4000),
+) -> dict[str, Any]:
+ """File an uploaded file, with the origin the importer states for it.
+
+ A file fetched by hand and then dropped here carries no address of its own, so
+ the import is the first chance to say where it came from — and for a batch out
+ of one thread, the same chance for all of it.
+ """
case = get_case(case_id)
- result = media_engine.import_stream(case, file.filename or "file", file.file)
- return result
+ return media_engine.import_stream(
+ case, file.filename or "file", file.file, source_url=stated_source(source_url)
+ )
@router.post("/cases/{case_id}/media/paste")
@@ -291,17 +319,11 @@ async def paste(
except Exception as exc:
raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc
- source_url = source_url.strip()
- if source_url:
- split = urlsplit(source_url)
- if split.scheme not in ("http", "https") or not split.hostname:
- raise HTTPException(status_code=422, detail="the source must be an http(s) URL")
-
return media_engine.import_paste(
get_case(case_id),
file.filename or "pasted-image.png",
io.BytesIO(raw),
- source_url=source_url,
+ source_url=stated_source(source_url),
title=title,
)
@@ -331,7 +353,7 @@ def download(case_id: str, body: DownloadIn) -> dict[str, str]:
elif d.get("status") == "finished":
set_progress({"percent": 100, "stage": "processing"})
- return media_engine.download_url(
+ return media_engine.fetch_url(
case, url, progress_hook=hook, index=index, title=title, cookies=cookies
)
@@ -347,6 +369,21 @@ def job_status(job_id: str) -> dict[str, Any]:
return job
[email protected]("/jobs/{job_id}/cancel")
+def cancel_job(job_id: str) -> dict[str, bool]:
+ """Ask a job to stop where stopping is safe.
+
+ Only the jobs that took the promise can answer it — a download is one call
+ into yt-dlp and has no safe point inside it, where a sheet building a hundred
+ proofs has one between every two rows. ``stopped`` is false for a job that was
+ already finished, which is the honest answer to cancelling something that is
+ over rather than an error about it.
+ """
+ if jobs.get(job_id) is None:
+ raise HTTPException(status_code=404, detail="job not found")
+ return {"stopped": jobs.cancel(job_id)}
+
+
@router.post("/cases/{case_id}/media/export")
def export_media_item(case_id: str, body: ExportIn) -> dict[str, str]:
"""Copy one media file out of the case, into the media export folder.
@@ -404,6 +441,8 @@ def update_media_item(case_id: str, body: UpdateIn) -> dict[str, Any]:
patch["folder"] = body.folder
if body.title is not None:
patch["title"] = body.title
+ if body.source_url is not None:
+ patch["source_url"] = stated_source(body.source_url)
try:
return media_engine.update_media(case, body.path, patch)
except (ValueError, CaseError) as exc:
diff --git a/src/azimut/api/notes.py b/src/azimut/api/notes.py
index 2465612..3304f31 100644
--- a/src/azimut/api/notes.py
+++ b/src/azimut/api/notes.py
@@ -51,6 +51,13 @@ MAX_DIAGRAM_TOTAL_BYTES = 16_000_000
#: receive wrapper before Pydantic materialises the request.
MAX_PDF_BODY_BYTES = 24_000_000
+#: What one note's Markdown may weigh, bounded like every other document the browser
+#: hands back whole (`server.BulkBodyLimit`). Eight mebibytes is some eight million
+#: characters — far past any note somebody writes, and a bound rather than none, which is
+#: what this was. A note embeds its pictures by case-relative path, never as base64, so
+#: the body is text and nothing else.
+MAX_NOTE_BODY_BYTES = 8 * 1024 * 1024
+
class Notes(BaseModel):
text: str
diff --git a/src/azimut/api/plates.py b/src/azimut/api/plates.py
new file mode 100644
index 0000000..8a35a2f
--- /dev/null
+++ b/src/azimut/api/plates.py
@@ -0,0 +1,156 @@
+"""REST API for analysis plates: the Graph or the Timeline, written out as a page.
+
+A plate is what an analysis reading looks like once it has left the tab — the drawing
+plus the lens, the question, the window, the clock and the legend it was read under.
+It is drawn in the browser, because that is where the geometry lives: Konva serialises
+no SVG and the Timeline is HTML, so both surfaces write their own SVG from the same
+scene their screen rendering uses (`frontend/src/lib/plate.js`).
+
+What is left for the backend is what a browser cannot do: write the file into the
+folder the analyst chose for this kind of work (`engine/exportdir.py`), and open that
+folder afterwards. A plate is a file, like a note's PDF — not a case artifact — so
+nothing here touches the graph, the Trash or a bundle.
+
+**The posted markup is bounded and inspected before it is written.** The app's own
+generator emits no script, no event handler and no remote reference, so a body carrying
+one is not ours; it is refused rather than filed. The file is never re-read or rendered
+by Azimut, but it is written where the analyst opens documents, and an SVG a browser
+opens is a document a browser executes.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import re
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from .. import layout
+from ..engine import exportdir
+from ..engine import reveal as reveal_engine
+from .cases import get_case
+
+router = APIRouter(prefix="/api/cases", tags=["plates"])
+
+#: Which saved destination a plate goes to, and the case subdir it falls back to.
+KIND = "views"
+EXPORTS_DIR = "exports"
+
+#: Bounds on one plate. A vector page of a few hundred nodes is tens of kilobytes; a
+#: megabyte is already a case nobody can read on one page, and the raster of it is
+#: capped in the browser at twice a 4000px edge.
+MAX_SVG_CHARS = 8_000_000
+MAX_PNG_BYTES = 24_000_000
+#: JSON + base64 overhead above the payload limits. Enforced by the ASGI receive
+#: wrapper in `server.py` before Pydantic materialises the request.
+MAX_PLATE_BODY_BYTES = 34_000_000
+
+#: Half of a surrogate pair, which JSON carries and UTF-8 cannot express.
+#:
+#: It reaches here when a label holding an emoji was cut mid-pair — the truncation that
+#: did it is fixed in `lib/graph.js`, but the route has to hold anyway: one broken
+#: character in one entity name must not be the reason a whole export fails, and a lone
+#: surrogate stands for nothing that could be drawn.
+_LONE_SURROGATE = re.compile(r"[\ud800-\udfff]")
+
+#: What the app's own generator never writes, and what an SVG must not carry into a
+#: folder where documents are opened: script, event handlers, embedded HTML, and any
+#: reference that leaves the file.
+_FORBIDDEN = (
+ re.compile(r"<\s*script", re.IGNORECASE),
+ re.compile(r"<\s*foreignObject", re.IGNORECASE),
+ re.compile(r"<\s*(iframe|embed|object|use)\b", re.IGNORECASE),
+ re.compile(r"\son[a-z]+\s*=", re.IGNORECASE),
+ re.compile(r"javascript\s*:", re.IGNORECASE),
+ re.compile(r"(?:xlink:)?href\s*=\s*[\"'](?!#)", re.IGNORECASE),
+)
+
+
+class PlateIn(BaseModel):
+ """One serialised reading, and what to call it."""
+
+ filename: str = Field(min_length=1, max_length=120)
+ format: str = Field(default="svg", pattern="^(svg|png)$")
+ svg: str = ""
+ png: str = ""
+
+
+def _clean_svg(markup: str) -> bytes:
+ text = _LONE_SURROGATE.sub("", markup.strip())
+ if not text:
+ raise HTTPException(status_code=422, detail="the plate is empty")
+ if len(text) > MAX_SVG_CHARS:
+ raise HTTPException(status_code=413, detail="the plate is too large to write")
+ if not text.startswith("<svg"):
+ raise HTTPException(status_code=422, detail="that is not an SVG plate")
+ for pattern in _FORBIDDEN:
+ if pattern.search(text):
+ raise HTTPException(
+ status_code=422,
+ detail="a plate carries no script, no embedded document and no remote reference",
+ )
+ return text.encode("utf-8")
+
+
+def _clean_png(encoded: str) -> bytes:
+ try:
+ raw = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise HTTPException(status_code=422, detail="the plate image is invalid") from exc
+ if not raw:
+ raise HTTPException(status_code=422, detail="the plate is empty")
+ if len(raw) > MAX_PNG_BYTES:
+ raise HTTPException(status_code=413, detail="the plate is too large to write")
+ if not raw.startswith(b"\x89PNG\r\n\x1a\n"):
+ raise HTTPException(status_code=422, detail="the plate image is not a PNG")
+ return raw
+
+
[email protected]("/{case_id}/plates")
+def write_plate(case_id: str, body: PlateIn) -> dict[str, Any]:
+ """Write one plate into the folder saved for analysis views.
+
+ Inside the case a re-export overwrites, the way a note's PDF does: that folder is
+ refreshed in one click rather than accumulating copies. In a folder of the
+ analyst's own nothing is ever overwritten, because the files there are theirs.
+ """
+ case = get_case(case_id)
+ data = _clean_png(body.png) if body.format == "png" else _clean_svg(body.svg)
+ stem = layout.slugify(body.filename, "plate")
+ filename = f"{stem}.{body.format}"
+ try:
+ destination = exportdir.destination(KIND, case.path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ in_case = destination == layout.subdir(case.path, EXPORTS_DIR)
+ try:
+ if in_case:
+ path = destination / filename
+ path.write_bytes(data)
+ else:
+ path = exportdir.write_out(data, destination, filename)
+ except (OSError, exportdir.ExportDirError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not write the plate: {exc}") from exc
+ return {"file": path.name, "path": str(destination)}
+
+
[email protected]("/{case_id}/plates/reveal")
+def reveal_plates(case_id: str) -> dict[str, str]:
+ """Open the folder the plates were written to, in the system file manager.
+
+ Takes no path: the case id and the saved destination are enough to find the folder,
+ so nothing the browser sends can point somewhere else.
+ """
+ case = get_case(case_id)
+ try:
+ destination = exportdir.destination(KIND, case.path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ try:
+ reveal_engine.reveal(destination, workspace_only=False)
+ except reveal_engine.RevealError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"status": "revealed", "path": str(destination)}
diff --git a/src/azimut/api/proofimports.py b/src/azimut/api/proofimports.py
new file mode 100644
index 0000000..ab0c51f
--- /dev/null
+++ b/src/azimut/api/proofimports.py
@@ -0,0 +1,397 @@
+"""REST API for importing a geolocated post as a proof.
+
+The engine owns the staging directory, the scan and the preview; this owns the
+order the pieces are written in, because that order is the whole guarantee:
+
+1. ``POST /proof-imports`` mints a token and a directory to hold files in;
+2. ``fetch`` downloads — the post's picture into one slot, the footage the post
+ points at into the other. Both land in the staging directory, and both go
+ through the same yt-dlp/gallery-dl path the Media Library uses, so a login
+ wall and a post with several attachments behave exactly as they do there;
+3. ``attach`` fills a slot by hand, which is the answer to a download that
+ failed and the whole of the paste-an-image route;
+4. ``preview`` says what would be created, reading the held bytes;
+5. ``commit`` writes it, and only then does anything enter the case.
+
+``DELETE`` at any point leaves no trace. So does walking away: the next import
+sweeps what was abandoned.
+
+Step 5 is also a function, :func:`write_import`, because a sheet's geolocation
+index builds a hundred of these in a job (`api/sheetproofs.py`) and the order
+above is exactly the guarantee it needs too.
+"""
+
+from __future__ import annotations
+
+import base64
+import shutil
+from typing import Any
+
+from fastapi import APIRouter, Form, HTTPException, UploadFile
+from pydantic import BaseModel, Field, HttpUrl
+
+from .. import config, jobs, layout
+from ..engine import links as link_engine
+from ..engine import media as media_engine
+from ..engine import proofimport as import_engine
+from ..workspace import Case, CaseError, ensure_dir
+from . import proofs
+from .cases import get_case
+from .limits import MAX_IMAGE_BYTES
+from .media import stated_source
+
+router = APIRouter(prefix="/api", tags=["proof-imports"])
+
+
+class FetchIn(BaseModel):
+ url: HttpUrl
+ #: Which half of the import this download is for.
+ slot: str = Field(default=import_engine.SLOT_PANEL)
+ #: 1-based pick when the post carries several attachments, as in Media.
+ index: int | None = None
+ #: Several picks: a post publishing a geolocation as a set publishes one proof and the
+ #: set becomes its panels, and a post carrying two photos of the scene is two pieces
+ #: of material, not one. In the order they were ticked.
+ indexes: list[int] = Field(default_factory=list, max_length=import_engine.MAX_PANELS)
+ use_cookies: bool = False
+
+
+class FormIn(BaseModel):
+ """What the analyst filled in. Coordinates and a source are required, and
+ the preview is where that is said rather than at the end of a save.
+
+ ``source_urls`` is a list because a thread states one point and hangs the photos and
+ the clips it rests on off several posts. Each address holds its own files, is
+ retried on its own and is dropped on its own.
+ """
+
+ title: str = Field(default="", max_length=layout.MAX_SLUG)
+ coords: str = Field(default="", max_length=200)
+ source_urls: list[str] = Field(
+ default_factory=list, max_length=import_engine.MAX_SOURCES
+ )
+ note: str = Field(default="", max_length=500)
+ pov: bool = False
+
+
+def _slot(value: str) -> str:
+ if value not in import_engine.SLOTS:
+ raise HTTPException(status_code=422, detail=f"unknown slot '{value}'")
+ return value
+
+
+def _open_draft(case: Case, token: str) -> dict[str, Any]:
+ try:
+ return import_engine.read_draft(case, token)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/proof-imports")
+def start_import(case_id: str) -> dict[str, str]:
+ return {"token": import_engine.open_import(get_case(case_id))}
+
+
[email protected]("/cases/{case_id}/proof-imports/{token}")
+def cancel_import(case_id: str, token: str) -> dict[str, bool]:
+ case = get_case(case_id)
+ try:
+ import_engine.discard(case, token)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {"discarded": True}
+
+
[email protected]("/cases/{case_id}/proof-imports/{token}/fetch")
+def fetch(case_id: str, token: str, body: FetchIn) -> dict[str, str]:
+ """Download into a slot, without filing anything.
+
+ The picture slot also reads the post: its text is scanned for positions and
+ addresses, and both ride back with the job so the form can be prefilled from
+ one round trip.
+ """
+ case = get_case(case_id)
+ slot = _slot(body.slot)
+ _open_draft(case, token)
+ stage = import_engine.staging_dir(case, token)
+ ensure_dir(stage)
+ url = str(body.url)
+ cookies = (
+ media_engine.cookies_from_preference(config.load_settings().get("download_cookies"))
+ if body.use_cookies
+ else None
+ )
+
+ #: What to download, in order. `None` is "whatever the post holds", which is the
+ #: answer before anybody has seen a picker.
+ picks: list[int | None] = [n for n in body.indexes if n > 0] or [body.index]
+
+ def work(set_progress):
+ def hook(d):
+ if d.get("status") == "downloading":
+ total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0
+ done = d.get("downloaded_bytes") or 0
+ set_progress(
+ {
+ "percent": round(done * 100 / total, 1) if total else None,
+ "speed": d.get("_speed_str", "").strip() or None,
+ }
+ )
+ elif d.get("status") == "finished":
+ set_progress({"percent": 100, "stage": "processing"})
+
+ held: list[dict[str, Any]] = []
+ for at, pick in enumerate(picks):
+ set_progress({"percent": None, "of": len(picks), "done": at})
+ result = media_engine.fetch_url(
+ case, url, progress_hook=hook, index=pick, cookies=cookies, stage=stage,
+ # The panel is a picture by definition, and yt-dlp reads a post for its
+ # video: a post publishing a geolocation beside a quoted clip would hand
+ # back the clip and the picture would be unreachable from here.
+ wants="image" if slot == import_engine.SLOT_PANEL else "",
+ )
+ staged = result.get("staged")
+ if not staged:
+ return result # a picker, a login wall, a Telegram-only post
+ held.append(staged)
+ # Keyed by the address it came from: a second source address holds its own files
+ # beside the first one's, and retrying one that failed replaces only its own.
+ import_engine.fill_files(case, token, slot, held, for_url=url)
+ answer: dict[str, Any] = {"slot": slot, "staged": held[0], "held": held}
+ if slot == import_engine.SLOT_PANEL:
+ post = import_engine.read_post(held[0].get("source") or {}, url)
+ import_engine.record_post(case, token, post)
+ answer["post"] = post
+ return answer
+
+ return {"job_id": jobs.start("proof-import", work)}
+
+
[email protected]("/cases/{case_id}/proof-imports/{token}/attach")
+async def attach(
+ case_id: str,
+ token: str,
+ file: UploadFile,
+ slot: str = Form(default=import_engine.SLOT_PANEL),
+ source_url: str = Form(default="", max_length=4000),
+) -> dict[str, Any]:
+ """Fill a slot from the computer or the clipboard.
+
+ The one route behind both "paste an image instead" and "the download failed,
+ here is the file". ``source_url`` is what the analyst says the bytes came
+ from, which a hand-attached file is the only chance to state.
+
+ Read through `stated_source`, like the upload and the later correction in Details:
+ an origin is a link, refused when it is not one. This is the surface where the
+ address is typed by hand, so it is the one that most needed the reading.
+ """
+ case = get_case(case_id)
+ slot = _slot(slot)
+ # Before the bytes are streamed: a refused origin should not leave a staged file.
+ stated = stated_source(source_url)
+ _open_draft(case, token)
+ stage = import_engine.staging_dir(case, token)
+ ensure_dir(stage)
+ name = media_engine.safe_filename(file.filename or "attachment")
+ path = media_engine.unique_path(stage, name)
+ # Streamed rather than read into memory: the source slot takes whatever the
+ # footage weighs, and a video the downloader could not reach is exactly the
+ # file somebody attaches here. Only the picture is bounded, by the same clamp
+ # every other image entering the app answers to.
+ with path.open("wb") as out:
+ shutil.copyfileobj(file.file, out)
+ if slot == import_engine.SLOT_PANEL:
+ # A proof is composed of pictures: the composer lays panels out on a canvas and
+ # a clip has nothing to lay out. Said at the door the file comes through rather
+ # than at the preview, which is two screens and one staged file later.
+ if media_engine.media_kind(name) != "image":
+ path.unlink(missing_ok=True)
+ raise HTTPException(
+ status_code=422,
+ detail="a proof is composed of pictures, and this file is not one",
+ )
+ if path.stat().st_size > MAX_IMAGE_BYTES:
+ path.unlink(missing_ok=True)
+ raise HTTPException(status_code=413, detail="that picture is too large")
+ source: dict[str, Any] = {"type": "manual", "original_name": file.filename or name}
+ if stated:
+ source["url"] = stated
+ staged = media_engine.stage_descriptor(path, source)
+ # For the material, the stated origin is also the row this file answers for, so it
+ # replaces what that one address holds and leaves the other addresses alone.
+ # Attaching a picture still replaces the whole set: "here is my picture instead" is
+ # what that route means, and a set built from a post is not something it adds to.
+ import_engine.fill_files(
+ case, token, slot, [staged],
+ for_url=stated if slot == import_engine.SLOT_SOURCE else "",
+ )
+ return {"slot": slot, "staged": staged}
+
+
[email protected]("/cases/{case_id}/proof-imports/{token}/preview")
+def preview(case_id: str, token: str, body: FormIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ return import_engine.preview(case, token, body.model_dump())
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+
+
[email protected]("/cases/{case_id}/proof-imports/{token}/commit")
+def commit(case_id: str, token: str, body: FormIn) -> dict[str, Any]:
+ return write_import(case_id, token, body.model_dump())
+
+
+def write_import(
+ case_id: str, token: str, form: dict[str, Any], *, by: str = "proof-import"
+) -> dict[str, Any]:
+ """Write one held import, in the order that keeps the graph readable.
+
+ The footage is filed first so the picture can record that it came out of it;
+ the proof is saved through the composer's own route, so the place, the verbs
+ and the derivation are the ones a hand-made proof would have written. There
+ is no second implementation of any of that here.
+
+ Called by the dialog's own commit and by the sheet road that builds a hundred
+ of these in a job (`api/sheetproofs.py`). ``by`` is the only thing that
+ differs between them, and it is what lets the graph say which press wrote a
+ file. Splitting the two would have been the second implementation.
+ """
+ case = get_case(case_id)
+ _open_draft(case, token)
+ report = import_engine.preview(case, token, form)
+ if not report["ready"]:
+ raise HTTPException(status_code=400, detail=" ".join(report["blocking"]))
+
+ created: dict[str, Any] = {}
+
+ # Paired here for the same reason the pictures are: a file whose bytes have gone
+ # must not shift the rest onto their neighbours' provenance.
+ source_rels: list[dict[str, str]] = []
+ filed_sources: list[dict[str, Any]] = []
+ pairs = import_engine.staged_pairs(case, token, import_engine.SLOT_SOURCE)
+ by_name = {str(held.get("filename") or ""): path for path, held in pairs}
+ # Only what the form still states, and in its order — the same reading the preview
+ # ran on, so the commit files exactly what the analyst was shown.
+ for held in import_engine.stated_sources(
+ [held for _path, held in pairs], import_engine.read_source_urls(form)
+ ):
+ source_path = by_name[str(held.get("filename") or "")]
+ filed = media_engine.import_produced_file(
+ case,
+ source_path,
+ str(held["filename"]),
+ dict(held.get("source") or {}),
+ by=by,
+ )
+ # The file and the address it came from: the composer reconciles its Source list
+ # against these, so a source taken off the proof takes its files with it.
+ source_rels.append(
+ {"path": filed["entity"]["attrs"]["path"], "url": str(held.get("for_url") or "")}
+ )
+ filed_sources.append(_summary(filed))
+ if filed_sources:
+ created["source"] = filed_sources[0]
+ if len(filed_sources) > 1:
+ created["sources"] = filed_sources
+
+ # Path and manifest entry together: pairing them by position meant a file whose bytes
+ # had gone — quarantined by an antivirus, swept by hand — filed every picture after it
+ # under its neighbour's origin.
+ held_panels = import_engine.staged_pairs(case, token, import_engine.SLOT_PANEL)
+ if not held_panels:
+ raise HTTPException(status_code=400, detail="the picture is no longer held")
+ panel_paths = [path for path, _ in held_panels]
+ name = import_engine.proof_name(form["title"])
+ # Both read before a single file moves: filing a produced file *moves* it out of the
+ # staging directory, so anything the spec needs from the bytes has to be taken first.
+ naturals = [import_engine.panel_size(path) for path in panel_paths]
+ # One picture is already a rendered proof, so it is filed as the export. A set has no
+ # render — the layout is the composer's canvas, in the browser — and a second renderer
+ # here would drift from it at the first change. So the set is saved without one, and
+ # the first save in the composer writes the real thing.
+ export = (
+ base64.b64encode(import_engine.png_bytes(panel_paths[0])).decode("ascii")
+ if len(panel_paths) == 1
+ else None
+ )
+ panels: list[tuple[str, tuple[int, int]]] = []
+ filed_panels: list[dict[str, Any]] = []
+ for at, (panel_path, held) in enumerate(held_panels):
+ # The picture states where it came from once, in its provenance: the post that
+ # published it. What the geolocation *rests* on is the proof's own claim, filed
+ # from the spec below — a published picture is one file among the several the
+ # proof was read from, not the thing they all hang off.
+ panel_source = dict(held.get("source") or {}) # the post, and nothing else
+ # Numbered from the second, so a single-picture import keeps the name it had.
+ stem = name if at == 0 else f"{name} {at + 1}"
+ filed = media_engine.import_produced_file(
+ case,
+ panel_path,
+ layout.visible_filename(stem, panel_path.suffix),
+ panel_source,
+ by=by,
+ )
+ panels.append((filed["entity"]["attrs"]["path"], naturals[at]))
+ filed_panels.append(filed)
+ created["panel"] = _summary(filed_panels[0])
+ if len(filed_panels) > 1:
+ created["panels"] = [_summary(one) for one in filed_panels]
+
+ spec = import_engine.build_spec(panels, form, material=source_rels)
+ saved = proofs.save_proof(
+ case_id,
+ proofs.ProofIn(title=form["title"], spec=spec, png_base64=export),
+ )
+ proof_entity = case.find_entity(attr="spec", value=layout.proof_spec_rel(str(saved["name"])))
+ # Without an export there is no thumbnail, and a proof draws in the graph off the one
+ # recorded on its own row (`graph._previews`) — so it would be the only blank node of
+ # its own constellation. It borrows the first picture's, read off that media's sidecar
+ # where the thumbnailer put it. A thumbnail is a preview and never an assertion, which
+ # is what makes borrowing honest here where filing one picture as `proofs/<name>.png`
+ # would not be.
+ borrowed = (filed_panels[0].get("item") or {}).get("thumbnail")
+ if export is None and borrowed and proof_entity is not None:
+ case.update_entity(proof_entity["id"], {"attrs": {"thumb": borrowed}})
+ created["proof"] = {
+ "name": saved["name"],
+ "png": saved.get("png"),
+ "id": (proof_entity or {}).get("id"),
+ }
+
+ place = saved.get("place")
+ if isinstance(place, dict) and place.get("asking") and proof_entity is not None:
+ # `proof_place_auto` is off, so the composer's own save would have asked.
+ # The import already asked — that is what the preview was — so the answer
+ # is filed here rather than handed back as a second question.
+ proofs.file_proof_points(case, proof_entity)
+ # Read off the edge rather than off the save's answer: the save reports
+ # nothing when the point was already in the case, and "which place did this
+ # land on" has to be answerable whether the import pinned it or reused it.
+ created["place"] = _concluded_place(case, proof_entity)
+
+ import_engine.discard(case, token)
+ return created
+
+
+def _concluded_place(case: Case, proof: dict[str, Any] | None) -> dict[str, Any] | None:
+ """The point the saved proof concludes on, as the graph now holds it."""
+ if proof is None:
+ return None
+ for link in case.links_of(proof["id"]):
+ if link["from"] != proof["id"] or link["type"] != link_engine.DEPICTS:
+ continue
+ target = case.get_entity(link["to"])
+ if target is not None and target["type"] == "place":
+ return {"id": target["id"], "label": target["label"]}
+ return None
+
+
+def _summary(filed: dict[str, Any]) -> dict[str, Any]:
+ entity = filed["entity"]
+ return {
+ "id": entity["id"],
+ "label": entity["label"],
+ "path": entity["attrs"]["path"],
+ "duplicate": bool(filed.get("duplicate")),
+ }
diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.py
index 5adab9c..b86dd49 100644
--- a/src/azimut/api/proofs.py
+++ b/src/azimut/api/proofs.py
@@ -48,6 +48,25 @@ ASSET_NAME = re.compile(r"^[0-9a-f]{16}\.(?:png|jpe?g|webp)$")
MAX_ASSET_BYTES = 20 * 1024 * 1024
MAX_ASSETS = 12
+#: Room for the rendered export. One picture, so it is bounded like the others the
+#: browser hands back (`api/limits.MAX_IMAGE_BYTES`), with the slack a multi-panel
+#: composition needs over a single screenshot.
+MAX_EXPORT_BYTES = 48 * 1024 * 1024
+
+#: What `POST /cases/{id}/proofs` may weigh, refused by `server.BulkBodyLimit` before
+#: Pydantic materialises it. Computed rather than picked, from the two limits the route
+#: already declares: the export plus every pasted image a save may carry, at base64's
+#: four-thirds, plus room for the spec. Guessing a round number here would either refuse a
+#: save the composer considers legal or leave the declared maxima unreachable.
+#:
+#: The ceiling is deliberately high, because those maxima are: twelve pastes at 20 MiB is a
+#: real first save. What this stops is the *unbounded* case — the export field carried no
+#: limit at all, and every refusal in `_decode_assets` arrived after the whole body had
+#: been parsed into memory.
+MAX_PROOF_BODY_BYTES = (
+ (MAX_EXPORT_BYTES + MAX_ASSETS * MAX_ASSET_BYTES) * 4
+) // 3 + 2 * 1024 * 1024
+
class AssetIn(BaseModel):
"""A pasted image the composer is holding but has never written.
@@ -61,13 +80,6 @@ class AssetIn(BaseModel):
data: str # base64 body
-class ProofPlaceIn(BaseModel):
- """The point the composer asked about, answered yes."""
-
- lat: float = Field(ge=-90, le=90)
- lon: float = Field(ge=-180, le=180)
-
-
class ProofIn(BaseModel):
# The filename always follows the title, so renaming a saved proof moves its
# spec and its export. ``rename_from`` is the stem the composer is currently
@@ -76,7 +88,9 @@ class ProofIn(BaseModel):
rename_from: str | None = None
title: str = Field(min_length=1, max_length=200)
spec: dict[str, Any]
- png_base64: str | None = None # rendered export, data URL body
+ # The rendered export, as the data URL's body. Bounded twice: the whole request by
+ # `server.BulkBodyLimit`, and the decoded picture by `MAX_EXPORT_BYTES` below.
+ png_base64: str | None = None
# Pasted images the spec references but the case does not hold yet. They ride
# along with the save rather than through an upload of their own, so a proof
# the analyst never saves leaves nothing behind.
@@ -229,9 +243,9 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:
"updated_at": spec.get("updated_at"),
"panels": len(spec.get("panels", [])),
"shapes": len(spec.get("shapes", [])),
- # the point the proof states for itself, read before its
- # derivation so it keeps it when the capture is deleted
- "coords": satellite_engine.own_point(spec),
+ # the points the proof states for itself, read before its
+ # derivation so it keeps them when the capture is deleted
+ "points": satellite_engine.spec_points(spec),
"png": layout.proof_export_rel(png.stem) if png.exists() else None,
"thumb": thumb,
"spec_path": layout.proof_spec_rel(spec_path.stem),
@@ -243,6 +257,14 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:
@router.get("/cases/{case_id}/proofs/{name}")
def load_proof(case_id: str, name: str) -> dict[str, Any]:
+ """The saved spec, opened on every point the proof concludes on.
+
+ A sheet row can file a point for a proof it did not compose, so the graph holds
+ points the spec never learned (``satellite.proof_points``). Opening on the spec
+ alone showed one row for a proof the map drew twice, and the next save would
+ have written that missing point out of the composition for good. The list comes
+ back complete instead, and saving is what makes the spec agree with the map.
+ """
case = get_case(case_id)
try:
spec_path = case.resolve_inside(layout.proof_spec_rel(name))
@@ -250,7 +272,11 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:
raise HTTPException(status_code=403, detail=str(exc)) from exc
if not spec_path.exists():
raise HTTPException(status_code=404, detail="proof not found")
- return json.loads(spec_path.read_text(encoding="utf-8"))
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(spec_path.stem))
+ if isinstance(spec, dict) and proof is not None:
+ return satellite_engine.open_spec(case, proof["id"], spec)
+ return spec
@router.post("/cases/{case_id}/proofs/{name}/export")
@@ -306,13 +332,27 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# Decoded up front: a bad batch must be refused before anything is written.
incoming = _decode_assets(body.assets)
+ # The export too, and for a stronger reason — the rename below deletes the
+ # old PNG and moves the assets folder, so a payload refused after that point
+ # would leave the proof under its old name with both of them gone.
+ png_bytes: bytes | None = None
+ if body.png_base64:
+ try:
+ png_bytes = base64.b64decode(body.png_base64, validate=True)
+ except (binascii.Error, ValueError) as exc:
+ raise HTTPException(status_code=422, detail="invalid PNG payload") from exc
+ if len(png_bytes) > MAX_EXPORT_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"the export must be under {MAX_EXPORT_BYTES // 1024 // 1024} MB",
+ )
# The export moves with the spec, so a rename saved without fresh pixels
# keeps the PNG the proof already had rather than dropping it.
if old_rel and old:
old_png = case.resolve_inside(layout.proof_export_rel(old))
if old_png.exists():
- if body.png_base64:
+ if png_bytes is not None:
old_png.unlink()
else:
old_png.replace(case.resolve_inside(layout.proof_export_rel(name)))
@@ -324,11 +364,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# the export lands first: its thumbnail is recorded in the spec written below
png_rel = thumb_rel = None
- if body.png_base64:
- try:
- png_bytes = base64.b64decode(body.png_base64, validate=True)
- except (binascii.Error, ValueError) as exc:
- raise HTTPException(status_code=422, detail="invalid PNG payload") from exc
+ if png_bytes is not None:
case.resolve_inside(layout.proof_export_rel(name)).write_bytes(png_bytes)
png_rel = layout.proof_export_rel(name)
thumb_rel = _proof_thumb(case, name, png_bytes)
@@ -388,14 +424,21 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
if old_rel:
case.resolve_inside(layout.proof_spec_rel(str(old))).unlink(missing_ok=True)
- # A proof is derived from the panels it composes: the same click that saves
- # it files the chain (ONTOLOGY §3). Restated on every save, so a panel
- # dropped from the proof drops its edge too.
+ # A proof is derived from what it composes *and* from what it rests on: the same
+ # click that saves it files the chain (ONTOLOGY §3). Panels are the pictures laid
+ # out on the canvas; `material` is the footage behind them — the clip a frame was
+ # cut from, the second angle nothing was cropped out of — brought in from a source
+ # address the analyst stated. Restated on every save, so a panel dropped from the
+ # proof or an address taken off its list drops its edge too.
+ #
+ # The point follows on its own: `satellite.restate_proof_point` poses a proof's
+ # place on its whole derivation closure, so material joins the map by being in the
+ # chain rather than by a second rule written here.
link_engine.sync(
case,
entity_id,
link_engine.DERIVED_FROM,
- [p.get("src") for p in spec.get("panels", []) if p.get("src")],
+ [p.get("src") for p in spec.get("panels", []) if p.get("src")] + _material_paths(spec),
by="proof-composer",
)
@@ -412,90 +455,124 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
}
+def _material_paths(spec: dict[str, Any]) -> list[str]:
+ """The case files a proof states it rests on.
+
+ Each entry is the file and the address that brought it in, which is what lets the
+ composer take a source off a proof and take its files out of the chain with it. A
+ bare string is what a proof saved before that carried: a file no address answers
+ for, kept as one.
+ """
+ held: list[str] = []
+ for entry in spec.get("material", []):
+ rel = entry if isinstance(entry, str) else (entry or {}).get("path")
+ if isinstance(rel, str) and rel:
+ held.append(rel)
+ return held
+
+
def _place_for(
case: Case, proof_id: str, spec: dict[str, Any]
) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
- """File the point this proof carries, or hand the composer the question.
+ """File the points this proof carries, or hand the composer the question.
- A proof is where a geolocation is concluded, so its point is what becomes a
- node — once, here, rather than on every capture taken while looking for it.
+ A proof is where a geolocation is concluded, so its points are what become
+ nodes — here, rather than on every capture taken while looking for them.
``proof_place_auto`` decides which of the two happens; neither is a
suggestion, because both spell out the analyst's own answer.
Every path restates what the proof says (``satellite.restate_proof_point``),
which is what makes a *re*-save mean something: corrected coordinates move the
- edges instead of adding a second set, and a POV answer changed on the way back
- through changes the verb. The first half of the answer is the question to ask,
- ``None`` when there is none — **a point the case already holds is neither
- filed twice nor asked about**, so a proof re-saved untouched stays silent while
- still restating what it says. The second half is the points it let go of.
+ edges instead of adding a second set, a point taken off the list rends its
+ place, and POV moved to another line changes both verbs. The first half of the
+ answer is what the composer has to report — what was filed, and what it must
+ ask about — ``None`` when there is neither, so **a point the case already holds
+ is neither filed twice nor asked about** and a proof re-saved untouched stays
+ silent while still restating what it says. The second half is the points it let
+ go of.
"""
- point = satellite_engine.own_point(spec)
- pov = bool(spec.get("pov"))
- if point is None:
- # the coordinate field was cleared: the proof withdraws the point it stated
- return None, satellite_engine.restate_proof_point(case, proof_id, None, pov=pov)
- standing = satellite_engine.place_at(case, point["lat"], point["lon"], keyed_only=False)
- if standing is not None:
- # nothing to file, so nothing to ask — but the proof still says it is there
- return None, satellite_engine.restate_proof_point(
- case, proof_id, standing["id"], pov=pov
- )
- if not config.load_settings().get("proof_place_auto", True):
- # the point moved somewhere the case cannot hold yet: the old claim is
- # withdrawn either way, and the new one waits on the analyst's yes
- released = satellite_engine.restate_proof_point(case, proof_id, None, pov=pov)
- return {
- "filed": False,
- "lat": point["lat"],
- "lon": point["lon"],
- # so the question can say what the point will mean
- "pov": pov,
- }, released
- place, released = file_proof_place(case, proof_id, point["lat"], point["lon"], pov=pov)
- return {"filed": True, "id": place["id"], "label": place["label"]}, released
-
-
-def file_proof_place(
- case: Case, proof_id: str, lat: float, lon: float, *, pov: bool = False
-) -> tuple[dict[str, Any], list[dict[str, Any]]]:
- """Write the place, then resolve its country, as every other place save does.
-
- Shared by the automatic path above and the composer's own answer to the
- question, so both leave exactly the same trace.
+ return _state_points(
+ case,
+ proof_id,
+ satellite_engine.spec_points(spec),
+ auto=bool(config.load_settings().get("proof_place_auto", True)),
+ )
+
+
+def _state_points(
+ case: Case, proof_id: str, points: list[dict[str, Any]], *, auto: bool
+) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
+ """File what has nowhere to live yet, then state the whole list at once.
+
+ **Only the conclusion is looked up.** Geography costs a paced Nominatim call
+ (``engine/geo._pace``), so three points would hold the save for three seconds
+ to answer a question the Locate pass answers for free: the first point is
+ resolved because the analyst is about to look at it, and the rest are born
+ unlocated for that pass to pick up, exactly as an offline save already is.
+ """
+ stated: list[dict[str, Any]] = []
+ filed: list[dict[str, Any]] = []
+ asking: list[dict[str, Any]] = []
+ for rank, point in enumerate(points):
+ standing = satellite_engine.place_at(case, point["lat"], point["lon"], keyed_only=False)
+ if standing is not None:
+ stated.append({"id": standing["id"], "pov": point["pov"]})
+ continue
+ if not auto:
+ # the point moved somewhere the case cannot hold yet: the old claim is
+ # withdrawn either way, and the new one waits on the analyst's yes
+ asking.append(
+ {
+ "lat": point["lat"],
+ "lon": point["lon"],
+ "label": point["label"],
+ # so the question can say what the point will mean
+ "pov": point["pov"],
+ }
+ )
+ continue
+ place = satellite_engine.place_for_proof(case, point)
+ if rank == 0:
+ locate_on_save(case, place["id"], point["lat"], point["lon"])
+ stated.append({"id": place["id"], "pov": point["pov"]})
+ filed.append({"id": place["id"], "label": place["label"]})
+ released = satellite_engine.restate_proof_point(case, proof_id, stated)
+ answer = {"filed": filed, "asking": asking} if (filed or asking) else None
+ return answer, released
+
+
+def file_proof_points(case: Case, proof: dict[str, Any]) -> list[dict[str, Any]]:
+ """File every point a saved proof states, whatever the setting says.
+
+ The composer's yes, and the sheet's way of filing a point the composer would
+ have asked about. The spec on disk is the authority — it was written a moment
+ ago by the save that raised the question, and re-reading it is what keeps the
+ answer about the proof rather than about whatever the caller still held.
"""
- place, released = satellite_engine.place_for_proof(case, proof_id, lat, lon, pov=pov)
- locate_on_save(case, place["id"], lat, lon)
- return place, released
+ points = satellite_engine.spec_points(read_spec(case, proof))
+ answer, _released = _state_points(case, proof["id"], points, auto=True)
+ return (answer or {}).get("filed", [])
@router.post("/cases/{case_id}/proofs/{name}/place")
-def save_proof_place(case_id: str, name: str, body: ProofPlaceIn) -> dict[str, Any]:
- """File the point of a proof the composer just asked the analyst about.
-
- The other half of ``proof_place_auto`` being off: the save reported a point
- with nowhere to live, the composer asked, and this is the yes. It re-checks
- that nothing stands there, so two open tabs answering the same question file
- one place rather than two.
+def save_proof_place(case_id: str, name: str) -> list[dict[str, Any]]:
+ """File the points of a proof the composer just asked the analyst about.
+
+ The other half of ``proof_place_auto`` being off: the save reported points with
+ nowhere to live, the composer asked, and this is the yes. Everything is read
+ off the spec rather than taken from the request — the points, their labels,
+ which one is POV — so two open tabs answering the same question file one set of
+ places rather than two, and a point somebody filed in between is joined instead
+ of minted again.
"""
case = get_case(case_id)
proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(slugify(name, "proof")))
if proof is None:
raise HTTPException(status_code=404, detail="no such proof")
- # POV is read off the spec on disk rather than taken from the body: it is a
- # property of the proof that was just saved, not of the answer to the question.
- pov = bool(_read_spec(case, proof).get("pov"))
- existing = satellite_engine.place_at(case, body.lat, body.lon, keyed_only=False)
- if existing is not None:
- # somebody filed that point between the question and the yes: the proof
- # joins the place standing there rather than minting a second one
- satellite_engine.restate_proof_point(case, proof["id"], existing["id"], pov=pov)
- return existing
- place, _released = file_proof_place(case, proof["id"], body.lat, body.lon, pov=pov)
- return place
-
-
-def _read_spec(case: Case, proof: dict[str, Any]) -> dict[str, Any]:
+ return file_proof_points(case, proof)
+
+
+def read_spec(case: Case, proof: dict[str, Any]) -> dict[str, Any]:
"""The saved spec of a proof, or an empty one if it cannot be read."""
rel = (proof.get("attrs") or {}).get("spec")
if not isinstance(rel, str) or not rel:
@@ -510,7 +587,8 @@ def _read_spec(case: Case, proof: dict[str, Any]) -> dict[str, Any]:
@router.delete("/cases/{case_id}/proofs/{name}")
def delete_proof(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
- rel = layout.proof_spec_rel(name)
+ # Named the way the save named it — see `api/satellite.delete_search_grid`.
+ rel = layout.proof_spec_rel(slugify(name, "proof"))
try:
case.resolve_inside(rel)
except CaseError as exc:
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 08e94a6..4fb6fb8 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -21,6 +21,7 @@ from pydantic import BaseModel, Field
from .. import config
from ..engine import (
+ cities,
geo,
google_tiles,
localtime,
@@ -91,7 +92,10 @@ class PlaceIn(BaseModel):
class ParseIn(BaseModel):
- text: str
+ #: One coordinate, however it is spelled. Bounded on the field rather than through
+ #: `server.BulkBodyLimit`: the middleware is for bodies too big to parse, and a
+ #: position never is — what this stops is a paste into the box arriving as a document.
+ text: str = Field(max_length=2000)
class SatelliteUpdateIn(BaseModel):
@@ -481,6 +485,47 @@ def geocode(q: str) -> dict[str, Any]:
return result
[email protected]("/geo/suggest")
+def suggest_offline(
+ q: str, limit: int = Query(default=8, ge=1, le=20)
+) -> dict[str, Any]:
+ """What the search bar can offer on a keystroke, without touching the network.
+
+ Two things: the coordinates the text parses to, if it parses, and cities from
+ the bundled gazetteer. The geocoder is deliberately not consulted here — see
+ `/geo/places`, which the UI only calls once typing stops.
+ """
+ query = q.strip()
+ parsed = geo.parse_coords(query) if query else None
+ found = cities.search(query, limit) if query else []
+ return {
+ "coords": {"lat": parsed[0], "lon": parsed[1]} if parsed else None,
+ "cities": found,
+ "attribution": cities.ATTRIBUTION if found else None,
+ }
+
+
[email protected]("/geo/places")
+def suggest_places(q: str, limit: int = Query(default=5, ge=1, le=10)) -> dict[str, Any]:
+ """Geocoder matches for a partial place name: the slow layer under `/geo/suggest`.
+
+ Never called on a keystroke. `busy` says the request was dropped rather than
+ queued, which is not the same as the geocoder having nothing.
+ """
+ query = q.strip()
+ if not query:
+ raise HTTPException(status_code=422, detail="empty query")
+ found = geo.suggest(query, limit)
+ if found is None:
+ return {"places": [], "busy": True, "throttled": geo.throttled(), "attribution": None}
+ return {
+ "places": found,
+ "busy": False,
+ "throttled": False,
+ "attribution": "© OpenStreetMap contributors (Nominatim)" if found else None,
+ }
+
+
@router.get("/geo/reverse")
def reverse(lat: float, lon: float) -> dict[str, Any]:
result = geo.reverse_geocode(lat, lon)
@@ -1133,10 +1178,15 @@ def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any
@router.delete("/cases/{case_id}/search-grids/{name}")
def delete_search_grid(case_id: str, name: str) -> dict[str, Any]:
- """Discard one saved grid."""
+ """Discard one saved grid.
+
+ The name goes through `slugify` exactly as the save did: the delete has to
+ address the file the save wrote, and a raw name is one `\\` away from
+ addressing a different one on Windows.
+ """
case = get_case(case_id)
try:
- spec_path = case.resolve_inside(layout.grid_rel(name))
+ spec_path = case.resolve_inside(layout.grid_rel(slugify(name, "grid")))
except CaseError as exc:
raise HTTPException(status_code=403, detail=str(exc)) from exc
existed = spec_path.exists()
diff --git a/src/azimut/api/sheetproofs.py b/src/azimut/api/sheetproofs.py
new file mode 100644
index 0000000..8ff87ec
--- /dev/null
+++ b/src/azimut/api/sheetproofs.py
@@ -0,0 +1,658 @@
+"""REST API for building proofs out of a geolocation index.
+
+The one road out of a sheet that goes and fetches bytes, and therefore the one that is
+not a mode of the pass. Two routes:
+
+- ``POST .../proofs/preview`` reads the plan. Offline: the three refusals come out of the
+ cells and the three "already there" answers come out of the case, so an analyst knows
+ what a hundred downloads would do before one of them starts.
+- ``POST .../proofs`` starts a job and hands back its id. The browser polls
+ ``GET /api/jobs/{id}`` for a per-row progress and ``POST /api/jobs/{id}/cancel`` to stop
+ it, which is the same pattern a media download already follows.
+
+**Atomic per row, not over the batch** — the opposite of the pass, for the opposite
+reason. Failing at row 47 is no reason to hand back the 46 that worked, so each row is its
+own unit: the files are fetched into a staging directory first, and nothing enters the
+case until both of them are held. A row that cannot be reached writes nothing at all and
+is simply taken again at the next press.
+
+**Pressing twice is safe without a memory of the first press.** A proof is found by the
+name it would be saved under, a media by the page it was downloaded from, and a place by
+its point — three questions the case answers on its own. So a browser that closed halfway
+through, or a job that died, costs one press and never a twin.
+
+Nothing is reimplemented here. `proofimports.write_import` writes the constellation, the
+composer's own save writes the proof, and `satellite` files the points.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from .. import config, jobs, layout
+from ..engine import links as link_engine
+from ..engine import media as media_engine
+from ..engine import proofimport as import_engine
+from ..engine import satellite as satellite_engine
+from ..engine import sheetpromote as promote_engine
+from ..engine import sheetproofs as build_engine
+from ..engine import sheets as sheet_engine
+from ..workspace import Case, CaseError, ensure_dir
+from . import proofimports, proofs
+from .cases import get_case
+from .satellite import locate_on_save
+
+router = APIRouter(prefix="/api/cases", tags=["sheets"])
+
+
+class SheetBuildIn(BaseModel):
+ """One declaration of which column holds what, and the rows to build from.
+
+ The table travels with the request for the same reason every other road out of a sheet
+ takes it: the analyst builds from what is on screen, which may hold edits the autosave
+ has not written yet.
+ """
+
+ #: The same ceilings every other model carrying a table declares, so the refusal comes
+ #: from the shape of the table rather than from whatever the engine reaches first.
+ columns: list[str] = Field(default_factory=list, max_length=sheet_engine.MAX_COLUMNS)
+ rows: list[list[str]] = Field(default_factory=list, max_length=sheet_engine.MAX_ROWS)
+ #: Bounded at the pass's own ceiling rather than at this road's, so the hundred-row cap
+ #: is refused by the engine — which says how many are left — instead of by the model,
+ #: which can only say the list is too long.
+ keys: list[str] = Field(default_factory=list, max_length=promote_engine.MAX_PROMOTED)
+ #: The name the proof is saved under, so also its filename.
+ title: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ #: The address of what was filmed on the spot.
+ source: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ #: The address of the published geolocation picture.
+ proof: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ point: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ note: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ status: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ #: Which states are left out. Absent means the default one; an empty list means the
+ #: analyst put the ruled-out rows back, which is a different answer and has to survive
+ #: as one.
+ skip_states: list[str] | None = Field(default=None, max_length=20)
+ #: Whether the camera was at the point. One answer for the press: a column of its own
+ #: waits for a binder that actually holds one.
+ pov: bool = False
+ #: Rows the analyst read in the plan and put aside.
+ skip: list[str] = Field(default_factory=list, max_length=build_engine.MAX_ROWS)
+
+
+def _declaration(body: SheetBuildIn) -> dict[str, Any]:
+ """The arguments the plan and the press both take, stated once."""
+ return {
+ "columns": body.columns,
+ "rows": body.rows,
+ "keys": body.keys,
+ "title": body.title,
+ "source": body.source,
+ "proof": body.proof,
+ "point": body.point,
+ "note": body.note,
+ "status": body.status,
+ "skip_states": body.skip_states,
+ "pov": body.pov,
+ }
+
+
+def _planned(case: Case, body: SheetBuildIn) -> dict[str, Any]:
+ names, table = sheet_engine.normalize(body.columns, body.rows)
+ return build_engine.plan(case, **{**_declaration(body), "columns": names, "rows": table})
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/proofs/preview")
+def preview_build(case_id: str, sheet_id: str, body: SheetBuildIn) -> dict[str, Any]:
+ """What a build would write, with nothing downloaded and nothing written."""
+ case = get_case(case_id)
+ try:
+ return _planned(case, body)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/proofs")
+def build_proofs(case_id: str, sheet_id: str, body: SheetBuildIn) -> dict[str, str]:
+ """Start the build, and answer with the job that is doing it.
+
+ The plan is read here rather than in the thread, so a declaration the door refuses
+ comes back as a refusal on the press instead of a job that fails a second later.
+ """
+ case = get_case(case_id)
+ try:
+ reading = _planned(case, body)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ left_out = set(body.skip)
+ doing = [
+ decision
+ for decision in reading["rows"]
+ if decision["action"] in build_engine.DOING and decision["key"] not in left_out
+ ]
+ def work(set_progress: Any, stopping: Any) -> dict[str, Any]:
+ done: list[dict[str, Any]] = []
+ for at, decision in enumerate(doing):
+ if stopping():
+ break
+ set_progress({
+ "done": at,
+ "total": len(doing),
+ "key": decision["key"],
+ "label": decision["title"] or decision["coords"],
+ })
+ wrote = _build_row(case, case_id, decision, pov=body.pov, stopping=stopping)
+ # `None` is the row that was cancelled after its downloads and before its
+ # write. It is not a failure and it is not a result — it is a row nobody asked
+ # for any more, and the next press takes it exactly as it was.
+ if wrote is None:
+ break
+ done.append(wrote)
+ set_progress({"done": len(done), "total": len(doing)})
+ return {
+ "rows": done,
+ "counts": {
+ word: sum(1 for row in done if row["outcome"] == word)
+ for word in ("built", "restated", "failed")
+ },
+ "links": _sidecar(body, done),
+ "stopped": len(done) < len(doing),
+ }
+
+ return {"job_id": jobs.start("sheet-proofs", work, stoppable=True)}
+
+
+#: Which column a row's cell points at, once the row has produced it. The sidecar keys
+#: entities by the column their cell sits in, so a built row gets its own chips: the title
+#: points at the proof it named, the two addresses at the files they fetched, and the
+#: coordinates at the ground.
+_IN_COLUMN = {"proof": "title", "source": "source", "panel": "proof", "place": "point"}
+
+
+def _sidecar(body: SheetBuildIn, done: list[dict[str, Any]]) -> dict[str, dict[str, str]]:
+ """What the browser writes back into the sheet's sidecar, by row key then column.
+
+ Handed back rather than written here: the sheet's file is the browser's to save, and a
+ job holding a stamp for two minutes would fight every autosave in that window. What
+ makes a second press safe is the case itself, so a sidecar that never arrives costs
+ the chips and never a duplicate.
+ """
+ named = {slot: getattr(body, field) for slot, field in _IN_COLUMN.items()}
+ found: dict[str, dict[str, str]] = {}
+ for row in done:
+ cells = {
+ named[slot]: entity
+ for slot, entity in (row.get("made") or {}).items()
+ if named.get(slot)
+ }
+ if cells:
+ found[row["key"]] = cells
+ return found
+
+
+# -- one row ------------------------------------------------------------------
+
+
+def _build_row(
+ case: Case,
+ case_id: str,
+ decision: dict[str, Any],
+ *,
+ pov: bool,
+ stopping: Any,
+) -> dict[str, Any] | None:
+ """Build one row, and answer with what it wrote or why it could not.
+
+ A row never raises: a dead link on line 12 is a fact about line 12, and taking the job
+ down over it would lose the eleven rows above and the eighty-eight below. What it
+ answers with is what the grid logs beside the row and what the sidecar records, so the
+ next press knows this line is done.
+
+ ``None`` is the one answer that is neither: a cancel that landed while this row was
+ downloading. The bytes are dropped with the staging directory and the case never heard
+ of the row, which is what makes cancelling safe to press.
+ """
+ answer: dict[str, Any] = {
+ "key": decision["key"],
+ "outcome": "failed",
+ "reason": "",
+ "made": {},
+ }
+ point = decision["point"] or {}
+ try:
+ if decision["proof_url"]:
+ written = _row_proof(case, case_id, decision, pov=pov, stopping=stopping)
+ elif decision["source_url"]:
+ written = _row_media(case, decision, pov=pov, stopping=stopping)
+ else:
+ written = {"place": _place_for(case, point["lat"], point["lon"])}
+ answer["made"] = {slot: entity["id"] for slot, entity in written.items() if entity}
+ answer["outcome"] = "restated" if decision["action"] != "make" else "built"
+ except _Stopped:
+ return None
+ except _RowFailed as failure:
+ answer["reason"] = str(failure)
+ except Exception as failure: # noqa: BLE001 — a row is not allowed to end the press
+ # Broad on purpose, and it is the whole promise of this road: whatever a
+ # downloader raises about one address — and they raise anything — costs that row
+ # and no other. The reason is kept whole so the grid can show what happened rather
+ # than "it did not work".
+ answer["reason"] = str(getattr(failure, "detail", None) or failure)
+ return answer
+
+
+class _RowFailed(Exception):
+ """What stopped one row, in the words the grid shows beside it."""
+
+
+def _walled(answer: dict[str, Any]) -> str:
+ """A login wall, said with the next move rather than with the platform's wording.
+
+ A stored session has already been tried by the time a row comes back walled, so the
+ three cases are different instructions and not one sentence: none saved, one saved
+ that did not get through, and Windows refusing to hand over a Chromium store at all.
+ """
+ if answer.get("guidance") == "windows-chromium":
+ return "needs a login: Windows locks Chrome's cookies, use a cookies.txt file"
+ if answer.get("refused"):
+ return "needs a login: the browser in Settings is not signed in to this site"
+ session = media_engine.cookies_from_preference(
+ config.load_settings().get("download_cookies")
+ )
+ return (
+ "needs a login: the browser in Settings is not signed in to this site"
+ if session
+ else "needs a login: pick your browser in Settings → Downloads"
+ )
+
+
+class _Stopped(Exception):
+ """A cancel that arrived while this row was on the network.
+
+ Raised where the bytes are held and nothing is filed yet, which is the last moment a
+ row can be abandoned without leaving anything of itself in the case.
+ """
+
+
+def _place_for(case: Case, lat: float, lon: float) -> dict[str, Any]:
+ """The place at this point, reused when one already stands there.
+
+ Filed unnamed, by its coordinates, exactly as the composer files a proof's point: a
+ place is the one entity in this app whose identity is a number, and two rows about the
+ same spot are one pin. The sheet's own title names the *proof*, not the ground.
+ """
+ standing = satellite_engine.place_at(case, lat, lon, keyed_only=False)
+ if standing is not None:
+ return standing
+ place = satellite_engine.save_place(
+ case,
+ lat,
+ lon,
+ by=build_engine.BY,
+ extra_attrs={satellite_engine.COORD_KEY: satellite_engine.coord_key(lat, lon)},
+ )
+ # Never fatal, by construction: the lookup swallows a Nominatim that did not answer
+ # and the Locate pass retries what it left `failed`. A point without a country is
+ # still a point, and losing a hundred of them to one timeout would not be.
+ locate_on_save(case, place["id"], lat, lon)
+ return place
+
+
+#: What each slot has somewhere to put. The panel is a picture — that is what a proof is
+#: composed of — and the source is the footage. Which is also how a post carrying both is
+#: told apart without asking: a hundred rows cannot each raise a picker.
+_SLOT_WANTS = {import_engine.SLOT_PANEL: "image", import_engine.SLOT_SOURCE: "video"}
+
+
+def _fetch(case: Case, token: str, slot: str, url: str) -> dict[str, Any]:
+ """One download into the staging directory, with its failures named.
+
+ The names matter more than usual here: a hundred rows cannot each raise a dialog, so
+ what a row could not do has to be legible in one line of a log.
+
+ **A post with several attachments is answered rather than refused.** That is the
+ ordinary shape of the thing this road is for — a published geolocation is a picture,
+ and the post carries the footage beside it — so the slot's own kind picks the one it
+ has somewhere to put, and only a post holding nothing of that kind is a row to do by
+ hand.
+ """
+ stage = import_engine.staging_dir(case, token)
+ ensure_dir(stage)
+ wants = _SLOT_WANTS.get(slot, "")
+ try:
+ result = media_engine.fetch_url(case, url, stage=stage, wants=wants)
+ except media_engine.WrongKind as refusal:
+ # The post was read and holds nothing this slot has room for. One line, because a
+ # hundred rows cannot each raise a dialog and this one is actionable: the row goes
+ # to the pile to do by hand.
+ raise _RowFailed(str(refusal)) from refusal
+ if result.get("multi"):
+ return _every_file(case, token, slot, url, result, stage=stage)
+ if result.get("needs_auth"):
+ raise _RowFailed(_walled(result))
+ staged = result.get("staged")
+ if not staged:
+ raise _RowFailed("nothing at that address could be downloaded")
+ # Keyed by its address, so a row listing three of them holds three sets rather than
+ # each one wiping the last.
+ import_engine.fill_files(case, token, slot, [staged], for_url=url)
+ return staged
+
+
+#: What a slot can use out of a post carrying several attachments. A panel is a picture
+#: by definition; material is whatever was recorded on the spot, which is why a still
+#: photographed there counts and a PDF hanging off the post does not.
+_SLOT_KINDS = {
+ import_engine.SLOT_PANEL: ("image",),
+ import_engine.SLOT_SOURCE: ("image", "video", "audio"),
+}
+
+#: What a row says the post was missing, in the words of what the slot is for.
+_SLOT_MISSING = {import_engine.SLOT_PANEL: "image", import_engine.SLOT_SOURCE: "media"}
+
+
+def _every_file(
+ case: Case,
+ token: str,
+ slot: str,
+ url: str,
+ offered: dict[str, Any],
+ *,
+ stage: Any,
+) -> dict[str, Any]:
+ """Take the whole set a post carries, in the order it published it.
+
+ A post that publishes a geolocation as several pictures — the overhead, the ground
+ shot, the match — published *one* proof, and keeping the first of three keeps a third
+ of it. They become the panels of one composition, which is what a proof already is.
+ The material side answers the same way for the same reason: a post carrying two photos
+ of the scene and the clip under them is three things that were shot there, and a
+ hundred rows cannot each be asked which one counted.
+
+ A slot takes only what it can use — pictures for the panels, anything recorded for the
+ material — and a post holding none of it is a row to do by hand.
+ """
+ kinds = _SLOT_KINDS.get(slot, ())
+ # Vouched for as the post's own, and of a kind this slot can use. A hundred rows
+ # cannot each be asked whether the clip a post quotes belongs to the geolocation,
+ # and taking it would file somebody else's video on this row's point.
+ wanted = [
+ item
+ for item in offered.get("items") or []
+ if item.get("kind") in kinds and item.get("own", True)
+ ]
+ if not wanted:
+ held_count = len(offered.get("items") or [])
+ # Named for what the slot was after rather than for the kind it prefers: the
+ # material takes a photograph as readily as a clip, so "no video" would be a
+ # refusal about the wrong thing.
+ raise _RowFailed(
+ f"that post holds {held_count} files and no {_SLOT_MISSING[slot]}, "
+ "so pick one by hand"
+ )
+ held: list[dict[str, Any]] = []
+ cap = import_engine.SLOT_CAPS[slot]
+ for item in wanted[:cap]:
+ # Asked for by its own kind: `wants="image"` is what reaches the image extractor
+ # for a picture yt-dlp would answer with the clip quoted beside it.
+ answer = media_engine.fetch_url(
+ case, url, index=int(item["index"]), stage=stage, wants=str(item.get("kind") or "")
+ )
+ if answer.get("needs_auth"):
+ raise _RowFailed(_walled(answer))
+ staged = answer.get("staged")
+ if staged:
+ held.append(staged)
+ if not held:
+ raise _RowFailed("nothing could be downloaded from that address")
+ import_engine.fill_files(case, token, slot, held, for_url=url)
+ return held[0]
+
+
+def _row_media(
+ case: Case,
+ decision: dict[str, Any],
+ *,
+ pov: bool,
+ stopping: Any,
+) -> dict[str, Any]:
+ """A row with footage and a point but no published proof: the media, on its ground.
+
+ Downloaded to staging and filed from there rather than straight into the case, so a
+ row that stops halfway leaves the case untouched — the same order the proof road
+ takes, for the same reason.
+ """
+ point = decision["point"]
+ filed: list[dict[str, Any]] = []
+ wanted: list[str] = []
+ for url in decision["source_urls"]:
+ held = build_engine.held_media(case, url)
+ if held is None:
+ wanted.append(url)
+ else:
+ filed.append(held)
+ if wanted:
+ token = import_engine.open_import(case)
+ try:
+ for url in wanted:
+ _fetch(case, token, import_engine.SLOT_SOURCE, url)
+ if stopping():
+ raise _Stopped()
+ pairs = import_engine.staged_pairs(case, token, import_engine.SLOT_SOURCE)
+ if not pairs:
+ raise _RowFailed("the download is no longer held")
+ for path, staged in pairs:
+ produced = media_engine.import_produced_file(
+ case, path, str(staged["filename"]), dict(staged.get("source") or {}),
+ by=build_engine.BY,
+ )
+ filed.append(produced["entity"])
+ finally:
+ import_engine.discard(case, token)
+ place = _place_for(case, point["lat"], point["lon"])
+ verb = build_engine.proof_verb(pov)
+ # Each file states the point for itself: they were all recorded there, and an edge
+ # standing on only the first would leave the rest off the map.
+ for one in filed:
+ _state(case, one["id"], place["id"], verb)
+ made: dict[str, Any] = {"source": filed[0], "place": place}
+ made.update({f"source {at + 2}": one for at, one in enumerate(filed[1:])})
+ return made
+
+
+def _row_proof(
+ case: Case,
+ case_id: str,
+ decision: dict[str, Any],
+ *,
+ pov: bool,
+ stopping: Any,
+) -> dict[str, Any]:
+ """A row with everything: the footage, the picture, the proof and the point.
+
+ Written by `proofimports.write_import`, so the five edges are the ones a hand-made
+ import writes and there is no second reading of them here.
+ """
+ point = decision["point"]
+ if decision["action"] == "join":
+ return _added_point(case, decision, pov=pov)
+ form = {
+ "title": decision["title"],
+ # The canonical spelling of the point this row was planned on, rather than the
+ # cell: the import reads coordinates with its own parser, and handing it the two
+ # numbers is what keeps the plan and the press about the same spot.
+ "coords": f"{point['lat']}, {point['lon']}",
+ "source_urls": decision["source_urls"],
+ "note": decision["note"],
+ "pov": pov,
+ }
+ if decision["action"] == "update":
+ return _restate_proof(case, case_id, decision, form, pov=pov)
+
+ token = import_engine.open_import(case)
+ try:
+ for url in decision["source_urls"]:
+ _fetch(case, token, import_engine.SLOT_SOURCE, url)
+ _fetch(case, token, import_engine.SLOT_PANEL, decision["proof_url"])
+ # The last moment this row is only bytes. Past it the media are filed and a cancel
+ # can no longer mean "as if it never ran".
+ if stopping():
+ raise _Stopped()
+ written = proofimports.write_import(case_id, token, form, by=build_engine.BY)
+ finally:
+ # A no-op once the import committed, since it discards its own directory; the
+ # point of it is the row that stopped between the two downloads.
+ import_engine.discard(case, token)
+ made: dict[str, Any] = {}
+ for slot in ("source", "panel"):
+ entry = written.get(slot)
+ if entry:
+ made[slot] = {"id": entry["id"], "label": entry.get("label") or ""}
+ proof = written.get("proof") or {}
+ if proof.get("id"):
+ made["proof"] = {"id": proof["id"], "label": proof.get("name") or ""}
+ place = written.get("place")
+ if place:
+ made["place"] = place
+ return made
+
+
+def _added_point(case: Case, decision: dict[str, Any], *, pov: bool) -> dict[str, Any]:
+ """A second row about a proof this press already built: its other point.
+
+ The binder's cross-border shape — one video, one published picture, two places, so two
+ lines. Composing the picture again under the second row's name would put two exports of
+ one image in the case, and **a proof concludes on one point** by design: reopening it
+ with different coordinates withdraws the first, or the case reads as two geolocations
+ (ONTOLOGY §"Where a geolocation becomes a point").
+
+ So the composition is not written twice — but the point still belongs to it. The
+ published proof is what establishes both positions, and that is what the analyst is
+ saying by writing two lines about one picture, so **the proof reaches this place too**.
+ Written under this road's own provenance, so the graph says which press wrote it, and
+ the composer **opens on it** rather than beside it (``satellite.open_spec``): the proof
+ reads the same in the tool that made it as it does on the map. Which also means the
+ composer can take it back — a row it shows is a row it owns
+ (``satellite.restate_proof_point``), and a point nothing can delete is worse than one
+ that was never offered.
+
+ `depicts` and never `located-at`, whatever POV says: a proof was composed and recorded
+ nowhere. POV picks the verb for the material, and only there.
+
+ **Nothing to join is this row's own failure.** When the row above did not build — a dead
+ link, a login wall, an extractor that said nothing — there is no proof and no material
+ here, and writing a place while reporting the row as restated marked it done in the
+ grid's log with its point resting on nothing. The next press would not take it again.
+ """
+ panel = build_engine.held_media(case, decision["proof_url"])
+ sources = [
+ one
+ for one in (build_engine.held_media(case, url) for url in decision["source_urls"])
+ if one is not None
+ ]
+ proof = build_engine.built_proof(case, decision["proof_url"])
+ if proof is None and panel is None and not sources:
+ raise _RowFailed("the row this one joins did not build")
+ # Read before the place is filed, so a row with nothing to join leaves no bare pin
+ # behind either.
+ point = decision["point"]
+ place = _place_for(case, point["lat"], point["lon"])
+ verb = build_engine.proof_verb(pov)
+ made: dict[str, Any] = {"place": place}
+ named = [("panel", panel)] + [
+ (f"source {at + 2}" if at else "source", one) for at, one in enumerate(sources)
+ ]
+ for slot, held in named:
+ if held is None:
+ continue
+ _state(case, held["id"], place["id"], verb)
+ made[slot] = held
+ if proof is not None:
+ _state(case, proof["id"], place["id"], link_engine.DEPICTS)
+ made["proof"] = proof
+ return made
+
+
+def _restate_proof(
+ case: Case, case_id: str, decision: dict[str, Any], form: dict[str, Any], *, pov: bool
+) -> dict[str, Any]:
+ """A second press over a proof this sheet already built: its point and its note.
+
+ Nothing is fetched — the files are already in the case, and re-downloading them to
+ learn what the case already knows is what the plan exists to avoid. The proof is saved
+ through the composer's own route, so a corrected point moves its edges instead of
+ stating a second geolocation.
+
+ A blank note leaves the caption alone. The column says what the worklist knows about
+ the row; an empty cell is nothing said, not an instruction to erase what somebody
+ wrote in the composer.
+ """
+ proof = case.get_entity(str(decision["entity"] or ""))
+ if proof is None:
+ raise _RowFailed("that proof is no longer in the case")
+ spec = dict(proofs.read_spec(case, proof))
+ if not spec:
+ raise _RowFailed("that proof's composition could not be read")
+ # Through the engine rather than by hand: a proof composed with several points
+ # holds a list, and setting the old field beside it would be read as nothing
+ # said. A sheet row states one point, and this is how it says so.
+ satellite_engine.state_points(spec, [{"coords": form["coords"], "pov": form["pov"]}])
+ if form["note"]:
+ panels = [dict(panel) for panel in spec.get("panels") or []]
+ if panels:
+ panels[0]["caption"] = form["note"]
+ spec["panels"] = panels
+ # The name follows the cell, which is what makes the Title column the proof's name
+ # rather than a label it was given once. A rename moves the spec and the export; a name
+ # another proof already holds is refused, and that refusal is this row's alone.
+ standing = str(proof["label"])
+ wanted = decision["title"] or standing
+ saved = proofs.save_proof(
+ case_id,
+ proofs.ProofIn(
+ title=wanted,
+ spec=spec,
+ rename_from=standing if layout.slugify(wanted, "Proof") != standing else None,
+ ),
+ )
+ # The save already settled the point — it restates what a proof says on every save —
+ # so the place is read off its answer rather than filed a second time. `None` there
+ # means the case already held that point, which is the quiet common case.
+ lat, lon = decision["point"]["lat"], decision["point"]["lon"]
+ reported = saved.get("place") or {}
+ filed = reported.get("filed") or []
+ if filed:
+ place = case.get_entity(str(filed[0]["id"]))
+ elif reported.get("asking"):
+ # `proof_place_auto` is off, so the composer's own save would have asked. The
+ # analyst answered when they read the plan.
+ filed = proofs.file_proof_points(case, proof)
+ place = case.get_entity(str(filed[0]["id"])) if filed else None
+ else:
+ place = satellite_engine.place_at(case, lat, lon, keyed_only=False)
+ return {
+ "proof": {"id": proof["id"], "label": str(saved["name"])},
+ "place": place,
+ }
+
+
+def _state(case: Case, subject: str, place: str, verb: str) -> None:
+ """Put a file on its ground, skipping an edge the vocabulary refuses.
+
+ A PDF cannot be `located-at` anywhere, and no reading of the two types alone rules it
+ out — so the refusal is a fact about that row rather than a reason to lose the media
+ it had just filed.
+ """
+ try:
+ link_engine.add_relation(case, subject, place, verb, by=build_engine.BY)
+ except CaseError:
+ return
diff --git a/src/azimut/api/sheets.py b/src/azimut/api/sheets.py
new file mode 100644
index 0000000..f769e87
--- /dev/null
+++ b/src/azimut/api/sheets.py
@@ -0,0 +1,862 @@
+"""REST API for case sheets: list, create, import, read, save and hand over.
+
+Three of the routes here are not about the table at all, and they exist because the
+grid's own state and the file's own state are different things:
+
+- ``PUT .../meta`` writes the sidecar alone. A filter, a colour, a hidden column and a
+ pinned row are the grid, not the table, and rewriting the CSV to record one of them
+ moved the modification time the stamp is made of.
+- ``GET .../stamp`` is a stat, asked when the window comes back into focus, so an analyst
+ who edited the file in a spreadsheet hears about it then rather than at their next save.
+- ``POST .../links/check`` asks whether a column of sources still answers. It reaches the
+ network, and only on a press. The other road that does is not here at all: building
+ proofs out of a geolocation index runs as a job in `api/sheetproofs.py`, because it
+ fetches files and everything in this module is a reading of what the analyst typed.
+
+The tables themselves live in `engine/sheets.py`, which owns the one CSV parser
+and the one CSV writer in the app. That matters more here than it looks: the
+browser never parses or serialises CSV, so an imported file and a saved grid go
+through the same code and cannot drift into two readings of the same table.
+
+An import therefore posts **text**, not a parsed table — a dropped file and a
+pasted block are the same request, and the delimiter is guessed on the side that
+will write the file back.
+
+Saving also restates what the sheet's cells point at. Every entity a cell links to
+becomes a ``mentions`` edge, so a row naming a subject is visible from that
+subject's side too, and a link the analyst clears loses its edge on the next save.
+
+A save is **conditional**. The read handed out a stamp of the file; presenting it
+back is what proves the grid is editing the table that is on disk. Since the file is
+the artifact, the analyst may well have it open in a spreadsheet at the same time,
+and a 409 telling them to reload is the only honest answer to two writers.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException, UploadFile
+from pydantic import BaseModel, Field
+
+from .. import layout
+from ..engine import exportdir
+from ..engine import reveal as reveal_engine
+from ..engine import sheetfromcase as fromcase_engine
+from ..engine import sheetlinks
+from ..engine import sheetpass as pass_engine
+from ..engine import sheetpromote as promote_engine
+from ..engine import sheetroles
+from ..engine import sheets as sheet_engine
+from ..engine import sheetxlsx as xlsx_engine
+from ..workspace import CaseError
+from .cases import get_case
+
+router = APIRouter(prefix="/api/cases", tags=["sheets"])
+
+#: JSON overhead above a full table of maximum cells. Enforced by the ASGI body
+#: guard in `server.py` before Pydantic materialises the request.
+MAX_SHEET_BODY_BYTES = 32_000_000
+
+#: Where a downloaded file records the page it came from (`engine/media.py`). Matched
+#: rather than guessed at: it is the one field that means "this file came from that
+#: page", where a title looking like a filename means nothing at all.
+SOURCE_URL_ATTR = "source_url"
+
+
+class SheetIn(BaseModel):
+ title: str = Field(min_length=1, max_length=200)
+
+
+class SheetImportIn(SheetIn):
+ """A CSV to file as a sheet, as the text of the file.
+
+ Text rather than an upload because the same route serves a dropped file and a
+ table pasted out of a browser, and because parsing belongs on the side that
+ writes the result back.
+ """
+
+ text: str = Field(max_length=sheet_engine.MAX_IMPORT_BYTES)
+
+
+class SheetSaveIn(BaseModel):
+ """A table to write, and the stamp of the file it was read from.
+
+ ``stamp`` is what the grid received from the read it is editing. Sent, the save
+ is refused when the file has moved on; omitted, the write is unconditional. The
+ grid always sends it — the field is optional so that a caller holding a table it
+ built itself is not made to invent one.
+ """
+
+ columns: list[str] = Field(max_length=sheet_engine.MAX_COLUMNS)
+ rows: list[list[str]] = Field(max_length=sheet_engine.MAX_ROWS)
+ meta: dict[str, Any] = Field(default_factory=dict)
+ stamp: str | None = Field(default=None, max_length=80)
+
+
+def _sheets(case: Any) -> list[dict[str, Any]]:
+ return [
+ sheet_engine.summary(case, entity)
+ for entity in case.list_entities()
+ if entity.get("type") == "sheet"
+ ]
+
+
[email protected]("/{case_id}/sheets")
+def list_sheets(case_id: str) -> dict[str, Any]:
+ return {"sheets": _sheets(get_case(case_id))}
+
+
+class SheetCreateIn(SheetIn):
+ """A new sheet, and the columns it is born with.
+
+ ``columns`` is what a template amounts to: the four tables an analyst rebuilds by hand
+ every case — a verification worklist, a geolocation index, a list of accounts, a run of
+ events — are a list of headings and nothing more. What the app should *know* about those
+ columns is a sidecar, so it arrives by the ordinary save that follows: there is one
+ writer for a sidecar and this is not it.
+ """
+
+ columns: list[str] | None = Field(default=None, max_length=sheet_engine.MAX_COLUMNS)
+
+
[email protected]("/{case_id}/sheets")
+def create_sheet(case_id: str, body: SheetCreateIn) -> dict[str, Any]:
+ """A new sheet, born with columns rather than empty.
+
+ An empty grid asks the analyst to design a table before they have anything to
+ put in it. *Subject · Status · Notes* is the worklist every case starts with,
+ and renaming a column is one click.
+ """
+ case = get_case(case_id)
+ try:
+ return sheet_engine.create(case, body.title.strip(), body.columns)
+ except (CaseError, sheet_engine.SheetError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/sheets/import")
+def import_sheet(case_id: str, body: SheetImportIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ columns, rows = sheet_engine.parse_csv(body.text)
+ return sheet_engine.create(case, body.title.strip(), columns, rows)
+ except (CaseError, sheet_engine.SheetError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
+class SheetFromCaseIn(SheetIn):
+ """A worklist to build out of the catalog, in one of two shapes.
+
+ ``generic`` is the one that was here first: one row per entity of a chosen type, with
+ the fields the analyst named. The fields are named rather than swept, because a sheet
+ holding every attribute of every entity would be a second copy of the graph, and the
+ second copy is the one that goes stale. Anything the type does not declare is dropped
+ rather than refused, the same rule a promotion's column mapping follows.
+
+ ``proofs`` reads the edges instead of the attributes: one row per proof, carrying the
+ media it was made from and the place it puts on the map. It takes neither ``type``
+ nor ``fields`` — its shape is fixed, which is what lets it be kept level with the case
+ afterwards.
+ """
+
+ shape: Literal["generic", "proofs"] = "generic"
+ # Required by `generic` and unread by `proofs`, so it cannot be a required field on
+ # the model: a caller asking for the proofs shape has no type to name.
+ type: str = Field(default="", max_length=40)
+ fields: list[str] = Field(default_factory=list, max_length=sheet_engine.MAX_COLUMNS)
+ limit: int = Field(default=fromcase_engine.MAX_FROM_CASE, ge=1)
+
+
[email protected]("/{case_id}/sheets/from-case")
+def sheet_from_case(case_id: str, body: SheetFromCaseIn) -> dict[str, Any]:
+ """File a sheet whose rows are entities the case already holds.
+
+ The other direction of the promotion road. Written in two steps on purpose: the
+ create route owns making the file, and the save owns the sidecar — so the links this
+ build hangs on the rows go through the one writer that cleans them, and the sheet
+ gains its ``mentions`` edges by the same code every other save uses.
+ """
+ case = get_case(case_id)
+ if body.shape == "generic" and not body.type.strip():
+ raise HTTPException(status_code=422, detail="a worklist needs a type to be built from")
+ try:
+ built = (
+ fromcase_engine.build_proofs(case, limit=body.limit)
+ if body.shape == "proofs"
+ else fromcase_engine.build(
+ case, entity_type=body.type, fields=body.fields, limit=body.limit
+ )
+ )
+ entity = sheet_engine.create(case, body.title.strip(), built["columns"], built["rows"])
+ saved = sheet_engine.write(
+ case, entity["id"], built["columns"], built["rows"], built["meta"]
+ )
+ except (CaseError, sheet_engine.SheetError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ _sync_mentions(case, entity["id"], saved["meta"])
+ return {**entity, "taken": built["taken"], "total": built["total"]}
+
+
+#: How many entities one request may ask the place of, and how many addresses one row may
+#: offer the media library. A bound rather than the row limit: both are answered out of the
+#: graph in one read, and a caller asking about twenty thousand is not asking a question.
+MAX_POINTS = 2000
+
+
+class SheetPointsIn(BaseModel):
+ """The entities a column's cells point at, whose place the sheet wants to read."""
+
+ ids: list[str] = Field(max_length=MAX_POINTS)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/points")
+def sheet_points(case_id: str, sheet_id: str, body: SheetPointsIn) -> dict[str, Any]:
+ """Where the case puts each of these entities.
+
+ What makes a column of place names two halves rather than one: the rows already
+ pointing at something the case has placed are answered here — exactly, offline and at
+ once — and only the words left over are worth a paced request to a geocoder that is
+ guessing from a name. Before this, a linked row cost a second of somebody else's
+ server to be told nothing.
+
+ An entity reached by two different points is left out rather than resolved: the row
+ keeps its analyst.
+ """
+ case = get_case(case_id)
+ # Checked and not read, like `match`: this is a question about the graph, and parsing
+ # twenty thousand rows to prove the caller owns a column would be a read nothing uses.
+ entity = case.get_entity(sheet_id)
+ if entity is None or entity.get("type") != "sheet":
+ raise HTTPException(status_code=404, detail=f"sheet '{sheet_id}' not found")
+ return {"points": sheetroles.entity_points(case, body.ids)}
+
+
+class SheetTextIn(BaseModel):
+ """The text of a CSV, to be read into a table and handed straight back."""
+
+ text: str = Field(max_length=sheet_engine.MAX_IMPORT_BYTES)
+
+
[email protected]("/{case_id}/sheets/parse")
+def parse_sheet_text(case_id: str, body: SheetTextIn) -> dict[str, Any]:
+ """A CSV read into a table, without filing anything.
+
+ What "add these rows to the sheet I already have" needs, and the reason it is a route
+ rather than three lines in the browser: there is one CSV parser in this app. A second
+ one on the other side would guess the delimiter differently, and the file it disagreed
+ about would be the one an analyst is importing at that moment.
+
+ Nothing is written, so nothing is named: the case is read only to prove the caller
+ holds one.
+ """
+ get_case(case_id)
+ try:
+ columns, rows = sheet_engine.parse_csv(body.text)
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {"columns": columns, "rows": rows}
+
+
+class SheetTitleIn(BaseModel):
+ title: str | None = Field(default=None, max_length=200)
+ #: Whether the copy carries the rows or only the shape. A binder is three tables at
+ #: one schema — an inbox, a worklist, a reference — and the second of them starts as
+ #: the first one's columns with nothing under them.
+ empty: bool = Field(default=False)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/duplicate")
+def duplicate_sheet(case_id: str, sheet_id: str, body: SheetTitleIn) -> dict[str, Any]:
+ """A second sheet holding the same table and the same sidecar, or only its shape.
+
+ "Another reading of these rows is another sheet" is this app's answer to saved views,
+ and it was an answer with no button behind it: the only way to fork a sheet was to
+ export the CSV and import it back, which arrives stripped of every colour, role and
+ link. The copy gains its own `mentions` edges, because its cells point where the
+ original's did.
+
+ ``empty`` forks the headings and everything the app knows about them and leaves the
+ rows behind. Which is the *other* thing an analyst wanted from a duplicate, and the
+ two are one route because they are one write with one flag between them.
+ """
+ case = get_case(case_id)
+ try:
+ made = sheet_engine.duplicate(case, sheet_id, body.title, with_rows=not body.empty)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ _sync_mentions(case, made["id"], made["meta"])
+ return made
+
+
+class SheetMoveIn(SheetSaveIn):
+ """The rows to take out of this sheet, and the sheet to put them in.
+
+ The table travels with the request for the same reason a promotion's does: the
+ analyst moves what is on screen, and the version on disk may be a minute behind. So
+ the stamp is presented and the write is refused if the file moved on underneath.
+ """
+
+ to: str = Field(min_length=1, max_length=80)
+ keys: list[str] = Field(max_length=sheet_engine.MAX_ROWS)
+ #: Which column lands in which, over there. Omitted, the names are matched as they
+ #: always were; given, it is the answer to a screen that read both shapes and let the
+ #: analyst line up two spellings of the same column.
+ mapping: dict[str, str] | None = Field(default=None, max_length=sheet_engine.MAX_COLUMNS)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/move")
+def move_sheet_rows(case_id: str, sheet_id: str, body: SheetMoveIn) -> dict[str, Any]:
+ """Move the ticked rows into another sheet, columns matched by name.
+
+ The gesture the binders' tabs were built out of: an inbox, a worklist and a reference
+ table at one schema, and a row moves up a floor once it has been worked out. Both
+ sheets are written, and both restate what they mention, so a promoted row that moves
+ is still reachable from its subject's side afterwards.
+ """
+ case = get_case(case_id)
+ try:
+ return sheet_engine.move_rows(
+ case,
+ sheet_id,
+ body.to,
+ body.keys,
+ body.columns,
+ body.rows,
+ body.meta,
+ mapping=body.mapping,
+ expected=body.stamp,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
+class SheetUndoMoveIn(SheetSaveIn):
+ """The sheet as it stood before a move, and the keys the rows landed under.
+
+ The table travels for a second reason here: it *is* the undo. A move is not replayed
+ backwards — it drops the columns the destination does not have, so a reverse move
+ would hand the rows back with holes in them — so what goes back on disk is the copy
+ the grid still has on screen.
+ """
+
+ to: str = Field(min_length=1, max_length=80)
+ keys: list[str] = Field(max_length=sheet_engine.MAX_ROWS)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/move/undo")
+def undo_sheet_move(case_id: str, sheet_id: str, body: SheetUndoMoveIn) -> dict[str, Any]:
+ """Put a move back, both ends of it, in one call.
+
+ A move writes two files and the grid's own undo stack reaches neither, which is what
+ made a mis-aimed one final. The stamp is presented as usual: an analyst who has typed
+ into the sheet since is not overwritten by a button they pressed on the toast.
+ """
+ case = get_case(case_id)
+ try:
+ return sheet_engine.undo_move(
+ case,
+ sheet_id,
+ body.to,
+ body.keys,
+ body.columns,
+ body.rows,
+ body.meta,
+ expected=body.stamp,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
+class SheetMediaIn(BaseModel):
+ """Addresses out of a row, to be matched against what the library already imported."""
+
+ urls: list[str] = Field(max_length=MAX_POINTS)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/media")
+def sheet_media(case_id: str, sheet_id: str, body: SheetMediaIn) -> dict[str, Any]:
+ """Which media the case already holds for each of these addresses.
+
+ A worklist's link column and the Media Library's imports are the same pages twice, and
+ until this existed nothing joined them: the analyst had downloaded the video, and the
+ row pointing at its post could not say so. Matched on the **source URL the download
+ recorded**, which is the one field that means "this file came from that page" — not on
+ a resemblance between a title and a filename.
+ """
+ case = get_case(case_id)
+ entity = case.get_entity(sheet_id)
+ if entity is None or entity.get("type") != "sheet":
+ raise HTTPException(status_code=404, detail=f"sheet '{sheet_id}' not found")
+ found: dict[str, dict[str, str]] = {}
+ for url in dict.fromkeys(text.strip() for text in body.urls):
+ if not url:
+ continue
+ held = case.find_entity(attr=SOURCE_URL_ATTR, value=url)
+ if held is not None:
+ found[url] = {
+ "id": str(held["id"]),
+ "label": str(held.get("label") or ""),
+ "type": str(held.get("type") or ""),
+ }
+ return {"media": found}
+
+
+class SheetLinksIn(BaseModel):
+ """Addresses out of one column, to be asked whether they still answer."""
+
+ urls: list[str] = Field(max_length=sheetlinks.MAX_LINKS)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/links/check")
+def check_sheet_links(case_id: str, sheet_id: str, body: SheetLinksIn) -> dict[str, Any]:
+ """Whether these addresses answer. The one part of a sheet that reaches the network.
+
+ On a press and never on a read: a sheet that checked its own sources when it opened
+ would tell forty hosts which case is being worked on, which is the boundary this app
+ does not cross on its own.
+
+ The sheet is checked and not read: the addresses come from the grid, so parsing twenty
+ thousand rows to prove the caller owns a column would be a read nothing here uses.
+ """
+ case = get_case(case_id)
+ entity = case.get_entity(sheet_id)
+ if entity is None or entity.get("type") != "sheet":
+ raise HTTPException(status_code=404, detail=f"sheet '{sheet_id}' not found")
+ return {"links": sheetlinks.check_all(body.urls)}
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/stamp")
+def sheet_stamp(case_id: str, sheet_id: str) -> dict[str, str]:
+ """What the file looks like right now, as the token a save would present.
+
+ Cheap on purpose — a stat, not a read — because the grid asks it every time the window
+ comes back into focus. Without it, an analyst who edited the CSV in a spreadsheet went
+ on working in a grid that showed the old table and only found out at the next save,
+ which is the worst moment to be told.
+ """
+ case = get_case(case_id)
+ entity = case.get_entity(sheet_id)
+ if entity is None or entity.get("type") != "sheet":
+ raise HTTPException(status_code=404, detail=f"sheet '{sheet_id}' not found")
+ rel = (entity.get("attrs") or {}).get("path")
+ if not isinstance(rel, str) or not rel:
+ raise HTTPException(status_code=404, detail=f"sheet '{sheet_id}' has no file")
+ return {"stamp": sheet_engine.stamp(case.resolve_inside(rel))}
+
+
+class SheetMetaIn(BaseModel):
+ """The grid's own state, on its own.
+
+ No table and no stamp, because neither is touched: this is the route behind a filter
+ ticked, a column hidden, a colour painted, a row pinned.
+ """
+
+ meta: dict[str, Any] = Field(default_factory=dict)
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/meta")
+def save_sheet_meta(case_id: str, sheet_id: str, body: SheetMetaIn) -> dict[str, Any]:
+ """Write the sidecar alone, leaving the CSV byte-identical.
+
+ Half of what the grid remembers is not in the table — the widths, the sort, the
+ filters, the colours — and routing those through the ordinary save meant rewriting the
+ CSV to record that a funnel had been clicked. That moved the file's modification time,
+ which is what the stamp is made of, so the analyst's own next save answered a conflict
+ nobody caused and a spreadsheet open on the same file was told it had been overwritten.
+
+ Since nothing here can lose a cell, no stamp is presented and none is checked.
+ """
+ case = get_case(case_id)
+ try:
+ saved = sheet_engine.write_meta(case, sheet_id, body.meta)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ _sync_mentions(case, sheet_id, saved["meta"])
+ return {"status": "saved", **saved}
+
+
[email protected]("/{case_id}/sheets/{sheet_id}")
+def read_sheet(case_id: str, sheet_id: str) -> dict[str, Any]:
+ try:
+ return sheet_engine.read(get_case(case_id), sheet_id)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/sheets/{sheet_id}")
+def save_sheet(case_id: str, sheet_id: str, body: SheetSaveIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ try:
+ saved = sheet_engine.write(
+ case, sheet_id, body.columns, body.rows, body.meta, expected=body.stamp
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ _sync_mentions(case, sheet_id, saved["meta"])
+ return {"status": "saved", **saved}
+
+
+class SheetRefreshIn(SheetSaveIn):
+ """The proofs sheet as the grid holds it, to be brought level with the case.
+
+ The table travels with the request for the same reason a move's does: the analyst
+ presses this on what is on screen, and the copy on disk may be a minute behind. The
+ stamp is presented and the write refused if the file moved underneath.
+ """
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/refresh")
+def refresh_sheet(case_id: str, sheet_id: str, body: SheetRefreshIn) -> dict[str, Any]:
+ """Add the proofs filed since this sheet was built, and rewrite what the case owns.
+
+ Pressed, never automatic. Refreshing on open would mean that looking at a sheet
+ changes it — and it would fight the stamp, which exists so that two readers of one
+ file cannot overwrite each other silently.
+
+ Nothing is ever removed. A proof deleted since the build keeps its row and answers NO
+ in `In case`; what happens to that row is the analyst's decision, because the notes on
+ it are theirs.
+ """
+ case = get_case(case_id)
+ try:
+ fresh = fromcase_engine.refresh_proofs(case, body.columns, body.rows, body.meta)
+ saved = sheet_engine.write(
+ case, sheet_id, fresh["columns"], fresh["rows"], fresh["meta"], expected=body.stamp
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ _sync_mentions(case, sheet_id, saved["meta"])
+ return {
+ "status": "saved",
+ **saved,
+ "added": fresh["added"],
+ "updated": fresh["updated"],
+ "gone": fresh["gone"],
+ }
+
+
+class SheetExportIn(BaseModel):
+ """The table as the grid is showing it, to be written out as a CSV.
+
+ No stamp and no sidecar: an export reads, it does not write, and what it reads is
+ the screen rather than the file — a sheet filtered to the rows left to check
+ exports those rows.
+ """
+
+ columns: list[str] = Field(max_length=sheet_engine.MAX_COLUMNS)
+ rows: list[list[str]] = Field(max_length=sheet_engine.MAX_ROWS)
+
+
+#: Which saved destination a sheet's CSV goes to, and the case subdir it falls back to.
+#: Its own kind rather than the plates': an analyst files a table where they file tables,
+#: and one folder for both would be a setting that cannot say either.
+EXPORT_KIND = "sheets"
+EXPORTS_DIR = "exports"
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/csv")
+def export_sheet(case_id: str, sheet_id: str, body: SheetExportIn) -> dict[str, str]:
+ """Write the rows on screen as a CSV, into the folder saved for sheet exports.
+
+ A file rather than a download, the way a note's PDF and an analysis plate are: every
+ other finished thing in this app lands in a folder the analyst chose, and a table that
+ arrived in the browser's downloads instead was the one export nobody could find twice.
+
+ Inside the case a re-export **overwrites**, so that folder is refreshed in one click
+ rather than accumulating copies; in a folder of the analyst's own nothing is ever
+ overwritten, because the files there are theirs.
+ """
+ case = get_case(case_id)
+ try:
+ written = sheet_engine.export_csv(case, sheet_id, body.columns, body.rows)
+ destination = exportdir.destination(EXPORT_KIND, case.path)
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ # The same encoding the case's own CSV is written with, so a table handed to a
+ # colleague opens in Excel the way the one in the case folder does.
+ data = written["csv"].encode(sheet_engine.CSV_ENCODING)
+ in_case = destination == layout.subdir(case.path, EXPORTS_DIR)
+ try:
+ if in_case:
+ path = destination / written["filename"]
+ path.write_bytes(data)
+ else:
+ path = exportdir.write_out(data, destination, written["filename"])
+ except (OSError, exportdir.ExportDirError) as exc:
+ raise HTTPException(status_code=409, detail=f"could not write the CSV: {exc}") from exc
+ return {"file": path.name, "path": str(destination)}
+
+
[email protected]("/{case_id}/sheets/csv/reveal")
+def reveal_sheet_exports(case_id: str) -> dict[str, str]:
+ """Open the folder the CSVs were written to, in the system file manager.
+
+ Takes no path: the case and the saved destination are enough to find the folder, so
+ nothing the browser sends can point somewhere else.
+ """
+ case = get_case(case_id)
+ try:
+ destination = exportdir.destination(EXPORT_KIND, case.path)
+ except exportdir.ExportDirError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ try:
+ reveal_engine.reveal(destination, workspace_only=False)
+ except reveal_engine.RevealError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"status": "revealed", "path": str(destination)}
+
+
+class SheetSubjectIn(BaseModel):
+ """The one column that is the row's subject, and what it becomes.
+
+ At most one per pass: two subjects in a row is the question the joins answer, not a
+ second column in this mode.
+ """
+
+ column: str = Field(min_length=1, max_length=sheet_engine.MAX_COLUMN_NAME)
+ type: str = Field(min_length=1, max_length=40)
+ #: Column name to declared attr key. Anything undeclared is dropped rather than
+ #: stored: it would become a field of the vocabulary nothing can show.
+ fields: dict[str, str] = Field(default_factory=dict)
+ attach: dict[str, str] = Field(default_factory=dict, max_length=promote_engine.MAX_PROMOTED)
+ skip: list[str] = Field(default_factory=list, max_length=promote_engine.MAX_PROMOTED)
+ #: Whether the ticked rows become one entity instead of one each.
+ group: bool = Field(default=False)
+ group_label: str | None = Field(default=None, max_length=sheet_engine.MAX_CELL)
+
+
+class SheetValueColumnIn(BaseModel):
+ """A column whose distinct words each become an entity, created or attached."""
+
+ column: str = Field(min_length=1, max_length=sheet_engine.MAX_COLUMN_NAME)
+ type: str = Field(min_length=1, max_length=40)
+ attach: dict[str, str] = Field(default_factory=dict, max_length=promote_engine.MAX_COLUMN_WORDS)
+ skip: list[str] = Field(default_factory=list, max_length=promote_engine.MAX_COLUMN_WORDS)
+
+
+class SheetRowEdgeIn(BaseModel):
+ """A column naming other rows of the same sheet, and the verb between them."""
+
+ column: str = Field(min_length=1, max_length=sheet_engine.MAX_COLUMN_NAME)
+ verb: str = Field(min_length=1, max_length=40)
+
+
+class SheetJoinIn(BaseModel):
+ """Two columns that designate something, and the verb the analyst picked.
+
+ Ordered: the verb runs from the first to the second, and the reading the screen
+ showed is what settled the direction.
+ """
+
+ from_: str = Field(alias="from", min_length=1, max_length=sheet_engine.MAX_COLUMN_NAME)
+ to: str = Field(min_length=1, max_length=sheet_engine.MAX_COLUMN_NAME)
+ verb: str = Field(min_length=1, max_length=40)
+
+ model_config = {"populate_by_name": True}
+
+
+class SheetPassIn(SheetSaveIn):
+ """One declaration of what a sheet's columns become, and what joins what.
+
+ The table travels with the request for the same reason every other promotion's does:
+ the analyst sends what is on screen, which may hold edits the autosave has not written
+ yet, and promoting the version on disk would promote yesterday's labels.
+
+ One scope for the whole pass — `keys`, the ticked rows — so a count that does not add
+ up has one reading rather than one per mode.
+ """
+
+ keys: list[str] = Field(default_factory=list, max_length=promote_engine.MAX_PROMOTED)
+ subject: SheetSubjectIn | None = Field(default=None)
+ #: Which column holds the coordinates. A place is deduplicated on the point itself,
+ #: and the verb joining the subject to it is read out of the registry.
+ point: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ #: Which column holds the pages a row rests on. Each becomes a bookmark that mentions
+ #: the subject, which is a `bookmark` and never a file: this road fetches nothing.
+ addresses: str = Field(default="", max_length=sheet_engine.MAX_COLUMN_NAME)
+ values: list[SheetValueColumnIn] = Field(default_factory=list, max_length=20)
+ #: The claims engine's own arguments, passed through. A column of hours is a statement
+ #: about the row's subject, and that engine already builds the whole thing.
+ statement: dict[str, Any] | None = Field(default=None)
+ row_edges: list[SheetRowEdgeIn] = Field(default_factory=list, max_length=20)
+ joins: list[SheetJoinIn] = Field(default_factory=list, max_length=40)
+ #: One confidence for the pass, applied to the edges the registry declares ratable.
+ #: Absent means the analyst asserted nothing beyond the edge itself.
+ confidence: int | None = Field(default=None)
+
+
+def _declaration(body: SheetPassIn, names: list[str], table: list[list[str]]) -> dict[str, Any]:
+ """The arguments the plan and the press both take, stated once."""
+ return {
+ "columns": names,
+ "rows": table,
+ "meta": body.meta,
+ "keys": body.keys,
+ "subject": body.subject.model_dump() if body.subject else None,
+ "point": body.point,
+ "addresses": body.addresses,
+ "values": [column.model_dump() for column in body.values],
+ "statement": body.statement,
+ "row_edges": [column.model_dump() for column in body.row_edges],
+ "joins": [{"from": join.from_, "to": join.to, "verb": join.verb} for join in body.joins],
+ "confidence": body.confidence,
+ }
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/promote/preview")
+def preview_sheet_pass(case_id: str, sheet_id: str, body: SheetPassIn) -> dict[str, Any]:
+ """Both layers of one pass, counted, with nothing written and no stamp checked.
+
+ Reading a plan is not a change, and a preview refused because a spreadsheet touched
+ the file would be a refusal to *look*. The press itself still checks.
+ """
+ case = get_case(case_id)
+ try:
+ names, table = sheet_engine.normalize(body.columns, body.rows)
+ return pass_engine.plan(case, **_declaration(body, names, table))
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/sheets/{sheet_id}/promote")
+def run_sheet_pass(case_id: str, sheet_id: str, body: SheetPassIn) -> dict[str, Any]:
+ """Write one pass: every column's mode, the edges between them, the sheet's own save.
+
+ All of it or none of it. The graph writes and the sheet's save run inside one
+ `case.batch()`, so a file that moved under the analyst rolls the entities back on the
+ way out — where the older roads had to hand their `made` ids to a compensating undo,
+ which is code that only ever runs when something has already gone wrong.
+
+ The stamp is still checked first, before a single entity exists: it used to be checked
+ only by the save at the end, which meant a file touched in a spreadsheet produced a
+ 409 the analyst read as "nothing happened" over a case that had already gained forty
+ subjects.
+ """
+ case = get_case(case_id)
+ try:
+ names, table = sheet_engine.normalize(body.columns, body.rows)
+ sheet_engine.ensure_current(case, sheet_id, body.stamp)
+ with case.batch():
+ result = pass_engine.run(case, sheet_id, **_declaration(body, names, table))
+ saved = sheet_engine.write(
+ case,
+ sheet_id,
+ names,
+ table,
+ {
+ **body.meta,
+ "links": result["links"],
+ "values": result["values"],
+ "promoted": result["promoted"],
+ },
+ expected=body.stamp,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except sheet_engine.SheetConflict as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return {
+ "status": "promoted",
+ "entities": result["entities"],
+ "joins": result["joins"],
+ **saved,
+ }
+
+
+#: Restating what a sheet mentions lives beside the sidecar it reads
+#: (`engine/sheets.sync_mentions`): the edges are a function of the sidecar, and the
+#: routes here need exactly the same restatement after they have written one.
+_sync_mentions = sheet_engine.sync_mentions
+
+
+def _unfile(case: Any, made: list[dict[str, Any]]) -> None:
+ """Take back the sheets one import filed, before its refusal is answered."""
+ for filed in made:
+ sheet_engine.discard(case, filed)
+
+
[email protected]("/{case_id}/sheets/import-xlsx")
+async def import_workbook(case_id: str, file: UploadFile) -> dict[str, Any]:
+ """File every tab of a workbook as its own sheet, keeping the tabs' names.
+
+ Multipart rather than the text the CSV import takes, because an .xlsx is a zip and
+ base64 in JSON would be a third of the file again for nothing. What lands is the same
+ thing a dropped CSV lands: real files in `sheets/`, parsed by the one parser.
+
+ A tab with no cells is **named and not filed**: two tabs of a timeline binder hold
+ nothing but pasted screenshots, and filing two empty sheets nobody asked for is worse
+ than saying they were empty.
+
+ An import is all of the tabs or none of them. A tab whose file cannot be written takes
+ the ones already filed back out with it, so the retry that follows does not land a
+ second copy of half a binder.
+
+ ``dropped`` and ``cut`` are what the three ceilings left out. Said rather than applied
+ quietly: the toast is the only place an analyst could learn that a thirty thousand row
+ export arrived as twenty thousand.
+ """
+ case = get_case(case_id)
+ data = await file.read(xlsx_engine.MAX_XLSX_BYTES + 1)
+ if len(data) > xlsx_engine.MAX_XLSX_BYTES:
+ raise HTTPException(status_code=413, detail="this workbook is too large to read")
+ try:
+ book = xlsx_engine.read_book(data)
+ except sheet_engine.SheetError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+ made: list[dict[str, Any]] = []
+ empty: list[str] = []
+ cut: list[dict[str, Any]] = []
+ for tab in book["tabs"]:
+ if not tab["columns"]:
+ empty.append(tab["title"])
+ continue
+ try:
+ made.append(sheet_engine.create(case, tab["title"], tab["columns"], tab["rows"]))
+ except (CaseError, sheet_engine.SheetError) as exc:
+ _unfile(case, made)
+ raise HTTPException(status_code=422, detail=f"{tab['title']}: {exc}") from exc
+ except sheet_engine.SheetUnwritable:
+ # Answered 409 by the application handler, with the sentence naming the file.
+ _unfile(case, made)
+ raise
+ if tab["cut_rows"] or tab["cut_columns"]:
+ cut.append(
+ {
+ "title": tab["title"],
+ "rows": tab["cut_rows"],
+ "columns": tab["cut_columns"],
+ }
+ )
+ return {"sheets": made, "empty": empty, "dropped": book["dropped"], "cut": cut}
diff --git a/src/azimut/api/templates.py b/src/azimut/api/templates.py
index 14b9c12..a4fc449 100644
--- a/src/azimut/api/templates.py
+++ b/src/azimut/api/templates.py
@@ -93,6 +93,11 @@ class ProofTemplateData(CanonicalModel):
footerSize: TextSize = 15
footer: str = Field(default="", max_length=200)
footerEnabled: StrictBool = True
+ # What the band prints. A style stored before these existed reads with these
+ # defaults, which is what it has always looked like: the credit line prints,
+ # the coordinates do not.
+ footerText: StrictBool = True
+ footerCoords: StrictBool = False
footerColor: Color | None = None
footerAlign: Literal["left", "right"] = "left"
captionsEnabled: StrictBool = True
diff --git a/src/azimut/casestore.py b/src/azimut/casestore.py
index 210229c..965ac31 100644
--- a/src/azimut/casestore.py
+++ b/src/azimut/casestore.py
@@ -18,6 +18,7 @@ writes, folders, the trash journal, the durable job queue.
from __future__ import annotations
+from contextlib import AbstractContextManager
from typing import TYPE_CHECKING, Any
from .repository import EntityStatus
@@ -310,6 +311,11 @@ class CaseStore:
def save_analysis_view(self, view: dict[str, Any]) -> dict[str, Any]:
return self._graph().save_analysis_view(view)
+ def rename_analysis_view(
+ self, view_id: str, name: str, updated_at: str
+ ) -> dict[str, Any] | None:
+ return self._graph().rename_analysis_view(view_id, name, updated_at)
+
def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
return self._graph().remove_analysis_view(view_id)
@@ -326,6 +332,11 @@ class CaseStore:
"""Entity total for the case switcher — one indexed count."""
return self._graph().count_entities()
+ def batch(self) -> AbstractContextManager[None]:
+ """One transaction for every store write made inside it. See
+ `sqlite_backend.SqliteCase.batch` for what it costs and when not to."""
+ return self._graph().batch()
+
def save_temporal_claim(
self,
*,
@@ -374,6 +385,7 @@ class CaseStore:
*,
by: str,
status: EntityStatus = "confirmed",
+ own_only: bool = False,
) -> list[dict[str, Any]]:
"""Make ``from_id``'s outgoing links of ``type_`` exactly ``to_ids``.
@@ -381,8 +393,19 @@ class CaseStore:
edges that are still true are left untouched (same id, same timestamp),
edges that are no longer true are dropped, new ones are appended. Unknown
targets and a self-reference are ignored.
+
+ ``own_only`` narrows the dropping to the edges ``by`` wrote itself, and the
+ caller picks it by asking whether its list is the *whole* truth about that
+ type. A proof's spec is: it names every panel the composition holds, and a
+ derivation is never stated by hand, so an edge outside the list is a leftover.
+ A sheet's sidecar is not: `mentions` and a Claim's connectors are relations the
+ analyst may also state in Details, and those are separate claims about the same
+ two entities. Reconciling over them deleted somebody's own statement on a
+ funnel being clicked — permanently, since nothing holds a removed edge.
"""
- return self._graph().sync_links(from_id, type_, to_ids, by=by, status=status)
+ return self._graph().sync_links(
+ from_id, type_, to_ids, by=by, status=status, own_only=own_only
+ )
def update_link(self, link_id: str, patch: dict[str, Any]) -> dict[str, Any]:
return self._graph().update_link(link_id, patch)
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 1d002aa..880a795 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -98,7 +98,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {
"units": "metric",
# Where the Satellite tab opens before anything points it somewhere else
# (a case artifact, a "go to coords" handoff). {"lat", "lon", "zoom"}.
- "home_view": {"lat": 48.8584, "lon": 2.2945, "zoom": 16},
+ "home_view": {"lat": 43.0, "lon": 25.0, "zoom": 3},
# Saving a proof files the point it carries as a `place`, joined by `depicts`
# (engine/satellite.place_for_proof). A geolocation is concluded in the
# composer, not while framing the map, so the point becomes a node once —
@@ -604,9 +604,14 @@ SETTINGS_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {}
def _settings_schema(data: dict[str, Any]) -> int:
"""The schema a loaded settings.json declares. Files predating the tag are
- the first schema."""
+ the first schema.
+
+ A number below the first schema is treated as the first: no migration was
+ ever written for it, and answering with it would send the runner looking for
+ one that cannot exist.
+ """
value = data.get("schema")
- return value if isinstance(value, int) else 1
+ return max(1, value) if isinstance(value, int) else 1
def migrate_settings(data: dict[str, Any]) -> dict[str, Any]:
@@ -617,6 +622,11 @@ def migrate_settings(data: dict[str, Any]) -> dict[str, Any]:
Pure: it never writes. ensure_workspace() persists the result once at start.
"""
version = _settings_schema(data)
+ if data.get("schema") != version:
+ # The file declared a number no schema was ever written for, or none at
+ # all. Restating it as the one the file is actually being read as keeps
+ # the next save from handing the same puzzle back.
+ data = {**data, "schema": version}
for step in range(version, SETTINGS_SCHEMA):
data = SETTINGS_MIGRATIONS[step](data)
data["schema"] = step + 1
@@ -630,6 +640,13 @@ def load_settings() -> dict[str, Any]:
data = json.loads(settings_path().read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return copy.deepcopy(DEFAULT_SETTINGS)
+ # Valid JSON that is not an object is as unusable as a truncated file, and
+ # it arrives by the same accident. Falling back to defaults is the whole
+ # point of the guard above; a file shaped `null` or `[]` must not be the one
+ # corruption that takes every settings read — and `ensure_workspace` with
+ # it — down at startup.
+ if not isinstance(data, dict):
+ return copy.deepcopy(DEFAULT_SETTINGS)
merged = copy.deepcopy(DEFAULT_SETTINGS)
merged.update(migrate_settings(data))
return merged
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 3384a5e..a1c816a 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -112,6 +112,7 @@ KINDS: dict[str, Kind] = {
"post": Kind(path_attr="draft"),
"inspect-session": Kind(path_attr="spec"),
"note": Kind(path_attr="path"),
+ "sheet": Kind(path_attr="path", companions=(Named(layout.sheet_meta_rel),)),
}
#: Types with no intrinsic main artifact, and why. Supported entities can still
diff --git a/src/azimut/engine/cities.py b/src/azimut/engine/cities.py
new file mode 100644
index 0000000..ea41d08
--- /dev/null
+++ b/src/azimut/engine/cities.py
@@ -0,0 +1,134 @@
+"""Offline city gazetteer, for search that answers while the analyst types.
+
+Nominatim's usage policy forbids autocomplete, and its 1.1 s pace (``geo._pace``)
+would queue a keystroke behind whatever backfill is running anyway. So the cities
+travel with the app: ~34k places of 15 000 people or more, gzipped to about
+770 KiB, read off disk on first use and searched in memory afterwards. Nothing
+here touches the network, ever — the geocoder is a separate, slower layer that
+the UI only reaches for once typing stops.
+
+Refresh the file with ``python scripts/build_cities.py``. Source: GeoNames,
+CC BY 4.0 — the attribution rides with every answer.
+"""
+
+from __future__ import annotations
+
+import gzip
+import threading
+import unicodedata
+from bisect import bisect_left
+from pathlib import Path
+from typing import Any
+
+from . import countries
+
+DATA = Path(__file__).parent / "data" / "cities.tsv.gz"
+ATTRIBUTION = "© GeoNames (CC BY 4.0)"
+
+#: A rank, not a filter: an exact name beats a name that starts with the query,
+#: which beats a match on a later word ("york" finding New York).
+EXACT, STARTS, WORD = 0, 1, 2
+
+_lock = threading.Lock()
+_rows: list[str] | None = None
+#: ``(key, kind, row)`` sorted by key, so a prefix is one bisect and a short walk.
+_index: list[tuple[str, int, int]] = []
+
+
+def normalize(text: str) -> str:
+ """Casefold, strip accents, and reduce punctuation to single spaces.
+
+ ``"Saint-Étienne"`` and ``"saint etienne"`` have to meet somewhere, and a
+ query is normalized by this same function so they meet here.
+ """
+ folded = unicodedata.normalize("NFKD", text).casefold()
+ kept = [
+ c if c.isalnum() else " "
+ for c in folded
+ if not unicodedata.combining(c)
+ ]
+ return " ".join("".join(kept).split())
+
+
+def _load() -> None:
+ """Read the gazetteer once. Cheap enough to do lazily (~120 ms), and a
+ missing file is not fatal: search just finds nothing and the geocoder still
+ answers."""
+ global _rows, _index
+ with _lock:
+ if _rows is not None:
+ return
+ rows: list[str] = []
+ index: list[tuple[str, int, int]] = []
+ try:
+ text = gzip.decompress(DATA.read_bytes()).decode("utf-8")
+ except (OSError, EOFError, gzip.BadGzipFile, UnicodeDecodeError):
+ _rows, _index = [], []
+ return
+ for line in text.splitlines():
+ if not line or line.startswith("#"):
+ continue
+ row = len(rows)
+ rows.append(line)
+ name, ascii_name = line.split("\t", 2)[:2]
+ keys = {normalize(name)}
+ if ascii_name:
+ keys.add(normalize(ascii_name))
+ for key in keys:
+ if not key:
+ continue
+ index.append((key, STARTS, row))
+ # Later words are searchable on their own, so "york" reaches New
+ # York, but they rank below a name that opens with the query.
+ for word in key.split(" ")[1:]:
+ index.append((word, WORD, row))
+ index.sort()
+ _rows, _index = rows, index
+
+
+def _reset() -> None:
+ """Test seam: forget the loaded table."""
+ global _rows, _index
+ with _lock:
+ _rows, _index = None, []
+
+
+def _unpack(line: str) -> dict[str, Any]:
+ name, _ascii, country, region, lat, lon, population = line.split("\t")
+ return {
+ "name": name,
+ "region": region,
+ "country": country,
+ "country_name": countries.name_for(country) or country.upper(),
+ "lat": float(lat),
+ "lon": float(lon),
+ "population": int(population),
+ }
+
+
+def search(query: str, limit: int = 8) -> list[dict[str, Any]]:
+ """The best `limit` cities whose name starts with `query`.
+
+ Ranked by match kind, then by population — the file is written biggest-first,
+ so a row's position is its rank and no second sort is needed.
+ """
+ key = normalize(query)
+ if not key or limit <= 0:
+ return []
+ if _rows is None:
+ _load()
+ rows, index = _rows or [], _index
+ best: dict[int, tuple[int, int]] = {}
+ at = bisect_left(index, (key,))
+ while at < len(index):
+ entry_key, kind, row = index[at]
+ if not entry_key.startswith(key):
+ break
+ at += 1
+ if kind == STARTS and entry_key == key:
+ kind = EXACT
+ rank = (kind, row)
+ if row not in best or rank < best[row]:
+ best[row] = rank
+ top = sorted(best.values())[:limit]
+ return [_unpack(rows[row]) for _kind, row in top]
diff --git a/src/azimut/engine/coords.py b/src/azimut/engine/coords.py
index 46909c5..3d6b79c 100644
--- a/src/azimut/engine/coords.py
+++ b/src/azimut/engine/coords.py
@@ -74,7 +74,10 @@ def utm_zone(lat: float, lon: float) -> int:
if lon < 33:
return 35
return 37
- return int((lon + 180) // 6) + 1
+ # Zone 60 ends *at* 180°, so the open interval the division assumes closes
+ # there: without the clamp the antimeridian answers 61, a zone that does not
+ # exist and that `to_utm` would project against.
+ return min(60, int((lon + 180) // 6) + 1)
def lat_band(lat: float) -> str | None:
diff --git a/src/azimut/engine/data/cities.tsv.gz b/src/azimut/engine/data/cities.tsv.gz
new file mode 100644
index 0000000..a2d5200
Binary files /dev/null and b/src/azimut/engine/data/cities.tsv.gz differ
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index 6fd786b..d8e8a63 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -537,6 +537,13 @@ ENTITY_TYPES: tuple[EntityType, ...] = (
hint="a prepared thread or report, saved rather than published"),
EntityType("note", "Note", DOCUMENT, "note", ANNEX,
hint="a Markdown page in the case notebook"),
+ # A table the analyst works in: a list being worked through, a comparison grid,
+ # rows too soft to be entities yet. `ANNEX` for the same reason a note is one —
+ # it is consulted, and no path through the case runs across it. What it *does*
+ # carry are `mentions` edges, one per cell pointing at an entity, so a row that
+ # names a subject is visible from that subject's side too.
+ EntityType("sheet", "Sheet", DOCUMENT, "table", ANNEX,
+ hint="a CSV table in the case, edited as a grid"),
EntityType("inspect-session", "Inspect session", DOCUMENT, "inspect", ANNEX,
hint="saved adjustments over one file, which die with it"),
# The page a claim rests on. `url` and `fetched_at` are written by whatever
diff --git a/src/azimut/engine/exportdir.py b/src/azimut/engine/exportdir.py
index 1d0baa0..8ad1cbd 100644
--- a/src/azimut/engine/exportdir.py
+++ b/src/azimut/engine/exportdir.py
@@ -3,8 +3,8 @@
Every export used to write into the case's own `exports/` folder. That is still
the default, but a finished PDF or a media file is usually wanted somewhere the
case is not — a shared drive, a report folder, the desktop. So each kind of
-export (notes, media, proofs) remembers one destination app-wide, and the analyst
-changes it by browsing the filesystem from here.
+export (notes, media, proofs, analysis plates) remembers one destination app-wide,
+and the analyst changes it by browsing the filesystem from here.
Two rules shape this module:
@@ -32,9 +32,10 @@ from typing import Any, BinaryIO, Iterator
from .. import config, layout
-#: The exports that remember a destination of their own. Notes and proofs are
-#: documents the analyst files somewhere; media is the original coming back out.
-KINDS = ("notes", "media", "proofs")
+#: The exports that remember a destination of their own. Notes, proofs and analysis
+#: plates are documents the analyst files somewhere; media is the original coming
+#: back out.
+KINDS = ("notes", "media", "proofs", "views", "sheets")
#: The case subdir an export falls back to when its kind has no folder saved.
CASE_EXPORTS = "exports"
diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.py
index ec49ce2..2ee3704 100644
--- a/src/azimut/engine/geo.py
+++ b/src/azimut/engine/geo.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import re
import threading
import time
+from collections import OrderedDict
from typing import Any
import httpx
@@ -30,6 +31,14 @@ _pace_lock = threading.Lock()
_last_request = 0.0
_throttled_until = 0.0
+#: Suggestions answered from memory, keyed by the trimmed lowercase query. A
+#: search bar walks the same prefixes over and over (backspace, retype, pick a
+#: different one), and every repeat we can answer here is a slot the geocoder
+#: keeps for a query it has never seen.
+SUGGEST_CACHE_SIZE = 96
+_suggest_cache: OrderedDict[str, tuple[dict[str, Any], ...]] = OrderedDict()
+_cache_lock = threading.Lock()
+
def _pace() -> None:
"""Hold the caller until the interval since the last Nominatim request has
@@ -42,6 +51,27 @@ def _pace() -> None:
_last_request = time.monotonic()
+def _try_pace() -> bool:
+ """Claim the next Nominatim slot, or give up at once.
+
+ The blocking `_pace` is right for work the analyst asked for and will wait
+ for. It is wrong for the search bar's suggestions: a suggestion that arrives
+ after the next keystroke is worse than no suggestion, and queueing them
+ behind a country backfill is how a typing analyst earns a 429 for everyone.
+ So this one never waits — it returns False and the caller says so.
+ """
+ global _last_request
+ if throttled() or not _pace_lock.acquire(blocking=False):
+ return False
+ try:
+ if time.monotonic() - _last_request < NOMINATIM_INTERVAL:
+ return False
+ _last_request = time.monotonic()
+ return True
+ finally:
+ _pace_lock.release()
+
+
def _note_throttling(response: Any) -> None:
"""Remember a 429. Reads the status defensively: the only thing this needs
from the response is a number, and a caller's stub may not carry one."""
@@ -57,10 +87,12 @@ def throttled() -> bool:
def _reset_pace() -> None:
- """Test seam: forget the last request and any throttling."""
+ """Test seam: forget the last request, any throttling, and the suggestions."""
global _last_request, _throttled_until
_last_request = 0.0
_throttled_until = 0.0
+ with _cache_lock:
+ _suggest_cache.clear()
# -- parsing -------------------------------------------------------------------
@@ -72,6 +104,9 @@ _DMS = (
r"(?P<deg>\d{1,3})\s*[°d]\s*(?:(?P<min>\d{1,2}(?:\.\d+)?)\s*[’'m]\s*)?"
r"(?:(?P<sec>\d{1,2}(?:\.\d+)?)\s*[”\"s]\s*)?(?P<hemi>[NSEW])"
)
+#: Open Location Code's alphabet, read by the plus-code parser, the encoder and
+#: the text scanner's pattern.
+_OLC_ALPHABET = "23456789CFGHJMPQRVWX"
# UTM: "31U 448251 5411932" (zone, band, easting, northing; spacing loose).
_UTM = (
r"(?P<zone>\d{1,2})\s*(?P<band>[C-HJ-NP-X])\s+"
@@ -158,6 +193,103 @@ def parse_plus_code(text: str) -> tuple[float, float] | None:
return lat - 90 + res / 2, lon - 180 + res / 2
+# -- scanning free text ----------------------------------------------------------
+#
+# `parse_coords` answers "is this string a coordinate", which is the right
+# question for a field somebody pasted into. Reading a post asks a different one:
+# "does this prose state a position anywhere". So the scan finds *candidates* by
+# shape and hands each one to the parser above — the formats live in one place,
+# and nothing is accepted here that could not be typed into the field.
+#
+# Two of the parsed formats are deliberately not scanned for. A geohash is bare
+# lowercase letters and digits, so half the words in a sentence are one; a UTM
+# reference is three numbers in a row, which prose produces by accident. Both
+# still paste into a field, where the analyst meant them.
+
+#: How many distinct positions one scan reports. A post states one, occasionally
+#: a handful; past this the text is a list and the analyst is better served by
+#: reading it than by a wall of chips.
+MAX_SCANNED_COORDS = 8
+
+#: Decimal degrees written out. The decimal point is required: without it every
+#: "2, 3" in a sentence is a coordinate, and no geolocation is stated to the
+#: nearest degree anyway.
+_SCAN_DEC = r"[-+]?\d{1,3}\.\d+"
+_SCAN_DEC_PAIR = re.compile(rf"({_SCAN_DEC})\s*(?:,|;|\s)\s*({_SCAN_DEC})")
+_SCAN_DMS = re.compile(_DMS, re.IGNORECASE)
+_SCAN_PLUS = re.compile(rf"\b[{_OLC_ALPHABET}]{{8}}\+[{_OLC_ALPHABET}]{{2}}\b")
+_SCAN_MGRS = re.compile(r"\b\d{1,2}\s?[C-HJ-NP-X]\s?[A-Z]{2}\s?\d{2,10}(?:\s\d{1,5})?\b")
+#: Positions carried by a map link rather than written out. One pattern per
+#: convention, each anchored on what makes it unambiguous.
+_SCAN_URL = (
+ re.compile(rf"@({_SCAN_DEC}),({_SCAN_DEC})"), # Google Maps
+ re.compile(rf"!3d({_SCAN_DEC})!4d({_SCAN_DEC})"), # a Google place pin
+ re.compile(rf"[?&#](?:q|ll|sll|center|cp)=({_SCAN_DEC})[,~]({_SCAN_DEC})", re.IGNORECASE),
+ re.compile(rf"#map=\d+/({_SCAN_DEC})/({_SCAN_DEC})"), # OpenStreetMap
+ re.compile(rf"mlat=({_SCAN_DEC})&mlon=({_SCAN_DEC})"), # an OSM marker
+)
+
+
+def _in_range(lat: float, lon: float) -> bool:
+ return -90 <= lat <= 90 and -180 <= lon <= 180
+
+
+def scan_coords(text: str) -> list[dict[str, Any]]:
+ """Every position a free text states, in the order it states them.
+
+ Each answer carries the substring it was read from, so a surface can show
+ the analyst *what* it found rather than asking them to trust a number that
+ appeared in a field. Duplicates collapse at about a metre: a post that
+ writes its point twice, once in prose and once inside a map link, is
+ offering one position.
+ """
+ found: list[tuple[int, dict[str, Any]]] = []
+
+ def add(at: int, lat: float, lon: float, raw: str, form: str) -> None:
+ if _in_range(lat, lon):
+ found.append((at, {"lat": lat, "lon": lon, "text": raw.strip(), "format": form}))
+
+ for match in _SCAN_DEC_PAIR.finditer(text):
+ add(match.start(), float(match.group(1)), float(match.group(2)), match.group(0), "decimal")
+
+ # A DMS position is two halves written side by side, so the pair is what is
+ # read — one lone "48°51'N" states a parallel, not a point.
+ dms = list(_SCAN_DMS.finditer(text))
+ for first, second in zip(dms, dms[1:]):
+ raw = text[first.start() : second.end()]
+ parsed = parse_coords(raw)
+ if parsed:
+ add(first.start(), parsed[0], parsed[1], raw, "dms")
+
+ for pattern, form in ((_SCAN_PLUS, "plus-code"), (_SCAN_MGRS, "mgrs")):
+ for match in pattern.finditer(text):
+ parsed = parse_coords(match.group(0))
+ if parsed:
+ add(match.start(), parsed[0], parsed[1], match.group(0), form)
+
+ for pattern in _SCAN_URL:
+ for match in pattern.finditer(text):
+ add(
+ match.start(),
+ float(match.group(1)),
+ float(match.group(2)),
+ match.group(0),
+ "map-link",
+ )
+
+ seen: set[tuple[float, float]] = set()
+ answer: list[dict[str, Any]] = []
+ for _, candidate in sorted(found, key=lambda item: item[0]):
+ key = (round(candidate["lat"], 5), round(candidate["lon"], 5))
+ if key in seen:
+ continue
+ seen.add(key)
+ answer.append(candidate)
+ if len(answer) == MAX_SCANNED_COORDS:
+ break
+ return answer
+
+
# -- formatting ------------------------------------------------------------------
@@ -241,6 +373,13 @@ def parse_geohash(text: str) -> tuple[float, float] | None:
code = text.strip().lower()
if not code or len(code) < 4: # too short to be an unambiguous paste
return None
+ if code.isdigit():
+ # Base32 holds the ten digits, so "2023" decodes as happily as "u09tvw0f"
+ # does — and a bare number pasted into a coordinate field is a year, an
+ # altitude or a case number, never a place. A real geohash carries at
+ # least one letter, so requiring one costs nothing and stops the parser
+ # from inventing a location out of a caption.
+ return None
lat_lo, lat_hi = -90.0, 90.0
lon_lo, lon_hi = -180.0, 180.0
even = True
@@ -267,8 +406,8 @@ def parse_geohash(text: str) -> tuple[float, float] | None:
# -- Open Location Code (plus codes) ----------------------------------------------
# Standard encoding, full 10-character code + '+'. Public-domain algorithm.
-
-_OLC_ALPHABET = "23456789CFGHJMPQRVWX"
+# The alphabet sits up with the other parsing constants: both halves of the
+# format read it, and the text scanner builds its pattern from it at import.
def plus_code(lat: float, lon: float) -> str:
@@ -358,6 +497,54 @@ def geocode(query: str) -> dict[str, Any] | None:
return None
+def suggest(query: str, limit: int = 5) -> list[dict[str, Any]] | None:
+ """Several matches for a partial place name, for the search bar's slow layer.
+
+ What the bundled gazetteer cannot answer — streets, hamlets, anything under
+ 15 000 people — lives here. Returns the matches, or **None** when the slot
+ was refused: an empty list means the geocoder answered and had nothing, and
+ the two read very differently to somebody watching a list not fill in.
+ """
+ key = " ".join(query.split()).casefold()
+ if not key:
+ return []
+ with _cache_lock:
+ cached = _suggest_cache.get(key)
+ if cached is not None:
+ _suggest_cache.move_to_end(key)
+ return [dict(place) for place in cached[:limit]]
+ if not _try_pace():
+ return None
+ try:
+ response = httpx.get(
+ "https://nominatim.openstreetmap.org/search",
+ # `limit` is capped by the route; the cache keeps whatever came back,
+ # so a widened limit on the next keystroke is not a second request.
+ params={"q": query, "format": "jsonv2", "limit": 10, "accept-language": "en"},
+ headers={"User-Agent": USER_AGENT},
+ timeout=8,
+ )
+ _note_throttling(response)
+ response.raise_for_status()
+ found = [
+ {
+ "lat": float(item["lat"]),
+ "lon": float(item["lon"]),
+ "display_name": item.get("display_name") or "",
+ "kind": item.get("type") or item.get("category") or "",
+ }
+ for item in response.json()
+ if item.get("lat") is not None and item.get("lon") is not None
+ ]
+ except Exception:
+ return None
+ with _cache_lock:
+ _suggest_cache[key] = tuple(found)
+ while len(_suggest_cache) > SUGGEST_CACHE_SIZE:
+ _suggest_cache.popitem(last=False)
+ return [dict(place) for place in found[:limit]]
+
+
def reverse_geocode(
lat: float, lon: float, timeout: float = 8, language: str | None = None
) -> dict[str, Any] | None:
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index 4bd26ae..fc50682 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -370,7 +370,7 @@ RELATION_TYPES: tuple[RelationType, ...] = (
inverse_label="is mentioned by",
from_families=frozenset({entities.DOCUMENT}),
to_families=frozenset(entities.FAMILIES),
- from_only=frozenset({"note", "post", "proof", "bookmark"}),
+ from_only=frozenset({"note", "post", "proof", "bookmark", "sheet"}),
hint="the document refers to the entity",
group="Mentions",
action="mention",
@@ -452,6 +452,36 @@ def relation_type(type_: str) -> RelationType | None:
return next((entry for entry in RELATION_TYPES if entry.type == type_), None)
+def pair_verbs(
+ from_type: str, to_type: str, *, action: str = ""
+) -> tuple[RelationType, ...]:
+ """Every verb the vocabulary allows from one type to another, in menu order.
+
+ The **type-only** half of `_check_endpoints`, asked before either entity exists.
+ That is what planning a batch of edges needs: a plan that had to create the nodes
+ first to learn the pair is illegal would have written half of them to find out.
+ `place_verb` is the one-column case of the same question, kept apart because it
+ ranks its answers rather than listing them.
+
+ Media kinds are deliberately **not** decided here. `located-at` takes image, video
+ and audio media and not a PDF, and a type alone does not say which of those a row
+ holds. So a verb offered here can still be refused for one row, and the caller that
+ writes a batch validates every resolved pair before it writes any of them.
+
+ Only what an analyst may state: `same-image-as` is enrichment's own claim, and the
+ derivation chain is recorded by the save that produced it rather than asserted after
+ the fact — which is why it is absent from the registry entirely.
+ """
+ return tuple(
+ spec
+ for spec in RELATION_TYPES
+ if spec.manual
+ and (not action or spec.action == action)
+ and from_type in spec.from_types
+ and to_type in spec.to_types
+ )
+
+
def add_relation(
case: CaseRepository, from_id: str, to_id: str, type_: str, *, by: str
) -> dict[str, Any]:
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index 69462fb..bc088c4 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import hashlib
import json
+import logging
import mimetypes
import re
import shutil
@@ -16,6 +17,7 @@ import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, BinaryIO
+from urllib.parse import urlsplit
from PIL import Image
@@ -26,6 +28,8 @@ from . import ffmpeg as ffmpeg_engine
from . import links as link_engine
from . import thumbnails as thumbnail_engine
+logger = logging.getLogger(__name__)
+
# The thumbnail cache lives here; content-addressed generation, the durable job
# model and cache budgeting are owned by `thumbnails.py`. Re-exported for the
# test fixtures that build a case's `.thumbs/` directly.
@@ -39,6 +43,19 @@ MAX_PICKER_ITEMS = 20
_CHROMIUM_BROWSERS = {"chrome", "chromium", "edge", "brave", "vivaldi", "opera", "whale"}
# Best-effort phrases that identify an authentication failure.
+#
+# Some of these are what a site says about content it will not *show* rather than about
+# a session it will not accept, and X is the reason: a tweet a guest cannot read comes
+# back as "Unavailable", word for word what a deleted one gives. Read as a plain failure,
+# that made a login wall unrecoverable — no `needs_auth`, so no prompt, so no cookie
+# source was ever stored and every retry went out cookie-less too.
+#
+# So it is read as a wall, and **the cost of being wrong is a retry that carries the
+# session**: `fetch_url` answers a wall by trying once more with whatever the settings
+# hold, without asking, so a post that is merely deleted sends the analyst's cookies to a
+# host that did not need them. Accepted deliberately — a hundred-row press cannot stop on
+# a question, and the first attempt is always cookie-less — and recorded in SPEC's
+# security posture rather than left to be discovered here.
_AUTH_FAILURE_PHRASES = (
"log in",
"login",
@@ -57,18 +74,69 @@ _AUTH_FAILURE_PHRASES = (
"forbidden",
"nsfw",
"account",
+ # What a site says about content a guest cannot see, which is the same sentence it
+ # says about content that is gone. Deliberately *not* yt-dlp's "no video could be
+ # found in this tweet": that is also what a perfectly public photo-only post gets, and
+ # it is the ordinary road to the image extractor rather than a refusal.
+ "unavailable",
+ "not available",
)
+#: The one kind a caller can be short of somewhere to put. A slot that holds a picture
+#: has nowhere for a video: the composer lays panels out on a canvas and a clip has
+#: nothing to lay out, so handing one back fills the slot with a refusal.
+#:
+#: Every other value is a **preference**, not a requirement, and treating it as one broke
+#: the road it was written for: the footage is only *usually* a video, a still
+#: photographed on the spot is material too, and a source address holding four
+#: photographs is an ordinary geolocation rather than a row to refuse.
+_BINDING_KINDS = frozenset({"image"})
+
+
+def _binding(wants: str) -> bool:
+ """Whether ``wants`` is a slot with nowhere else to put what it is offered."""
+ return wants in _BINDING_KINDS
+
+
+class WrongKind(RuntimeError):
+ """The address holds something, and none of it is what the caller has room for.
+
+ Its own type because it is not a failure to reach the post: the bytes are there and
+ the answer is still no. A proof is composed of pictures, so a post carrying only a
+ clip holds no proof — and saying so at the address, where the analyst can type
+ another one, beats saying it at the preview once the file is already staged.
+ """
+
+
+class UnknownLink(RuntimeError):
+ """Neither downloader knows this address.
+
+ Its own type because it is the one failure a session can never fix, and the phrases
+ that identify a wall are loose enough to catch it by accident — which turned "this is
+ not a link Azimut can read" into "sign in to read it".
+ """
+
+
def _looks_like_auth_failure(message: str) -> bool:
low = message.lower()
return any(phrase in low for phrase in _AUTH_FAILURE_PHRASES)
def _is_gallery_auth_error(exc: BaseException) -> bool:
- """gallery-dl raises typed ``AuthenticationError`` / ``AuthorizationError``
- from ``gallery_dl.exception`` when a link needs a login."""
- return type(exc).__name__ in {"AuthenticationError", "AuthorizationError"}
+ """Whether gallery-dl stopped on something a session would get past.
+
+ Typed first: it raises ``AuthenticationError`` / ``AuthorizationError`` from
+ ``gallery_dl.exception`` when a link plainly needs a login. Then by message,
+ because the common case is not typed at all — X aborts with a bare
+ ``AbortExtraction('Unavailable')`` for a tweet the guest session cannot read,
+ and reading that as a plain failure is what kept the cookie prompt from ever
+ appearing for the site it is most needed on.
+ """
+ return type(exc).__name__ in {
+ "AuthenticationError",
+ "AuthorizationError",
+ } or _looks_like_auth_failure(str(exc))
def _resolve_cookie_file(file: str) -> Path:
@@ -111,13 +179,22 @@ def cookies_from_preference(pref: dict[str, Any] | None) -> dict[str, Any] | Non
return None
-def _apply_gallery_cookies(cookies: dict[str, Any] | None) -> None:
- """Thread a cookie source into gallery-dl via its global config: a browser
- as a ``[name]`` list, a file as a path string."""
- if not cookies:
- return
+def _apply_gallery_config(cookies: dict[str, Any] | None) -> None:
+ """What gallery-dl needs told before it reads a link.
+
+ A cookie source, when there is one: a browser as a ``[name]`` list, a file as a
+ path string.
+
+ And Bluesky's facets, always. An AT Protocol post keeps its links beside its words
+ rather than in them — the words hold what is *printed*, which is an address cut off
+ at an ellipsis — and gallery-dl only carries them when asked. Without it the source
+ a post points at cannot be recovered from anything the import can see.
+ """
import gallery_dl.config as gdl_config
+ gdl_config.set(("extractor", "bluesky"), "metadata", "facets")
+ if not cookies:
+ return
if cookies.get("browser"):
gdl_config.set(("extractor",), "cookies", [cookies["browser"]])
elif cookies.get("file"):
@@ -202,6 +279,25 @@ def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:
temporary.unlink(missing_ok=True)
+# The files whose origin only the analyst can state: brought in off a disk, out of
+# the clipboard, or placed in the case folder and adopted. Everything else was
+# fetched or made by a tool, and what that tool recorded about where the bytes came
+# from is not something a later edit gets to write over — a case that cannot tell a
+# fetched address from a stated one is holding neither.
+STATED_SOURCE_TYPES = frozenset({"upload", "clipboard", "manual"})
+
+
+def is_address(text: str) -> bool:
+ """Whether a stated origin is an address at all.
+
+ One reading for every surface that lets one be typed: the API refuses on it and
+ the proof import blocks on it, rather than each writing the same three-line test
+ and drifting. An origin that is not a link is a note, and Notes is where it goes.
+ """
+ split = urlsplit(text.strip())
+ return split.scheme in ("http", "https") and bool(split.hostname)
+
+
def _source_paths(source: dict[str, Any]) -> list[str]:
"""The case files a derivative was produced from, as its producer recorded them.
@@ -215,6 +311,43 @@ def _source_paths(source: dict[str, Any]) -> list[str]:
return paths
+def stage_descriptor(staged_path: Path, source: dict[str, Any]) -> dict[str, Any]:
+ """What a held file is, without filing it.
+
+ A download that is going to be reviewed before it lands answers with this
+ instead of an entity: the same facts a sidecar would carry, read off the
+ bytes that are already on disk, so a preview can say whether the case
+ already holds them without the case holding them yet.
+ """
+ return {
+ "filename": staged_path.name,
+ "title": staged_path.stem,
+ "kind": media_kind(staged_path.name),
+ "sha256": sha256_file(staged_path),
+ "size": staged_path.stat().st_size,
+ "source": source,
+ }
+
+
+def _deliver(
+ case: Case,
+ media_path: Path,
+ source: dict[str, Any],
+ *,
+ by: str = "import",
+ stage: Path | None = None,
+) -> dict[str, Any]:
+ """File a freshly downloaded file, or hold it where the caller asked.
+
+ Every download path ends here. ``stage`` is what the proof importer passes:
+ the bytes stay outside the library until the analyst approves what they are
+ about to create, and a cancelled import leaves nothing behind.
+ """
+ if stage is None:
+ return _register(case, media_path, source, by=by)
+ return {"multi": False, "staged": stage_descriptor(media_path, source)}
+
+
def _register(
case: Case,
media_path: Path,
@@ -299,13 +432,25 @@ def _register(
return {"duplicate": False, "entity": entity, "item": indexed}
-def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]:
- """Import an uploaded file into the case."""
+def import_stream(
+ case: Case, filename: str, stream: BinaryIO, *, source_url: str = ""
+) -> dict[str, Any]:
+ """Import an uploaded file into the case.
+
+ ``source_url`` is where the analyst says the file came from: a file downloaded
+ by hand and then imported has an origin the bytes cannot state, and only the
+ person who fetched it knows it. Stated, never observed — the type stays
+ ``upload``, so a reader can always tell this URL from the one a download
+ really pulled from.
+ """
media_dir = case.subdir("media")
dest = unique_path(media_dir, safe_filename(filename))
with dest.open("wb") as out:
shutil.copyfileobj(stream, out)
- return _register(case, dest, {"type": "upload", "original_name": filename})
+ source: dict[str, Any] = {"type": "upload", "original_name": filename}
+ if source_url:
+ source["url"] = source_url
+ return _register(case, dest, source)
def import_paste(
@@ -501,7 +646,33 @@ def import_produced_file(
return _register(case, dest, source, by=by)
+def _entry_kind(entry: dict[str, Any] | None) -> str:
+ """What an extracted entry would land as, read off its extension.
+
+ Before the download rather than after: a caller that has nowhere to put a video
+ should hear so while there is still another extractor to try.
+ """
+ ext = (entry or {}).get("ext")
+ return media_kind(f"file.{ext}") if ext else "video"
+
+
def _picker_items(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """The attachments yt-dlp reports, as picker rows.
+
+ **Only the first is vouched for as the post's own.** yt-dlp's X extractor reads a
+ tweet's media *and* the media of the tweet it quotes into one list — the post's own
+ first, then the quoted one's (`yt_dlp/extractor/twitter.py`, the `(None,
+ 'quoted_status')` traversal) — and nothing in what comes back says which is which.
+ A post carrying a clip and quoting another post carrying a clip hands back two, and
+ taking both files somebody else's video and, on the roads that pose material on a
+ point, claims it was recorded there.
+
+ So `own` is a vouch, not a verdict: true where the file is certainly the post's,
+ false where it may be what the post quotes. A picker still lists everything, since
+ a quoted clip is sometimes exactly what the analyst wants; it just is not taken by
+ a rule. The cost is a tweet carrying two of its own clips offering the second
+ unticked, which is the safe side of a distinction the extractor does not draw.
+ """
items = []
for i, entry in enumerate(entries, start=1):
thumb = entry.get("thumbnail")
@@ -513,6 +684,7 @@ def _picker_items(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
"title": entry.get("title") or entry.get("id") or f"item {i}",
"thumbnail": thumb,
"kind": media_kind(f"file.{entry['ext']}") if entry.get("ext") else "file",
+ "own": i == 1,
}
)
return items
@@ -526,6 +698,7 @@ def _register_downloaded_item(
*,
title: str | None,
source_extra: dict[str, Any],
+ stage: Path | None = None,
) -> dict[str, Any]:
"""Shared tail for the non-yt-dlp download paths (gallery-dl, the Telegram
photo scraper): write ``content`` into the case's media dir, register it,
@@ -544,19 +717,35 @@ def _register_downloaded_item(
)
tmp_path = tmp_dir / fname
tmp_path.write_bytes(content)
- dest = unique_path(media_dir, fname)
+ dest = unique_path(stage or media_dir, fname)
shutil.move(str(tmp_path), str(dest))
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
source = {"type": "download", "url": post_url, "webpage_url": post_url, **source_extra}
- result = _register(case, dest, source)
+ result = _deliver(case, dest, source, stage=stage)
result["multi"] = False
return result
+#: What a post's own words are called, extractor by extractor. `content` is X's and
+#: Mastodon's, `description` covers the sites that name it that, and `text` is the
+#: field an AT Protocol record carries — Bluesky's, and the one whose absence made a
+#: Bluesky import arrive with a filename for a title, no position read out of it and
+#: no source link, since every one of those is read from the post's words.
+_POST_TEXT_KEYS = ("content", "description", "text")
+
+#: And what an author is called. A handle is not a display name, so it is the last
+#: resort rather than the first.
+_AUTHOR_KEYS = ("nick", "name", "displayName", "handle")
+
+
def _gallery_dl_item(file_url: str, kwdict: dict[str, Any]) -> dict[str, Any]:
- content = (kwdict.get("content") or kwdict.get("description") or "").strip()
+ content = ""
+ for key in _POST_TEXT_KEYS:
+ content = str(kwdict.get(key) or "").strip()
+ if content:
+ break
first_line = content.splitlines()[0][:120] if content else None
filename = kwdict.get("filename") or "file"
ext = kwdict.get("extension") or ""
@@ -569,7 +758,11 @@ def _gallery_dl_item(file_url: str, kwdict: dict[str, Any]) -> dict[str, Any]:
"kind": media_kind(f"file.{ext}") if ext else "file",
"title": first_line or filename,
"description": content or None,
- "uploader": author.get("nick") or author.get("name"),
+ "uploader": next((author[k] for k in _AUTHOR_KEYS if author.get(k)), None),
+ # The addresses the post *points* at, as the platform records them rather than
+ # as it prints them: a Bluesky link is shown truncated to an ellipsis, so a
+ # scan of the words comes back with half an address and no way to know it.
+ "links": [one for one in (kwdict.get("uris") or []) if isinstance(one, str)],
"upload_date": date.strftime("%Y%m%d")
if date is not None and hasattr(date, "strftime")
else None,
@@ -577,7 +770,13 @@ def _gallery_dl_item(file_url: str, kwdict: dict[str, Any]) -> dict[str, Any]:
def _register_gallery_dl_item(
- case: Case, extractor, post_url: str, item: dict[str, Any], *, title: str | None = None
+ case: Case,
+ extractor,
+ post_url: str,
+ item: dict[str, Any],
+ *,
+ title: str | None = None,
+ stage: Path | None = None,
) -> dict[str, Any]:
resp = extractor.request(item["url"])
fname = f"{item['filename']}.{item['extension']}" if item["extension"] else item["filename"]
@@ -587,17 +786,30 @@ def _register_gallery_dl_item(
fname,
resp.content,
title=title,
+ stage=stage,
source_extra={
"downloader": "gallery-dl",
"title": item["title"],
"description": item.get("description"),
"uploader": item.get("uploader"),
"upload_date": item.get("upload_date"),
+ "links": item.get("links") or None,
"extractor": "gallery-dl",
},
)
+#: A status on a Mastodon server gallery-dl does not name. Its extractor ships three
+#: patterns — mastodon.social, pawoo, baraag — and the fediverse is the one place where
+#: a list of servers can never be the answer, since the point of it is that everybody
+#: runs their own. ``mastodon:<url>`` is gallery-dl's own way of saying "read this
+#: address with that extractor", so a link nothing recognized is offered to it before
+#: being refused. Only a status, and only by shape: an account page is not a download.
+_MASTODON_STATUS = re.compile(
+ r"^https?://[^/?#]+/(?:@[^/?#]+|users/[^/?#]+/statuses)/\d+/?(?:[?#].*)?$"
+)
+
+
def _download_via_gallery_dl(
case: Case,
url: str,
@@ -605,6 +817,8 @@ def _download_via_gallery_dl(
index: int | None = None,
title: str | None = None,
cookies: dict[str, Any] | None = None,
+ stage: Path | None = None,
+ wants: str = "",
) -> dict[str, Any]:
"""Fallback for links yt-dlp can't extract at all.
@@ -612,46 +826,67 @@ def _download_via_gallery_dl(
drops photos from what it reports. gallery-dl covers standalone images
instead: photo tweets, direct image links, Instagram posts, Facebook
photos. Used when yt-dlp raises (e.g. "No video could be found").
+
+ ``wants`` binds here exactly as it does on the yt-dlp path: a caller with
+ somewhere for a picture and nowhere for a video is answered with nothing rather
+ than with the clip. This is the *last* road, so a wrong kind is a refusal instead
+ of a fallback — and it is the road a video-only post took to reach a slot that
+ holds pictures, which the preview then refused two screens later.
"""
import gallery_dl.extractor as gdl_extractor
- _apply_gallery_cookies(cookies)
+ _apply_gallery_config(cookies)
extractor = gdl_extractor.find(url)
+ if extractor is None and _MASTODON_STATUS.match(url):
+ extractor = gdl_extractor.find(f"mastodon:{url}")
if extractor is None:
- raise RuntimeError(f"no extractor (yt-dlp or gallery-dl) recognizes this link: {url}")
+ raise UnknownLink(f"no extractor (yt-dlp or gallery-dl) recognizes this link: {url}")
items = [_gallery_dl_item(msg[1], msg[2]) for msg in extractor if msg[0] == 3] # Message.Url
if not items:
raise RuntimeError("gallery-dl found no downloadable media at this link")
+ if _binding(wants) and not any(it["kind"] == wants for it in items):
+ raise WrongKind("nothing at that address is an image")
if index is None and 1 < len(items) <= MAX_PICKER_ITEMS:
return {
"multi": True,
"items": [
- {"index": i, "title": it["title"], "thumbnail": it["url"], "kind": it["kind"]}
+ {
+ "index": i,
+ "title": it["title"],
+ "thumbnail": it["url"],
+ "kind": it["kind"],
+ # gallery-dl drops a quoted tweet before it lists anything
+ # (`extractor.twitter.quoted`, off), so all of these are the post's.
+ "own": True,
+ }
for i, it in enumerate(items, start=1)
],
}
picked = items[(index or 1) - 1]
- return _register_gallery_dl_item(case, extractor, url, picked, title=title)
+ if _binding(wants) and picked["kind"] != wants:
+ raise WrongKind("that file is not an image")
+ return _register_gallery_dl_item(case, extractor, url, picked, title=title, stage=stage)
_TELEGRAM_POST_RE = re.compile(r"^https?://(www\.)?(t|telegram)\.me/[^/]+/\d+")
-def _telegram_extra_photos(url: str) -> list[dict[str, Any]]:
+def _telegram_embed_media(url: str) -> tuple[list[dict[str, Any]], bool]:
"""yt-dlp's Telegram extractor only regex-matches ``<video>`` players in
the public embed page — it has no notion of photos at all, so a mixed
video+photo album silently loses its photos (verified against a real
post: 2 videos + 2 photos in the HTML, yt-dlp reports only the 2 videos).
gallery-dl has no Telegram extractor either. Scrape the same embed page
- ourselves for photo attachments to fill that gap. Best-effort: any
- failure (markup change, non-Telegram URL, network hiccup) yields ``[]``
- rather than breaking the main download flow.
+ ourselves for photo attachments to fill that gap and notice the explicit
+ ``Media is too big`` wall. Best-effort: any failure (markup change,
+ non-Telegram URL, network hiccup) yields no media and no wall rather than
+ breaking the main download flow.
"""
if not _TELEGRAM_POST_RE.match(url):
- return []
+ return [], False
import requests
try:
@@ -660,16 +895,28 @@ def _telegram_extra_photos(url: str) -> list[dict[str, Any]]:
resp.raise_for_status()
html = resp.text
except Exception:
- return []
+ return [], False
urls = re.findall(
r"tgme_widget_message_photo_wrap[^\"]*\"[^>]*background-image:url\('([^']+)'\)", html
)
- return [{"url": u} for u in dict.fromkeys(urls)] # de-dup, keep order
+ too_large = bool(
+ re.search(
+ r'message_media_not_supported_label"[^>]*>\s*Media is too big\s*<',
+ html,
+ re.IGNORECASE,
+ )
+ )
+ return [{"url": u} for u in dict.fromkeys(urls)], too_large # de-dup, keep order
def _register_telegram_photo(
- case: Case, post_url: str, photo: dict[str, Any], *, title: str | None = None
+ case: Case,
+ post_url: str,
+ photo: dict[str, Any],
+ *,
+ title: str | None = None,
+ stage: Path | None = None,
) -> dict[str, Any]:
import requests
@@ -684,6 +931,7 @@ def _register_telegram_photo(
f"{uuid.uuid4().hex[:10]}{ext}",
resp.content,
title=title,
+ stage=stage,
source_extra={
"downloader": "telegram-scrape",
"title": photo.get("title") or "Telegram photo",
@@ -692,6 +940,33 @@ def _register_telegram_photo(
)
+def fetch_url(case: Case, url: str, **asked: Any) -> dict[str, Any]:
+ """Download, and use the session the settings hold if a wall comes back.
+
+ The app's rule is that nothing reaches the network unless the analyst's action needs
+ it, and reading a browser's cookie store is reading their credentials for every site —
+ so it is asked for, once, and it is stored (`download_cookies`). What was missing was
+ the other half: **an answer given once should not be asked for again.** Every road went
+ out cookie-less, hit the wall, and put the question back on screen, which for a hundred
+ rows of a binder is a hundred questions with the same answer.
+
+ So: cookie-less first, still, because public media must never touch the session. Then,
+ on a wall and only on a wall, once, with whatever the settings hold. A caller that
+ already passed a session, or a workspace with none configured, is answered unchanged —
+ the prompt is what stores one, and it still appears when there is nothing to use.
+
+ The retry is what makes a loose wall phrase cost more than a question: a dead link that
+ only says "Unavailable" gets the session too. See `_AUTH_FAILURE_PHRASES`.
+ """
+ answer = download_url(case, url, **asked)
+ if not answer.get("needs_auth") or asked.get("cookies") is not None:
+ return answer
+ session = cookies_from_preference(config.load_settings().get("download_cookies"))
+ if session is None:
+ return answer
+ return download_url(case, url, **{**asked, "cookies": session})
+
+
def _fallback_or_needs_auth(
case: Case,
url: str,
@@ -700,6 +975,8 @@ def _fallback_or_needs_auth(
title: str | None,
cookies: dict[str, Any] | None,
yt_auth: bool,
+ stage: Path | None = None,
+ wants: str = "",
) -> dict[str, Any]:
"""yt-dlp found nothing — try gallery-dl, but turn a login wall into a
``needs_auth`` signal instead of an error, so the UI can offer cookies.
@@ -709,13 +986,49 @@ def _fallback_or_needs_auth(
as the underlying error rather than an endless re-prompt.
"""
try:
- return _download_via_gallery_dl(case, url, index=index, title=title, cookies=cookies)
+ return _download_via_gallery_dl(
+ case, url, index=index, title=title, cookies=cookies, stage=stage, wants=wants
+ )
+ except UnknownLink:
+ # Not knowing the address is not a refusal — but yt-dlp having *seen* a wall is,
+ # and gallery-dl simply not being the tool for that site does not undo it.
+ if cookies is None and yt_auth:
+ return {"needs_auth": True, "platform": sys.platform}
+ raise
+ except WrongKind:
+ # The post was read and holds nothing this caller has room for. Passed through
+ # before the wall handler below, which would otherwise answer a plain "no
+ # picture here" with a login prompt that could never fix it.
+ raise
except Exception as exc:
if cookies is None and (yt_auth or _is_gallery_auth_error(exc)):
return {"needs_auth": True, "platform": sys.platform}
+ if cookies is not None and (yt_auth or _is_gallery_auth_error(exc)):
+ # Tried with a session and still refused. Said as such rather than as the
+ # platform's own wording, which is a tombstone the analyst cannot act on.
+ return {"needs_auth": True, "platform": sys.platform, "refused": True}
raise
+class _YtdlpLog:
+ """Catch yt-dlp's console output instead of letting it reach the terminal.
+
+ ``quiet`` silences its progress chatter but not its errors, and the errors
+ it reports here are ones this module answers by itself: "No video could be
+ found in this tweet" is how an image-only post announces itself, one line
+ before gallery-dl downloads it. Printed as ERROR, a download that worked
+ looks broken. What the extractor said stays available under debug logging,
+ and the caller keeps deciding what the user is told.
+ """
+
+ def debug(self, msg: str) -> None:
+ logger.debug("yt-dlp: %s", msg)
+
+ info = debug
+ warning = debug
+ error = debug
+
+
def download_url(
case: Case,
url: str,
@@ -724,11 +1037,13 @@ def download_url(
index: int | None = None,
title: str | None = None,
cookies: dict[str, Any] | None = None,
+ stage: Path | None = None,
+ wants: str = "",
) -> dict[str, Any]:
"""Resolve and download a URL via yt-dlp. Blocking — run in a worker.
One extraction total (plus, for Telegram links, one lightweight extra
- fetch — see ``_telegram_extra_photos``). Without ``index``, a post with
+ fetch — see ``_telegram_embed_media``). Without ``index``, a post with
several attachments (a tweet with several photos, a mixed Telegram
album, …) is *not* downloaded — ``{"multi": True, "items": [...]}`` is
returned instead so the caller can show a picker and call back with the
@@ -738,6 +1053,20 @@ def download_url(
Falls back to gallery-dl (see ``_download_via_gallery_dl``) for links
yt-dlp can't extract at all — most commonly image-only posts.
+ ``stage`` diverts the result: the file lands in that directory and comes back
+ as ``{"staged": {...}}`` rather than as a media entity, so a caller that
+ reviews before filing (the proof importer) holds the bytes without the case
+ holding them. Everything before the last step is identical.
+
+ ``wants="image"`` says the caller has somewhere for a picture and nowhere for
+ a video — a proof's panel is the only such slot. yt-dlp reads posts for their
+ *video*, so a post publishing a picture beside a quoted clip hands back the
+ clip and the picture stays invisible: the image extractor is the one that can
+ reach it, and today it is only tried when yt-dlp found nothing at all. With
+ ``wants`` set, a pick of the wrong kind counts as nothing found. Any other
+ value only records what the caller was after; the fallback is gallery-dl, and
+ gallery-dl fetches images.
+
``cookies`` is a login session for gated media (``{"browser": name}`` or
``{"file": path}``); ``None`` (the default) downloads cookie-less, so public
media never touches the session. A gated link tried cookie-less comes back
@@ -757,12 +1086,16 @@ def download_url(
tmp_dir = media_dir / ".dl" / uuid.uuid4().hex[: layout.DOWNLOAD_ID_LENGTH]
ensure_dir(tmp_dir)
- extra_photos = _telegram_extra_photos(url) # [] — and free — for non-Telegram links
+ # Both values come from the same embed fetch. A large Telegram video has no
+ # URL in that page, only an instruction to open the app; keep that distinct
+ # from an extractor failure so the UI can give the useful next step.
+ extra_photos, telegram_too_large = _telegram_embed_media(url)
ydl_opts = {
"outtmpl": str(tmp_dir / "%(title).120B [%(id)s].%(ext)s"),
"quiet": True,
"no_warnings": True,
+ "logger": _YtdlpLog(),
"restrictfilenames": False,
}
# Narrow yt-dlp to the one picked entry, as an optimization, ONLY when
@@ -790,7 +1123,7 @@ def download_url(
yt_auth = False
try:
info = ydl.extract_info(url, download=False)
- entries = [e for e in (info.get("entries") or []) if e]
+ entries = [e for e in ((info or {}).get("entries") or []) if e]
except yt_dlp.utils.DownloadError as exc:
yt_auth = _looks_like_auth_failure(str(exc))
info = None
@@ -800,7 +1133,8 @@ def download_url(
if info is None and not entries:
shutil.rmtree(tmp_dir, ignore_errors=True)
return _fallback_or_needs_auth(
- case, url, index=index, title=title, cookies=cookies, yt_auth=yt_auth
+ case, url, index=index, title=title, cookies=cookies, yt_auth=yt_auth,
+ stage=stage, wants=wants,
)
target_info = entries[0] if entries else info
else:
@@ -809,8 +1143,11 @@ def download_url(
if total == 0:
shutil.rmtree(tmp_dir, ignore_errors=True)
+ if telegram_too_large:
+ return {"telegram_only": True}
return _fallback_or_needs_auth(
- case, url, index=index, title=title, cookies=cookies, yt_auth=yt_auth
+ case, url, index=index, title=title, cookies=cookies, yt_auth=yt_auth,
+ stage=stage, wants=wants,
)
if index is None and 1 < total <= MAX_PICKER_ITEMS:
@@ -826,6 +1163,7 @@ def download_url(
"title": info.get("title") or info.get("id") or "item 1",
"thumbnail": info.get("thumbnail"),
"kind": "video",
+ "own": True,
}
]
else:
@@ -836,6 +1174,9 @@ def download_url(
"title": "Telegram photo",
"thumbnail": p["url"],
"kind": "image",
+ # An embed page holds one post and quotes nothing, so every
+ # photo on it is that post's own.
+ "own": True,
}
for i, p in enumerate(extra_photos, start=1)
]
@@ -846,10 +1187,20 @@ def download_url(
# not a yt-dlp entry — one of the extra Telegram photos
shutil.rmtree(tmp_dir, ignore_errors=True)
photo = extra_photos[pick - yt_count - 1]
- return _register_telegram_photo(case, url, photo, title=title)
+ return _register_telegram_photo(case, url, photo, title=title, stage=stage)
target_info = entries[pick - 1] if entries else info
+ # A slot that holds a picture is not served by the video this post quotes.
+ # Handing it back would fill the panel with fifty seconds of footage and say
+ # so only at the preview, two screens later.
+ if _binding(wants) and _entry_kind(target_info) != wants:
+ shutil.rmtree(tmp_dir, ignore_errors=True)
+ return _fallback_or_needs_auth(
+ case, url, index=index, title=title, cookies=cookies, yt_auth=yt_auth,
+ stage=stage, wants=wants,
+ )
+
# download from the info we already extracted — no second extraction
info = ydl.process_ie_result(target_info, download=True)
downloaded = Path(ydl.prepare_filename(info))
@@ -872,7 +1223,7 @@ def download_url(
if display_title
else original
)
- dest = unique_path(media_dir, filename)
+ dest = unique_path(stage or media_dir, filename)
shutil.move(str(downloaded), str(dest))
shutil.rmtree(tmp_dir, ignore_errors=True)
@@ -888,7 +1239,7 @@ def download_url(
"extractor": info.get("extractor"),
"duration": info.get("duration"),
}
- result = _register(case, dest, source)
+ result = _deliver(case, dest, source, stage=stage)
result["multi"] = False
return result
@@ -1135,6 +1486,11 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,
same filing may already be writing the file's own facts to the same sidecar.
Unguarded, whichever finished second dropped the other's fields — and the one
users noticed was the name they had just typed.
+
+ ``source_url`` states where a collected file came from, and is refused on a
+ download: that URL is what the app actually fetched, and letting a later edit
+ write over it would leave the case unable to say which of the two it is
+ holding. An empty value drops the claim.
"""
if "title" in patch:
renamed = rename_media(case, rel_path, patch["title"])
@@ -1159,6 +1515,18 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,
else:
data[key] = str(val)
+ if "source_url" in patch:
+ source = data.get("source")
+ if not isinstance(source, dict):
+ source = {}
+ if source.get("type") not in STATED_SOURCE_TYPES:
+ raise CaseError("only a file brought in by hand can be given a source")
+ stated = str(patch["source_url"] or "")
+ source = {key: value for key, value in source.items() if key != "url"}
+ if stated:
+ source["url"] = stated
+ data["source"] = source
+
_write_sidecar(media_path, data)
# mirror onto the media entity (label mirrors the title; folder/notes attrs)
@@ -1170,6 +1538,10 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,
attrs["folder"] = patch["folder"] or ""
if "notes" in patch:
attrs["notes"] = patch["notes"] or ""
+ if "source_url" in patch:
+ # The attribute, never `provenance.source`: provenance records the act
+ # that filed the file, and that act was an import with nothing stated.
+ attrs["source_url"] = patch["source_url"] or ""
if attrs:
entity_patch["attrs"] = attrs
if entity_patch:
diff --git a/src/azimut/engine/proofimport.py b/src/azimut/engine/proofimport.py
new file mode 100644
index 0000000..5a2c7d0
--- /dev/null
+++ b/src/azimut/engine/proofimport.py
@@ -0,0 +1,749 @@
+"""Importing a geolocated post as a proof.
+
+A post states a position and points at the footage it was read from. That is a
+proof and its material, written in prose, and this module turns the pair into
+the same nodes the composer writes when somebody geolocates a clip by hand:
+
+- the **source media** — what was filmed on the spot. It takes ``located-at``
+ when the analyst says the camera was there, because the registry gives that
+ verb to material and to nothing else;
+- the **panel images** — the pictures the post published. They are files the case
+ collected too, and they are what the proof composes. A post publishing a set —
+ the overhead, the ground shot, the match — is one proof of several panels, not
+ one picture kept and the rest dropped;
+- the **place** — filed exactly as the composer files one, so a point already in
+ the case is reused rather than pinned twice;
+- the **proof** — a real spec, so it lists, exports, travels in a bundle and
+ reopens for editing like every other proof. Nothing here is a second class of
+ proof.
+
+**One picture exports itself; a set waits for the composer.** A published panel is
+already a rendered proof, so a single-picture import files it as ``proofs/<name>.png``
+and is done. Several panels have no render — laying them out is the composer's
+canvas, in the browser — and inventing a second renderer here would drift from it
+at the first change to a layout. So a set is filed **without an export**, borrowing
+the first picture's thumbnail so the proof still draws in the graph, and the first
+save in the composer writes the real one. A composition nobody composed is worth
+opening anyway.
+
+**Nothing is written until the analyst approves the preview.** Both downloads
+land in a staging directory under ``media/.dl/``, which the bundle already
+leaves behind and the Doctor already ignores, and a cancelled import deletes it.
+That is why the download runs *before* the preview rather than after: once the
+bytes are on disk their hash is known, so the preview can say the case already
+holds this file instead of promising it will not.
+
+**No format is special.** What the platform hands over — the media, the post
+URL, the author, the date, the text — is read for every site the downloaders
+support. What the text is asked for is shapes, never lines or keywords: a
+position in any notation the app can parse (``geo.scan_coords``) and a URL. A
+post that spells none of it out simply prefills nothing, and the form is filled
+by hand, which is the same screen.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+import shutil
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from .. import layout
+from ..workspace import Case, CaseError, ensure_dir
+from . import enrich as enrich_engine
+from . import geo as geo_engine
+from . import links as link_engine
+from . import media as media_engine
+from . import satellite as satellite_engine
+
+#: Held downloads live beside the in-progress ones. `media/.dl` is already the
+#: directory that means "this machine's, not the case's": bundles skip it and the
+#: Doctor never offers to adopt what is in it.
+#:
+#: A staging directory is named exactly like a download's scratch one — a token of
+#: `layout.DOWNLOAD_ID_LENGTH` hex digits, no prefix — because the Windows path
+#: budget is computed from that branch (`tests/test_layout.py`) and it has two
+#: characters of room left. What tells the two apart is the manifest inside, which
+#: is also what keeps the sweep from deleting a download still writing.
+STAGING_PARENT = ".dl"
+MANIFEST = "import.json"
+
+#: The two things an import holds. `panel` is the published picture, `source` the
+#: material it was read from; either may be filled by a download or by hand.
+#:
+#: **Both slots hold several files, and for opposite reasons.** A post often publishes a
+#: geolocation as a set — the overhead, the ground shot, the match — and taking one and
+#: dropping the rest keeps a third of what was published; those become the panels of one
+#: composition, which is what a proof already is. The material runs the other way: a
+#: thread states one point and hangs the photos and the clips it rests on off several
+#: posts, so a slot that held one file filed one file and left the rest of the case's own
+#: evidence outside it.
+SLOT_PANEL = "panel"
+SLOT_SOURCE = "source"
+SLOTS = (SLOT_PANEL, SLOT_SOURCE)
+
+#: How many pictures one import composes. A published set is a handful; past this it is an
+#: album, and an album is not a proof.
+MAX_PANELS = 8
+
+#: How much material one proof may rest on. A thread hangs a handful of photos and clips
+#: off its point; past this it is a channel dump, and that is the Media Library's job.
+MAX_SOURCES = 8
+
+#: What each slot may hold at once.
+SLOT_CAPS = {SLOT_PANEL: MAX_PANELS, SLOT_SOURCE: MAX_SOURCES}
+
+#: A staging directory the analyst walked away from. Swept when the next import
+#: opens, so an abandoned tab costs one directory until then and nothing after.
+MAX_STAGED_AGE = 24 * 60 * 60
+
+#: How far a file's own recorded position may sit from the one the analyst typed
+#: before the preview says so. Below this the two are the same spot written to a
+#: different precision; above it, one of them is about somewhere else.
+GPS_CONFLICT_METRES = 150
+
+#: Scheme-less links are accepted only with a path, so ordinary prose ("i.e.",
+#: a decimal ending a sentence) is not read as an address.
+_URL = re.compile(
+ r"\bhttps?://[^\s<>\"'\]]+"
+ r"|\b(?:[\w-]+\.)+[a-zA-Z]{2,24}/[^\s<>\"'\]]*",
+)
+#: Trailing punctuation a sentence leaves stuck to a link, and the ellipsis a
+#: timeline truncates one with.
+_URL_TRIM = ".,;:!?)]}…"
+
+MAX_SCANNED_URLS = 10
+
+#: How much of a post's text is scanned. A caption is a paragraph; what arrives
+#: past this is a transcript or a wall of tags, and both are attacker-controlled
+#: input running through patterns that backtrack. Bounded at the door, once, so
+#: neither scan has to defend itself.
+MAX_POST_TEXT = 4000
+
+
+def _now() -> float:
+ return time.time()
+
+
+# -- the staging directory -------------------------------------------------------
+
+
+def _parent(case: Case) -> Path:
+ return case.subdir("media") / STAGING_PARENT
+
+
+def staging_dir(case: Case, token: str) -> Path:
+ """Where one import holds its files. Refuses a token it did not mint, so a
+ request cannot name a directory of its own."""
+ if not re.fullmatch(r"[0-9a-f]{%d}" % layout.DOWNLOAD_ID_LENGTH, token):
+ raise CaseError("unknown import")
+ return _parent(case) / token
+
+
+def sweep(case: Case) -> int:
+ """Drop staging directories nothing came back for. Answers how many went."""
+ parent = _parent(case)
+ if not parent.is_dir():
+ return 0
+ dropped = 0
+ cutoff = _now() - MAX_STAGED_AGE
+ for path in parent.iterdir():
+ # The manifest is what makes a directory here an import rather than a
+ # download in flight, and deleting one of those would break it.
+ if not path.is_dir() or not (path / MANIFEST).is_file():
+ continue
+ try:
+ if path.stat().st_mtime >= cutoff:
+ continue
+ except OSError:
+ continue
+ shutil.rmtree(path, ignore_errors=True)
+ dropped += 1
+ return dropped
+
+
+def open_import(case: Case) -> str:
+ """Mint a token and its directory. Sweeps first: an import that is starting
+ is the moment an abandoned one costs nothing to notice."""
+ sweep(case)
+ token = uuid.uuid4().hex[: layout.DOWNLOAD_ID_LENGTH]
+ directory = staging_dir(case, token)
+ ensure_dir(directory)
+ _write_draft(case, token, {"token": token, "opened_at": _now(), "slots": {}, "post": {}})
+ return token
+
+
+def _draft_path(case: Case, token: str) -> Path:
+ return staging_dir(case, token) / MANIFEST
+
+
+def read_draft(case: Case, token: str) -> dict[str, Any]:
+ path = _draft_path(case, token)
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError) as exc:
+ raise CaseError("this import is no longer open") from exc
+ if not isinstance(data, dict):
+ raise CaseError("this import is no longer open")
+ return data
+
+
+def _write_draft(case: Case, token: str, draft: dict[str, Any]) -> None:
+ media_engine.write_json_atomic(_draft_path(case, token), draft)
+
+
+def discard(case: Case, token: str) -> None:
+ """Cancel: the held files go, and the case is exactly as it was.
+
+ Only a directory carrying the manifest, so a token naming a download still
+ writing into its own scratch directory cannot delete it.
+ """
+ directory = staging_dir(case, token)
+ if (directory / MANIFEST).is_file():
+ shutil.rmtree(directory, ignore_errors=True)
+
+
+def _held(draft: dict[str, Any], slot: str) -> list[dict[str, Any]]:
+ """What a slot holds, always as a list.
+
+ The source holds one file and the panel holds a set, and reading them through one
+ shape is what keeps every caller from having to know which of the two it is asking.
+ """
+ found = (draft.get("slots") or {}).get(slot)
+ if isinstance(found, list):
+ return [entry for entry in found if isinstance(entry, dict) and entry.get("filename")]
+ return [found] if isinstance(found, dict) and found.get("filename") else []
+
+
+def held_files(case: Case, token: str, slot: str) -> list[dict[str, Any]]:
+ """Everything this slot holds, in the order it was held."""
+ if slot not in SLOTS:
+ raise CaseError(f"unknown slot '{slot}'")
+ return _held(read_draft(case, token), slot)
+
+
+def _at(case: Case, token: str, staged: dict[str, Any]) -> Path | None:
+ path = staging_dir(case, token) / str(Path(str(staged.get("filename") or "")).name)
+ return path if path.is_file() else None
+
+
+def staged_path(case: Case, token: str, slot: str) -> Path | None:
+ """The first file held in a slot, or None when the slot is empty."""
+ held = held_files(case, token, slot)
+ return _at(case, token, held[0]) if held else None
+
+
+def staged_pairs(case: Case, token: str, slot: str) -> list[tuple[Path, dict[str, Any]]]:
+ """Every file held in a slot with the entry describing it, the missing ones left out.
+
+ Paired here rather than by the caller, and that is the whole reason it exists: the paths
+ that survive and the entries that describe them were two lists zipped by position, so
+ one file gone from the staging directory shifted every picture after it onto its
+ neighbour's provenance — the post it came from, its title, the footage it derives from.
+ A wrong origin on a proof is worse than none.
+ """
+ found = ((_at(case, token, staged), staged) for staged in held_files(case, token, slot))
+ return [(path, staged) for path, staged in found if path is not None]
+
+
+def fill_slot(case: Case, token: str, slot: str, staged: dict[str, Any]) -> dict[str, Any]:
+ """Record what a download or a hand-attached file put in a slot, alone.
+
+ Filling replaces: retrying a failed source download does not leave the abandoned
+ attempt on disk, and re-picking a picture drops the one that was there.
+ """
+ return fill_files(case, token, slot, [staged])
+
+
+def fill_files(
+ case: Case, token: str, slot: str, staged: list[dict[str, Any]], *, for_url: str = ""
+) -> dict[str, Any]:
+ """Hold this set in a slot, dropping whatever it held that is not in it.
+
+ ``for_url`` narrows the replacement to one address: what came from *that* post goes,
+ what came from the others stays. Without it a second source address would have taken
+ the first one's files with it, and retrying one failed address would have taken the
+ lot. The address is written onto each entry rather than read back off the
+ downloader's metadata, because a hand-attached file has no metadata to read.
+ """
+ if slot not in SLOTS:
+ raise CaseError(f"unknown slot '{slot}'")
+ draft = read_draft(case, token)
+ if for_url:
+ staged = [{**entry, "for_url": for_url} for entry in staged]
+ kept = [one for one in _held(draft, slot) if one.get("for_url") != for_url]
+ else:
+ kept = []
+ if len(kept) + len(staged) > SLOT_CAPS[slot]:
+ raise CaseError(
+ f"a proof composes at most {MAX_PANELS} pictures"
+ if slot == SLOT_PANEL
+ else f"a proof rests on at most {MAX_SOURCES} files"
+ )
+ holding = kept + staged
+ keeping = {str(entry.get("filename") or "") for entry in holding}
+ for previous in _held(draft, slot):
+ name = str(previous.get("filename") or "")
+ if name and name not in keeping:
+ (staging_dir(case, token) / str(Path(name).name)).unlink(missing_ok=True)
+ draft.setdefault("slots", {})[slot] = holding
+ _write_draft(case, token, draft)
+ return draft
+
+
+def drop_for_url(case: Case, token: str, slot: str, url: str) -> dict[str, Any]:
+ """Let go of what one address put in a slot, files and all."""
+ return fill_files(case, token, slot, [], for_url=url)
+
+
+def record_post(case: Case, token: str, post: dict[str, Any]) -> dict[str, Any]:
+ """Keep what the platform said about the post, and what its text states."""
+ draft = read_draft(case, token)
+ draft["post"] = post
+ _write_draft(case, token, draft)
+ return draft
+
+
+# -- reading the post ------------------------------------------------------------
+
+
+def scan_urls(text: str, *, exclude: str = "") -> list[str]:
+ """Every address a text points at, in order, minus the post's own.
+
+ Candidates, not an answer: which one is the source is the analyst's call,
+ and a post that names three is not being ambiguous by mistake.
+ """
+ found: list[str] = []
+ excluded = exclude.rstrip("/").casefold()
+ for match in _URL.finditer(text or ""):
+ url = match.group(0).rstrip(_URL_TRIM)
+ if not url or url.rstrip("/").casefold() == excluded:
+ continue
+ if url not in found:
+ found.append(url)
+ if len(found) == MAX_SCANNED_URLS:
+ break
+ return found
+
+
+def read_post(source: dict[str, Any], post_url: str) -> dict[str, Any]:
+ """What the downloaders reported about a post, plus what its text states.
+
+ The first half is universal — every extractor answers with a title, a body,
+ an author and a date, or leaves them out. The second half is the scan, and
+ it prefills; it never decides.
+
+ **The addresses it points at come from two places.** A platform that records them
+ beside the words is believed first: an AT Protocol post prints a link truncated to
+ an ellipsis and keeps the whole of it in a facet, so scanning the words there gives
+ half an address and nothing to say it is half. The scan follows, for everything that
+ writes its links out in full.
+ """
+ text = " \n".join(
+ part for part in (source.get("title"), source.get("description")) if isinstance(part, str)
+ ).strip()[:MAX_POST_TEXT]
+ recorded = [one for one in (source.get("links") or []) if isinstance(one, str) and one]
+ excluded = post_url.rstrip("/").casefold()
+ urls = [one for one in recorded if one.rstrip("/").casefold() != excluded]
+ for one in scan_urls(text, exclude=post_url):
+ if one not in urls:
+ urls.append(one)
+ return {
+ "url": post_url,
+ "title": source.get("title") or "",
+ "text": text,
+ "uploader": source.get("uploader") or "",
+ "upload_date": source.get("upload_date") or "",
+ "coords": geo_engine.scan_coords(text),
+ "urls": urls[:MAX_SCANNED_URLS],
+ }
+
+
+# -- what the import would create ------------------------------------------------
+
+
+def _distance_metres(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
+ """Great-circle metres between two points, on a spherical earth. Precise
+ enough for "is this the same spot", which is all it is asked."""
+ radius = 6_371_000.0
+ phi1, phi2 = math.radians(lat1), math.radians(lat2)
+ d_phi = math.radians(lat2 - lat1)
+ d_lambda = math.radians(lon2 - lon1)
+ a = math.sin(d_phi / 2) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2) ** 2
+ return 2 * radius * math.asin(min(1.0, math.sqrt(a)))
+
+
+def _stated_gps(path: Path, kind: str) -> dict[str, float] | None:
+ """The position a held file states about itself, read locally.
+
+ The same readers import enrichment uses, called here so a contradiction
+ between the file and the typed coordinates surfaces while the analyst can
+ still act on it rather than weeks later in the graph.
+ """
+ try:
+ if kind == "image":
+ gps = enrich_engine.exif_facts(path).get("gps")
+ elif kind == "video":
+ gps = (enrich_engine.video_facts(path) or {}).get("gps")
+ else:
+ return None
+ except Exception:
+ return None
+ return gps if isinstance(gps, dict) and "lat" in gps and "lon" in gps else None
+
+
+def _numbered(slot: str, count: int) -> list[str]:
+ """One name per file a slot holds: `panel`, `panel 2`, `panel 3`.
+
+ The report is a list of *files* and every line of it is about one of them. Calling
+ three of them `panel` made the reading ambiguous — "panel derived-from source", three
+ times, says nothing about which — and made the screen that renders it keyed on a name
+ three rows shared. Numbered from the second, so a slot holding one keeps its name.
+ """
+ return [slot] + [f"{slot} {at}" for at in range(2, count + 1)]
+
+
+def stated_sources(
+ held: list[dict[str, Any]], urls: list[str]
+) -> list[dict[str, Any]]:
+ """What a slot holds for the addresses the form states, in the order it states them.
+
+ The staging directory is a cache and the form is the claim, so an address the analyst
+ took off the list leaves its download behind rather than filing it — the screen and
+ the case cannot drift apart over a row somebody removed. Ordering by the form is also
+ what makes `source 2` in the report mean the second box on the screen.
+
+ A file held for no address at all is one somebody attached without saying where it
+ came from. It is kept, last: the form cannot disown what it cannot name.
+ """
+ by_url: dict[str, list[dict[str, Any]]] = {}
+ for entry in held:
+ by_url.setdefault(str(entry.get("for_url") or ""), []).append(entry)
+ return [one for url in urls for one in by_url.get(url, [])] + by_url.get("", [])
+
+
+def read_source_urls(form: dict[str, Any]) -> list[str]:
+ """The addresses the form states, in the order it states them, without repeats."""
+ stated = form.get("source_urls")
+ if not isinstance(stated, list):
+ stated = [stated] if stated else []
+ return list(dict.fromkeys(str(one or "").strip() for one in stated if str(one or "").strip()))
+
+
+def proof_name(title: str) -> str:
+ return layout.slugify(title, "Proof")
+
+
+def preview(case: Case, token: str, form: dict[str, Any]) -> dict[str, Any]:
+ """Everything this import would write, before it writes any of it.
+
+ Read-only, and deliberately offline: resolving the country is a Nominatim
+ call the creation makes anyway, and a preview is not an action that needs
+ the network. A place already in the case shows the country it already has.
+ """
+ draft = read_draft(case, token)
+ panels = _held(draft, SLOT_PANEL)
+ #: One name per picture, because the report is a list of *files* and every line of it
+ #: is about one of them. Calling three of them `panel` made the reading ambiguous —
+ #: "panel derived-from source", three times, says nothing about which — and made the
+ #: screen that renders it keyed on a name three rows shared.
+ panel_slots = _numbered(SLOT_PANEL, len(panels))
+ panel = panels[0] if panels else {}
+ source_urls = read_source_urls(form)
+ held_source = stated_sources(_held(draft, SLOT_SOURCE), source_urls)
+ source_slots = _numbered(SLOT_SOURCE, len(held_source))
+ #: Both halves as one list of (name, file), which is the order the report reads in:
+ #: the material first, then the pictures composed out of it.
+ material = list(zip(source_slots, held_source))
+ composed = list(zip(panel_slots, panels))
+
+ title = str(form.get("title") or "").strip()
+ coords_text = str(form.get("coords") or "").strip()
+ pov = bool(form.get("pov"))
+
+ blocking: list[str] = []
+ warnings: list[dict[str, str]] = []
+ entities: list[dict[str, Any]] = []
+ links: list[dict[str, str]] = []
+
+ if not panels:
+ blocking.append("There is no image for the proof yet.")
+ elif any(held.get("kind") != "image" for held in panels):
+ blocking.append("A proof is composed of pictures, and this file is not one.")
+ if not title:
+ blocking.append("The proof needs a name.")
+ if not source_urls:
+ blocking.append("A source is required.")
+ elif len(source_urls) > MAX_SOURCES:
+ blocking.append(f"A proof rests on at most {MAX_SOURCES} sources.")
+ elif any(len(scan_urls(one)) > 1 for one in source_urls):
+ # A box is the address its own file is fetched from as well as a line the proof
+ # carries, so two of them pasted into one is not extra information: it is an
+ # address nothing can be downloaded from. The import used to take it, warn that
+ # the source "was not downloaded", and file a proof with no material at all.
+ blocking.append("A source is one address, and this is several.")
+ elif not all(media_engine.is_address(one) for one in source_urls):
+ blocking.append("A source is an address, and this is not one.")
+
+ point = geo_engine.parse_coords(coords_text) if coords_text else None
+ if not coords_text:
+ blocking.append("Coordinates are required.")
+ elif point is None:
+ blocking.append(f"'{coords_text}' is not a position Azimut can read.")
+
+ name = proof_name(title) if title else ""
+ if name and case.find_entity(attr="spec", value=layout.proof_spec_rel(name)) is not None:
+ blocking.append(f"A proof is already called '{name}'.")
+
+ # -- the place
+ if point is not None:
+ standing = satellite_engine.place_at(case, point[0], point[1], keyed_only=False)
+ if standing is None:
+ entities.append(
+ {
+ "slot": "place",
+ "type": "place",
+ "label": geo_engine.to_dms(point[0], point[1]),
+ "state": "new",
+ "detail": "country resolved after creation",
+ }
+ )
+ else:
+ geo_attrs = (standing.get("attrs") or {}).get("geo") or {}
+ entities.append(
+ {
+ "slot": "place",
+ "type": "place",
+ "label": standing["label"],
+ "state": "existing",
+ "detail": str(geo_attrs.get("country") or "already in the case"),
+ }
+ )
+
+ # -- the material, then the pictures that compose it
+ for slot, staged in material + composed:
+ if not staged.get("filename"):
+ continue
+ held = case.find_entity(attr="sha256", value=staged.get("sha256"))
+ entities.append(
+ {
+ "slot": slot,
+ "type": "media",
+ "label": str(staged.get("title") or staged.get("filename")),
+ "state": "existing" if held else "new",
+ "detail": _media_detail(staged, held),
+ }
+ )
+
+ # Only for an address that has one. With the field still empty the blocking line
+ # above already says so, and saying it twice reads as two different problems.
+ fetched = {str(one.get("for_url") or "") for one in held_source}
+ missing = [one for one in source_urls if one not in fetched]
+ if missing:
+ warnings.append(
+ {
+ "code": "no-source-media",
+ "text": (
+ "The source was not downloaded, so the proof will carry its address "
+ "and no file."
+ if len(missing) == 1
+ else f"{len(missing)} sources were not downloaded, so the proof will "
+ "carry their addresses and no files."
+ ),
+ }
+ )
+
+ if name:
+ entities.append(
+ {"slot": "proof", "type": "proof", "label": name, "state": "new", "detail": ""}
+ )
+
+ # -- the edges, and every one the save will write
+ #
+ # The point reaches the whole derivation closure, not just the footage: the
+ # picture the proof composes is in that closure too, so it takes the verb as
+ # well. Drawing only the footage would make the preview quieter than the
+ # graph, which is the one way a preview can be wrong.
+ if point is not None and name and panels:
+ verb = link_engine.LOCATED_AT if pov else link_engine.DEPICTS
+ kinds = ("image", "video", "audio") if pov else ("image", "video")
+ for slot, staged in material + composed:
+ if staged.get("filename") and str(staged.get("kind") or "") in kinds:
+ links.append(_edge(slot, verb, "place"))
+ # **The proof rests on the material, and composes the pictures.** Both are its own
+ # edges, which is what makes it the node the constellation hangs off — the reading
+ # somebody looking at the graph is after, since the proof is the finding and a
+ # published picture is one file among the several it was read from. Hanging the
+ # material off the *picture* instead made a media node the hub of the geolocation
+ # and left the proof a leaf beside it.
+ #
+ # It is also the shape the composer writes by hand (`spec.material`, ONTOLOGY §3),
+ # so a proof re-saved there restates exactly these edges rather than losing them.
+ for source_slot, staged in material:
+ if staged.get("filename"):
+ links.append(_edge("proof", link_engine.DERIVED_FROM, source_slot))
+ for slot in panel_slots:
+ links.append(_edge("proof", link_engine.DERIVED_FROM, slot))
+ links.append(_edge("proof", link_engine.DEPICTS, "place"))
+
+ # -- what the files say about themselves
+ if point is not None:
+ # The first file held, material before pictures. One reading, because the
+ # warning names a position and a distance and two of them read as two points.
+ path = staged_path(case, token, SLOT_SOURCE) or staged_path(case, token, SLOT_PANEL)
+ staged = held_source[0] if held_source else panel
+ if path is not None:
+ own = _stated_gps(path, str(staged.get("kind") or ""))
+ if own is not None:
+ away = _distance_metres(point[0], point[1], own["lat"], own["lon"])
+ if away > GPS_CONFLICT_METRES:
+ warnings.append(
+ {
+ "code": "gps-conflict",
+ "text": (
+ f"The file states {own['lat']:.6f}, {own['lon']:.6f} — "
+ f"{round(away):,} m from the coordinates entered."
+ ).replace(",", " "),
+ }
+ )
+
+ # -- has this post already been through here
+ already = _already_imported(case, draft, panel)
+ if already:
+ warnings.append(already)
+
+ return {
+ "ready": not blocking,
+ "blocking": blocking,
+ "entities": entities,
+ "links": links,
+ "warnings": warnings,
+ }
+
+
+def _media_detail(staged: dict[str, Any], held: dict[str, Any] | None) -> str:
+ if held is not None:
+ return f"already in the case as '{held['label']}'"
+ size = int(staged.get("size") or 0)
+ kind = str(staged.get("kind") or "file")
+ return f"{kind} · {size / (1024 * 1024):.1f} MB" if size else kind
+
+
+def _already_imported(
+ case: Case, draft: dict[str, Any], panel: dict[str, Any]
+) -> dict[str, str] | None:
+ """Whether this post's picture is already filed, by its bytes then its URL.
+
+ Two questions, because the same post can arrive twice with a re-encoded
+ image, and the same picture can arrive from two posts.
+ """
+ digest = panel.get("sha256")
+ if digest:
+ held = case.find_entity(attr="sha256", value=digest)
+ if held is not None:
+ return {
+ "code": "already-imported",
+ "text": f"This picture is already in the case as '{held['label']}'.",
+ }
+ post_url = str((draft.get("post") or {}).get("url") or "")
+ if post_url:
+ held = case.find_entity(attr="source_url", value=post_url)
+ if held is not None:
+ return {
+ "code": "already-imported",
+ "text": f"This post was already imported as '{held['label']}'.",
+ }
+ return None
+
+
+#: The derivation chain has no entry in the relation registry — it is not a
+#: relation — so the one edge the preview draws from it carries its reading here.
+_CHAIN_LABELS = {link_engine.DERIVED_FROM: "derived from"}
+
+
+def _edge(from_slot: str, type_: str, to_slot: str) -> dict[str, str]:
+ relation = link_engine.relation_type(type_)
+ return {
+ "from": from_slot,
+ "to": to_slot,
+ "type": type_,
+ "label": relation.label if relation else _CHAIN_LABELS.get(type_, type_),
+ }
+
+
+def panel_size(path: Path) -> tuple[int, int]:
+ """The picture's own pixel size, which the composer lays a panel out from."""
+ with Image.open(path) as img:
+ return int(img.width), int(img.height)
+
+
+def png_bytes(path: Path) -> bytes:
+ """The imported picture as the proof's export.
+
+ A published panel is already a rendered proof, so the import files it as one
+ rather than re-rendering a composition nobody composed. Re-encoded to PNG
+ because that is what `proofs/<name>.png` claims to be, and a JPEG under that
+ name is a lie the next reader has to sniff its way out of.
+ """
+ import io
+
+ with Image.open(path) as img:
+ buffer = io.BytesIO()
+ (img if img.mode in ("RGB", "RGBA", "L") else img.convert("RGB")).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def build_spec(
+ panels: list[tuple[str, tuple[int, int]]],
+ form: dict[str, Any],
+ material: list[dict[str, str]] | None = None,
+) -> dict[str, Any]:
+ """The proof an import writes: the pictures it published, the point, the source.
+
+ Everything else is left out on purpose. A spec omits what it does not state,
+ and the composer's `normalizeProofStyle` fills every look from its own
+ defaults — so an imported proof opens as a plain composition the analyst can
+ annotate, rather than one frozen into whatever this module happened to think a
+ proof should look like.
+
+ **A post publishing several pictures is one proof of several panels**, laid in
+ one row and in the order they were published. Which is not a new kind of thing:
+ a proof is a composition, and the only reason an import used to write exactly
+ one panel is that it had exactly one picture. The note lands on the first — it
+ is one sentence about the proof, not a caption per picture.
+ """
+ spec = {
+ "azimut_proof": 1,
+ "panels": [
+ {
+ "id": f"p{uuid.uuid4().hex[:8]}",
+ "src": rel,
+ "caption": str(form.get("note") or "").strip() if at == 0 else "",
+ "row": 0,
+ "scale": 1,
+ "natural": [natural[0], natural[1]],
+ "meta": {},
+ }
+ for at, (rel, natural) in enumerate(panels)
+ ],
+ "pastes": [],
+ "shapes": [],
+ "notes": {},
+ "legendOrder": [],
+ # The files the proof rests on without composing them, each with the address it
+ # came from. Written into the spec rather than onto the pictures, so the save
+ # states the edges and a re-save in the composer restates them — and so taking a
+ # source off the proof there takes its files out of the chain with it. The
+ # composer's own Source list writes the same key.
+ "material": [dict(one) for one in material or []],
+ "sources": read_source_urls(form),
+ }
+ return satellite_engine.state_points(
+ spec, [{"coords": form.get("coords"), "pov": bool(form.get("pov"))}]
+ )
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index 0fd7e1c..6074014 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -140,14 +140,11 @@ def place_at(
def place_for_proof(
case: Case,
- proof_id: str,
- lat: float,
- lon: float,
+ point: dict[str, Any],
*,
- pov: bool = False,
by: str = "proof-composer",
-) -> tuple[dict[str, Any], list[dict[str, Any]]]:
- """File a proof's point as a ``place``, and join what the proof establishes.
+) -> dict[str, Any]:
+ """File one point a proof states as a ``place``.
**A geolocation is concluded in the composer, not while framing the map.** The
coordinates a proof carries are the analyst's answer — what they typed, or the
@@ -155,139 +152,175 @@ def place_for_proof(
the dozen views taken while looking. So the point becomes a node here, once,
at the moment somebody commits to it, rather than on every crop.
+ **The label names the ground.** A place is the one entity whose identity is a
+ number, so it is normally called by its coordinates; a proof that says which
+ impact this is has already named it better than the numbers can, and the tree
+ reads "impact 2" instead of `64.148100, -21.940100`.
+
Filed ``confirmed``: whether it was typed or accepted from the panels, the
proof is the analyst's own act, and a review step over one's own answer is a
step over nothing.
- **The proof itself always ``depicts``.** It was composed, never recorded
- anywhere, so ``located-at`` is not a reading it can take — which is what the
- registry says too. ``pov`` decides the verb for the *material*, and only there.
-
- The caller decides *whether* to ask (``config.proof_place_auto``); this only
- files. Callers check :func:`place_at` first, so a point already in the case is
- never duplicated and never asked about.
-
- Answers with the place and whatever the proof let go of to conclude on it
- (:func:`restate_proof_point`).
+ Files only. The caller decides *whether* to ask (``config.proof_place_auto``),
+ checks :func:`place_at` first so a point already in the case is never
+ duplicated, and states the whole list at once
+ (:func:`restate_proof_point`) — a point cannot be joined on its own without
+ withdrawing the others the same proof concludes on.
"""
- place = save_place(
- case, float(lat), float(lon), by=by,
- extra_attrs={COORD_KEY: coord_key(float(lat), float(lon))},
+ lat, lon = float(point["lat"]), float(point["lon"])
+ label = str(point.get("label") or "").strip()
+ return save_place(
+ case, lat, lon, title=label or None, by=by,
+ extra_attrs={COORD_KEY: coord_key(lat, lon)},
)
- return place, restate_proof_point(case, proof_id, place["id"], pov=pov, by=by)
#: The two verbs a proof's point is stated with. `depicts` for the composition and
#: for anything it shows; `located-at` for material POV says was recorded there.
PLACE_VERBS = (links.DEPICTS, links.LOCATED_AT)
+#: The roads that pose a proof's point on its **material**, and the whole reason the set
+#: is smaller than "everybody": a proof reaching a place is the proof's own conclusion,
+#: so it is read and withdrawn whoever filed it — but a media reaching a place is one
+#: claim among several about that file, and only these two write one *because a proof
+#: concluded there*. The composer's save, and the sheet's build (`sheetproofs.BY`, named
+#: here rather than imported since that module reads this one). Import enrichment's EXIF
+#: reading and an edge the analyst stated in Details are not this save's to take back.
+POINT_ROADS = ("proof-composer", "sheet-proofs")
+
def restate_proof_point(
case: Case,
proof_id: str,
- place_id: str | None,
+ stated: list[dict[str, Any]],
*,
- pov: bool = False,
by: str = "proof-composer",
) -> list[dict[str, Any]]:
"""Make the graph say what this proof says now, and stop saying what it said.
- **A proof states one point, and a save is the restatement of it** — the same
- rule its panels already follow (``links.sync``, ONTOLOGY §3). Re-opening a
- proof and correcting the coordinates is the analyst withdrawing an answer, so
- the old edges go rather than piling up beside the new ones; toggling POV is
- them saying the point means something else, so the verb on the material
- changes. Without this a corrected proof read as two geolocations, and a POV
- answer could only ever be given once.
-
- ``place_id`` is the point the proof concludes on now, or ``None`` when it
- concludes on none — a coordinate field cleared withdraws the claim rather than
- freezing the last one.
-
- **Only what the composer itself wrote is reconciled** (``by``). An edge the
- analyst stated by hand in Details, or one import enrichment proposed from a
- photo's EXIF, is a separate claim about the same file: saving a proof must not
- silently drop it.
+ **A save is the restatement of everything a proof states** — the same rule its
+ panels already follow (``links.sync``, ONTOLOGY §3). Re-opening a proof and
+ correcting the coordinates is the analyst withdrawing an answer, so the old
+ edges go rather than piling up beside the new ones; taking a point off the list
+ rends its place exactly as clearing the field once did; moving POV to another
+ line is them saying the two points mean something else, so the verbs on the
+ material follow. Without this a corrected proof read as two geolocations, and a
+ POV answer could only ever be given once.
+
+ ``stated`` is the whole list the proof concludes on now — ``{"id", "pov"}`` per
+ place, in the composer's own order — and an empty one withdraws everything.
+ **It has to be the whole list**: this reconciles by difference, so filing one
+ point on its own would take back every other point the same proof holds.
+
+ **Every point the proof states, whoever filed it.** A sheet row files one for a
+ proof it never composed, and the composer *opens on it* as a row of its own
+ (:func:`open_spec`) — so read on the composer's own provenance, deleting that row
+ found nothing to withdraw: the save reported no orphan, the mark stayed on the map,
+ and the next open adopted the point again. A row that cannot be deleted is worse
+ than one that was never offered. The material is the narrower question, and it keeps
+ its own answer (:data:`POINT_ROADS`).
Answers with the places this proof let go of that nothing else holds — the
caller asks about deleting them (``api/proofs``), since a point nobody points
at is the analyst's own leftover to keep or drop, not ours to sweep.
"""
- material = [
- entity
- for entity in (links.derivation_subgraph(case, proof_id) or {}).get("entities", [])
- if entity["id"] != proof_id
- ]
+ material = _material_of(case, proof_id)
+ wanted = {entry["id"]: bool(entry.get("pov")) for entry in stated}
released: list[dict[str, Any]] = []
- for old_id in _stated_places(case, proof_id, by=by):
- if old_id == place_id:
+ for old_id in _stated_places(case, proof_id):
+ if old_id in wanted:
continue
- _withdraw_point(case, proof_id, old_id, material, by=by)
+ _withdraw_point(case, proof_id, old_id, material)
old = case.get_entity(old_id)
if old is not None and not case.links_of(old_id):
released.append(old)
- if place_id is not None:
+ for place_id, pov in wanted.items():
_state_point(case, proof_id, place_id, material, pov=pov, by=by)
return released
-def _stated_places(case: Case, proof_id: str, *, by: str) -> list[str]:
+def _material_of(case: Case, proof_id: str) -> list[dict[str, Any]]:
+ """The files a proof was composed from, the whole chain down: the frame, the collage,
+ the video two hops up, the capture. Read off the derivation closure rather than the
+ panels, since a frame stands between a proof and the clip it came from."""
+ return [
+ entity
+ for entity in (links.derivation_subgraph(case, proof_id) or {}).get("entities", [])
+ if entity["id"] != proof_id
+ ]
+
+
+def _stated_places(case: Case, proof_id: str) -> list[str]:
"""The points this proof currently concludes on, read off its own edges.
The proof is the only reliable record of where a save put its material: the
edges it wrote on a video carry no proof id, so what a re-save has to undo is
read from the composition that wrote them.
+
+ **Whoever wrote them.** A proof reaching a place has one reading — this composition
+ concludes there — so a row filed by another road is a row this list holds, and the
+ same list the composer opens on (:func:`_adopted_points`) is the one a save
+ reconciles. Read on one provenance, the two disagreed and a point nobody could
+ delete was the result.
"""
seen: list[str] = []
for link in case.links_of(proof_id):
if link["from"] != proof_id or link["type"] not in PLACE_VERBS:
continue
- if (link.get("provenance") or {}).get("by") != by:
- continue
target = case.get_entity(link["to"])
if target is not None and target["type"] == "place" and link["to"] not in seen:
seen.append(link["to"])
return seen
-def _other_proof_states(case: Case, place_id: str, proof_id: str, *, by: str) -> bool:
+def _other_proof_states(case: Case, place_id: str, proof_id: str) -> bool:
"""True if another proof still concludes on this point.
Two proofs built from one video can land on the same roof, and the edges they
wrote on that video are indistinguishable. So a save withdraws its own point
only while it is the last one claiming it: dropping the material's edge here
- would undo a conclusion this proof never made.
+ would undo a conclusion this proof never made — including one a sheet built,
+ which is why this asks what the other proof says and not who wrote it down.
"""
for link in case.links_of(place_id):
if link["to"] != place_id or link["type"] not in PLACE_VERBS or link["from"] == proof_id:
continue
- if (link.get("provenance") or {}).get("by") != by:
- continue
source = case.get_entity(link["from"])
if source is not None and source["type"] == "proof":
return True
return False
-def _drop_stated(case: Case, entity_id: str, place_id: str, verbs: tuple[str, ...], by: str) -> None:
- """Remove this entity's own statements about a point, and nothing else's."""
+def _drop_stated(
+ case: Case,
+ entity_id: str,
+ place_id: str,
+ verbs: tuple[str, ...],
+ authors: tuple[str, ...] | None,
+) -> None:
+ """Remove statements about a point, from the authors named — and nothing else's.
+
+ ``None`` is every author, which is what a proof's own edge to a place is reconciled
+ on: there is one thing that edge can mean. A media's edge is scoped instead, since
+ the same edge is what a camera's EXIF and the analyst's own hand also write.
+ """
for link in case.links_of(entity_id):
if link["from"] != entity_id or link["to"] != place_id or link["type"] not in verbs:
continue
- if (link.get("provenance") or {}).get("by") == by:
+ if authors is None or (link.get("provenance") or {}).get("by") in authors:
case.remove_link(link["id"])
def _withdraw_point(
- case: Case, proof_id: str, place_id: str, material: list[dict[str, Any]], *, by: str
+ case: Case, proof_id: str, place_id: str, material: list[dict[str, Any]]
) -> None:
"""Take back a point this proof no longer concludes on, material included."""
- shared = _other_proof_states(case, place_id, proof_id, by=by)
- _drop_stated(case, proof_id, place_id, PLACE_VERBS, by)
+ shared = _other_proof_states(case, place_id, proof_id)
+ _drop_stated(case, proof_id, place_id, PLACE_VERBS, None)
if shared:
return
for entity in material:
- _drop_stated(case, entity["id"], place_id, PLACE_VERBS, by)
+ _drop_stated(case, entity["id"], place_id, PLACE_VERBS, POINT_ROADS)
def _state_point(
@@ -317,7 +350,7 @@ def _state_point(
shows, and a skyline is shown from kilometres away. Neither entails the other,
and a match between a frame and an imagery says only that they meet — not
whether the analyst located the camera or what it was pointed at. So the
- composer asks once, and the answer travels in the spec:
+ answer is given per point, on the line it belongs to, and travels in the spec:
- ``pov`` — the point is where the camera stood → ``located-at`` on the media
(an image, a video or a recording of the moment);
@@ -345,7 +378,7 @@ def _state_point(
"""
verb = links.LOCATED_AT if pov else links.DEPICTS
kinds = ("image", "video", "audio") if pov else ("image", "video")
- shared = _other_proof_states(case, place_id, proof_id, by=by)
+ shared = _other_proof_states(case, place_id, proof_id)
case.add_link(proof_id, place_id, links.DEPICTS, by=by, unique=True)
for entity in material:
wanted: str | None = None
@@ -355,7 +388,7 @@ def _state_point(
wanted = verb
if not shared:
stale = tuple(v for v in PLACE_VERBS if v != wanted)
- _drop_stated(case, entity["id"], place_id, stale, by)
+ _drop_stated(case, entity["id"], place_id, stale, POINT_ROADS)
if wanted is not None:
case.add_link(entity["id"], place_id, wanted, by=by, unique=True)
@@ -559,28 +592,290 @@ def saved_index(case: Case) -> list[dict[str, Any]]:
return rows
-def own_point(spec: dict[str, Any]) -> dict[str, float] | None:
- """The point a proof states for itself, or None if it states none.
+#: How many points one proof may state. A composition arguing fifteen positions is
+#: a case rather than a proof, and the cap is what keeps a spec written by hand from
+#: filing a hundred places on one save. Same number as ``PLACEMENT_LIMIT``, for the
+#: same reason: past that a panel is a wall rather than a reading.
+MAX_PROOF_POINTS = 15
+
- A proof is not only placed by what it composes. ``coordsText`` is what the
- analyst typed into the composer's coordinate field, in whatever format they
- use, and it wins: it is their own assertion, and it is the reason the field
- exists. ``coords`` is what the panels gave the proof, frozen at save — which
- is what keeps a proof on the map after the capture it was built from is
- deleted, since outputs outlive their sources (ONTOLOGY §3).
+def _typed_point(text: Any) -> dict[str, Any] | None:
+ """One coordinate field read as a point, or None when it holds no point.
+
+ The text comes back with it. A proof reopened has to show the analyst what
+ they wrote, not a rendering of it: somebody who works in DMS typed DMS.
"""
- text = str(spec.get("coordsText") or "").strip()
- if text:
- parsed = geo_engine.parse_coords(text)
- if parsed: # prose in the field is a caption, not a point
- return {"lat": parsed[0], "lon": parsed[1]}
- coords = spec.get("coords")
- if isinstance(coords, dict) and coords.get("lat") is not None and coords.get("lon") is not None:
- try:
- return {"lat": float(coords["lat"]), "lon": float(coords["lon"])}
- except (TypeError, ValueError):
- return None
- return None
+ trimmed = str(text or "").strip()
+ parsed = geo_engine.parse_coords(trimmed)
+ return {"lat": parsed[0], "lon": parsed[1], "coords": trimmed} if parsed else None
+
+
+def _stated_once(spec: dict[str, Any]) -> list[dict[str, Any]]:
+ """The single point a spec written before the list states.
+
+ ``coordsText`` is what the analyst typed into the composer's coordinate field,
+ in whatever format they use, and it wins: it is their own assertion, and it is
+ the reason the field exists. ``coords`` is what the panels gave the proof,
+ frozen at save — which is what keeps a proof on the map after the capture it
+ was built from is deleted, since outputs outlive their sources (ONTOLOGY §3).
+
+ Still the live reading for a sheet row and an import, which each state one
+ point and have no reason to learn the list to say so.
+ """
+ point = _typed_point(spec.get("coordsText"))
+ if point is None:
+ coords = spec.get("coords")
+ frozen = _point((coords or {}).get("lat"), (coords or {}).get("lon")) \
+ if isinstance(coords, dict) else None
+ # nothing was typed, so the row carries no text: the composer shows the
+ # panels' own answer there and the reset arrow stays away, as it always has
+ point = {**frozen, "coords": ""} if frozen else None
+ if point is None:
+ return []
+ return [{**point, "label": "", "pov": bool(spec.get("pov"))}]
+
+
+def _mirror_broken(spec: dict[str, Any], entries: list[Any]) -> bool:
+ """True when the single-point field says something the list does not.
+
+ Only when the field is *there*: a spec holding a list and no ``coordsText`` was
+ written by something that states them all, and has nothing to disagree with.
+ """
+ if "coordsText" not in spec:
+ return False
+ first = entries[0] if entries and isinstance(entries[0], dict) else {}
+ return str(spec.get("coordsText") or "").strip() != str(first.get("coords") or "").strip()
+
+
+def spec_points(spec: dict[str, Any]) -> list[dict[str, Any]]:
+ """Every point a proof states, its conclusion first.
+
+ **A proof shows more than one place more often than it shows one** — three
+ impacts, a building and the camera that filmed it. Each is a point the analyst
+ concluded on, and they are peers: the list is what they typed, in the order
+ they typed it.
+
+ **The first one is the conclusion.** It places the proof on the map, a post
+ cites it, the export prints it — every surface that can carry only one answer
+ reads that one. Nothing else about a point takes that rank, POV included: an
+ analyst concluding on the camera moves it to the top themselves, and a list
+ that reordered itself would take a coordinate out of a tweet without saying so.
+
+ **``pov`` rides on the point, not on the proof**, because that is what it says:
+ the material was recorded *there*. At most one point carries it — a camera
+ stood in one place, and two would have one video recorded twice — so the first
+ to claim it keeps it whatever a hand-written spec asked for.
+
+ Text that reads as no point is skipped (prose in the field is a caption), and
+ two entries a metre apart are one place, so the second is dropped rather than
+ drawn as a second mark on the same roof.
+
+ A spec holding no list falls back to the single point it was written with
+ (:func:`_stated_once`), so nothing has to be migrated and nothing that states
+ one point has to learn the list.
+
+ **The mirror is also a check.** ``coordsText`` and the first entry are written
+ together and never drift (:func:`state_points`), so when they disagree the
+ field was set by something that does not know the list — an older build, a
+ route stating one point by hand — and what it says is the newer answer. The
+ list is dropped rather than quietly outvoting the coordinates somebody typed.
+ """
+ entries = spec.get("points")
+ points: list[dict[str, Any]] = []
+ if isinstance(entries, list) and not _mirror_broken(spec, entries):
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ point = _typed_point(entry.get("coords"))
+ if point is None:
+ continue
+ points.append(
+ {
+ **point,
+ "label": str(entry.get("label") or "").strip(),
+ "pov": bool(entry.get("pov")),
+ }
+ )
+ return _settled(points or _stated_once(spec))
+
+
+def _settled(points: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """One entry per point, one POV at most, capped — whatever order they arrived in.
+
+ A point written twice is one row, and it keeps the answer **either** line gave about
+ the camera: dropped with the duplicate, a POV ticked on the second of two lines a
+ metre apart was an assertion nothing in the graph carried, on a line the composer
+ still showed it on.
+ """
+ kept: list[dict[str, Any]] = []
+ at: dict[str, int] = {}
+ pov_taken = False
+ for point in points:
+ key = coord_key(point["lat"], point["lon"])
+ pov = point["pov"] and not pov_taken
+ if key in at:
+ if pov:
+ kept[at[key]] = {**kept[at[key]], "pov": True}
+ pov_taken = True
+ continue
+ at[key] = len(kept)
+ kept.append({**point, "pov": pov})
+ pov_taken = pov_taken or pov
+ if len(kept) == MAX_PROOF_POINTS:
+ break
+ return kept
+
+
+def _recorded_there(case: Case, place_id: str, material: set[str]) -> bool:
+ """True when this proof's material says it was recorded at this point — POV, read off
+ the graph rather than off a spec that never learned about the point.
+
+ **Its own material.** Two proofs conclude on one place often enough, and somebody
+ else's footage being recorded there says nothing about this composition: read on any
+ media at all, a second proof's clip ticked POV on a row of this one, and the next save
+ wrote `located-at` onto footage that had never claimed it.
+ """
+ for link in case.links_of(place_id):
+ if link["to"] == place_id and link["type"] == links.LOCATED_AT:
+ if link["from"] not in material:
+ continue
+ source = case.get_entity(link["from"])
+ if source is not None and source["type"] == "media":
+ return True
+ return False
+
+
+def _adopted_points(
+ case: Case,
+ proof_id: str,
+ held: set[str],
+ incident: list[dict[str, Any]] | None = None,
+) -> list[dict[str, Any]]:
+ """Points filed for this proof by a road that never wrote its composition.
+
+ A sheet row does exactly that (``api/sheetproofs._added_point``): the binder's
+ cross-border shape is one picture and two lines, so the second line's point
+ joins the proof under the sheet's own provenance rather than composing the
+ picture twice. The graph then holds a point the spec never learned, and a
+ composer opening on one row while the map draws two is the proof saying two
+ different things.
+
+ ``held`` is what the spec already states, and skipping those early is what
+ keeps the common case cheap: every proof points at its own places, so without
+ it the index would read the POV of every point it already knows about.
+
+ A place named by its own coordinates is unnamed — that label is what a place
+ with nothing else to say gets — so it arrives as a point with no name.
+
+ The proof's chain is read once, and only when there is an adopted point to read it
+ for: POV is a question about this composition's own footage
+ (:func:`_recorded_there`), and every other proof answers it without a query.
+ """
+ found: list[tuple[str, dict[str, Any]]] = []
+ for link in incident if incident is not None else case.links_of(proof_id):
+ if link["from"] != proof_id or link["type"] not in PLACE_VERBS:
+ continue
+ place = case.get_entity(link["to"])
+ if place is None or place.get("type") != "place":
+ continue
+ attrs = place.get("attrs") or {}
+ point = _point(attrs.get("lat"), attrs.get("lon"))
+ if point is None or coord_key(point["lat"], point["lon"]) in held:
+ continue
+ label = str(place.get("label") or "").strip()
+ if label == coords_label(point["lat"], point["lon"]):
+ label = ""
+ found.append((
+ place["id"],
+ {
+ **point,
+ "coords": coords_label(point["lat"], point["lon"], "dd"),
+ "label": label,
+ },
+ ))
+ if not found:
+ return []
+ material = {entity["id"] for entity in _material_of(case, proof_id)}
+ return [
+ {**point, "pov": _recorded_there(case, place_id, material)}
+ for place_id, point in found
+ ]
+
+
+def proof_points(
+ case: Case,
+ proof_id: str,
+ stated: list[dict[str, Any]],
+ incident: list[dict[str, Any]] | None = None,
+) -> list[dict[str, Any]]:
+ """Every point a proof concludes on: what it states, then what was filed for it.
+
+ ``stated`` is :func:`spec_points` — the analyst's own list, and the authority
+ on order, so the conclusion stays the conclusion. What another road filed
+ follows, and only where the list does not already hold that point.
+
+ Every surface that asks what a proof concludes on reads this one: the map rows,
+ the composer opening the proof, the placement walk. Reading only the spec left
+ the composer showing one row for a proof the map drew twice.
+ """
+ held = {coord_key(one["lat"], one["lon"]) for one in stated}
+ return _settled([*stated, *_adopted_points(case, proof_id, held, incident)])
+
+
+def open_spec(case: Case, proof_id: str, spec: dict[str, Any]) -> dict[str, Any]:
+ """The spec a proof reopens on, holding every point it concludes on.
+
+ Untouched when the spec already states them all, which is every proof but the
+ one a sheet row filed a second point for — reopening must not rewrite what the
+ analyst wrote, down to the format they typed it in.
+
+ When there *is* more to show, the rows are materialised: a point with no text
+ is the panels answering for the proof, and that answer has to become the
+ conclusion in writing before another point can sit under it. Same rule as the
+ composer's own `+`.
+ """
+ stated = spec_points(spec)
+ merged = proof_points(case, proof_id, stated)
+ if len(merged) <= len(stated):
+ return spec
+ return state_points(spec, [
+ {**one, "coords": one["coords"] or coords_label(one["lat"], one["lon"], "dd")}
+ for one in merged
+ ])
+
+
+def state_points(spec: dict[str, Any], entries: list[dict[str, Any]]) -> dict[str, Any]:
+ """Write what a proof states into its spec: the list, and the mirror of it.
+
+ **One place writes a point, on both sides at once**, so a spec on disk never
+ carries the two saying different things. Setting ``coordsText`` alone on a proof
+ that holds a list leaves a contradiction behind, and while the read resolves it
+ the right way (:func:`spec_points`), a file nobody can read twice the same way
+ is not a file to write. Everything that states a point for a proof it did not
+ compose comes through here.
+
+ **The mirror is not a leftover.** A case bundle travels between installations
+ and the binaries are versioned, so a build older than the list has to find the
+ conclusion where it has always been rather than open a proof with no point.
+ It carries the first point, which is the one such a build could hold anyway.
+ """
+ points: list[dict[str, Any]] = []
+ for entry in entries:
+ coords = str(entry.get("coords") or "").strip()
+ if not coords:
+ continue
+ point: dict[str, Any] = {"coords": coords}
+ label = str(entry.get("label") or "").strip()
+ if label:
+ point["label"] = label
+ if entry.get("pov"):
+ point["pov"] = True
+ points.append(point)
+ spec["points"] = points
+ first = points[0] if points else {}
+ spec["coordsText"] = first.get("coords", "")
+ spec["pov"] = bool(first.get("pov"))
+ return spec
def _source_points(
@@ -642,16 +937,65 @@ def _linked_posts(
return linked
-def _geo_at(sources: list[dict[str, Any]], point: dict[str, float]) -> dict[str, Any]:
- """The attrs of the source standing on this exact point, or nothing.
+def _at(lat: Any, lon: Any) -> tuple[float, float] | None:
+ """One point rounded to about a metre — the precision the map groups marks at."""
+ try:
+ return (round(float(lat), 5), round(float(lon), 5))
+ except (TypeError, ValueError):
+ return None
+
+
+def _located(attrs: dict[str, Any]) -> bool:
+ """True once this entity's geography came back with a country."""
+ geo = attrs.get("geo")
+ return isinstance(geo, dict) and geo.get("state") == "ok"
+
- Five decimals is about a metre — the same precision the map groups marks at.
+def _place_geo(case: Case) -> dict[tuple[float, float], dict[str, Any]]:
+ """The geography of the case's places, by the point each one stands on.
+
+ A proof carries no geography of its own and no Locate pass ever gives it one
+ (``saved_entities`` is places and captures). But the point it states in the
+ composer is filed as a ``place``, whose country is resolved right there
+ (``api/proofs._state_points``) — so the answer is already in the case, one
+ node away, for exactly the proofs whose panels place nothing: a frame and a
+ photo carry no point, and their proof would otherwise file under Unlocated
+ while the place it just wrote knows the country.
+
+ Read once per index rather than once per row, since a case holds far fewer
+ places than the proofs index has rows.
+
+ A located place wins a point two of them share: a pin dropped before the
+ Locate pass ran and the place a proof filed on the same metre are one spot,
+ and only the one that knows its country answers anything.
+ """
+ found: dict[tuple[float, float], dict[str, Any]] = {}
+ for place in _page_all(case, ["place"]):
+ attrs = place.get("attrs") or {}
+ key = _at(attrs.get("lat"), attrs.get("lon"))
+ if key is not None and not _located(found.get(key) or {}):
+ found[key] = attrs
+ return found
+
+
+def _geo_at(
+ sources: list[dict[str, Any]],
+ point: dict[str, float],
+ places: dict[tuple[float, float], dict[str, Any]] | None = None,
+) -> dict[str, Any]:
+ """The attrs of whatever stands on this exact point, or nothing.
+
+ A source the proof composes answers first — it is what the proof was built
+ from. Failing that, the place standing there does, which is how a proof made
+ of photos still files under its country.
"""
- here = (round(point["lat"], 5), round(point["lon"], 5))
+ here = _at(point["lat"], point["lon"])
+ if here is None:
+ return {}
for source in sources:
- if (round(float(source["lat"]), 5), round(float(source["lon"]), 5)) == here:
+ if _at(source["lat"], source["lon"]) == here:
return dict(source["attrs"])
- return {}
+ return dict((places or {}).get(here) or {})
def _proof_row(
@@ -673,6 +1017,10 @@ def _proof_row(
# folder as well as by place
"folder": (entity.get("attrs") or {}).get("folder") or "",
"notes": "",
+ # what the analyst called this point, when they called it anything. It is
+ # what tells three rows of one proof apart: same title, same thumbnail,
+ # three places.
+ "label": (point or {}).get("label") or "",
"lat": lat,
"lon": lon,
"geo": geo,
@@ -691,12 +1039,14 @@ def proof_index(
listing: list[dict[str, Any]],
draft_listing: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
- """Proofs as map rows, newest first — one row per distinct source point.
+ """Proofs as map rows, newest first — one row per distinct point.
- ``listing`` is the proofs listing (title, export, thumbnail), which the
- proofs API owns; everything geographic is read here so the Saved panel gets
- the row shape it already knows. A proof whose panels are all unlocated still
- comes back, without a point, and files under ``Unlocated`` in the tree.
+ ``listing`` is the proofs listing (title, export, thumbnail, the points its
+ spec states), which the proofs API owns; everything geographic is read here so
+ the Saved panel gets the row shape it already knows. A proof stating three
+ points is three rows: the map is about places, and a proof arguing three of
+ them draws three marks. A proof whose panels are all unlocated still comes
+ back, without a point, and files under ``Unlocated`` in the tree.
Kept out of ``saved_index`` on purpose: that one is read on every case open,
this one only when the Proofs position of the switch is first opened.
@@ -709,6 +1059,7 @@ def proof_index(
drafts = {
layout.draft_rel(draft["name"]): draft for draft in (draft_listing or [])
}
+ places = _place_geo(case)
rows: list[dict[str, Any]] = []
for proof in listing:
entity = by_spec.get(proof.get("spec_path"))
@@ -718,13 +1069,17 @@ def proof_index(
linked_posts = _linked_posts(entity["id"], incident, post_entities, drafts)
proof = {**proof, "posts": len(linked_posts), "linked_posts": linked_posts}
sources = _source_points(case, entity["id"], incident)
- stated = proof.get("coords")
+ stated = proof_points(case, entity["id"], proof.get("points") or [], incident)
if stated:
- # the proof says where it is, so it says it once. Its geography is
- # borrowed only from a source standing on that same point — a
- # neighbouring capture's country would be a guess, and a wrong
- # country files the proof under the wrong branch.
- points: list[dict[str, Any] | None] = [{**stated, "attrs": _geo_at(sources, stated)}]
+ # the proof says where it is, so what it composes stops answering for
+ # it. Each point's geography is borrowed only from what stands on that
+ # same point: a source it composes, or the place the save filed there.
+ # A neighbouring capture's country would be a guess, and a place the
+ # analyst linked by hand from somewhere else is about somewhere else —
+ # a wrong country files the proof under the wrong branch.
+ points: list[dict[str, Any] | None] = [
+ {**point, "attrs": _geo_at(sources, point, places)} for point in stated
+ ]
else:
# a proof none of whose panels carry a point still lists, without
# one: it files under Unlocated rather than leaving its own tool
@@ -766,28 +1121,32 @@ def _point(lat: Any, lon: Any) -> dict[str, float] | None:
return None
-def _entity_point(case: Case, entity: dict[str, Any]) -> dict[str, float] | None:
- """The point this entity carries itself, or None if it carries none.
+def _entity_points(case: Case, entity: dict[str, Any]) -> list[dict[str, Any]]:
+ """The points this entity carries itself, or nothing if it carries none.
- Two types hold one inside a chain. A ``capture`` records the marker it was taken
- at. A ``proof`` states its own through the composer, and ``own_point`` is what
- decides which: what the analyst typed wins over what the panels froze. Reusing it
- here is what keeps a video from reporting a capture's raw point while the proof
- beside it shows the corrected one.
+ Two types hold them inside a chain. A ``capture`` records the one marker it was
+ taken at. A ``proof`` states its own through the composer, and ``spec_points``
+ is what decides which: what the analyst typed wins over what the panels froze,
+ and a proof arguing three impacts reports all three. Reading them here is what
+ keeps a video from reporting a capture's raw point while the proof beside it
+ shows the corrected one — and what makes the footage behind a three-point proof
+ answer for all three rather than for its conclusion alone.
"""
attrs = entity.get("attrs") or {}
if entity.get("type") == "capture":
- return _point(attrs.get("lat"), attrs.get("lon"))
+ point = _point(attrs.get("lat"), attrs.get("lon"))
+ return [point] if point is not None else []
if entity.get("type") != "proof":
- return None
+ return []
spec_rel = attrs.get("spec")
if not isinstance(spec_rel, str) or not spec_rel:
- return None
+ return []
try:
spec = json.loads(case.resolve_inside(spec_rel).read_text(encoding="utf-8"))
except (OSError, ValueError, CaseError):
- return None # a spec deleted or half-written places nothing
- return own_point(spec) if isinstance(spec, dict) else None
+ return [] # a spec deleted or half-written places nothing
+ stated = spec_points(spec) if isinstance(spec, dict) else []
+ return proof_points(case, entity["id"], stated)
def _filed_at(entity: dict[str, Any]) -> str:
@@ -805,9 +1164,9 @@ def placements(
and the entity's own point comes back with none, because nothing placed it.
**An artifact that carries a point is where the walk stops.** ``proof_index``
- already settles this for the map — a proof that states where it is says it once,
- rather than also drawing at the panels it overrode — and a panel that listed both
- would contradict the map about the same proof. Stopping there is also what keeps
+ already settles this for the map — a proof that states where it is answers with
+ its own points, rather than also drawing at the panels it overrode — and a panel
+ that listed both would contradict the map about the same proof. Stopping there is also what keeps
a video to its own argument: the capture behind its proof is reached, the second
proof that happens to reuse that capture is not.
@@ -842,14 +1201,15 @@ def placements(
frontier.sort(key=_filed_at, reverse=True)
neighbours: list[str] = []
for node in frontier:
- point = _entity_point(case, node)
- if point is not None:
- key = (point["lat"], point["lon"])
- if key in found: # a nearer artifact already stands here
- continue
- if len(found) >= cap:
- truncated = True
- else:
+ carried = _entity_points(case, node)
+ if carried:
+ for point in carried:
+ key = (point["lat"], point["lon"])
+ if key in found: # a nearer artifact already stands here
+ continue
+ if len(found) >= cap:
+ truncated = True
+ break
found[key] = {
"lat": point["lat"],
"lon": point["lon"],
diff --git a/src/azimut/engine/sheetclaims.py b/src/azimut/engine/sheetclaims.py
new file mode 100644
index 0000000..051a59a
--- /dev/null
+++ b/src/azimut/engine/sheetclaims.py
@@ -0,0 +1,498 @@
+"""Turn a sheet's columns of times into dated statements the case holds.
+
+The binders do not hold dates. They hold a **reasoning about** a date, spread across
+three or four columns: the hour that was established, the hour that was estimated, how it
+was worked out ("the author gave me this time", "a private video shows 1:57", "between
+2:00 and 2:10", "probably after 2 a.m."), and the UTC publication time of the first
+source. Copied into a `when` field that would be one number and three lost columns.
+
+Azimut already has the shape those columns are: a **Claim** — a statement that points at
+what it is about, carries when it applies, how sure the analyst is and the reasoning a
+reader would need to check it (ONTOLOGY §2). So the road runs there and nowhere else, and
+nothing here writes a timestamp back into a cell.
+
+Two ways in, one shape out:
+
+**A column of times.** The established hour if there is one, the estimated hour if there
+is not, an interval when the note says "between 2:00 and 2:10". An estimate is recorded
+one rung lower in confidence than an established reading and the reasoning says which it
+was, because a case where the two are the same value is a case that has lost the
+distinction its own analyst drew.
+
+**An offset from an anchor.** Ten videos carry `-00:01:50` against one shot that is
+visible and audible in all of them. Their relative order is usable straight away; the
+moment somebody dates that shot, every one of them has an absolute time to the second.
+That time is an **inference**, so it is a Claim with `probable` confidence and reasoning
+naming the anchor — never a timestamp copied into a `when` cell, which would present a
+deduction as an observation.
+
+Both are planned before they are done, both are idempotent through the sidecar the way a
+row promotion is, and both stay inside `engine/temporal`'s profile: a reduced date for a
+cell that named a day, a timestamp for one that named an hour, an interval for a range.
+A local hour stays local unless the analyst says otherwise, because the column is called
+`Local time` and stamping it `Z` would move the evidence by however far away it happened.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING, Any
+
+from ..workspace import CaseError
+from . import entities as entity_engine
+from . import links as link_engine
+from . import sheetroles
+from .sheetpromote import BY, ERROR, MAKE, SKIP, UPDATE, cite_source, counts_of, urls_in
+from .sheets import SheetError, key_index, sync_mentions
+from .temporal import TemporalError, parse_temporal
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: The type a dated reading becomes. Not promotable from a bare row — a Claim about
+#: nothing is not a statement — which is precisely why it has a road of its own.
+CLAIM_TYPE = "claim"
+
+#: How many rows one press may date. The row promotion's bound, for the same reason.
+MAX_CLAIMS = 500
+
+#: How sure an established reading is taken to be unless the analyst says otherwise.
+#: Not `certain`: an hour read off a binder is an hour somebody worked out, and the case
+#: has a word for that.
+DEFAULT_CONFIDENCE = "probable"
+
+#: What an *estimate* is worth beside an established reading: one rung down, always. The
+#: binders kept two columns because the difference matters, and a promotion that filed
+#: both at one confidence would be the one that threw that away.
+LOWER = {"certain": "probable", "probable": "possible", "possible": "possible"}
+
+#: Which question the date answers. `occurred` is when the thing happened, which is what
+#: a timeline binder's hours are; `observed` is when somebody saw it, which is what an
+#: upload time is. Asked rather than assumed — treating the two as one moves evidence in
+#: time (`entities.CLAIM_TIME_ROLES`).
+TIME_ROLES = tuple(value for value, _ in entity_engine.CLAIM_TIME_ROLES)
+
+#: Time zones a column may be declared in. Empty is **local** and is the default: a
+#: local timestamp is valid in this app's temporal profile and honestly says that its
+#: UTC bounds are not known yet.
+ZONE = re.compile(r"^(Z|[+-]\d{2}:\d{2})$")
+
+#: How a cell writes a range. The separator has to be surrounded by spaces or introduced
+#: by a word, because `2026-01-03` is full of hyphens and splitting on a bare one would
+#: read every ISO date as an interval from the year to the day.
+_RANGE = re.compile(
+ r"^(?:between\s+|entre\s+|from\s+|de\s+)?(.+?)\s+(?:-|–|—|to|and|à|et)\s+(.+?)$",
+ re.IGNORECASE,
+)
+
+
+def _read_range(text: Any, role: dict[str, Any] | None) -> tuple[Any, Any] | None:
+ """Two readings out of one cell, or None. `between 02:00 and 02:10` is the case."""
+ found = _RANGE.match(str(text or "").strip())
+ if not found:
+ return None
+ start = sheetroles.parse_when(found.group(1), role)
+ end = sheetroles.parse_when(found.group(2), role)
+ return (start, end) if start and end else None
+
+
+def _value(read: dict[str, Any] | None, day: str, zone: str) -> str | None:
+ return sheetroles.claim_moment(read, day=day, zone=zone)
+
+
+def _interval(pair: tuple[Any, Any], day: str, zone: str) -> tuple[str | None, str]:
+ """A range as the one interval spelling `engine/temporal` reads, or why it is not one.
+
+ Both ends have to be the same shape — two dates or two timestamps — which is the
+ profile's own rule and not this module's. A range from a day to an hour is refused
+ rather than resolved: which of the two the analyst meant is not knowable from here.
+
+ And an interval **of hours** needs a time zone on both bounds, because the profile
+ only accepts a range it can turn into honest exclusive bounds and a local timestamp
+ has none until a zone is known. That is not a failure to report as a parse error: it
+ is one question to ask, so it is asked in those words.
+ """
+ start, end = (_value(pair[0], day, zone), _value(pair[1], day, zone))
+ if not start or not end:
+ return None, ""
+ if ("T" in start) != ("T" in end):
+ return None, "this range runs from a day to an hour"
+ if "T" in start and not zone:
+ return None, "a range of hours needs the time zone this column is written in"
+ return f"{start}/{end}", ""
+
+
+class _Reading:
+ """One row's moment: what it is, how sure it is, and how it was arrived at."""
+
+ def __init__(self, when: str, confidence: str, reasoning: str, said: str) -> None:
+ self.when = when
+ self.confidence = confidence
+ self.reasoning = reasoning
+ self.said = said
+
+
+def _from_columns(
+ row: list[str],
+ columns: list[str],
+ roles: dict[str, Any],
+ *,
+ when_column: str,
+ estimate_column: str,
+ method_column: str,
+ day: str,
+ zone: str,
+ confidence: str,
+) -> tuple[_Reading | None, str]:
+ """The moment a row's time columns describe, or the reason there is none.
+
+ Read in the order the analyst wrote them: what was established beats what was
+ estimated, and a range beats a point because a range is the more careful of the two
+ statements the same cell could be making.
+ """
+ method = str(row[columns.index(method_column)] if method_column in columns else "").strip()
+ tries: list[tuple[str, str, str]] = []
+ if when_column:
+ tries.append((when_column, confidence, "established"))
+ if estimate_column:
+ tries.append((estimate_column, LOWER.get(confidence, confidence), "estimated"))
+ for column, sure, how in tries:
+ cell = str(row[columns.index(column)]).strip()
+ if not cell:
+ continue
+ role = roles.get(column) or {}
+ # The cell first, then the note beside it — but only for an estimate, because
+ # "between 2:00 and 2:10" written next to an *established* hour is the reasoning
+ # that produced that hour, not a wider claim replacing it.
+ span = _read_range(cell, role)
+ if span is None and how == "estimated":
+ span = _read_range(method, roles.get(method_column) or {})
+ why = ""
+ if span:
+ when, why = _interval(span, day, zone)
+ else:
+ when = _value(sheetroles.parse_when(cell, role), day, zone)
+ if not when:
+ return None, why or f"'{cell}' in '{column}' is not a time this can date"
+ reasoning = f"{how} in '{column}': {cell}"
+ if method:
+ reasoning = f"{reasoning}. {method}"
+ return _Reading(when, sure, reasoning, cell), ""
+ return None, "no time in these columns"
+
+
+def _from_anchor(
+ row: list[str],
+ columns: list[str],
+ *,
+ offset_column: str,
+ anchor: str,
+ anchor_at: str,
+) -> tuple[_Reading | None, str]:
+ """The moment an offset lands on, once the anchor it counts from has been dated."""
+ cell = str(row[columns.index(offset_column)]).strip()
+ if not cell:
+ return None, f"nothing in '{offset_column}'"
+ seconds = sheetroles.parse_offset(cell)
+ if seconds is None:
+ return None, f"'{cell}' is not an offset"
+ when = sheetroles.offset_moment(anchor_at, seconds)
+ if not when:
+ return None, f"'{anchor}' has no time yet"
+ return (
+ _Reading(
+ when,
+ "probable",
+ f"{sheetroles.format_offset(seconds)} from '{anchor}', which is dated {anchor_at}",
+ cell,
+ ),
+ "",
+ )
+
+
+def _about_takes(entity_type: str) -> bool:
+ spec = link_engine.relation_type(link_engine.ABOUT)
+ return bool(spec and entity_type in spec.to_types)
+
+
+def plan(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ keys: list[str],
+ subject_column: str,
+ when_column: str = "",
+ estimate_column: str = "",
+ method_column: str = "",
+ place_column: str = "",
+ link_column: str = "",
+ offset_column: str = "",
+ day: str = "",
+ zone: str = "",
+ confidence: str = DEFAULT_CONFIDENCE,
+ time_role: str = TIME_ROLES[0],
+ skip: list[str] | None = None,
+ coming: dict[str, dict[str, dict[str, str]]] | None = None,
+) -> dict[str, Any]:
+ """What dating these rows would do, row by row, without doing any of it.
+
+ The subject is read from the sidecar rather than from the cell's words, and that is
+ deliberate: a Claim is a statement *about something the case holds*, so a row whose
+ subject has not been promoted has nothing to make a statement about. Said plainly —
+ "not in the case yet" — because the fix is one press away and guessing which entity a
+ name means is exactly what this app refuses.
+
+ `coming` is how one press says the fix is not away at all: `engine/sheetpass.py` runs
+ the modes in dependency order and threads the sidecar between them, so a subject
+ declared in the same declaration will be there by the time these statements are
+ written. It carries what an entity is asked for here — the type and the label — for
+ rows the case does not hold yet.
+ """
+ if len(keys) > MAX_CLAIMS:
+ raise SheetError(f"at most {MAX_CLAIMS} rows can be dated at once")
+ if bool(when_column or estimate_column) == bool(offset_column):
+ raise SheetError("date these rows either from a column of times or from an anchor")
+ if confidence not in dict(entity_engine.CLAIM_CONFIDENCE):
+ raise SheetError(f"'{confidence}' is not a confidence")
+ if time_role not in TIME_ROLES:
+ raise SheetError(f"'{time_role}' is not what a date can answer")
+ if zone and not ZONE.match(zone):
+ raise SheetError(f"'{zone}' is not a time zone")
+ # Read rather than taken as given, so a caller answering `03/01/2026` supplies a day
+ # and not a string that would be pasted into a timestamp and refused as one. Day-first
+ # like every other date this app reads, which is what the binders write; an ISO day is
+ # unambiguous either way, and that is what the picker sends.
+ read_day = sheetroles.parse_when(day) if day else None
+ if day and read_day is None:
+ raise SheetError(f"'{day}' is not a date")
+ day = read_day["date"] if read_day else ""
+ named = [subject_column, when_column, estimate_column, method_column, place_column,
+ link_column, offset_column]
+ for column in named:
+ 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")
+
+ roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}
+ links = (meta.get("links") or {}) if isinstance(meta, dict) else {}
+ attachments = (meta.get("attachments") or {}) if isinstance(meta, dict) else {}
+ anchors = (meta.get("anchors") or {}) if isinstance(meta, dict) else {}
+ anchor = str((roles.get(offset_column) or {}).get("anchor") or "") if offset_column else ""
+ anchor_at = str((anchors.get(anchor) or {}).get("at") or "") if anchor else ""
+ if offset_column and (roles.get(offset_column) or {}).get("kind") != "offset":
+ raise SheetError(f"'{offset_column}' is not a column of offsets")
+
+ # Where the claim's own reference is kept, so a second press updates rather than
+ # files a second statement of the same thing. The column the date came out of, which
+ # is the one the analyst would look at to ask whether it has been dated.
+ dated_by = offset_column or when_column or estimate_column
+ key_at = key_index(columns)
+ wanted = set(keys)
+ left_out = set(skip or [])
+
+ planned: list[dict[str, Any]] = []
+ for row in rows:
+ identity = row[key_at] if key_at < len(row) else ""
+ if identity not in wanted:
+ continue
+ subject = str(links.get(identity, {}).get(subject_column) or "")
+ said = str(row[columns.index(subject_column)]).strip()
+ decision: dict[str, Any] = {
+ "key": identity,
+ "label": "",
+ "subject": subject,
+ "subject_label": said,
+ "action": SKIP,
+ "reason": "",
+ "entity": None,
+ "entity_label": "",
+ "when": "",
+ "confidence": "",
+ "method": "",
+ "place": "",
+ "sources": [],
+ }
+ planned.append(decision)
+ if identity in left_out:
+ decision["reason"] = "left out"
+ continue
+
+ held = case.get_entity(subject) if subject else None
+ if held is None:
+ held = (coming or {}).get(subject_column, {}).get(identity)
+ subject = str((held or {}).get("id") or "")
+ decision["subject"] = subject
+ if held is None:
+ 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')}"
+ continue
+ decision["subject_label"] = str(held.get("label") or said)
+
+ if offset_column:
+ reading, why = _from_anchor(
+ row, columns, offset_column=offset_column, anchor=anchor, anchor_at=anchor_at
+ )
+ else:
+ reading, why = _from_columns(
+ row, columns, roles,
+ when_column=when_column,
+ estimate_column=estimate_column,
+ method_column=method_column,
+ day=day,
+ zone=zone,
+ confidence=confidence,
+ )
+ if reading is None:
+ decision["reason"] = why
+ continue
+ try:
+ parse_temporal(reading.when)
+ except TemporalError as exc:
+ decision.update(action=ERROR, reason=f"{reading.when} {exc}")
+ continue
+
+ decision.update(
+ label=f"{decision['subject_label']} at {reading.said}",
+ when=reading.when,
+ confidence=reading.confidence,
+ method=reading.reasoning,
+ )
+ if place_column:
+ placed = str(links.get(identity, {}).get(place_column) or "")
+ at = case.get_entity(placed) if placed else None
+ if at is not None and at.get("type") == "place":
+ decision["place"] = at["id"]
+ decision["sources"] = _sources(case, row, columns, link_column, attachments.get(identity))
+
+ pointed = str(links.get(identity, {}).get(dated_by) or "")
+ already = case.get_entity(pointed) if pointed else None
+ if already is not None and already.get("type") == CLAIM_TYPE:
+ decision.update(
+ action=UPDATE, entity=already["id"], entity_label=str(already.get("label") or "")
+ )
+ continue
+ if already is not None:
+ decision["reason"] = f"'{dated_by}' already points at a {already.get('type')}"
+ continue
+ decision["action"] = MAKE
+
+ return {
+ "rows": planned,
+ "counts": counts_of(planned),
+ "column": dated_by,
+ "anchor": {"name": anchor, "at": anchor_at} if offset_column else None,
+ }
+
+
+def _sources(
+ case: "Case",
+ row: list[str],
+ columns: list[str],
+ link_column: str,
+ attached: list[str] | None,
+) -> list[str]:
+ """What the statement will rest on: the row's source links and the pieces it carries.
+
+ Both, because the binders kept them apart for a reason that is theirs and not the
+ case's: a URL is where the claim was published, an attached screenshot is the proof
+ of the hour somebody pasted into a tab of its own. A statement rests on both.
+ """
+ found: list[str] = []
+ if link_column:
+ found.extend(urls_in(str(row[columns.index(link_column)])))
+ for entity_id in attached or ():
+ if case.get_entity(entity_id) is not None:
+ found.append(entity_id)
+ return found
+
+
+def promote(
+ case: "Case",
+ sheet_id: str,
+ **asked: Any,
+) -> dict[str, Any]:
+ """File the statements that plan describes, with their connectors.
+
+ ``about`` is restated rather than added, and so are ``at`` and ``cites``: a second
+ press after the analyst repointed a row must leave the Claim pointing where the sheet
+ now says, not at both. `sync_links` is what makes that one operation.
+
+ Nothing travels back for a compensating undo: the caller runs the whole press inside
+ one `case.batch()`, and a refusal there leaves the case as it was.
+ """
+ meta = asked["meta"]
+ reading = plan(case, **asked)
+ links = {identity: dict(cells) for identity, cells in (meta.get("links") or {}).items()}
+ said = {identity: dict(cells) for identity, cells in (meta.get("promoted") or {}).items()}
+ column = reading["column"]
+ time_role = asked.get("time_role", TIME_ROLES[0])
+ seen: dict[str, str] = {}
+
+ for decision in reading["rows"]:
+ if decision["action"] not in (MAKE, UPDATE):
+ continue
+ attrs = {
+ "when": decision["when"],
+ "time_role": time_role,
+ "confidence": decision["confidence"],
+ "method": decision["method"],
+ }
+ target = decision["entity"]
+ if decision["action"] == MAKE:
+ entity = case.add_entity(CLAIM_TYPE, decision["label"], attrs, by=BY)
+ target = entity["id"]
+ else:
+ case.update_entity(target, {"label": decision["label"], "attrs": attrs})
+
+ cites: list[str] = []
+ for source in decision["sources"]:
+ if source.startswith(("http://", "https://")):
+ cite_source(case, source, target, seen)
+ cites.append(seen[source])
+ else:
+ cites.append(source)
+ _connect(case, target, link_engine.ABOUT, [decision["subject"]])
+ _connect(case, target, link_engine.AT, [decision["place"]] if decision["place"] else [])
+ _connect(case, target, link_engine.CITES, cites)
+ links.setdefault(decision["key"], {})[column] = target
+ said.setdefault(decision["key"], {})[column] = decision["when"]
+
+ sync_mentions(case, sheet_id, {**meta, "links": links})
+ return {
+ "links": links,
+ "promoted": said,
+ "plan": reading["rows"],
+ **reading["counts"],
+ }
+
+
+def _connect(case: "Case", claim: str, verb: str, targets: list[str]) -> None:
+ """State exactly these connectors of one kind, dropping the ones that no longer hold.
+
+ **The ones this press wrote** (``own_only``). What the row says is the sheet's to
+ restate — repointing a row moves the connector rather than leaving the statement
+ pointing both ways — but `about`, `at` and `cites` are also what the Claim's own panel
+ offers, and a source added there is a second claim about the same statement. Read over
+ both, a second press deleted it: no Trash holds a removed edge, and re-filing one is a
+ new id, a new date and a new author.
+
+ A target the vocabulary refuses is left out rather than raised, the way a citation is:
+ the statement is still worth having, and taking a whole press down over one edge would
+ lose the rows that had nothing wrong with them.
+ """
+ source = case.get_entity(claim)
+ if source is None:
+ return
+ wanted: list[str] = []
+ for target in targets:
+ try:
+ link_engine.check_relation_target(case, source, target, verb)
+ except CaseError:
+ continue
+ wanted.append(target)
+ case.sync_links(claim, verb, wanted, by=BY, own_only=True)
diff --git a/src/azimut/engine/sheetfromcase.py b/src/azimut/engine/sheetfromcase.py
new file mode 100644
index 0000000..7a3b249
--- /dev/null
+++ b/src/azimut/engine/sheetfromcase.py
@@ -0,0 +1,429 @@
+"""A sheet built out of what the case already believes.
+
+Promotion runs one way — rows become entities — and until now nothing ran the other. So
+an analyst holding forty places in the graph and wanting to work through them had two
+answers, both bad: retype the forty, or work in a Board that has no column to write a
+verdict in. The graph says what the case believes; a sheet says what it is *checking*,
+and there was no road from the first to the second.
+
+This is that road. It reads a type out of the catalog and writes a worklist: one row per
+entity, its name, whichever declared fields the analyst asked for, and the two empty
+columns the work needs — a status and a note.
+
+Three things make it a bridge rather than an export:
+
+**Every row points back.** The name cell carries the entity's link in the sidecar, so the
+sheet gains a ``mentions`` edge per row and the entity is reachable from the sheet's side
+and the sheet from the entity's.
+
+**A second pass updates rather than twins.** The link is written into the same place a
+promotion writes one (``links[key][label_column]``), with what the cell said beside it, so
+promoting these rows back after editing them updates the entities they came from. Round
+trip, not fork.
+
+**Nothing is copied that was not asked for.** The label, and the fields named. A sheet
+that swept every attribute would be a second copy of the graph, drifting from the first
+the moment either is edited.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from . import entities as entity_engine
+from . import sheets as sheet_engine
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: How many entities one build may take. A sheet holds twenty thousand rows, but a
+#: worklist of two thousand is already past what anyone works through — and past this the
+#: honest answer is a filtered Board, not a longer table.
+MAX_FROM_CASE = 2_000
+
+#: The column carrying the entity's name, which is also the column the link hangs on —
+#: the same one a promotion uses, so the two agree about what a promoted row is.
+NAME_COLUMN = "Name"
+
+#: The two the work needs and the graph does not hold: where the checking got to, and
+#: why. They are the whole reason the rows are in a sheet rather than in the Board.
+STATUS_COLUMN = "Status"
+NOTES_COLUMN = "Notes"
+
+#: Fields not worth a column: a drawn shape is not something a cell can hold, and a grid
+#: showing its coordinates as a wall of digits would say the sheet is where it is edited.
+SKIPPED_KINDS = ("geojson",)
+
+
+def declared_fields(entity_type: str) -> list[entity_engine.Attr]:
+ """The fields of this type an analyst could put in a column."""
+ for declared in entity_engine.ENTITY_TYPES:
+ if declared.type == entity_type:
+ return [attr for attr in declared.attrs if attr.kind not in SKIPPED_KINDS]
+ return []
+
+
+def _cell(value: Any) -> str:
+ """One stored field as the text a CSV holds.
+
+ A list is joined rather than serialised: `aliases` is three names, and a cell reading
+ `["a", "b"]` is a cell nobody can filter on or hand to a spreadsheet.
+ """
+ if value is None:
+ return ""
+ if isinstance(value, bool):
+ return "YES" if value else "NO"
+ if isinstance(value, (list, tuple)):
+ return ", ".join(_cell(entry) for entry in value if entry not in (None, ""))
+ return str(value)
+
+
+def build(
+ case: "Case",
+ *,
+ entity_type: str,
+ fields: list[str] | None = None,
+ limit: int = MAX_FROM_CASE,
+) -> dict[str, Any]:
+ """The table, the sidecar and the counts for a worklist over one type.
+
+ Ordered by name rather than by insertion, because the analyst about to work through
+ it will look rows up by name. ``total`` is how many the case holds against ``taken``,
+ which is what lets the screen say a build was cut before it is pressed.
+ """
+ declared = {attr.key: attr for attr in declared_fields(entity_type)}
+ wanted = [key for key in (fields or []) if key in declared]
+ columns = [
+ sheet_engine.ID_COLUMN,
+ NAME_COLUMN,
+ *(declared[key].label for key in wanted),
+ STATUS_COLUMN,
+ NOTES_COLUMN,
+ ]
+
+ taken = max(0, min(int(limit), MAX_FROM_CASE))
+ page = case.page_entities(limit=taken or 1, types=[entity_type], order="label")
+ items = list(page.get("items", []))[:taken]
+
+ rows: list[list[str]] = []
+ links: dict[str, dict[str, str]] = {}
+ promoted: dict[str, dict[str, str]] = {}
+ for entity in items:
+ key = sheet_engine.new_row_id()
+ label = _cell(entity.get("label"))
+ attrs = entity.get("attrs") or {}
+ rows.append([key, label, *(_cell(attrs.get(field)) for field in wanted), "", ""])
+ links[key] = {NAME_COLUMN: str(entity["id"])}
+ promoted[key] = {NAME_COLUMN: label}
+
+ meta = {
+ **sheet_engine.empty_meta(),
+ "links": links,
+ "promoted": promoted,
+ # The status column arrives as a state with its four words: the sheet exists to
+ # be worked through, and a worklist whose progress cannot be counted on the day
+ # it is made is a worklist somebody has to set up first.
+ "roles": {STATUS_COLUMN: {"kind": "state"}},
+ "progress": STATUS_COLUMN,
+ }
+ return {
+ "columns": columns,
+ "rows": rows,
+ "meta": meta,
+ "taken": len(rows),
+ "total": int(page.get("total", len(rows))),
+ }
+
+
+# -- the outgoing shape: one row per proof -------------------------------------
+#
+# The other document in this app carrying these columns is the `geoloc` template, and it
+# runs the other way: addresses pasted in, pressed, downloaded, turned into proofs. This
+# one starts from proofs the case already holds and turns them into a table. Confusing
+# the two is the mistake to avoid — the incoming one holds *text of URLs*, this one holds
+# *links to entities*, and `canBuild()` refuses to offer the sheet-to-proofs build here
+# because there is nothing left to fetch.
+
+#: The label of the proof, and the column its link hangs on.
+TITLE_COLUMN = "Title"
+
+#: What the proof was made from, and where it says the picture was taken. Both carry a
+#: link and no role beyond `locked`: `linkable()` refuses a column holding `url` or any
+#: other kind, so a role naming what these hold would cost them their link.
+SOURCE_COLUMN = "Source media"
+PLACE_COLUMN = "Place"
+
+#: Filled by the app off the graph, never copied into the file by hand. `from` names the
+#: place column rather than the title column on purpose: `_points_by_entity` walks
+#: `located-at`, `sited-at`, `at` and `about`, and **not** `depicts` — so a hop from the
+#: proof would resolve nothing. The place holds its own point, which is one lookup.
+POINT_COLUMN = "Coordinates"
+
+#: Whether the case still holds the proof this row was built from. A row whose proof has
+#: since been deleted keeps its text, its notes and its place in the table, and says NO
+#: here — which is the column the analyst filters on to find them and decide.
+IN_CASE_COLUMN = "In case"
+
+#: What the proof derives from. `capture` as well as `media`: a frame grabbed out of a
+#: video is a source like any other, and a column that skipped it would be blank on
+#: exactly the proofs built the careful way.
+SOURCE_TYPES = ("media", "capture")
+
+
+def _edges(case: "Case") -> dict[str, dict[str, list[str]]]:
+ """The two edges this shape reads, indexed by the proof they leave.
+
+ One pass over the graph rather than two queries per row: a build may take two
+ thousand proofs and the graph is the same graph for all of them.
+ """
+ from . import links as link_engine
+
+ wanted = (link_engine.DERIVED_FROM, link_engine.DEPICTS)
+ found: dict[str, dict[str, list[str]]] = {}
+ for link in case.list_links():
+ kind = str(link.get("type") or "")
+ if kind not in wanted:
+ continue
+ source, target = str(link.get("from") or ""), str(link.get("to") or "")
+ if source and target:
+ found.setdefault(source, {}).setdefault(kind, []).append(target)
+ return found
+
+
+def _first(ids: list[str], known: dict[str, dict[str, Any]], types: tuple[str, ...]) -> str:
+ """Which of these a cell holds, when a cell holds one and the proof has several.
+
+ A proof rests on up to eight sources and a cell carries one link, so one is chosen —
+ otherwise "one row per proof" stops being true. Chosen **by label**, not by whatever
+ order the graph hands back: `list_links()` reads in insertion order today, which is
+ stable but arbitrary, and a bundle restored elsewhere may insert them in another one.
+ Sorting by what the analyst can see means two builds of the same case agree, and
+ agree with what somebody reading the panel would have picked.
+ """
+ holding = [
+ entity_id
+ for entity_id in ids
+ if (entity := known.get(entity_id)) is not None and entity.get("type") in types
+ ]
+ if not holding:
+ return ""
+ return min(holding, key=lambda entity_id: (str(known[entity_id].get("label") or ""), entity_id))
+
+
+def proof_columns() -> list[str]:
+ """The shape's headings, in reading order: what the case says, then what you say."""
+ return [
+ sheet_engine.ID_COLUMN,
+ TITLE_COLUMN,
+ SOURCE_COLUMN,
+ PLACE_COLUMN,
+ POINT_COLUMN,
+ IN_CASE_COLUMN,
+ STATUS_COLUMN,
+ NOTES_COLUMN,
+ ]
+
+
+def proof_roles() -> dict[str, Any]:
+ """What each column is, which is also what may be typed in and what may not.
+
+ Three locked, two computed, one state, one free. The analyst's half of the table is
+ `Status`, `Notes` and any column they add: the case's half is the app's to write, and
+ a view somebody can type over is a view that starts lying the first time they do.
+ """
+ return {
+ TITLE_COLUMN: {"kind": "locked"},
+ SOURCE_COLUMN: {"kind": "locked"},
+ PLACE_COLUMN: {"kind": "locked"},
+ POINT_COLUMN: {"kind": "computed", "of": "point", "from": PLACE_COLUMN},
+ IN_CASE_COLUMN: {"kind": "computed", "of": "in_case"},
+ STATUS_COLUMN: {"kind": "state"},
+ }
+
+
+def _resolve(case: "Case", proofs: list[dict[str, Any]]) -> tuple[
+ dict[str, dict[str, list[str]]], dict[str, dict[str, Any]]
+]:
+ """The graph this shape needs, read in two bounded lookups for the whole build."""
+ edges = _edges(case)
+ reachable: set[str] = set()
+ for proof in proofs:
+ for targets in edges.get(str(proof["id"]), {}).values():
+ reachable.update(targets)
+ known = {str(entity["id"]): entity for entity in case.entities_by_ids(sorted(reachable))}
+ return edges, known
+
+
+def _proof_cells(
+ proof: dict[str, Any],
+ edges: dict[str, dict[str, list[str]]],
+ known: dict[str, dict[str, Any]],
+) -> tuple[dict[str, str], dict[str, str]]:
+ """One proof as the three cells it fills and the three links behind them.
+
+ A proof with no place gives a row whose `Place` and `Coordinates` are empty, and the
+ row is filed anyway. That is information — the case holds a proof nobody has placed —
+ and refusing the row would be the build deciding which of the analyst's proofs count.
+ """
+ from . import links as link_engine
+
+ held = edges.get(str(proof["id"]), {})
+ media = _first(held.get(link_engine.DERIVED_FROM, []), known, SOURCE_TYPES)
+ place = _first(held.get(link_engine.DEPICTS, []), known, ("place",))
+ label = _cell(proof.get("label"))
+ cells = {
+ TITLE_COLUMN: label,
+ SOURCE_COLUMN: _cell((known.get(media) or {}).get("label")) if media else "",
+ PLACE_COLUMN: _cell((known.get(place) or {}).get("label")) if place else "",
+ }
+ links = {TITLE_COLUMN: str(proof["id"])}
+ if media:
+ links[SOURCE_COLUMN] = media
+ if place:
+ links[PLACE_COLUMN] = place
+ return cells, links
+
+
+def build_proofs(case: "Case", *, limit: int = MAX_FROM_CASE) -> dict[str, Any]:
+ """The table, the sidecar and the counts for one row per proof the case holds.
+
+ Ordered by label like the generic shape, because that is how a row is looked up.
+
+ `Status` arrives at `done` on every row rather than `to do`: each line is a proof that
+ exists, and forty rows claiming work still to do would be forty lies. The column earns
+ its keep the moment the analyst adds a line for a place **not** yet proven — that one
+ arrives at `to do`, and the column then means "is there a proof for this row".
+ """
+ columns = proof_columns()
+ taken = max(0, min(int(limit), MAX_FROM_CASE))
+ page = case.page_entities(limit=taken or 1, types=["proof"], order="label")
+ proofs = list(page.get("items", []))[:taken]
+ edges, known = _resolve(case, proofs)
+
+ rows: list[list[str]] = []
+ links: dict[str, dict[str, str]] = {}
+ promoted: dict[str, dict[str, str]] = {}
+ built: dict[str, str] = {}
+ for proof in proofs:
+ key = sheet_engine.new_row_id()
+ cells, cell_links = _proof_cells(proof, edges, known)
+ filled = {sheet_engine.ID_COLUMN: key, STATUS_COLUMN: "done", **cells}
+ rows.append([filled.get(name, "") for name in columns])
+ links[key] = cell_links
+ promoted[key] = {TITLE_COLUMN: cells[TITLE_COLUMN]}
+ built[key] = str(proof["id"])
+
+ meta = {
+ **sheet_engine.empty_meta(),
+ "links": links,
+ "promoted": promoted,
+ "built": built,
+ "roles": proof_roles(),
+ "progress": STATUS_COLUMN,
+ }
+ return {
+ "columns": columns,
+ "rows": rows,
+ "meta": meta,
+ "taken": len(rows),
+ "total": int(page.get("total", len(rows))),
+ }
+
+
+def refresh_proofs(
+ case: "Case",
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ *,
+ limit: int = MAX_FROM_CASE,
+) -> dict[str, Any]:
+ """Bring a proofs sheet back level with the case, and say what that took.
+
+ Three rules, and the second is the one that makes the button safe to press:
+
+ **Rows are added, never removed.** A proof the case no longer holds keeps its row,
+ its notes and its colour, and answers NO in `In case`. Deleting it is the analyst's
+ call — their notes are on that line and nothing here wrote them.
+
+ **Only the case's columns are rewritten.** `Status`, `Notes` and anything the analyst
+ added are read and put back untouched. A refresh that reset a status would be a
+ refresh nobody presses twice.
+
+ **New rows land at the end**, in label order among themselves. Inserting them in
+ place would reshuffle a table somebody is working down; the sheet's own sort is where
+ order is decided.
+
+ Refused on any other sheet. The shape is recognised by its `Title` column being
+ `locked` — a heading alone would not do, since nothing stops an imported binder from
+ holding a column called *Title*, and pouring every proof in the case into it would
+ file a hundred rows of empty cells nobody asked for. Only this build writes that role.
+ """
+ roles = (meta.get("roles") or {}) if isinstance(meta, dict) else {}
+ if (roles.get(TITLE_COLUMN) or {}).get("kind") != "locked" or TITLE_COLUMN not in columns:
+ raise sheet_engine.SheetError("this sheet was not built out of the case's proofs")
+ key_at = sheet_engine.key_index(columns)
+ index = {name: position for position, name in enumerate(columns)}
+ links = {str(key): dict(cells) for key, cells in (meta.get("links") or {}).items()}
+ promoted = {str(key): dict(cells) for key, cells in (meta.get("promoted") or {}).items()}
+ built = {str(key): str(value) for key, value in (meta.get("built") or {}).items() if value}
+
+ taken = max(0, min(int(limit), MAX_FROM_CASE))
+ page = case.page_entities(limit=taken or 1, types=["proof"], order="label")
+ proofs = list(page.get("items", []))[:taken]
+ edges, known = _resolve(case, proofs)
+
+ # Which row already stands for which proof. The sidecar's own record rather than a
+ # match on the text: the label is what changes, so matching on it would file a second
+ # row for every proof somebody renamed.
+ at_proof: dict[str, str] = {}
+ for row_key, entity_id in built.items():
+ at_proof.setdefault(entity_id, row_key)
+
+ table = [list(row) for row in rows]
+ where = {row[key_at]: position for position, row in enumerate(table) if key_at < len(row)}
+ updated, added = 0, 0
+ for proof in proofs:
+ cells, cell_links = _proof_cells(proof, edges, known)
+ standing = at_proof.get(str(proof["id"]))
+ if standing is not None and standing in where:
+ row = table[where[standing]]
+ for name, value in cells.items():
+ position = index.get(name)
+ if position is not None and position < len(row) and row[position] != value:
+ row[position] = value
+ updated += 1
+ links[standing] = cell_links
+ promoted[standing] = {TITLE_COLUMN: cells[TITLE_COLUMN]}
+ continue
+ key = sheet_engine.new_row_id()
+ row = [""] * len(columns)
+ if key_at < len(row):
+ row[key_at] = key
+ for name, value in {**cells, STATUS_COLUMN: "done"}.items():
+ position = index.get(name)
+ if position is not None and position < len(row):
+ row[position] = value
+ table.append(row)
+ links[key] = cell_links
+ promoted[key] = {TITLE_COLUMN: cells[TITLE_COLUMN]}
+ built[key] = str(proof["id"])
+ added += 1
+
+ # What the rows already on the table were built from, and which of those the case
+ # still holds. Asked of the case rather than of the page above: a build cut at the
+ # limit must not report every proof past it as deleted.
+ carried = {str(key): built[key] for key in where if key in built}
+ alive = {
+ str(entity["id"])
+ for entity in case.entities_by_ids(sorted(set(carried.values())))
+ }
+ gone = sum(1 for entity_id in carried.values() if entity_id not in alive)
+ return {
+ "columns": list(columns),
+ "rows": table,
+ "meta": {**meta, "links": links, "promoted": promoted, "built": built},
+ "added": added,
+ "updated": updated,
+ "gone": gone,
+ }
diff --git a/src/azimut/engine/sheetlinks.py b/src/azimut/engine/sheetlinks.py
new file mode 100644
index 0000000..421ac5e
--- /dev/null
+++ b/src/azimut/engine/sheetlinks.py
@@ -0,0 +1,213 @@
+"""Whether the addresses in a sheet's column still answer.
+
+A worklist is mostly links: the post a claim rests on, the channel it came from, the
+archive copy somebody made. They rot, and a column of four hundred sources says nothing
+about which of them are already gone — which is exactly the thing worth knowing before a
+finding is published on one.
+
+So this checks them, and it is deliberately **the only part of a sheet that reaches the
+network**. It runs on a press, never on a read or a save: the rule the whole app is under
+is that nothing leaves the machine unless the analyst's own action needs it to.
+
+Five answers, and the shape of them is the point — a checker that reported a bare
+true/false would put "this page is gone" and "this machine is offline" in one bucket:
+
+``ok``
+ It answered.
+``gone``
+ It answered that it is not there (404, 410). The finding.
+``refused``
+ It answered something else — a 403 behind a login, a 500, a rate limit. Not proof of
+ anything about the page, so it is not called dead.
+``unreachable``
+ Nothing answered. Says as much about the connection as about the address.
+``skipped``
+ Never tried, because the batch ran out of its time budget. Kept apart from the other
+ four: "we did not ask" is not a fact about the page.
+
+Bounded on purpose: a cap on the batch, a short timeout, a budget over the whole sweep,
+and one request at a time so a sweep over a hundred sources cannot read as an attack on a
+small host.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import time
+from typing import Any
+from urllib.parse import urlsplit
+
+import httpx
+
+from .tiles import USER_AGENT
+
+#: How many addresses one request may carry. The grid chunks a long column into several,
+#: which is also what lets it draw progress and be stopped half way.
+MAX_LINKS = 25
+#: How long one address gets. Short: a sweep of twenty five that each waited thirty
+#: seconds is a screen that appears to have hung.
+TIMEOUT = 6.0
+#: How long the whole batch gets. The per-address timeout alone did not bound the sweep:
+#: twenty five addresses each taking a HEAD and then a GET at six seconds is five minutes
+#: of one held request and one occupied thread, which is the same hung screen the timeout
+#: was chosen to avoid. Past it the rest come back `skipped`, which says they were not
+#: asked rather than that they did not answer.
+BUDGET = 30.0
+#: How many redirects one address may take. Bounded rather than left to httpx so the
+#: destination of each hop can be looked at before it is followed.
+MAX_HOPS = 5
+#: Statuses that mean the page itself is not there. Everything else that answers is
+#: reported as it came.
+GONE = (404, 410)
+
+
+def _is_local(host: str | None) -> bool:
+ """Whether this host is the machine itself or its own network.
+
+ The addresses come from the sheet, and a sheet arrives by import, by paste or as a
+ workbook somebody sent: a column of links from a third party could otherwise make this
+ app knock on its own ports and report which of them answered. Checked on the first hop
+ and on every redirect, since a remote host may answer with `Location: 127.0.0.1:<port>`
+ and the loopback guard in `server.py` asks only that the Host be a loopback name.
+
+ Literal addresses and the loopback names. A hostname that *resolves* to a private
+ address is not caught, which is written down in SPEC's security posture: what leaks is
+ "this port answered", never a body — `check` reads the status and nothing else.
+ """
+ name = (host or "").strip().strip("[]").casefold()
+ if not name:
+ return True
+ if name == "localhost" or name.endswith((".localhost", ".local", ".internal")):
+ return True
+ try:
+ address = ipaddress.ip_address(name)
+ except ValueError:
+ return False
+ return bool(
+ address.is_private
+ or address.is_loopback
+ or address.is_link_local
+ or address.is_reserved
+ or address.is_multicast
+ or address.is_unspecified
+ )
+
+
+class _Refused(Exception):
+ """A hop this will not follow, carrying the verdict to answer instead."""
+
+ def __init__(self, verdict: dict[str, Any]) -> None:
+ super().__init__(verdict.get("reason", ""))
+ self.verdict = verdict
+
+
+def _now() -> float:
+ """The clock the budget is measured on. Its own function so a test can move it without
+ patching `time.monotonic` for httpx and everything else running on this thread."""
+ return time.monotonic()
+
+
+def _client() -> httpx.Client:
+ """One client for a whole batch. Redirects are followed by hand (`_answered`), which is
+ the only way to look at where a hop goes before going there."""
+ return httpx.Client(
+ timeout=TIMEOUT,
+ follow_redirects=False,
+ headers={"User-Agent": USER_AGENT},
+ )
+
+
+def _answered(client: httpx.Client, request: httpx.Request) -> httpx.Response:
+ """Follow this request's redirects by hand.
+
+ By hand because `follow_redirects=True` never shows where a hop goes, and where it goes
+ is the question: see `_is_local`.
+ """
+ response = client.send(request)
+ for _ in range(MAX_HOPS):
+ hop = response.next_request
+ if hop is None:
+ return response
+ if _is_local(hop.url.host):
+ raise _Refused(
+ {
+ "state": "refused",
+ "code": response.status_code,
+ "reason": "redirected to a local address",
+ }
+ )
+ response = client.send(hop)
+ raise _Refused(
+ {"state": "refused", "code": response.status_code, "reason": "too many redirects"}
+ )
+
+
+def check(url: str, client: httpx.Client | None = None) -> dict[str, Any]:
+ """One address, as one verdict. Never raises: a checker that threw would take the
+ other twenty four answers of the batch down with it.
+
+ *client* is the batch's own, so a column of forty links to one host reuses one
+ connection instead of opening forty.
+ """
+ split = urlsplit(url)
+ if split.scheme not in ("http", "https") or not split.hostname:
+ return {"state": "refused", "code": None, "reason": "not an http address"}
+ if _is_local(split.hostname):
+ return {"state": "refused", "code": None, "reason": "a local address"}
+ own = client is None
+ client = client or _client()
+ try:
+ # HEAD first, because the body is not the question and a source can be a
+ # forty-megabyte video. Plenty of hosts refuse HEAD, so a refusal that looks
+ # like "we do not do that verb" is retried as a GET whose body is never read.
+ answer = _answered(client, client.build_request("HEAD", url))
+ if answer.status_code in (405, 400, 403, 501):
+ answer = _answered(
+ client, client.build_request("GET", url, headers={"Range": "bytes=0-0"})
+ )
+ except _Refused as refusal:
+ return refusal.verdict
+ except httpx.HTTPError as exc:
+ return {"state": "unreachable", "code": None, "reason": type(exc).__name__}
+ finally:
+ if own:
+ client.close()
+ code = answer.status_code
+ if code in GONE:
+ return {"state": "gone", "code": code, "reason": ""}
+ if code >= 400:
+ return {"state": "refused", "code": code, "reason": ""}
+ return {"state": "ok", "code": code, "reason": ""}
+
+
+def check_all(urls: list[str]) -> dict[str, dict[str, Any]]:
+ """A batch, deduplicated, in the order it arrived and capped at `MAX_LINKS`.
+
+ Deduplicated because a column of four hundred rows sourced to one channel holds one
+ address four hundred times, and asking that host four hundred times would be the
+ rudest possible way to learn one fact.
+
+ Sequential, on one client, under one budget. The order stays as it arrived so the
+ addresses that ran out of time are the ones at the end of the column rather than a
+ handful scattered through it.
+ """
+ seen: list[str] = []
+ for url in urls:
+ text = str(url or "").strip()
+ if text and text not in seen:
+ seen.append(text)
+ if len(seen) >= MAX_LINKS:
+ break
+ answers: dict[str, dict[str, Any]] = {}
+ started = _now()
+ with _client() as client:
+ for url in seen:
+ if _now() - started >= BUDGET:
+ answers[url] = {
+ "state": "skipped",
+ "code": None,
+ "reason": "the batch ran out of time",
+ }
+ continue
+ answers[url] = check(url, client)
+ return answers
diff --git a/src/azimut/engine/sheetpass.py b/src/azimut/engine/sheetpass.py
new file mode 100644
index 0000000..1f4fc4d
--- /dev/null
+++ b/src/azimut/engine/sheetpass.py
@@ -0,0 +1,760 @@
+"""One pass of a sheet into the case: what each column becomes, then the edges between.
+
+Six roads out of a sheet is what this replaces. Promoting rows, promoting a column's
+words, pointing a column at what the case already holds, dating a column of hours,
+turning a column of row names into edges — five presses, five plans to read, and nothing
+joining what any of them produced. A line of a binder says *this person, in that unit,
+seen in this video, at that point*; the case got the four nodes and lost the sentence.
+
+So a pass is **one declaration and one press**. Each column takes a mode, the modes run
+in the order their answers depend on each other, and then the edges between the columns
+are drawn from the vocabulary's own reading of the pair. Nothing here is a new engine:
+`sheetpromote` and `sheetclaims` already hold every write, and this module is the order
+they run in plus the layer none of them could see — an edge needs *two* columns, and a
+road that promotes one column at a time can never be the thing that draws it.
+
+**The whole pass is one transaction** (`case.batch()`). That is affordable precisely
+because nothing here touches the network: the road that downloads files is atomic per row
+instead, for the opposite reason. It also means the sheet's own save happens *inside* the
+batch, so a file that moved under the analyst rolls the graph back on its way out rather
+than leaving entities to be swept up by a compensating undo.
+
+What a pass may not do, ever: **create anything that owns a file.** A `media`, a
+`capture`, a `proof`, a `post` hold bytes, and a cell holds an address. Here an address
+becomes a `bookmark`, which claims to be nothing but the address. Going to fetch the file
+is the other road out of a sheet (`engine/sheetproofs.py`, which drives
+`engine/proofimport.py` a row at a time), and only what fetches the bytes may state what
+it observed of them.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+from ..workspace import CaseError
+from . import links as link_engine
+from . import sheetclaims, sheetpromote, sheetroles
+from .sheets import SheetError, key_index
+from .sheetpromote import ACTIONS, JOIN, MAKE, UPDATE
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: What a column may become. `ignore` is the default and the honest one: a worklist's
+#: private notes have no business in the case's record of a subject, so a column travels
+#: only when it was asked for.
+MODES = ("ignore", "row", "value", "point", "addresses", "statement", "row-edges")
+
+#: The modes that make something an edge can end at, in the order the join layer offers
+#: them. `addresses` is absent on purpose: a bookmark already arrives holding a `mentions`
+#: edge to the row's subject, so joining it a second time would state it twice.
+POINTING = ("row", "value", "point")
+
+
+class _Column:
+ """One column's declaration, after the door has read it."""
+
+ __slots__ = ("name", "mode", "type", "verb", "attach", "skip")
+
+ def __init__(
+ self,
+ name: str,
+ mode: str,
+ *,
+ type_: str = "",
+ verb: str = "",
+ attach: dict[str, str] | None = None,
+ skip: list[str] | None = None,
+ ) -> None:
+ self.name = name
+ self.mode = mode
+ self.type = type_
+ self.verb = verb
+ self.attach = attach or {}
+ self.skip = skip or []
+
+
+@dataclass(frozen=True)
+class _Join:
+ """One ordered pair of columns and the verb the analyst picked between them."""
+
+ from_column: str
+ to_column: str
+ verb: str
+
+
+@dataclass(frozen=True)
+class _Pass:
+ """A validated declaration: what each column becomes and what joins what."""
+
+ columns: list[str]
+ rows: list[list[str]]
+ meta: dict[str, Any]
+ keys: list[str]
+ key_at: int
+ #: The one column in `row` mode, or None when the pass promotes no subject.
+ subject: _Column | None
+ #: Column name to the declared field it fills, for the subject's own type.
+ fields: dict[str, str]
+ point: str
+ addresses: str
+ group: bool
+ group_label: str
+ values: list[_Column]
+ statement: dict[str, Any] | None
+ row_edges: list[_Column]
+ joins: list[_Join]
+ confidence: int | None
+ #: Every column that ends up designating something, by name, with its mode and type.
+ pointing: dict[str, _Column] = field(default_factory=dict)
+
+
+def read(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ keys: list[str],
+ subject: dict[str, Any] | None = None,
+ point: str = "",
+ addresses: str = "",
+ values: list[dict[str, Any]] | None = None,
+ statement: dict[str, Any] | None = None,
+ row_edges: list[dict[str, Any]] | None = None,
+ joins: list[dict[str, Any]] | None = None,
+ confidence: int | None = None,
+) -> _Pass:
+ """Read one declaration, or refuse it at the door with the reason.
+
+ Everything a plan and a press both have to agree about is settled here, once: a
+ second reading in the writing half is a second reading that will disagree with this
+ one the first time either is touched.
+ """
+ if len(keys) > sheetpromote.MAX_PROMOTED:
+ raise SheetError(
+ f"at most {sheetpromote.MAX_PROMOTED} rows can be sent to the case at once"
+ )
+ for name in (point, addresses):
+ if name and name not in columns:
+ raise SheetError(f"this sheet has no column '{name}'")
+
+ subject_column: _Column | None = None
+ if subject:
+ name = str(subject.get("column") or "")
+ if name not in columns:
+ raise SheetError(f"this sheet has no column '{name}'")
+ subject_column = _Column(
+ name,
+ "row",
+ type_=str(subject.get("type") or ""),
+ attach=subject.get("attach") or {},
+ skip=subject.get("skip") or [],
+ )
+
+ read_values: list[_Column] = []
+ for entry in values or []:
+ name = str(entry.get("column") or "")
+ if name not in columns:
+ raise SheetError(f"this sheet has no column '{name}'")
+ if subject_column and name == subject_column.name:
+ raise SheetError(f"'{name}' cannot both be the subject and a column of values")
+ if any(name == other.name for other in read_values):
+ raise SheetError(f"'{name}' is declared twice")
+ read_values.append(
+ _Column(
+ name,
+ "value",
+ type_=str(entry.get("type") or ""),
+ attach=entry.get("attach") or {},
+ skip=entry.get("skip") or [],
+ )
+ )
+
+ read_edges: list[_Column] = []
+ for entry in row_edges or []:
+ name = str(entry.get("column") or "")
+ if name not in columns:
+ raise SheetError(f"this sheet has no column '{name}'")
+ read_edges.append(_Column(name, "row-edges", verb=str(entry.get("verb") or "")))
+
+ # A row promoted *as* a place has its coordinates in a column, and most often that is
+ # the very column it was declared on: in a geolocation index the point is the entity,
+ # not a second one it is joined to. Asking for it twice is a question with one possible
+ # answer, so it is only asked when the subject column holds no point of its own — where
+ # the subject is a column of names, the door still says what is missing.
+ if subject_column and subject_column.type == sheetpromote.PLACE_TYPE and not point:
+ if _holds_points(columns, rows, keys, subject_column.name):
+ point = subject_column.name
+
+ if point and subject_column is None:
+ raise SheetError("a column of coordinates needs the column naming what sits there")
+ if point and subject_column and subject_column.type != sheetpromote.PLACE_TYPE:
+ if not sheetpromote.place_verb(subject_column.type):
+ raise SheetError(
+ f"the vocabulary has no way to put a {subject_column.type} at a place"
+ )
+ if addresses and subject_column is None:
+ raise SheetError("a column of addresses needs the column naming what they are about")
+ if statement is not None and subject_column is None:
+ raise SheetError("a statement needs the column naming what it is about")
+
+ pointing: dict[str, _Column] = {}
+ if subject_column:
+ pointing[subject_column.name] = subject_column
+ for column in read_values:
+ pointing[column.name] = column
+ if point and subject_column:
+ # A point column designates a place either way, so the pair reads the same to the
+ # registry. What differs is where the id comes from: on a `place` subject the point
+ # *is* the entity and the sidecar names it, anywhere else it is a second entity the
+ # row promotion filed. `_ends_*` is where that fork lives.
+ pointing[point] = _Column(point, "point", type_=sheetpromote.PLACE_TYPE)
+
+ read_joins: list[_Join] = []
+ for entry in joins or []:
+ start, end = str(entry.get("from") or ""), str(entry.get("to") or "")
+ verb = str(entry.get("verb") or "")
+ if start not in pointing or end not in pointing:
+ raise SheetError("a join runs between two columns that designate something")
+ if start == end:
+ raise SheetError(f"'{start}' cannot be joined to itself")
+ allowed = link_engine.pair_verbs(pointing[start].type, pointing[end].type)
+ if verb not in {spec.type for spec in allowed}:
+ readable = ", ".join(spec.type for spec in allowed) or "nothing"
+ raise SheetError(
+ f"the vocabulary joins a {pointing[start].type} to a "
+ f"{pointing[end].type} by {readable}"
+ )
+ read_joins.append(_Join(start, end, verb))
+
+ if confidence is not None and confidence not in link_engine.CONFIDENCE_STATES:
+ raise SheetError(f"'{confidence}' is not a confidence")
+
+ fields = {
+ column: attr
+ for column, attr in ((subject or {}).get("fields") or {}).items()
+ if column in columns
+ }
+ return _Pass(
+ columns=columns,
+ rows=rows,
+ meta=meta if isinstance(meta, dict) else {},
+ keys=keys,
+ key_at=key_index(columns),
+ subject=subject_column,
+ fields=fields,
+ point=point,
+ addresses=addresses,
+ group=bool((subject or {}).get("group")),
+ group_label=str((subject or {}).get("group_label") or ""),
+ values=read_values,
+ statement=statement,
+ row_edges=read_edges,
+ joins=read_joins,
+ confidence=confidence,
+ pointing=pointing,
+ )
+
+
+# -- what one press would do ---------------------------------------------------
+
+
+def plan(case: "Case", **asked: Any) -> dict[str, Any]:
+ """Both layers of one pass, counted, with nothing written.
+
+ The entity layer is each mode's own plan, unchanged — the same five words every road
+ in this app answers in. The edge layer is the one that could not exist before: for
+ each pair the analyst joined, how many rows have **both** ends, and which rows have
+ only one and why. A row whose subject is ambiguous keeps its entities and loses its
+ edges, and it says so here rather than at the moment the edge is not drawn.
+ """
+ reading = read(case, **asked)
+ layers = _entity_plans(case, reading)
+ return {
+ "entities": layers,
+ "joins": _join_plans(reading, layers),
+ "confidence": reading.confidence,
+ }
+
+
+def _entity_plans(case: "Case", reading: _Pass) -> list[dict[str, Any]]:
+ """Each declared mode's own plan, in the order the press will run them."""
+ plans: list[dict[str, Any]] = []
+ if reading.subject:
+ plans.append({
+ "mode": "row",
+ "column": reading.subject.name,
+ **sheetpromote.plan(case, **_row_arguments(reading)),
+ })
+ for column in reading.values:
+ plans.append({
+ "mode": "value",
+ "column": column.name,
+ **sheetpromote.plan_column(
+ case,
+ columns=reading.columns,
+ rows=reading.rows,
+ meta=reading.meta,
+ column=column.name,
+ entity_type=column.type,
+ attach=column.attach,
+ skip=column.skip,
+ ),
+ })
+ coming = _coming(reading, plans)
+ if reading.statement is not None:
+ plans.append({
+ "mode": "statement",
+ "column": str(reading.statement.get("when_column") or ""),
+ **sheetclaims.plan(case, **_statement_arguments(reading), coming=coming),
+ })
+ for column in reading.row_edges:
+ plans.append({
+ "mode": "row-edges",
+ "column": column.name,
+ **sheetpromote.plan_row_links(
+ case,
+ columns=reading.columns,
+ rows=reading.rows,
+ meta=reading.meta,
+ column=column.name,
+ verb=column.verb,
+ coming=coming,
+ ),
+ })
+ return plans
+
+
+def _coming(
+ reading: _Pass, plans: list[dict[str, Any]]
+) -> dict[str, dict[str, dict[str, str]]]:
+ """Per column, per row key, what that column will designate once the press is through.
+
+ The press threads the sidecar from one mode to the next, so a statement sees the
+ subject the same press just promoted. A plan has no sidecar to thread, and without
+ this it reads the one on disk: every statement of a fresh sheet comes back "not in
+ the case yet", and then the press files every one of them. The two halves of one
+ screen disagreeing about the same rows is the one thing a plan may not do.
+
+ What travels is what an entity is asked for downstream — the type, the label, and the
+ id where there already is one. A row about to be made has no id, and that is exactly
+ the case `case.get_entity` cannot answer.
+ """
+ found: dict[str, dict[str, dict[str, str]]] = {}
+ if reading.subject:
+ promised: dict[str, dict[str, str]] = {}
+ for key, decision in _decisions_by_key(_layer_rows(plans, mode="row")).items():
+ if decision.get("action") in RESOLVING:
+ promised[key] = {
+ "id": str(decision.get("entity") or ""),
+ "type": reading.subject.type,
+ "label": str(decision.get("label") or ""),
+ }
+ found[reading.subject.name] = promised
+ for column in reading.values:
+ layer = next(
+ (
+ entry
+ for entry in plans
+ if entry.get("mode") == "value" and entry.get("column") == column.name
+ ),
+ None,
+ )
+ # A column with a separator writes no link — a row pointing at the third of its
+ # three pieces of kit is an answer nobody could read — so it promises nothing.
+ if layer is None or layer.get("multi"):
+ continue
+ promised = {}
+ for decision in layer.get("rows") or []:
+ if decision.get("action") not in RESOLVING:
+ continue
+ for key in decision.get("keys") or []:
+ promised[str(key)] = {
+ "id": str(decision.get("entity") or ""),
+ "type": column.type,
+ "label": str(decision.get("value") or ""),
+ }
+ found[column.name] = promised
+ return found
+
+
+def _row_arguments(reading: _Pass) -> dict[str, Any]:
+ subject = reading.subject
+ assert subject is not None # the caller checked; kept for the type reader
+ return {
+ "columns": reading.columns,
+ "rows": reading.rows,
+ "meta": reading.meta,
+ "keys": reading.keys,
+ "entity_type": subject.type,
+ "label_column": subject.name,
+ "attr_columns": reading.fields,
+ "point_column": reading.point or None,
+ "link_column": reading.addresses or None,
+ "attach": subject.attach,
+ "skip": subject.skip,
+ "group": reading.group,
+ "group_label": reading.group_label or None,
+ }
+
+
+def _statement_arguments(reading: _Pass) -> dict[str, Any]:
+ """The claims engine's own arguments, with the subject and scope this pass settled.
+
+ Passed through rather than re-derived: a column of hours becoming a dated statement is
+ entirely `engine/sheetclaims.py`, and what was missing was never the engine — it was
+ a screen that said the time promotes here.
+ """
+ subject = reading.subject
+ assert subject is not None
+ asked = dict(reading.statement or {})
+ asked.pop("subject_column", None)
+ return {
+ "columns": reading.columns,
+ "rows": reading.rows,
+ "meta": reading.meta,
+ "keys": reading.keys,
+ "subject_column": subject.name,
+ **asked,
+ }
+
+
+# -- the layer that needed two columns -----------------------------------------
+
+
+def _holds_points(
+ columns: list[str], rows: list[list[str]], keys: list[str], column: str
+) -> bool:
+ """Whether this column reads as coordinates in any of the rows being sent."""
+ at = columns.index(column)
+ wanted = set(keys)
+ key_at = key_index(columns)
+ for row in rows:
+ if _key_of(row, key_at) not in wanted:
+ continue
+ if at < len(row) and sheetroles.parse_latlon(row[at]):
+ return True
+ return False
+
+
+def _key_of(row: list[str], at: int) -> str:
+ """A row's identity, which is the column the sheet reserves for it."""
+ return row[at] if at < len(row) else ""
+
+
+def _cell(row: list[str], columns: list[str], name: str) -> str:
+ at = columns.index(name)
+ return str(row[at]) if at < len(row) else ""
+
+
+def _words_of(reading: _Pass, row: list[str], column: str) -> list[str]:
+ """A value column's words in one row, split on the column's own separator.
+
+ Which is what makes `Buk-M2E, ZU23-2, S-125` three edges from the row's subject
+ rather than one to a thing called all three: the sidecar already holds a meaning per
+ word, so the fan is free.
+ """
+ role = (reading.meta.get("roles") or {}).get(column)
+ return sheetroles.split_values(_cell(row, reading.columns, column), role)
+
+
+def _decisions_by_key(plan_rows: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ """A row plan by row key. A group's one decision answers for every key it holds."""
+ found: dict[str, dict[str, Any]] = {}
+ for decision in plan_rows:
+ for key in decision.get("keys") or [decision.get("key", "")]:
+ found[str(key)] = decision
+ return found
+
+
+def _by_word(plan_rows: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ return {str(decision.get("value", "")): decision for decision in plan_rows}
+
+
+def _layer_rows(
+ layers: list[dict[str, Any]], *, mode: str = "", column: str = ""
+) -> list[dict[str, Any]]:
+ """One layer's own row decisions, by the mode or the column that produced them."""
+ for layer in layers:
+ if (mode and layer.get("mode") == mode) or (column and layer.get("column") == column):
+ found = layer.get("rows") or layer.get("plan") or []
+ return found if isinstance(found, list) else []
+ return []
+
+
+#: The three answers that mean a column will have an entity for a row once the press is
+#: through. `SKIP` and `ERROR` mean it will not, which is what leaves an edge with one end.
+RESOLVING = (MAKE, JOIN, UPDATE)
+
+
+def _point_is_subject(reading: _Pass) -> bool:
+ """Whether the point column and the subject column name the same entity.
+
+ They do when the rows are being promoted *as* places: the coordinates are the entity's
+ own, so the sidecar already names it. Anywhere else the point is a second entity the
+ row was joined to, and only the row plan knows which one."""
+ return bool(reading.subject and reading.subject.type == sheetpromote.PLACE_TYPE)
+
+
+def _ends_at_plan(
+ reading: _Pass, layers: list[dict[str, Any]], column: str
+) -> dict[str, tuple[bool, str]]:
+ """Per row key, whether this column will designate something, and why not if it will
+ not. Read off the plans rather than the graph: a `make` has no id yet and is still an
+ end, which is the whole reason both layers can be counted before anything is written.
+ """
+ held = reading.pointing[column]
+ answer: dict[str, tuple[bool, str]] = {}
+ if held.mode in ("row", "point"):
+ found = _decisions_by_key(_layer_rows(layers, mode="row"))
+ for key in reading.keys:
+ decision = found.get(key)
+ if decision is None:
+ answer[key] = (False, "this row is not in the pass")
+ elif decision["action"] not in RESOLVING:
+ answer[key] = (False, decision.get("reason") or "nothing to point at")
+ elif held.mode == "point" and not _point_is_subject(reading):
+ answer[key] = (
+ (True, "")
+ if decision.get("points")
+ else (False, f"no point could be read in '{column}'")
+ )
+ else:
+ answer[key] = (True, "")
+ return answer
+
+ words = _by_word(_layer_rows(layers, column=column))
+ wanted = set(reading.keys)
+ for row in reading.rows:
+ key = _key_of(row, reading.key_at)
+ if key not in wanted:
+ continue
+ said = _words_of(reading, row, column)
+ if not said:
+ continue # nothing was asked of this row, so nothing is missing from it
+ resolving = [
+ word for word in said if (words.get(word, {}).get("action")) in RESOLVING
+ ]
+ if resolving:
+ answer[key] = (True, "")
+ else:
+ first = words.get(said[0], {})
+ answer[key] = (False, first.get("reason") or f"'{said[0]}' is not in the case")
+ return answer
+
+
+def _join_plans(
+ reading: _Pass, layers: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """How many rows each join will draw, and the rows it will not, with the reason."""
+ plans: list[dict[str, Any]] = []
+ for join in reading.joins:
+ starts = _ends_at_plan(reading, layers, join.from_column)
+ ends = _ends_at_plan(reading, layers, join.to_column)
+ drawing: list[str] = []
+ blocked: list[dict[str, str]] = []
+ for key in reading.keys:
+ start_ok, start_why = starts.get(key, (False, ""))
+ end_ok, end_why = ends.get(key, (False, ""))
+ if start_ok and end_ok:
+ drawing.append(key)
+ elif key in starts or key in ends:
+ blocked.append({"key": key, "reason": start_why or end_why})
+ spec = link_engine.relation_type(join.verb)
+ plans.append({
+ "from": join.from_column,
+ "to": join.to_column,
+ "verb": join.verb,
+ "label": spec.label if spec else join.verb,
+ "ratable": bool(spec and spec.ratable),
+ "rows": len(drawing),
+ "blocked": blocked,
+ })
+ return plans
+
+
+# -- doing it, all of it or none of it -----------------------------------------
+
+
+def run(case: "Case", sheet_id: str, **asked: Any) -> dict[str, Any]:
+ """Write both layers of one pass, inside one transaction.
+
+ The modes run in the order their answers depend on each other: the subject first,
+ because a statement is *about* it and an edge starts at it; the columns of values
+ next, because a join ends at one; then the statements and the row-to-row edges, which
+ read the sidecar the first two wrote. The sidecar is threaded through rather than
+ re-read, so the second mode sees what the first said in the same press.
+
+ Nothing is undone by hand. A refusal anywhere in here — a field that will not read, a
+ sheet that moved under the analyst — leaves the case exactly as it was, because the
+ caller ran all of it inside `case.batch()`.
+ """
+ reading = read(case, **asked)
+ meta = dict(reading.meta)
+ done: list[dict[str, Any]] = []
+
+ if reading.subject:
+ answer = sheetpromote.promote_rows(
+ case, sheet_id, **{**_row_arguments(reading), "meta": meta}
+ )
+ meta = _carried(meta, answer)
+ done.append(_layer("row", reading.subject.name, answer))
+
+ for column in reading.values:
+ answer = sheetpromote.promote_column(
+ case,
+ sheet_id,
+ columns=reading.columns,
+ rows=reading.rows,
+ meta=meta,
+ column=column.name,
+ entity_type=column.type,
+ attach=column.attach,
+ skip=column.skip,
+ )
+ meta = _carried(meta, answer)
+ done.append(_layer("value", column.name, answer))
+
+ if reading.statement is not None:
+ answer = sheetclaims.promote(
+ case, sheet_id, **{**_statement_arguments(reading), "meta": meta}
+ )
+ meta = _carried(meta, answer)
+ done.append(_layer("statement", str((reading.statement or {}).get("when_column") or ""), answer))
+
+ for column in reading.row_edges:
+ answer = sheetpromote.promote_row_links(
+ case,
+ columns=reading.columns,
+ rows=reading.rows,
+ meta=meta,
+ column=column.name,
+ verb=column.verb,
+ )
+ done.append(_layer("row-edges", column.name, answer))
+
+ joins = _draw(case, reading, meta, done)
+ return {
+ "entities": done,
+ "joins": joins,
+ "links": meta.get("links") or {},
+ "values": meta.get("values") or {},
+ "promoted": meta.get("promoted") or {},
+ }
+
+
+def _layer(mode: str, column: str, answer: dict[str, Any]) -> dict[str, Any]:
+ """One mode's answer, with its tally under the same key the plan uses.
+
+ The engines spread their counts flat, the plans nest them under ``counts``, and a
+ reader that had to know which of the two shapes it was holding is a reader that will
+ read the wrong one. So the press answers in the plan's shape as well.
+ """
+ return {
+ "mode": mode,
+ "column": column,
+ **answer,
+ "counts": {action: answer.get(action, 0) for action in ACTIONS},
+ }
+
+
+def _carried(meta: dict[str, Any], answer: dict[str, Any]) -> dict[str, Any]:
+ """The sidecar as the next mode must see it. Only the three keys a mode writes, so a
+ mode that never touched `values` cannot blank what another one put there."""
+ carried = dict(meta)
+ for key in ("links", "values", "promoted"):
+ if key in answer:
+ carried[key] = answer[key]
+ return carried
+
+
+def _ends_after_write(
+ reading: _Pass, meta: dict[str, Any], done: list[dict[str, Any]], column: str
+) -> dict[str, list[str]]:
+ """Per row key, the entities this column now designates.
+
+ The sidecar answers for a subject and for a column of values — that is what it is for
+ — but not for a point: a place is filed by the row promotion, so the ids come back on
+ the plan it returned.
+ """
+ held = reading.pointing[column]
+ links = meta.get("links") or {}
+ named = column
+ if held.mode == "point":
+ if _point_is_subject(reading):
+ # The rows *are* places, so the point column and the subject column name one
+ # entity, and the sidecar filed it under the subject's own column.
+ named = reading.subject.name if reading.subject else column
+ else:
+ found = _decisions_by_key(_layer_rows(done, mode="row"))
+ return {
+ key: [str(one) for one in (found.get(key, {}).get("places") or [])]
+ for key in reading.keys
+ if found.get(key, {}).get("places")
+ }
+ if held.mode in ("row", "point"):
+ return {
+ key: [str(links.get(key, {}).get(named))]
+ for key in reading.keys
+ if links.get(key, {}).get(named)
+ }
+ meant = (meta.get("values") or {}).get(column) or {}
+ answer: dict[str, list[str]] = {}
+ wanted = set(reading.keys)
+ for row in reading.rows:
+ key = _key_of(row, reading.key_at)
+ if key not in wanted:
+ continue
+ ids = [str(meant[word]) for word in _words_of(reading, row, column) if meant.get(word)]
+ if ids:
+ answer[key] = ids
+ return answer
+
+
+def _draw(
+ case: "Case", reading: _Pass, meta: dict[str, Any], done: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """Draw every join the declaration asked for, between the ends that resolved.
+
+ An edge the vocabulary refuses for *these two rows* — a `located-at` onto a PDF, which
+ no reading of the two types alone could rule out — is skipped with its reason rather
+ than raised: taking the whole pass down over one edge would lose the rows that had
+ nothing wrong with them, and the plan already said which rows had both ends.
+
+ The confidence of the pass lands here and only on the verbs the registry declares
+ `ratable`. Empty means the analyst asserted nothing beyond the edge itself, which is
+ not the same as asserting `possible`.
+ """
+ drawn: list[dict[str, Any]] = []
+ for join in reading.joins:
+ starts = _ends_after_write(reading, meta, done, join.from_column)
+ ends = _ends_after_write(reading, meta, done, join.to_column)
+ wrote = 0
+ failed: list[dict[str, str]] = []
+ for key in reading.keys:
+ for start in starts.get(key, []):
+ for end in ends.get(key, []):
+ if start == end:
+ continue
+ try:
+ link = link_engine.add_relation(
+ case, start, end, join.verb, by=sheetpromote.BY
+ )
+ except CaseError as exc:
+ failed.append({"key": key, "reason": str(exc)})
+ continue
+ wrote += 1
+ if reading.confidence is not None:
+ spec = link_engine.relation_type(join.verb)
+ if spec and spec.ratable:
+ link_engine.set_confidence(case, link["id"], reading.confidence)
+ drawn.append({
+ "from": join.from_column,
+ "to": join.to_column,
+ "verb": join.verb,
+ "drawn": wrote,
+ "failed": failed,
+ })
+ return drawn
diff --git a/src/azimut/engine/sheetpromote.py b/src/azimut/engine/sheetpromote.py
new file mode 100644
index 0000000..f6becbe
--- /dev/null
+++ b/src/azimut/engine/sheetpromote.py
@@ -0,0 +1,1244 @@
+"""Turn rows of a sheet into what the case believes.
+
+A sheet says what is being *checked*; the graph says what the case *believes*. Promotion
+is the one road between the two, and it runs one way: nothing here reads the graph back
+into a cell.
+
+**It is planned before it is done.** `plan` reads the table and answers, row by row, what
+would happen — a new entity, an existing one attached, one already promoted updated, a row
+left alone, or a cell that cannot be read at all. `promote_rows` executes exactly that
+plan. The analyst sees the answer before the case changes, which is the whole reason a
+promotion is safe to press: forty rows becoming forty entities is not a thing to find out
+about afterwards.
+
+Four rules make it safe to press twice, which matters because an analyst promotes ten
+rows, adds four more and promotes the lot again:
+
+**The sidecar remembers.** A promoted row's cell already points at the entity it made
+(`meta["links"][row][column]`), so the second promotion *updates* that entity instead of
+minting a twin. Only when the entity is still of the promoted type: a cell pointing at a
+place is not a person waiting to be overwritten.
+
+**A name is not an identity.** Two people can share a name, so a row whose label matches
+an entity already in the case is **not** joined to it behind the analyst's back — the plan
+says the case already holds that name, and attaching is a decision they make. The one
+exception is the ``identifier`` family, where the value *is* the identity (ONTOLOGY §2):
+one address is one email, and `entities.identity_key` is what compares them.
+
+**A field is checked before it is stored.** A column mapped onto a declared field goes
+through the same readings the API applies to a typed form, so a number column holding
+`about 12` is reported rather than stored as text in a field nothing can sum.
+
+**Only the columns asked for travel.** The label, whichever columns the analyst mapped
+onto declared fields, and — for a place — the point. A promotion that swept every column
+into the graph would put a worklist's private notes into the case's own record of a
+subject.
+
+What the sheet gets back is a `mentions` edge per promoted row, which is what makes the
+row visible from the subject's side, and the provenance says the sheet it came from.
+
+**Four roads, because a binder holds four shapes and only the first is one row per
+thing.** `promote_rows` is that first one. `promote_rows(group=True)` is the second: two
+lines of one cross-border event are one entity with two places, which row-by-row gets
+wrong by construction. `promote_column` is the third and works on **words** rather than
+rows — a column of four hundred rows holds forty pieces of equipment. `promote_row_links`
+is the fourth: a column naming other rows of the same sheet becomes the `part-of` edges
+an order of battle is actually made of, instead of the text validation the binders had,
+which had already decayed to `#REF!`.
+
+The fifth shape, a column of times becoming a dated statement, is `engine/sheetclaims.py`:
+a Claim is not an entity a row *is*, it is something the case *says* about one, and it
+carries its own connectors, confidence and reasoning.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
+
+from ..workspace import CaseError
+from . import entities as entity_engine
+from . import links as link_engine
+from . import sheetroles
+from .sheets import SheetError, key_index, sync_mentions
+from .temporal import TemporalError, parse_temporal
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: How many rows one press may promote. A worklist is promoted in passes — ticking a
+#: screenful, checking what landed, ticking the next — and a press that wrote two
+#: thousand entities is a press nobody can review.
+MAX_PROMOTED = 500
+
+#: How many different words one column may be promoted at once. The same bound read the
+#: same way: a press that wrote five hundred entities is a press nobody can review.
+MAX_COLUMN_WORDS = MAX_PROMOTED
+
+#: What the provenance of a promoted entity says wrote it.
+BY = "sheet"
+
+#: What one row's promotion does. Five answers rather than a count, because "forty rows
+#: promoted" hides the difference between forty new subjects and thirty-nine the case
+#: already had, and it hides a row that did nothing at all.
+MAKE = "make"
+JOIN = "join"
+UPDATE = "update"
+SKIP = "skip"
+ERROR = "error"
+ACTIONS = (MAKE, JOIN, UPDATE, SKIP, ERROR)
+
+#: How many same-name entities a row offers to attach to. A list past this is not a
+#: choice, it is a search — and the analyst has one of those in the entity picker.
+MAX_CANDIDATES = 5
+
+#: The type a point column promotes into, and the one type here that is not created by
+#: hand anywhere else in the app: a place is normally born from the map, with a point.
+#: A sheet column of coordinates is the other honest way to have one, so promotion
+#: declares it rather than reading `manual` and finding it absent.
+PLACE_TYPE = "place"
+
+#: What a promotion refuses to mint. A Claim is a statement *about* the rest of the
+#: graph — it carries what it is about, when it applies and what it rests on — and a
+#: sheet row promoted on its own would be a statement about nothing, with no date and no
+#: source. Timeline is where a Claim is made; the sheet points at one.
+NOT_PROMOTED = frozenset({"claim"})
+
+#: Where a bookmark keeps the page it stands for. Written by the extension's own filing
+#: (`api/ingest.py`), and matched here so a URL already saved is pointed at rather than
+#: saved twice.
+URL_ATTR = "url"
+
+_URL = re.compile(r"\bhttps?://[^\s<>\"'()\[\]]+")
+_NUMBER = re.compile(r"^[+-]?\d+(?:\.\d+)?$")
+#: What a European export puts inside a number: a space, a non-breaking space or an
+#: apostrophe grouping the thousands, and a comma where the decimal point goes. Taken
+#: out before the value is read, so `1 234,5` is a number and `about 12` is still not.
+_NUMBER_NOISE = str.maketrans({" ": "", "\u00a0": "", "\u202f": "", "'": "", ",": "."})
+
+
+def promotable_types() -> list[str]:
+ """The types a sheet row may become.
+
+ Everything an analyst creates by hand, less the ones a bare row cannot honestly
+ make, plus `place` — which is not created by hand anywhere else because it is
+ normally born from the map, and which a column of coordinates is the other honest
+ way to have.
+ """
+ types = [
+ declared.type
+ for declared in entity_engine.ENTITY_TYPES
+ if declared.manual and declared.type not in NOT_PROMOTED
+ ]
+ if PLACE_TYPE not in types:
+ types.append(PLACE_TYPE)
+ return types
+
+
+def _declared(entity_type: str) -> dict[str, entity_engine.Attr]:
+ """The fields an analyst may fill on this type, by key.
+
+ Promotion is held to these on purpose: an undeclared key would pass through and be
+ stored, so a column called `Notes 3` would become a field of the case's vocabulary
+ that nothing else in the app knows how to show or edit.
+ """
+ for declared in entity_engine.ENTITY_TYPES:
+ if declared.type == entity_type:
+ return {attr.key: attr for attr in declared.attrs}
+ return {}
+
+
+# -- reading one cell into one declared field ---------------------------------
+
+
+def read_attr(attr: entity_engine.Attr, text: str) -> tuple[Any, str | None]:
+ """One cell as the value a declared field takes, or the reason it cannot be.
+
+ A cell is text — every cell is, the file keeps the words — and a declared field is
+ typed. Promotion is where the two meet, and it is the only write in the app that
+ reached the store without passing a form. So the conversion is stated here and the
+ result still goes through `entities.check_attrs`: this decides what `12,5` means,
+ that decides whether the field accepts it.
+
+ An empty cell is *unknown*, which every field may be, so it yields no value and no
+ complaint.
+ """
+ body = str(text or "").strip()
+ if not body:
+ return None, None
+ if attr.kind in ("text", "longtext"):
+ return body, None
+ if attr.kind == "number":
+ digits = body.translate(_NUMBER_NOISE)
+ if not _NUMBER.match(digits):
+ return None, f"{attr.label}: '{body}' is not a number"
+ value = float(digits)
+ return (int(value) if value.is_integer() else value), None
+ if attr.kind == "url":
+ if not body.lower().startswith(("http://", "https://")):
+ return None, f"{attr.label}: '{body}' is not an http or https link"
+ return body, None
+ if attr.kind == "choice":
+ folded = body.casefold()
+ for stored, reading in attr.options:
+ if folded in (stored.casefold(), reading.casefold()):
+ return stored, None
+ allowed = ", ".join(reading for _, reading in attr.options)
+ return None, f"{attr.label}: '{body}' is not one of {allowed}"
+ if attr.kind == "temporal":
+ try:
+ parse_temporal(body)
+ except TemporalError as exc:
+ return None, f"{attr.label}: '{body}' {exc}"
+ return body, None
+ # A footprint is a drawn shape, not a cell. Said rather than silently dropped: the
+ # analyst mapped a column onto it and is owed the reason nothing landed.
+ return None, f"{attr.label} cannot be filled from a column"
+
+
+# -- what a column of coordinates may do, per type ----------------------------
+
+
+#: Verbs that put something at a place, in the order a promotion tries them. A
+#: structure is *sited at* its ground; a recording was *made* there. Read out of the
+#: registry rather than assumed, so a type that gains a place verb later gains this too.
+PLACE_VERBS = ("sited-at", "located-at", "depicts")
+
+
+def place_verb(entity_type: str) -> str | None:
+ """How this type is joined to a place, or None when the vocabulary joins it to none.
+
+ A ``place`` is its own answer — the coordinates are the entity — and that is the case
+ the promotion has always handled. For everything else the point in the cell is a
+ *second* entity: a structure's site is a place the structure stands on, and writing a
+ latitude onto the structure itself would put a field on it that nothing in the app
+ declares, shows or edits.
+ """
+ if entity_type == PLACE_TYPE:
+ return None
+ for verb in PLACE_VERBS:
+ spec = link_engine.relation_type(verb)
+ if spec and entity_type in spec.from_types and PLACE_TYPE in spec.to_types:
+ return verb
+ return None
+
+
+# -- planning ------------------------------------------------------------------
+
+
+def plan(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ keys: list[str],
+ entity_type: str,
+ label_column: str,
+ attr_columns: dict[str, str] | None = None,
+ point_column: str | None = None,
+ link_column: str | None = None,
+ attach: dict[str, str] | None = None,
+ skip: list[str] | None = None,
+ group: bool = False,
+ group_label: str | None = None,
+) -> dict[str, Any]:
+ """What promoting these rows would do, row by row, without doing any of it.
+
+ Read by the preview the analyst confirms and by the promotion itself, so what is
+ shown and what is written are the same answer rather than two that agree until one
+ of them is edited.
+
+ ``group`` turns the ticked rows into **one** entity instead of one each, which is the
+ only place the row-is-an-entity assumption breaks and it breaks on a common shape: the
+ binders' geolocation index puts a cross-border event on two lines, one point per
+ country, same title, same source. Promoted row by row that is two events, and the
+ second one is the copy that never gets corrected.
+ """
+ if entity_type not in promotable_types():
+ raise SheetError(f"'{entity_type}' is not a type a row can become")
+ if label_column not in columns:
+ raise SheetError(f"this sheet has no column '{label_column}'")
+ if len(keys) > MAX_PROMOTED:
+ raise SheetError(f"at most {MAX_PROMOTED} rows can be promoted at once")
+ if entity_type == PLACE_TYPE and not point_column:
+ raise SheetError("a place needs the column holding its coordinates")
+ if point_column and entity_type != PLACE_TYPE and not place_verb(entity_type):
+ raise SheetError(f"the vocabulary has no way to put a {entity_type} at a place")
+ for named in (point_column, link_column):
+ if named and named not in columns:
+ raise SheetError(f"this sheet has no column '{named}'")
+
+ declared = _declared(entity_type)
+ shape = _Shape(
+ columns=columns,
+ entity_type=entity_type,
+ label_column=label_column,
+ declared=declared,
+ mapping={
+ column: attr
+ for column, attr in (attr_columns or {}).items()
+ if column in columns and attr in declared
+ },
+ key_at=key_index(columns),
+ label_at=columns.index(label_column),
+ point_at=columns.index(point_column) if point_column else -1,
+ link_at=columns.index(link_column) if link_column else -1,
+ verb=place_verb(entity_type) if point_column else None,
+ )
+ held = _Held(
+ links=(meta.get("links") or {}) if isinstance(meta, dict) else {},
+ **_labels_held(case, entity_type),
+ )
+ wanted = set(keys)
+ taken = [row for row in rows if _key_of(row, shape.key_at) in wanted]
+ left_out = set(skip or [])
+ chosen = attach or {}
+
+ planned = (
+ _plan_group(case, taken, shape, held, left_out, chosen, group_label)
+ if group
+ else _plan_rows(case, taken, shape, held, left_out, chosen)
+ )
+ return {
+ "rows": planned,
+ "counts": counts_of(planned),
+ "type": entity_type,
+ "group": bool(group),
+ "verb": shape.verb or "",
+ }
+
+
+@dataclass(frozen=True)
+class _Shape:
+ """Where each answer sits in the table, resolved once for the whole plan."""
+
+ columns: list[str]
+ entity_type: str
+ label_column: str
+ declared: dict[str, entity_engine.Attr]
+ #: Column name to the declared field it fills.
+ mapping: dict[str, str]
+ key_at: int
+ label_at: int
+ point_at: int
+ link_at: int
+ #: How a point column joins this type to a place, or None when the point *is* the
+ #: entity (a `place`) or when no column of coordinates was given.
+ verb: str | None
+
+
+@dataclass(frozen=True)
+class _Held:
+ """What the case and the sidecar already say, read once rather than once a row."""
+
+ #: The sidecar's cell-to-entity table.
+ links: dict[str, Any]
+ #: Every label the case holds of this type, folded, so five hundred rows ask the
+ #: graph one question rather than five hundred.
+ holders: dict[str, list[dict[str, str]]]
+ #: And the same entities by identity key, for the family where the value *is* the
+ #: identity.
+ by_identity: dict[str, str]
+
+
+def _labels_held(case: "Case", entity_type: str) -> dict[str, Any]:
+ holders: dict[str, list[dict[str, str]]] = {}
+ by_identity: dict[str, str] = {}
+ for entity in case.list_entities():
+ if entity.get("type") != entity_type:
+ continue
+ label = str(entity.get("label") or "").strip()
+ holders.setdefault(label.casefold(), []).append({"id": entity["id"], "label": label})
+ identity = entity_engine.identity_key(entity_type, label)
+ if identity:
+ by_identity.setdefault(identity, entity["id"])
+ return {"holders": holders, "by_identity": by_identity}
+
+
+def _key_of(row: list[str], at: int) -> str:
+ return row[at] if at < len(row) else ""
+
+
+def _blank_decision(key: str, label: str) -> dict[str, Any]:
+ return {
+ "key": key,
+ "keys": [key],
+ "label": label,
+ "action": SKIP,
+ "reason": "",
+ "entity": None,
+ "entity_label": "",
+ "attrs": {},
+ "points": [],
+ "problems": [],
+ "notes": [],
+ "candidates": [],
+ "repeat": False,
+ }
+
+
+def _read_row(
+ row: list[str], shape: _Shape, problems: list[str], notes: list[str]
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ """One row as the fields it fills and the point it writes, if any.
+
+ The point is two different things depending on the type, which is why it comes back
+ separately: on a ``place`` it *is* the entity and goes into its own attrs; anywhere
+ else it is a second entity the first one is joined to, because a latitude written onto
+ a structure would be a field the app neither shows nor edits.
+
+ ``problems`` stop the row; ``notes`` are said and the row goes on. A place with no
+ readable point is nothing, so that is a problem — but a structure whose coordinates
+ cell still reads `To be found` is a structure, and half the cells in a live binder
+ read like that.
+ """
+ attrs: dict[str, Any] = {}
+ for column, key in shape.mapping.items():
+ value, problem = read_attr(shape.declared[key], row[shape.columns.index(column)])
+ if problem:
+ problems.append(problem)
+ elif value is not None:
+ attrs[key] = value
+ if shape.point_at == -1:
+ return attrs, []
+ said: list[str] = []
+ point = _read_point(row, shape.point_at, shape.columns[shape.point_at], said)
+ if shape.entity_type == PLACE_TYPE:
+ problems.extend(said)
+ for key, value in point.items():
+ # A column mapped onto the radius by hand beats the one read off the cell's
+ # own decimals: the analyst knows how the point was established.
+ attrs.setdefault(key, value)
+ return attrs, []
+ notes.extend(said)
+ return attrs, [point] if point else []
+
+
+def _settle(
+ case: "Case",
+ decision: dict[str, Any],
+ shape: _Shape,
+ held: _Held,
+ chosen: dict[str, str],
+ pointed: str | None,
+) -> None:
+ """Which of the five things this decision is: update, attach, join, make or fail.
+
+ Shared by the row-by-row plan and the group plan, because the question is the same
+ one — does the case already hold this, and did it get it from here — and two copies
+ of it would answer differently the first time either was touched.
+ """
+ label = decision["label"]
+ # What the row already points at, and only when it is still what was promoted: a cell
+ # pointing at a place is not a person waiting to be overwritten.
+ already = case.get_entity(pointed) if pointed else None
+ if already is not None and already.get("type") == shape.entity_type:
+ decision.update(
+ action=UPDATE, entity=already["id"], entity_label=str(already.get("label") or "")
+ )
+ return
+ if already is not None:
+ decision["reason"] = (
+ f"this cell already points at a {already.get('type')}, '{already.get('label')}'"
+ )
+ return
+
+ picked = chosen.get(decision["key"])
+ if picked:
+ target = case.get_entity(picked)
+ if target is None or target.get("type") != shape.entity_type:
+ decision["action"] = ERROR
+ decision["problems"] = ["the entity chosen for this row is gone"]
+ decision["reason"] = decision["problems"][0]
+ return
+ decision.update(
+ action=JOIN,
+ entity=target["id"],
+ entity_label=str(target.get("label") or ""),
+ reason="attached by hand",
+ )
+ return
+
+ # The one family where the value *is* the identity: two `email` entities holding one
+ # address are a bug, not two objects (ONTOLOGY §2).
+ key = entity_engine.identity_key(shape.entity_type, label)
+ if key and key in held.by_identity:
+ target_id = held.by_identity[key]
+ decision.update(
+ action=JOIN,
+ entity=target_id,
+ entity_label=str((case.get_entity(target_id) or {}).get("label") or ""),
+ reason="the case already holds this one",
+ )
+ return
+
+ decision["action"] = MAKE
+ decision["candidates"] = held.holders.get(label.casefold(), [])[:MAX_CANDIDATES]
+
+
+def _plan_rows(
+ case: "Case",
+ rows: list[list[str]],
+ shape: _Shape,
+ held: _Held,
+ left_out: set[str],
+ chosen: dict[str, str],
+) -> list[dict[str, Any]]:
+ """One entity per row, which is the ordinary promotion."""
+ planned: list[dict[str, Any]] = []
+ seen_labels: set[str] = set()
+ for row in rows:
+ identity = _key_of(row, shape.key_at)
+ label = str(row[shape.label_at] if shape.label_at < len(row) else "").strip()
+ decision = _blank_decision(identity, label)
+ planned.append(decision)
+
+ if identity in left_out:
+ decision["reason"] = "left out"
+ continue
+ if not label:
+ decision["reason"] = f"nothing in '{shape.label_column}' to name it"
+ continue
+
+ problems: list[str] = []
+ notes: list[str] = []
+ attrs, points = _read_row(row, shape, problems, notes)
+ if problems:
+ decision.update(action=ERROR, problems=problems, reason=problems[0])
+ continue
+ decision["attrs"] = attrs
+ decision["points"] = points
+ decision["notes"] = notes
+ try:
+ entity_engine.check_attrs(shape.entity_type, attrs)
+ except CaseError as exc:
+ decision.update(action=ERROR, problems=[str(exc)], reason=str(exc))
+ continue
+
+ if label.casefold() in seen_labels:
+ decision["repeat"] = True
+ seen_labels.add(label.casefold())
+
+ _settle(
+ case, decision, shape, held, chosen,
+ held.links.get(identity, {}).get(shape.label_column),
+ )
+ if decision["action"] == MAKE and shape.link_at != -1:
+ decision["sources"] = urls_in(str(row[shape.link_at]))
+ return planned
+
+
+def _plan_group(
+ case: "Case",
+ rows: list[list[str]],
+ shape: _Shape,
+ held: _Held,
+ left_out: set[str],
+ chosen: dict[str, str],
+ group_label: str | None,
+) -> list[dict[str, Any]]:
+ """One entity out of all the rows, which is the case row-by-row gets wrong.
+
+ Where two lines describe one thing — the binders' cross-border event, one line per
+ country — promoting each of them makes a twin nobody asked for and nobody maintains.
+ So the rows are read as one: the first answer wins per field, every point becomes its
+ own place, and **every** row's cell ends up pointing at the one entity, which is what
+ keeps a second press an update and lets the grid say the row is already in the case.
+
+ A field two rows disagree about keeps the first and says so. That is not a tie-break
+ dodged: rows grouped on purpose differ in the detail — that is why there are two of
+ them — and refusing the group over it would refuse the shape it exists for.
+ """
+ taking = [row for row in rows if _key_of(row, shape.key_at) not in left_out]
+ if not taking:
+ first = _key_of(rows[0], shape.key_at) if rows else ""
+ decision = _blank_decision(first, "")
+ decision.update(keys=[_key_of(row, shape.key_at) for row in rows], reason="left out")
+ return [decision]
+
+ keys = [_key_of(row, shape.key_at) for row in taking]
+ said = [str(row[shape.label_at] if shape.label_at < len(row) else "").strip() for row in taking]
+ label = str(group_label or "").strip() or next((word for word in said if word), "")
+ decision = _blank_decision(keys[0], label)
+ decision["keys"] = keys
+ decision["rows"] = len(keys)
+ if not label:
+ decision["reason"] = f"nothing in '{shape.label_column}' to name it"
+ return [decision]
+
+ attrs: dict[str, Any] = {}
+ points: list[dict[str, Any]] = []
+ problems: list[str] = []
+ notes: list[str] = []
+ conflicts: list[str] = []
+ sources: list[str] = []
+ for row in taking:
+ row_attrs, row_points = _read_row(row, shape, problems, notes)
+ for key, value in row_attrs.items():
+ if key in attrs and attrs[key] != value:
+ if key not in conflicts:
+ conflicts.append(shape.declared[key].label)
+ continue
+ attrs.setdefault(key, value)
+ for point in row_points:
+ if not any(_same_point(point, seen) for seen in points):
+ points.append(point)
+ if shape.link_at != -1:
+ sources.extend(urls_in(str(row[shape.link_at])))
+ if problems:
+ decision.update(action=ERROR, problems=problems, reason=problems[0])
+ return [decision]
+ decision["attrs"] = attrs
+ decision["points"] = points
+ decision["notes"] = list(dict.fromkeys(notes))
+ decision["conflicts"] = conflicts
+ if conflicts:
+ decision["reason"] = f"kept the first {', '.join(conflicts).lower()}"
+ try:
+ entity_engine.check_attrs(shape.entity_type, attrs)
+ except CaseError as exc:
+ decision.update(action=ERROR, problems=[str(exc)], reason=str(exc))
+ return [decision]
+
+ # Whichever of the grouped rows was promoted before answers for all of them: the
+ # group is one entity, so one of its rows already pointing at it is the group
+ # already being in the case.
+ pointed = next(
+ (
+ held.links.get(key, {}).get(shape.label_column)
+ for key in keys
+ if held.links.get(key, {}).get(shape.label_column)
+ ),
+ None,
+ )
+ _settle(case, decision, shape, held, chosen, pointed)
+ if decision["action"] == MAKE:
+ decision["sources"] = list(dict.fromkeys(sources))
+ return [decision]
+
+
+def _same_point(one: dict[str, Any], other: dict[str, Any]) -> bool:
+ """Whether two cells wrote the same ground, to the five decimals a cell is stored to."""
+ return (round(one["lat"], 5), round(one["lon"], 5)) == (
+ round(other["lat"], 5),
+ round(other["lon"], 5),
+ )
+
+
+def _read_point(
+ row: list[str], at: int, column: str, problems: list[str]
+) -> dict[str, Any]:
+ """A place's point, read out of one cell, with the precision it was written to.
+
+ The radius is not decoration. A cell holding `48.85, 2.35` is a claim about a
+ kilometre of ground, and a place stored without saying so reads on the map as a
+ pinpoint somebody established. Darwin Core's rule, which the type already declares:
+ the smallest circle containing the whole location.
+ """
+ point = sheetroles.parse_latlon(row[at] if at < len(row) else "")
+ if point is None:
+ problems.append(f"no point could be read in '{column}'")
+ return {}
+ if point["out_of_bounds"]:
+ problems.append(f"'{row[at]}' is off the globe")
+ return {}
+ radius = sheetroles.precision_metres(point["decimals"])
+ return {
+ "lat": point["lat"],
+ "lon": point["lon"],
+ "radius_m": max(1, min(entity_engine.MAX_RADIUS_M, radius)),
+ }
+
+
+def counts_of(planned: list[dict[str, Any]]) -> dict[str, int]:
+ """How many decisions of each kind a plan holds. Public because every road through
+ this app's promotion answers in the same five words, and a second tally would be a
+ second reading of the same list."""
+ return {action: sum(1 for row in planned if row["action"] == action) for action in ACTIONS}
+
+
+# -- doing it ------------------------------------------------------------------
+
+
+def promote_rows(
+ case: "Case",
+ sheet_id: str,
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ keys: list[str],
+ entity_type: str,
+ label_column: str,
+ attr_columns: dict[str, str] | None = None,
+ point_column: str | None = None,
+ link_column: str | None = None,
+ attach: dict[str, str] | None = None,
+ skip: list[str] | None = None,
+ group: bool = False,
+ group_label: str | None = None,
+) -> dict[str, Any]:
+ """Execute the plan these arguments describe, and give back what it did.
+
+ Returns the plan itself alongside the counts and the sidecar links earned, so the
+ grid can say what happened per row rather than only how many rows there were.
+
+ Nothing is handed back for a compensating undo. The whole press runs inside the
+ caller's `case.batch()`, so a refusal anywhere leaves the case exactly as it was —
+ which is the transaction's promise and not a list of ids to walk backwards.
+ """
+ reading = plan(
+ case,
+ columns=columns,
+ rows=rows,
+ meta=meta,
+ keys=keys,
+ entity_type=entity_type,
+ label_column=label_column,
+ attr_columns=attr_columns,
+ point_column=point_column,
+ link_column=link_column,
+ attach=attach,
+ skip=skip,
+ group=group,
+ group_label=group_label,
+ )
+ links = {identity: dict(cells) for identity, cells in (meta.get("links") or {}).items()}
+ # What each cell said at the moment the case took it. Kept so the row can say later
+ # that it has moved on: a link alone cannot, since it is still the same link after
+ # the label is rewritten.
+ said = {identity: dict(cells) for identity, cells in (meta.get("promoted") or {}).items()}
+ sources: dict[str, str] = {}
+ verb = reading["verb"] or None
+ # Every place the case already holds, read **once** for the whole press. `_place` used
+ # to build this itself, which put a full walk of the graph inside the row loop and
+ # inside the write lock: five hundred rows over twenty thousand entities materialised
+ # ten million rows while every other writer waited on `busy_timeout`. Threaded through
+ # instead, so the places this press mints are deduplicated against each other too.
+ at_point = _places_held(case) if verb else {}
+
+ for decision in reading["rows"]:
+ action = decision["action"]
+ attrs = decision["attrs"]
+ target: str | None = decision["entity"]
+ if action == MAKE:
+ entity = case.add_entity(entity_type, decision["label"], attrs, by=BY)
+ target = entity["id"]
+ elif action == UPDATE and target:
+ patch: dict[str, Any] = {"label": decision["label"]}
+ if attrs:
+ patch["attrs"] = attrs
+ case.update_entity(target, patch)
+ elif action == JOIN and target:
+ if attrs:
+ case.update_entity(target, {"attrs": attrs})
+ else:
+ continue
+ if target:
+ # Every key, which is one for an ordinary row and all of them for a group:
+ # the group is one entity, so each of its rows points at it and each of them
+ # can say it is already in the case.
+ for key in decision.get("keys") or [decision["key"]]:
+ links.setdefault(key, {})[label_column] = target
+ said.setdefault(key, {})[label_column] = decision["label"]
+ if verb:
+ _place(case, decision, target, verb, at_point)
+ for url in decision.get("sources", ()):
+ cite_source(case, url, target, sources)
+
+ # The whole sidecar, not the links alone: a sheet also mentions the words a column
+ # promotion pointed at the case and the pieces its rows carry, and restating from
+ # half of it would take those edges down on every promotion.
+ sync_mentions(case, sheet_id, {**meta, "links": links})
+ return {
+ "links": links,
+ "promoted": said,
+ "plan": reading["rows"],
+ **reading["counts"],
+ }
+
+
+def _places_held(case: "Case") -> dict[tuple[float, float], str]:
+ """Every place the case holds, by its rounded point.
+
+ Read once per press and never per row, the same rule `_labels_held` states: this is a
+ walk of the whole catalog, and it runs inside the transaction that holds SQLite's write
+ lock.
+ """
+ return {
+ (round(float(entity["attrs"]["lat"]), 5), round(float(entity["attrs"]["lon"]), 5)): str(
+ entity["id"]
+ )
+ for entity in case.list_entities()
+ if entity.get("type") == PLACE_TYPE
+ and isinstance((entity.get("attrs") or {}).get("lat"), (int, float))
+ and isinstance((entity.get("attrs") or {}).get("lon"), (int, float))
+ }
+
+
+def _place(
+ case: "Case",
+ decision: dict[str, Any],
+ subject: str,
+ verb: str,
+ at_point: dict[tuple[float, float], str],
+) -> None:
+ """File the points a row wrote as places, and join the row's entity to them.
+
+ The other half of "one event, two lines": a cross-border strike is two rows because
+ it happened at two points, and the entity is one. Each distinct point becomes a place
+ and each place gets an edge, so the map draws both and the Graph shows one subject.
+
+ A point the case already holds is **joined rather than filed again**, matched on the
+ coordinates themselves rather than on a name: a place is the only entity in this app
+ whose identity is a number, and two pins a metre apart with different labels are the
+ duplicate nobody notices until the map is unreadable.
+
+ A relation the vocabulary refuses is skipped rather than raised, like a citation: the
+ place is still worth having, and taking the promotion down over an edge would lose
+ the rows that had nothing wrong with them.
+
+ The places a row ended up at are recorded back onto its decision. A place is the one
+ thing a promotion files that the sidecar cannot name — a cell holds the coordinates,
+ not the entity — so without this the only record of which place a row made would be
+ the edge itself, and a caller drawing a *second* edge to that place (a column of media
+ joined to the row's point) would have nothing to aim at.
+
+ *at_point* is the caller's index of the places the case holds, read once for the press
+ and added to here: a walk of the graph per row is what this used to cost.
+ """
+ filed: list[str] = decision.setdefault("places", [])
+ for point in decision.get("points") or ():
+ key = (round(point["lat"], 5), round(point["lon"], 5))
+ target = at_point.get(key)
+ if target is None:
+ made = case.add_entity(PLACE_TYPE, decision["label"], dict(point), by=BY)
+ target = str(made["id"])
+ at_point[key] = target
+ if target not in filed:
+ filed.append(target)
+ try:
+ link_engine.add_relation(case, subject, target, verb, by=BY)
+ except CaseError:
+ continue
+
+
+def urls_in(text: str) -> list[str]:
+ """Every http address a cell holds, in the order it holds them.
+
+ One reader for a column of sources, because two of them would disagree about where a
+ link ends the first time one sat inside a parenthesis.
+ """
+ return _URL.findall(str(text))
+
+
+def cite_source(
+ case: "Case",
+ url: str,
+ subject: str,
+ seen: dict[str, str],
+) -> None:
+ """File a link column's URL as a bookmark that mentions the row's entity.
+
+ A page in a worklist is a source, and a source the case can point at is worth more
+ than a string in a cell: it carries its own reliability and it is reachable from
+ the subject's side. Filed once per URL per promotion and matched against what the
+ case already holds, so a page cited by forty rows is one bookmark with forty edges.
+
+ A relation the vocabulary refuses is skipped rather than raised: the bookmark is
+ still worth having, and taking the promotion down over an edge would lose the rows
+ that had nothing wrong with them.
+ """
+ target = seen.get(url)
+ if target is None:
+ found = case.find_entity(attr=URL_ATTR, value=url)
+ if found is not None and found.get("type") == "bookmark":
+ target = found["id"]
+ else:
+ host = urlsplit(url).hostname or url
+ entity = case.add_entity(
+ "bookmark", host, {URL_ATTR: url, "site": host, "folder": ""}, by=BY
+ )
+ target = entity["id"]
+ seen[url] = target
+ try:
+ link_engine.add_relation(case, target, subject, link_engine.MENTIONS, by=BY)
+ except CaseError:
+ return
+
+
+# -- a whole column, and the words in it the case has no answer for -----------
+#
+# Creating and attaching are one question here, asked once per word: the case is asked
+# what it holds spelled exactly that way, one answer attaches, none creates, and two are
+# offered and never merged. They used to be two screens and two roads, which meant a pass
+# whose halves each knew half of the plan.
+#
+# The grain is the **word**, not the row, and that is the whole reason it works: a column
+# of four hundred rows holds forty pieces of equipment, so the case is asked forty
+# questions and forty entities come out, not four hundred. Which is also why what it
+# writes back is a vocabulary (`meta["values"]`) and not a link per cell: a cell reading
+# `Buk-M2E, ZU23-2, S-125` points at three things, and one cell cannot hold three links.
+
+
+def column_words(
+ columns: list[str], rows: list[list[str]], column: str, role: dict[str, Any] | None
+) -> list[dict[str, Any]]:
+ """The distinct words of one column, most-said first, with the rows saying each.
+
+ Split on the column's own separator, so a cell listing three pieces of equipment is
+ three words. Ordered by how many rows say them, because that is the order in which
+ somebody reads a plan they are about to press.
+ """
+ at = columns.index(column)
+ key_at = key_index(columns)
+ held: dict[str, dict[str, Any]] = {}
+ for row in rows:
+ identity = _key_of(row, key_at)
+ for word in sheetroles.split_values(row[at] if at < len(row) else "", role):
+ entry = held.setdefault(word, {"value": word, "keys": []})
+ if identity not in entry["keys"]:
+ entry["keys"].append(identity)
+ return sorted(held.values(), key=lambda entry: (-len(entry["keys"]), entry["value"]))
+
+
+def plan_column(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ column: str,
+ entity_type: str,
+ attach: dict[str, str] | None = None,
+ skip: list[str] | None = None,
+) -> dict[str, Any]:
+ """What promoting this column's words would do, word by word, without doing it.
+
+ Same five answers as a row promotion and the same rule underneath: **a name is not an
+ identity**. A word the case holds once is joined; a word it holds twice is offered and
+ left alone, because choosing between two units with one name is the analyst's
+ judgement and a route that picked would be the merge this app refuses everywhere.
+ """
+ if entity_type not in promotable_types():
+ raise SheetError(f"'{entity_type}' is not a type a column can become")
+ if entity_type == PLACE_TYPE:
+ raise SheetError("a place needs coordinates, so it is promoted from rows and not words")
+ if column not in columns:
+ raise SheetError(f"this sheet has no column '{column}'")
+
+ role = ((meta.get("roles") or {}) if isinstance(meta, dict) else {}).get(column)
+ words = column_words(columns, rows, column, role)
+ if len(words) > MAX_COLUMN_WORDS:
+ raise SheetError(
+ f"'{column}' holds {len(words)} different words; at most {MAX_COLUMN_WORDS} "
+ "can be promoted at once"
+ )
+ held = _Held(links={}, **_labels_held(case, entity_type))
+ meant = ((meta.get("values") or {}) if isinstance(meta, dict) else {}).get(column) or {}
+ left_out = set(skip or [])
+ chosen = attach or {}
+
+ planned: list[dict[str, Any]] = []
+ for entry in words:
+ word = entry["value"]
+ decision: dict[str, Any] = {
+ "key": word,
+ "value": word,
+ "label": word,
+ "keys": entry["keys"],
+ "rows": len(entry["keys"]),
+ "action": SKIP,
+ "reason": "",
+ "entity": None,
+ "entity_label": "",
+ "candidates": [],
+ }
+ planned.append(decision)
+ if word in left_out:
+ decision["reason"] = "left out"
+ continue
+
+ # What this word already means in this column, and only while the case still
+ # holds it as the type being promoted.
+ was = str(meant.get(word) or "")
+ already = case.get_entity(was) if was else None
+ if already is not None and already.get("type") == entity_type:
+ decision.update(
+ action=UPDATE,
+ entity=already["id"],
+ entity_label=str(already.get("label") or ""),
+ reason="already promoted from this column",
+ )
+ continue
+
+ picked = chosen.get(word)
+ if picked:
+ target = case.get_entity(picked)
+ if target is None or target.get("type") != entity_type:
+ decision.update(
+ action=ERROR, reason="the entity chosen for this word is gone"
+ )
+ continue
+ decision.update(
+ action=JOIN,
+ entity=target["id"],
+ entity_label=str(target.get("label") or ""),
+ reason="attached by hand",
+ )
+ continue
+
+ holders = held.holders.get(word.casefold(), [])
+ if len(holders) == 1:
+ decision.update(
+ action=JOIN,
+ entity=holders[0]["id"],
+ entity_label=holders[0]["label"],
+ reason="the case already holds this one",
+ )
+ continue
+ if holders:
+ decision["candidates"] = holders[:MAX_CANDIDATES]
+ decision["reason"] = f"the case holds {len(holders)} of this name"
+ continue
+
+ try:
+ entity_engine.check_attrs(entity_type, {})
+ except CaseError as exc: # pragma: no cover - no declared field is required
+ decision.update(action=ERROR, reason=str(exc))
+ continue
+ decision["action"] = MAKE
+
+ return {
+ "rows": planned,
+ "counts": counts_of(planned),
+ "type": entity_type,
+ "column": column,
+ "multi": bool((role or {}).get("multi")) if isinstance(role, dict) else False,
+ }
+
+
+def promote_column(
+ case: "Case",
+ sheet_id: str,
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ column: str,
+ entity_type: str,
+ attach: dict[str, str] | None = None,
+ skip: list[str] | None = None,
+) -> dict[str, Any]:
+ """Execute that plan: make what is missing, join what is not, and record the meaning.
+
+ Two things are written back, and they answer two different questions.
+ ``meta["values"][column]`` says **what a word means** — that is what makes a second
+ press an update, what keeps the sheet's `mentions` edges alive, and the only thing
+ that can be said at all about a cell holding three values.
+ ``meta["links"]`` says **what a row points at**, and it is written only for a column
+ with no separator: it is the one the computed natures read, and a row pointing at the
+ third of its three pieces of equipment would be an answer nobody could interpret.
+ A link the analyst made by hand is never overwritten.
+ """
+ reading = plan_column(
+ case,
+ columns=columns,
+ rows=rows,
+ meta=meta,
+ column=column,
+ entity_type=entity_type,
+ attach=attach,
+ skip=skip,
+ )
+ values = {name: dict(words) for name, words in (meta.get("values") or {}).items()}
+ links = {identity: dict(cells) for identity, cells in (meta.get("links") or {}).items()}
+ said = {identity: dict(cells) for identity, cells in (meta.get("promoted") or {}).items()}
+ meant = values.setdefault(column, {})
+
+ for decision in reading["rows"]:
+ target: str | None = decision["entity"]
+ if decision["action"] == MAKE:
+ entity = case.add_entity(entity_type, decision["value"], {}, by=BY)
+ target = entity["id"]
+ elif decision["action"] not in (JOIN, UPDATE):
+ continue
+ if not target:
+ continue
+ meant[decision["value"]] = target
+ if reading["multi"]:
+ continue
+ for key in decision["keys"]:
+ if links.get(key, {}).get(column):
+ continue
+ links.setdefault(key, {})[column] = target
+ said.setdefault(key, {})[column] = decision["value"]
+
+ sync_mentions(case, sheet_id, {**meta, "links": links, "values": values})
+ return {
+ "values": values,
+ "links": links,
+ "promoted": said,
+ "plan": reading["rows"],
+ **reading["counts"],
+ }
+
+
+# -- one row's column pointing at another row, as real edges ------------------
+
+
+#: The verbs a `row` column may become. Both run from the row to what it names, which is
+#: the direction the binders' own column read: a company's line names its brigade. Kept
+#: to two rather than opened to the whole vocabulary, because those two are what an order
+#: of battle is made of and a select of eighteen verbs is a select nobody reads.
+ROW_LINK_VERBS = ("part-of", "member-of")
+
+def _pair_allows(from_type: str, to_type: str, verb: str) -> None:
+ """The type-only half of `check_relation_target`, for a pair neither end of which has
+ been filed yet. Media kinds cannot be read off a type, so the press still validates
+ every resolved pair before it writes one."""
+ if verb not in {spec.type for spec in link_engine.pair_verbs(from_type, to_type)}:
+ raise CaseError(f"a {from_type} cannot be the subject of '{verb}' to a {to_type}")
+
+
+def plan_row_links(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ column: str,
+ verb: str,
+ coming: dict[str, dict[str, dict[str, str]]] | None = None,
+) -> dict[str, Any]:
+ """What turning this column of row names into edges would do, row by row.
+
+ The binders wrote an order of battle as text — a brigade listing its companies, each
+ company naming its brigade back — with a spreadsheet validation holding the names
+ together. That validation cannot survive a row moving and theirs had **already**
+ decayed to `#REF!`. Here it is neither text nor a validation: both rows are entities
+ the case holds, and what joins them is an edge the Graph already draws.
+
+ Which means both ends have to have been promoted first, and a row whose end has not
+ been is said rather than guessed at: there is no honest way to invent the entity a
+ name refers to at the moment an edge is being drawn to it.
+
+ First, not before: `coming` is one press telling this plan which rows the mode ahead
+ of it will have promoted (`engine/sheetpass.py`). An order of battle lands in a single
+ press, so a plan reading only the sidecar on disk would report every edge missing an
+ end and then watch the press draw them all. Neither end has an id yet in that case, so
+ the pair is checked on its types, which is all `pair_verbs` ever needed.
+ """
+ if verb not in ROW_LINK_VERBS:
+ raise SheetError(f"a row column cannot become '{verb}'")
+ if column not in columns:
+ raise SheetError(f"this sheet has no column '{column}'")
+ role = ((meta.get("roles") or {}) if isinstance(meta, dict) else {}).get(column) or {}
+ if role.get("kind") != "row":
+ raise SheetError(f"'{column}' is not a column of row names")
+
+ named = role.get("of")
+ if not isinstance(named, str) or named not in columns:
+ named = next((name for name in columns if name != columns[key_index(columns)]), "")
+ links = (meta.get("links") or {}) if isinstance(meta, dict) else {}
+ promised = (coming or {}).get(named, {}) if isinstance(named, str) else {}
+ targets = sheetroles.row_targets(columns, rows, column, role)
+ labels = {
+ _key_of(row, key_index(columns)): str(
+ row[columns.index(named)] if named in columns else ""
+ ).strip()
+ for row in rows
+ }
+
+ def _end(key: str) -> tuple[dict[str, Any] | None, str]:
+ """What this row designates: in the case already, or by the time the press is
+ through. The second answer says which of the two it was missing."""
+ found = str(links.get(key, {}).get(named) or "")
+ if found:
+ held = case.get_entity(found)
+ return held, ("" if held is not None else "gone")
+ return promised.get(key), ("" if key in promised else "missing")
+
+ planned: list[dict[str, Any]] = []
+ for identity, found in targets.items():
+ for word in found["missing"]:
+ planned.append({
+ "key": identity,
+ "label": labels.get(identity, identity),
+ "target": "",
+ "target_label": word,
+ "action": ERROR,
+ "reason": f"no single row is called '{word}'",
+ })
+ source, why_source = _end(identity)
+ for other in found["keys"]:
+ decision = {
+ "key": identity,
+ "label": labels.get(identity, identity),
+ "target": other,
+ "target_label": labels.get(other, other),
+ "action": SKIP,
+ "reason": "",
+ }
+ planned.append(decision)
+ target, why_target = _end(other)
+ if "missing" in (why_source, why_target):
+ which = (
+ decision["label"] if why_source == "missing" else decision["target_label"]
+ )
+ decision["reason"] = f"'{which}' is not in the case yet"
+ continue
+ if source is None or target is None:
+ decision["reason"] = "one of these two is gone from the case"
+ continue
+ try:
+ end = str(target.get("id") or "")
+ if end and source.get("id"):
+ link_engine.check_relation_target(case, source, end, verb)
+ else:
+ _pair_allows(str(source.get("type")), str(target.get("type")), verb)
+ except CaseError as exc:
+ decision.update(action=ERROR, reason=str(exc))
+ continue
+ decision["action"] = MAKE
+ return {"rows": planned, "counts": counts_of(planned), "verb": verb, "column": column}
+
+
+def promote_row_links(
+ case: "Case",
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ meta: dict[str, Any],
+ column: str,
+ verb: str,
+) -> dict[str, Any]:
+ """Draw the edges that plan describes.
+
+ Nothing is written to the sidecar: the edge lives in the graph, which is where a
+ relation belongs, and the cell keeps the words it always held. Re-pressing restates
+ the same edges, which `add_relation` already makes idempotent.
+ """
+ reading = plan_row_links(
+ case, columns=columns, rows=rows, meta=meta, column=column, verb=verb
+ )
+ links = (meta.get("links") or {}) if isinstance(meta, dict) else {}
+ named = ((meta.get("roles") or {}).get(column) or {}).get("of")
+ if not isinstance(named, str) or named not in columns:
+ named = next((name for name in columns if name != columns[key_index(columns)]), "")
+ drawn = 0
+ for decision in reading["rows"]:
+ if decision["action"] != MAKE:
+ continue
+ source = links.get(decision["key"], {}).get(named)
+ target = links.get(decision["target"], {}).get(named)
+ try:
+ link_engine.add_relation(case, source, target, verb, by=BY)
+ except CaseError as exc:
+ decision.update(action=ERROR, reason=str(exc))
+ continue
+ drawn += 1
+ return {"drawn": drawn, "plan": reading["rows"], **counts_of(reading["rows"])}
diff --git a/src/azimut/engine/sheetproofs.py b/src/azimut/engine/sheetproofs.py
new file mode 100644
index 0000000..d31a1e2
--- /dev/null
+++ b/src/azimut/engine/sheetproofs.py
@@ -0,0 +1,414 @@
+"""A geolocation index into proofs: the one road out of a sheet that fetches bytes.
+
+Every other road from a sheet is a reading of what the analyst typed. This one goes and
+gets the files two of the columns point at, so it is not a mode of the pass and never
+will be: the pass is one transaction because nothing in it touches the network, and a
+transaction held open across a hundred downloads would lock the case for minutes.
+
+**What a row states.** Three columns and a note: the footage that was filmed on the spot,
+the picture the geolocation was published as, the point, and what to call the result. What
+the row becomes depends on how much of that it holds:
+
+=============================== ===============================================
+the row holds what is written
+=============================== ===============================================
+coordinates alone a ``place``
+coordinates and a source the media, posed on that place
+coordinates, source and proof the whole constellation `engine/proofimport` writes
+a proof with no source refused: a geolocation nobody can check
+a source or a proof, no point refused: no geolocation without a point
+a proof with no title refused: a proof without a name is a file without one
+a proof whose name is taken refused: a name is also a filename
+=============================== ===============================================
+
+The fourth is stricter than importing one post by hand, which accepts a proof whose
+footage would not download and says so in a warning. Deliberate: a binder holds dozens of
+those and nobody re-reads them one by one, so a line without the video is a line nobody
+will ever verify.
+
+**Planned before it is pressed, and the plan downloads nothing.** Which is what makes it
+readable at all: the three refusals are decided from the cells, and the three "already
+there" answers are read off the case — a proof by the name it would be saved under, a
+media by the page it was downloaded from, a place by its point. So a second press knows
+it has nothing to fetch before it fetches anything.
+
+**A hundred rows a press**, against five hundred for the pass, because these are a hundred
+downloads. The door says how many are left over so the cap reads as a queue rather than a
+breakdown.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+
+from .. import layout
+from . import links as link_engine
+from . import satellite as satellite_engine
+from . import sheetroles
+from .sheetpromote import ERROR, JOIN, MAKE, SKIP, UPDATE, counts_of, urls_in
+from .proofimport import MAX_SOURCES
+from .sheets import SheetError, key_index
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: Provenance on everything this road files, so the graph says which press wrote it.
+BY = "sheet-proofs"
+
+#: How many rows one press may take. A fifth of `MAX_PROMOTED`, because each of these
+#: is a download rather than a row of arithmetic, and a press an analyst cannot watch to
+#: the end is a press they cannot cancel meaningfully either.
+MAX_ROWS = 100
+
+#: Which states are left out unless the analyst says otherwise. One word, and the one that
+#: means the row was looked at and dropped — a filter that hid anything more would be
+#: deciding for them.
+SKIPPED_STATES = ("ruled out",)
+
+#: What the media a row downloads means about the point, and it is a choice about the
+#: whole press: `located-at` says the camera was there, `depicts` says the frame shows it.
+POV_VERB = "located-at"
+SHOWS_VERB = "depicts"
+
+
+@dataclass(frozen=True)
+class _Build:
+ """A validated declaration: which column holds what, and how the press reads them."""
+
+ columns: list[str]
+ rows: list[list[str]]
+ keys: list[str]
+ key_at: int
+ title: str
+ source: str
+ proof: str
+ point: str
+ note: str
+ status: str
+ #: The states left out of this press, folded, empty when nothing is.
+ left_out: set[str]
+ pov: bool
+
+
+def read(
+ *,
+ columns: list[str],
+ rows: list[list[str]],
+ keys: list[str],
+ title: str,
+ source: str,
+ proof: str,
+ point: str,
+ note: str = "",
+ status: str = "",
+ skip_states: list[str] | None = None,
+ pov: bool = False,
+) -> _Build:
+ """Read one declaration, or refuse it at the door with the reason.
+
+ The cap is said here rather than in the press, and it says what is left: a limit that
+ only refuses reads as a fault, where the same limit naming the remainder reads as the
+ queue it is.
+ """
+ if len(keys) > MAX_ROWS:
+ left = len(keys) - MAX_ROWS
+ raise SheetError(
+ f"{MAX_ROWS} rows a press, because each one is a download. "
+ f"Send these and press again for the other {left}."
+ )
+ for name in (title, source, proof, point, note, status):
+ if name and name not in columns:
+ raise SheetError(f"this sheet has no column '{name}'")
+ if not point:
+ raise SheetError("a build needs the column holding the coordinates")
+ if not proof and not source:
+ raise SheetError("a build needs the column holding the addresses to fetch")
+ named = [name for name in (title, source, proof, point, note, status) if name]
+ if len(set(named)) != len(named):
+ raise SheetError("each column can only be one thing in a build")
+ return _Build(
+ columns=columns,
+ rows=rows,
+ keys=keys,
+ key_at=key_index(columns),
+ title=title,
+ source=source,
+ proof=proof,
+ point=point,
+ note=note,
+ status=status,
+ # `None` is "the analyst did not say", `[]` is "they said none" — two different
+ # answers, and folding them together is what makes a default impossible to undo.
+ left_out={
+ word.strip().casefold()
+ for word in (SKIPPED_STATES if skip_states is None else skip_states)
+ if word
+ },
+ pov=bool(pov),
+ )
+
+
+def proof_verb(pov: bool) -> str:
+ """The verb the material takes towards the point. The proof itself always `depicts`:
+ it was composed, never recorded anywhere, which is what the registry says too."""
+ return POV_VERB if pov else SHOWS_VERB
+
+
+# -- what one press would do ---------------------------------------------------
+
+
+def plan(case: "Case", **asked: Any) -> dict[str, Any]:
+ """Row by row, what a build would write, with nothing downloaded and nothing written.
+
+ Read by the screen the analyst confirms and by the press itself, so the two cannot
+ drift into two readings of the same rows. The same five words every other road in this
+ app answers in, which here mean: file it, it is already filed, refresh what it says,
+ leave it alone, or this row cannot be read.
+ """
+ reading = read(**asked)
+ wanted = set(reading.keys)
+ claimed = _Claimed()
+ planned: list[dict[str, Any]] = []
+ for row in reading.rows:
+ key = _key_of(row, reading.key_at)
+ if key not in wanted:
+ continue
+ planned.append(_decide(case, reading, row, key, claimed))
+ return {
+ "rows": planned,
+ "counts": counts_of(planned),
+ "pov": reading.pov,
+ "verb": proof_verb(reading.pov),
+ }
+
+
+class _Claimed:
+ """What earlier rows of this same press have taken, so the plan sees itself.
+
+ Two rows are two proofs, one proof, or a collision, and which one they are is not
+ something either row can answer alone:
+
+ - **the same published address** is one proof seen at two points. The binder's own
+ shape: a cross-border strike is two lines because it happened at two places, and
+ one picture was published about it. The second row adds its point to the material
+ rather than composing the picture a second time under another name.
+ - **the same name over two addresses** is a collision. A proof's name is its filename,
+ so the second would write over the first — refused, as the single-post import
+ refuses a name already taken. Read against the case as well as against the press
+ (`_decide`): a proof already standing under that name is as much in the way as one
+ two rows up, and the row cannot tell which of them it would have overwritten.
+ """
+
+ __slots__ = ("by_url", "by_name")
+
+ def __init__(self) -> None:
+ self.by_url: dict[str, str] = {}
+ self.by_name: set[str] = set()
+
+
+def _decide(
+ case: "Case", reading: _Build, row: list[str], key: str, claimed: _Claimed
+) -> dict[str, Any]:
+ title = _cell(row, reading.columns, reading.title).strip()
+ coords = _cell(row, reading.columns, reading.point).strip()
+ # Every address the cell holds, because a geolocation states one point and rests on
+ # whatever was shot at it: the photos, the clip, the second angle. There is no `+` in
+ # a spreadsheet, so a cell listing them is how a hundred rows say it. The published
+ # picture stays one: a row builds one proof, and two pictures would be two.
+ source_urls = urls_in(_cell(row, reading.columns, reading.source))[:MAX_SOURCES]
+ source_url = source_urls[0] if source_urls else ""
+ proof_url = _first_url(_cell(row, reading.columns, reading.proof))
+ state = _cell(row, reading.columns, reading.status).strip().casefold()
+ decision: dict[str, Any] = {
+ "key": key,
+ "action": SKIP,
+ "title": title,
+ "coords": coords,
+ "point": None,
+ "source_urls": source_urls,
+ #: The first of them, which is what the questions asked of one file ask about:
+ #: whether the row has any material at all, and what to name in a refusal.
+ "source_url": source_url,
+ "proof_url": proof_url,
+ "note": _cell(row, reading.columns, reading.note).strip(),
+ "writes": "",
+ "reason": "",
+ "entity": None,
+ "entity_label": "",
+ }
+
+ if reading.status and state and state in reading.left_out:
+ decision["reason"] = f"left out on its status: {state}"
+ return decision
+ if not coords and not source_url and not proof_url:
+ decision["reason"] = "nothing to build from"
+ return decision
+
+ point = sheetroles.parse_latlon(coords) if coords else None
+ if coords and point is None:
+ decision.update(action=ERROR, reason=f"'{coords}' is not a position Azimut can read")
+ return decision
+ if point is not None and point["out_of_bounds"]:
+ decision.update(action=ERROR, reason=f"'{coords}' is not a position on the earth")
+ return decision
+ if point is None:
+ decision.update(action=ERROR, reason="a geolocation needs a point")
+ return decision
+ decision["point"] = {"lat": point["lat"], "lon": point["lon"]}
+
+ if proof_url and not source_url:
+ decision.update(action=ERROR, reason="a proof needs the footage it was read from")
+ return decision
+ if proof_url and not title:
+ decision.update(action=ERROR, reason="a proof needs a name")
+ return decision
+
+ if proof_url:
+ name = layout.slugify(title, "Proof")
+ first = claimed.by_url.get(proof_url)
+ if first is not None:
+ # One picture, two points: the row above composes it, this one only says the
+ # material is seen here too. Filing the proof twice would put two exports of
+ # the same image in the case under two names.
+ decision.update(
+ action=JOIN,
+ entity_label=first,
+ writes="its point, on the proof the row above builds",
+ reason=f"the same published proof as '{first}': only its point is added",
+ )
+ return decision
+ if name in claimed.by_name:
+ decision.update(
+ action=ERROR, reason=f"another row of this press is already called '{name}'"
+ )
+ return decision
+ claimed.by_url[proof_url] = name
+ claimed.by_name.add(name)
+ # By where it was published, and by that alone. The name is a cell somebody edits,
+ # so a corrected title still finds its own proof — but a name another proof already
+ # holds is a **collision**, whatever that proof was made from, exactly as the
+ # single-post import reads it (`engine/proofimport.blocking`). Read on the name as
+ # well, this wrote a row's single point over a composition it had nothing to do
+ # with: a proof states one point, so `state_points` replaced the list, and a
+ # geolocation concluding on three impacts and a camera came back as one address
+ # nobody had typed. The rule `_Claimed` states between two rows of a press holds
+ # against the case too, and this is where.
+ held = built_proof(case, proof_url)
+ taken = case.find_entity(attr="spec", value=layout.proof_spec_rel(name))
+ decision["writes"] = "a proof, its two files and its point"
+ if taken is not None and (held is None or taken["id"] != held["id"]):
+ decision.update(action=ERROR, reason=f"another proof is already called '{name}'")
+ return decision
+ if held is not None:
+ built_as = str(held.get("label") or name)
+ decision.update(
+ action=UPDATE,
+ entity=held["id"],
+ entity_label=built_as,
+ reason=(
+ f"already built as '{built_as}': renamed, and its point and note refreshed"
+ if built_as != name
+ else "already built: its point and its note are refreshed"
+ ),
+ )
+ else:
+ decision["action"] = MAKE
+ return decision
+
+ if source_urls:
+ decision["writes"] = (
+ "the footage, posed on its point"
+ if len(source_urls) == 1
+ else f"{len(source_urls)} files, posed on one point"
+ )
+ # All of them or none: a row half-downloaded is a row to run, and calling it
+ # "already there" on the strength of its first address would leave the rest out.
+ downloaded = [held_media(case, one) for one in source_urls]
+ leading = downloaded[0]
+ if leading is not None and all(one is not None for one in downloaded):
+ decision.update(
+ action=JOIN,
+ entity=leading["id"],
+ entity_label=str(leading.get("label") or ""),
+ reason="already downloaded: only its point is restated",
+ )
+ else:
+ decision["action"] = MAKE
+ return decision
+
+ decision["writes"] = "a place"
+ standing = satellite_engine.place_at(case, point["lat"], point["lon"], keyed_only=False)
+ if standing is not None:
+ decision.update(
+ action=JOIN,
+ entity=standing["id"],
+ entity_label=str(standing.get("label") or ""),
+ reason="this point is already in the case",
+ )
+ else:
+ decision["action"] = MAKE
+ return decision
+
+
+#: The types that mean "the app already fetched this address". A `bookmark` records a page
+#: rather than a file, and a `post` is a different thing to have of it — reading either as
+#: the footage would leave the row believing it holds a video it never downloaded.
+FETCHED_TYPES = ("media", "capture")
+
+
+def built_proof(case: "Case", proof_url: str) -> dict[str, Any] | None:
+ """The proof already built from this published address, whatever it is called now.
+
+ **A built proof is identified by where it was published, not by its name.** The name
+ is a cell an analyst edits, and keying on it makes a corrected title a second proof
+ rather than a rename — and, worse, makes two rows publishing *one* picture under two
+ titles two separate proofs of the same image.
+
+ Read off the panel: the picture was downloaded from that address and records it
+ (`attrs.source_url`), and the proof is what composes it.
+ """
+ panel = held_media(case, proof_url)
+ if panel is None:
+ return None
+ for link in case.links_of(panel["id"]):
+ if link["to"] != panel["id"] or link["type"] != link_engine.DERIVED_FROM:
+ continue
+ composing = case.get_entity(link["from"])
+ if composing is not None and composing.get("type") == "proof":
+ return composing
+ return None
+
+
+def held_media(case: "Case", url: str) -> dict[str, Any] | None:
+ """The file the case already downloaded from this address, or None.
+
+ What makes a second press cost nothing: the page a download came from is recorded on
+ the file (`attrs.source_url`), so the question "do we already have this" is asked of
+ the case rather than of the network.
+ """
+ found = case.find_entity(attr="source_url", value=url)
+ return found if found is not None and found.get("type") in FETCHED_TYPES else None
+
+
+#: The three answers that mean the press has work to do on this row.
+DOING = (MAKE, JOIN, UPDATE)
+
+
+def _key_of(row: list[str], at: int) -> str:
+ return row[at] if at < len(row) else ""
+
+
+def _cell(row: list[str], columns: list[str], name: str) -> str:
+ if not name or name not in columns:
+ return ""
+ at = columns.index(name)
+ return str(row[at]) if at < len(row) else ""
+
+
+def _first_url(text: str) -> str:
+ """The first address a cell holds. A cell of a `url` column may hold a sentence around
+ it, and which of two addresses is the footage is not a question a hundred rows can be
+ asked — so the first one, the way `urls_in` reads a column of sources."""
+ found = urls_in(text)
+ return found[0] if found else ""
diff --git a/src/azimut/engine/sheetroles.py b/src/azimut/engine/sheetroles.py
new file mode 100644
index 0000000..7342704
--- /dev/null
+++ b/src/azimut/engine/sheetroles.py
@@ -0,0 +1,1011 @@
+"""What the server has to know about a sheet's column roles.
+
+The browser owns reading a role — the chips, the badges, the sort — because that is
+presentation, and `lib/sheetRoles.js` is where it lives. This module is the other half:
+the two things a role does that **only the server can do**, plus the vocabulary both
+sides have to agree on.
+
+Those two things are the columns the app fills in rather than the analyst:
+
+``stamped``
+ The date a row first appeared. Written once, into a cell that is still empty, and
+ never touched again. It has to be here because the browser's clock is not the
+ case's, and because a row that arrives by import has no browser behind it.
+
+``computed``
+ What the case knows about the row, restated on every read and every save.
+ ``has_point`` asks whether the entity this row points at can be put on a map;
+ ``point`` and ``relations`` answer with what the case actually holds about it, the
+ coordinates and the far end of its edges. All three need the graph, so none of them
+ can be answered in a tab holding only a table.
+
+Both are **written into the CSV**, not kept beside it. That is deliberate and it is the
+one place a role touches the file: `On map: YES/NO` is precisely the column a
+collaborator opening the spreadsheet reads, and keeping it in the sidecar would make it
+vanish at the moment the file is handed over.
+
+The rest of what this module owns is arithmetic no side could do alone: an **offset**
+read as seconds from a named anchor, which is what turns ten videos lined up on one shot
+into ten absolute times the moment somebody dates that shot.
+
+The role *vocabulary* is declared twice, once per side, and a test compares the two
+lists (`tests/test_sheets.py`). One shared list in one language would mean the browser
+fetching its own vocabulary before it could draw a chip.
+"""
+
+from __future__ import annotations
+
+import re
+from datetime import UTC, datetime, timedelta
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: Every role a column may hold. Mirrors `lib/sheetRoles.ROLE_KINDS`. ``url`` is the
+#: column a promotion files as sources, ``row`` points at another row of the same
+#: sheet, ``offset`` carries a time relative to a named anchor.
+#:
+#: ``locked`` is the odd one and the newest: a column whose text the **app** owns and
+#: the analyst reads. It exists because a sheet built out of the case is a view of the
+#: case, and a view somebody can type over is a view that starts lying the first time
+#: they do. Unlike `stamped` and `computed` it carries a **link** — the whole point of
+#: those columns is that the cell opens the entity — so `linkable()` admits it where it
+#: refuses every other role.
+ROLE_KINDS = (
+ "state",
+ "choice",
+ "boolean",
+ "number",
+ "latlon",
+ "when",
+ "picture",
+ "url",
+ "row",
+ "offset",
+ "stamped",
+ "computed",
+ "locked",
+)
+
+#: The state vocabulary a column starts with, in order. Mirrors
+#: `lib/sheetRoles.STATE_DEFAULTS`. The order *is* the ranking the sort reads.
+STATE_DEFAULTS = ("to do", "in progress", "done", "ruled out")
+
+#: And the colour each of those four is painted, so a worklist reads at a glance before it
+#: reads row by row. Mirrors `lib/sheetRoles.STATE_COLOURS`. Seeded at birth like the
+#: words, and under them: what a role declares wins, so a colour cleared stays cleared.
+STATE_COLOURS = {
+ "to do": "grey",
+ "in progress": "blue",
+ "done": "green",
+ "ruled out": "red",
+}
+
+#: The two words a boolean column starts with, yes first, so the sort puts what is true
+#: above what is not. Mirrors `lib/sheetRoles.BOOLEAN_DEFAULTS`. The same pair a computed
+#: column writes, so a file holds one spelling of yes whichever side filled it.
+BOOLEAN_DEFAULTS = ("YES", "NO")
+
+#: The three things a ``when`` column can hold, which are the three the binders write.
+#: Mirrors `lib/sheetRoles.WHEN_SHAPES`. Declared rather than inferred, so a column that is
+#: still empty can be told it holds times.
+WHEN_SHAPES = ("date", "time", "datetime")
+
+#: What a computed column may hold. Mirrors `lib/sheetRoles.COMPUTED_NATURES`.
+#:
+#: ``has_point``
+#: Whether what the row points at can be put on a map. Needs the graph.
+#: ``filled_of``
+#: How many of the chosen columns this row has an answer in. The reading a
+#: comparison grid is built for: eleven candidates against six criteria, and the
+#: question is which rows are actually finished.
+#: ``yes_of``
+#: How many of the chosen columns say yes. The score of that same grid.
+#: ``point``
+#: Where the case puts what one column's cell points at, as ``lat, lon``.
+#: ``relations``
+#: What the case has joined that same entity to, as the labels at the far end.
+#: ``in_case``
+#: Whether the case still holds the entity this row was **built from**. Reads
+#: ``built`` rather than ``links``, and that is the difference that makes it work: a
+#: link to a deleted entity is swept on the next read, so by the time anyone asks,
+#: the cell that would have answered is already blank. The row that has lost its
+#: proof is exactly the row worth finding, and this is the column that finds it.
+#:
+#: The two counting ones are arithmetic over the row's own cells, so they could have been
+#: read in the browser — they are here because a computed column is **written into the
+#: CSV**, and the collaborator who opens the file is owed the number, not an empty column.
+#:
+#: The last two answer a different question from `has_point`, and it is the one that was
+#: asked at the desk: a column pointed at the case says *that* the case knows the subject
+#: and nothing about *what* it knows, so the coordinates and the parent unit went on being
+#: copied by hand into the next column along. One hop, like `has_point`: the relations of
+#: the relations answer a question nobody put.
+COMPUTED_NATURES = ("has_point", "filled_of", "yes_of", "point", "relations", "in_case")
+
+#: The natures that count over a chosen set of columns rather than asking the graph.
+COUNTING_NATURES = ("filled_of", "yes_of")
+
+#: The natures that read one column's link and restate what the case holds at the end of
+#: it. They take ``from``, which is the column whose cell points somewhere.
+LINKED_NATURES = ("point", "relations")
+
+#: What a yes looks like in a column nobody has declared a yes/no column. Mirrors
+#: `lib/sheetRoles.YES_WORDS`: a declared column's own first value wins over this, and
+#: this is what answers for the rest — a tick column drawn by hand holds `x`.
+YES_WORDS = ("yes", "y", "true", "oui", "x", "1", "ok", "done")
+
+#: How many columns one counting nature may be told to read. A score over sixty columns
+#: is not a score, and the bound keeps a save linear in the table.
+MAX_COUNTED_COLUMNS = 24
+
+#: The one answer a number column's footer gives. Mirrors `lib/sheetRoles.NUMBER_SUMMARIES`.
+#: Asked rather than assumed: a total is what a column of counts wants and nonsense on a
+#: column of percentages.
+NUMBER_SUMMARIES = ("none", "count", "sum", "mean", "range")
+
+#: How long a unit may be. `%`, `€`, `km`, `rounds` — a label, not a sentence.
+MAX_UNIT = 8
+
+#: The colours a value's chip may be painted, which are the row colours. Mirrors
+#: `engine/sheets.ROW_COLOURS` — imported rather than restated, because a second copy on
+#: this side is the one that would go wrong.
+def _row_colours() -> tuple[str, ...]:
+ from .sheets import ROW_COLOURS
+
+ return ROW_COLOURS
+
+#: Words a computed column writes. The binders' own, in a spreadsheet's own casing, so
+#: a filter set up on the old file still matches the new one.
+COMPUTED_YES = "YES"
+COMPUTED_NO = "NO"
+
+#: How many values a vocabulary may hold. Mirrors the browser's own bound on the values
+#: a filter menu offers.
+MAX_ROLE_VALUES = 40
+
+#: How long a synchronisation anchor may be named. `IGLA launch`, `second impact` — the
+#: name is read in a heading and in a Claim's reasoning, so it is a phrase, not a note.
+MAX_ANCHOR_NAME = 60
+
+#: How many anchors one sheet may declare. An event has a handful of moments several
+#: videos can all be lined up on; past that the sheet is a transcript.
+MAX_ANCHORS = 12
+
+#: How many values one ``relations`` cell writes out. The far end of an entity's edges is
+#: a reading, not a dump: a subject joined to sixty things says nothing in a cell, and the
+#: Graph is where that is looked at.
+MAX_RELATION_VALUES = 8
+
+#: What a ``relations`` cell separates its values with when the column says nothing.
+#: The binders' own, and what a spreadsheet's own concatenation produces.
+DEFAULT_SEPARATOR = ", "
+
+#: Verbs that put their holder at a place: a recording where it was made, a structure
+#: at its site, a statement at the place it is about. All three run *towards* the place,
+#: so the holder is the ``from`` side.
+PLACED_BY = ("located-at", "sited-at", "at")
+
+#: What a statement is about. A subject with no point of its own is on the map when a
+#: dated statement places it — which is how this ontology positions a vehicle or a
+#: unit, since `located-at` is for collected media and `sited-at` for structures. The
+#: walk stops there: two hops answers "this is placed", three would answer "something
+#: near this is placed", which is not what the column says.
+ABOUT = "about"
+
+#: Edges a ``relations`` column does not restate. A chain edge says how a file was
+#: produced rather than what the case joined; a `mentions` from the sheet itself would
+#: make the column answer with the sheet the analyst is reading.
+NOT_A_RELATION = ("derived-from", "depends-on", "mentions")
+
+
+def clean_role(role: Any, columns: list[str] | None = None) -> dict[str, Any] | None:
+ """One column's role, reduced to the fields its kind uses, or None.
+
+ Fields a kind does not use are dropped rather than carried: a column that was a
+ ``choice`` and became a ``when`` would otherwise keep a vocabulary nobody reads.
+
+ ``columns`` is the table's own headings, and it is only read by the counting
+ natures: a score told to read a column that has since been renamed must lose it,
+ the same way a role loses its own column.
+ """
+ if not isinstance(role, dict) or role.get("kind") not in ROLE_KINDS:
+ return None
+ kind = str(role["kind"])
+ clean: dict[str, Any] = {"kind": kind}
+ if kind in ("state", "choice", "boolean"):
+ raw = role.get("values")
+ values: list[str] = []
+ if isinstance(raw, list):
+ for value in raw:
+ text = str(value)
+ if text and text not in values:
+ values.append(text)
+ clean["values"] = values[:MAX_ROLE_VALUES]
+ # A state column nobody has said anything about is born with the four words and
+ # the four colours together: painting four chips by hand is what a default is for.
+ born = kind == "state" and not clean["values"]
+ if born:
+ clean["values"] = list(STATE_DEFAULTS)
+ # Exactly two: that is what makes one click a toggle rather than a menu.
+ if kind == "boolean":
+ clean["values"] = clean["values"][:2]
+ while len(clean["values"]) < 2:
+ clean["values"].append(BOOLEAN_DEFAULTS[len(clean["values"])])
+ # How the grid draws the cell, and nothing more. A tick column is a yes/no
+ # column: the file holds the same two words, so the CSV a collaborator opens
+ # reads the same whether the grid drew chips or boxes.
+ clean["tick"] = bool(role.get("tick"))
+ # A colour per value, kept apart from the values: a value is what a cell is
+ # matched against, so it stays exactly the word the file holds. What the role says
+ # wins over the birth colours, value by value: a colour can be changed and a
+ # colour can be removed.
+ colours = role.get("colours")
+ asked = dict(STATE_COLOURS) if born else {}
+ if isinstance(colours, dict):
+ asked.update(colours)
+ clean["colours"] = {
+ str(value): str(colour)
+ for value, colour in asked.items()
+ if value in clean["values"] and colour in _row_colours()
+ }
+ if kind == "choice":
+ # A separator or nothing. Reading `2x S-125` as two of `S-125` was stored here
+ # too and is gone: it kept a count in a column of values, and a count belongs in
+ # a number column beside a column naming what is counted.
+ multi = role.get("multi")
+ clean["multi"] = multi if isinstance(multi, str) and multi else None
+ if kind == "number":
+ # What follows the number when it is written out — `%`, `€`, `km`. A unit rather
+ # than a list of formats: a percentage and a currency differ by the sign after
+ # the digits.
+ unit = role.get("unit")
+ clean["unit"] = str(unit).strip()[:MAX_UNIT] if isinstance(unit, str) else ""
+ # Whether it is written after every cell as well as beside the heading. Asked
+ # rather than assumed: `40 %` reads as the value on a column of shares, and a
+ # column of distances repeated four hundred times reads as noise.
+ clean["unitInCells"] = bool(role.get("unitInCells"))
+ summary = role.get("summary")
+ clean["summary"] = summary if summary in NUMBER_SUMMARIES else "sum"
+ # A `whole` flag was stored here and read by nothing — no rounding, no editor
+ # step, no footer. Dropped rather than finished, like the time zone below.
+ if kind == "when":
+ shape = role.get("shape")
+ clean["shape"] = shape if shape in WHEN_SHAPES else WHEN_SHAPES[0]
+ # A time zone was stored here and read by nothing: the file keeps the words, so a
+ # date is never converted, and a field the sidecar carried without anyone acting
+ # on it was a setting that appeared to do something. Dropped rather than finished.
+ # Which number a slash date leads with. Guessing silently reverses twelve days
+ # a month, and the binders read `dd/MM/yyyy`, so it is stated, not inferred.
+ clean["dayFirst"] = True if role.get("dayFirst") is None else bool(role["dayFirst"])
+ if kind == "row":
+ # Which column's words name the other row. The binders wrote `Links with others`
+ # holding unit names, so the pointer is the **word a reader recognises** and not a
+ # key: a file whose links read `r7f3a` is a file the collaborator cannot follow,
+ # and the validation that held those names is the one already broken to `#REF!`.
+ target = role.get("of")
+ known = columns is None or (isinstance(target, str) and target in columns)
+ clean["of"] = str(target) if isinstance(target, str) and target and known else None
+ # A brigade lists several companies, so a cell holds several names by default.
+ multi = role.get("multi")
+ clean["multi"] = multi if isinstance(multi, str) and multi else None
+ if kind == "offset":
+ # Which anchor the cell is counted from. One column per anchor and no syntax in
+ # the cell: the binders already held `start synchro` *and* `end synchro`, so a
+ # single anchor per sheet would not have survived the first real event. Named
+ # rather than validated against the sidecar here — an anchor may be declared on a
+ # column before anyone has dated it, which is the whole point of relative order.
+ anchor = role.get("anchor")
+ clean["anchor"] = str(anchor).strip()[:MAX_ANCHOR_NAME] if isinstance(anchor, str) else ""
+ if kind == "computed":
+ of = role.get("of")
+ clean["of"] = of if of in COMPUTED_NATURES else COMPUTED_NATURES[0]
+ if clean["of"] in COUNTING_NATURES:
+ # Which columns it counts. Kept in the order the analyst chose them: the
+ # number does not depend on it, but the panel lists them back and a list
+ # that reshuffles itself reads as a different answer.
+ raw = role.get("columns")
+ counted: list[str] = []
+ if isinstance(raw, list):
+ for name in raw:
+ text = str(name)
+ known = columns is None or text in columns
+ if text and known and text not in counted:
+ counted.append(text)
+ clean["columns"] = counted[:MAX_COUNTED_COLUMNS]
+ if clean["of"] in LINKED_NATURES:
+ # Which column's link it follows. Named rather than swept, because a sheet
+ # may point at the case from more than one column — a subject and a place —
+ # and a nature reading "whatever this row points at" would answer about
+ # whichever of them the walk reached first.
+ source = role.get("from")
+ known = columns is None or (isinstance(source, str) and source in columns)
+ clean["from"] = str(source) if isinstance(source, str) and source and known else None
+ if clean["of"] == "relations":
+ multi = role.get("multi")
+ clean["multi"] = (
+ multi if isinstance(multi, str) and multi else DEFAULT_SEPARATOR
+ )
+ return clean
+
+
+def clean_roles(roles: Any, columns: list[str]) -> dict[str, Any]:
+ """Every role a sheet declares, dropped where its column is gone."""
+ if not isinstance(roles, dict):
+ return {}
+ known = set(columns)
+ kept: dict[str, Any] = {}
+ for column, role in roles.items():
+ clean = clean_role(role, columns)
+ if clean is not None and column in known:
+ kept[str(column)] = clean
+ return kept
+
+
+# -- reading a point out of a cell --------------------------------------------
+#
+# The browser reads points too (`lib/sheetRoles.parseLatLon`) and for the same three
+# shapes, because it draws the badge that says how precise a cell is. This copy exists
+# because **promotion writes to the graph**: a place minted from a cell the server never
+# read would be a point the case believes on the browser's word alone.
+
+_DECIMAL_PAIR = re.compile(
+ r"^\s*([+-]?\d{1,3}(?:[.,]\d+)?)\s*°?\s*([NnSs])?"
+ r"(\s*[,;/]\s*|\s+)"
+ r"([+-]?\d{1,3}(?:[.,]\d+)?)\s*°?\s*([EeWw])?\s*$"
+)
+_DMS = re.compile(r"(\d{1,3})\s*°\s*(\d{1,2})?\s*['′]?\s*([\d.]+)?\s*[\"″]?\s*([NnSsEeWw])")
+
+#: One degree of latitude, in metres. The last decimal a cell was written to is how
+#: precisely whoever wrote it was claiming to know the ground.
+DEGREE_M = 111_320
+
+
+def _decimals(text: str) -> int:
+ body = str(text).replace(",", ".")
+ at = body.find(".")
+ return 0 if at == -1 else len(body) - at - 1
+
+
+def _signed(value: str, hemisphere: str | None, negatives: str) -> float:
+ """The number a cell wrote, negated when its hemisphere says south or west.
+
+ The membership test is on a *list* rather than a string: `"" in "S"` is true, so a
+ pair written without hemispheres — which is most of them — came out mirrored into
+ the wrong hemisphere.
+ """
+ number = float(str(value).replace(",", "."))
+ letter = str(hemisphere or "").upper()
+ return -abs(number) if letter and letter in list(negatives) else number
+
+
+def parse_latlon(text: Any) -> dict[str, Any] | None:
+ """A cell read as a point, or None. Mirrors `lib/sheetRoles.parseLatLon`.
+
+ Three shapes, because one binder column held all three: `48.8566, 2.3522`,
+ `48.8566N 2.3522E`, and `48°51'24"N 2°21'08"E`.
+
+ ``decimals`` is how precisely the cell was written, which is a claim about the
+ ground rather than a detail of formatting: two decimals is about a kilometre.
+ ``out_of_bounds`` is reported rather than refused here — the caller decides, and a
+ transposed pair is a finding about the file.
+
+ **A comma is a decimal mark.** That is the app's one reading of a comma in a number
+ (`sheetpromote._NUMBER_NOISE` reads it the same way), so `48,8` is one number and not
+ two coordinates. It separates a pair only where it cannot be decimal: a space after it,
+ a hemisphere letter, or a full stop already doing the job.
+ """
+ body = str(text or "").strip()
+ if not body:
+ return None
+
+ pair = _DECIMAL_PAIR.match(body)
+ if pair:
+ raw_lat, lat_hem, separator, raw_lon, lon_hem = pair.groups()
+ if separator == "," and "." not in body and not (lat_hem or lon_hem):
+ return None
+ try:
+ lat = _signed(raw_lat, lat_hem, "S")
+ lon = _signed(raw_lon, lon_hem, "W")
+ except ValueError:
+ return None
+ return {
+ "lat": lat,
+ "lon": lon,
+ "decimals": min(_decimals(raw_lat), _decimals(raw_lon)),
+ "out_of_bounds": abs(lat) > 90 or abs(lon) > 180,
+ }
+
+ parts = _DMS.findall(body)
+ if len(parts) == 2:
+ read: list[tuple[str, float]] = []
+ for deg, minute, second, hem in parts:
+ value = float(deg) + float(minute or 0) / 60 + float(second or 0) / 3600
+ read.append((hem.upper(), _signed(str(value), hem, "SW")))
+ north = next((value for hem, value in read if hem in "NS"), None)
+ east = next((value for hem, value in read if hem in "EW"), None)
+ if north is None or east is None:
+ return None
+ # Seconds resolve to about thirty metres, which is five decimal places of
+ # confidence the writer did not claim; four is the honest reading.
+ return {
+ "lat": north,
+ "lon": east,
+ "decimals": 4,
+ "out_of_bounds": abs(north) > 90 or abs(east) > 180,
+ }
+ return None
+
+
+def precision_metres(places: int) -> int:
+ """About how far apart two points written to this many decimals could be."""
+ return round(DEGREE_M * 10 ** -max(0, int(places)))
+
+
+# -- offsets, and the anchor they are counted from ----------------------------
+#
+# The binders held `start synchro` and `end synchro` in `-00:01:50` / `00:04:04`: ten
+# videos lined up on one shot that is visible and audible in all of them. The relative
+# order is usable straight away; the moment the anchor gets a time, every one of those
+# videos has an absolute time to the second. Mirrors `lib/sheetRoles.parseOffset`.
+
+_OFFSET = re.compile(r"^([+-]?)(?:(\d+):)?(\d{1,3}):(\d{2})(?:[.,](\d{1,3}))?$")
+_BARE_SECONDS = re.compile(r"^([+-]?)(\d{1,5})(?:[.,](\d{1,3}))?\s*s?$", re.IGNORECASE)
+
+
+def parse_offset(text: Any) -> float | None:
+ """A cell read as seconds away from an anchor, or None.
+
+ `-00:01:50`, `00:04:04`, `1:05` and a bare `-110` — the four spellings a video
+ player and a spreadsheet between them produce. Negative means *before* the anchor,
+ which is what the binders' leading minus already meant.
+ """
+ body = str(text or "").strip()
+ if not body:
+ return None
+ match = _OFFSET.match(body)
+ if match:
+ sign, hours, minutes, seconds, fraction = match.groups()
+ if int(seconds) > 59 or (hours is not None and int(minutes) > 59):
+ return None
+ total = int(hours or 0) * 3600 + int(minutes) * 60 + int(seconds)
+ value = total + (float(f"0.{fraction}") if fraction else 0.0)
+ return -value if sign == "-" else value
+ bare = _BARE_SECONDS.match(body)
+ if bare:
+ sign, seconds, fraction = bare.groups()
+ value = int(seconds) + (float(f"0.{fraction}") if fraction else 0.0)
+ return -value if sign == "-" else value
+ return None
+
+
+def format_offset(seconds: float) -> str:
+ """Seconds written back the way the binders write them, `-00:01:50`.
+
+ One spelling out, several in: what the analyst typed stays in the cell, and this is
+ only for the reasoning a Claim carries, where the offset has to be quoted.
+ """
+ sign = "-" if seconds < 0 else ""
+ whole = int(abs(seconds))
+ return f"{sign}{whole // 3600:02d}:{whole % 3600 // 60:02d}:{whole % 60:02d}"
+
+
+_TIMESTAMP = re.compile(r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:\d{2})?$")
+
+
+def clean_anchor_at(text: Any) -> str:
+ """An anchor's own time, normalised to a UTC timestamp, or empty.
+
+ A **timestamp**, never a bare date: an anchor exists so ten videos can be given an
+ absolute time to the second, and a date silently read as midnight would hand every
+ one of them a moment nobody claimed. Empty is a real state and the common one — a
+ shot is named and lined up long before anyone works out when it happened.
+ """
+ body = str(text or "").strip()
+ if not body or not _TIMESTAMP.match(body):
+ return ""
+ return offset_moment(body, 0) or ""
+
+
+def offset_moment(anchor_at: str, seconds: float) -> str | None:
+ """The absolute instant an offset lands on, as the timestamp a Claim stores.
+
+ The anchor's own time is what `engine/temporal` calls an instant, so this stays
+ inside that profile: a UTC timestamp written to the second, which is the precision
+ a synchronised video actually supports.
+
+ None when the anchor has no time yet, which is a normal state rather than an error:
+ relative order is worth having before anybody has dated the shot.
+ """
+ body = str(anchor_at or "").strip()
+ if not body:
+ return None
+ try:
+ moment = datetime.fromisoformat(body.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if moment.tzinfo is None:
+ moment = moment.replace(tzinfo=UTC)
+ shifted = moment.astimezone(UTC) + timedelta(seconds=round(seconds))
+ return shifted.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+# -- dates and times ----------------------------------------------------------
+#
+# The browser reads these too (`lib/sheetRoles.parseWhen`) because it sorts by them and
+# offers a picker in the column's own spelling. This copy exists for the same reason
+# `parse_latlon` has one: **promotion writes to the graph**, and a Claim dated on the
+# browser's reading of a cell would be a moment the case believes on the browser's word.
+
+_CLOCK = re.compile(r"^(\d{1,2}):(\d{2})(?::(\d{2}))?$")
+_SLASH = re.compile(
+ r"^(\d{1,4})[/.\-](\d{1,2})[/.\-](\d{2,4})(?:[ T]+(\d{1,2}):(\d{2})(?::(\d{2}))?)?$"
+)
+_RFC = re.compile(
+ r"^(?:\w{3},\s*)?(\d{1,2})\s+(\w{3})\w*\s+(\d{4})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?",
+ re.IGNORECASE,
+)
+_MONTHS = ("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec")
+
+
+def _clock(hour: Any, minute: Any, second: Any) -> str:
+ return f"{int(hour or 0):02d}:{int(minute or 0):02d}:{int(second or 0):02d}"
+
+
+def _holds(hour: Any, minute: Any, second: Any) -> bool:
+ """Whether this is a time of day rather than one that rolls into the next.
+
+ Stated once because both shapes need it — a bare clock and a date carrying one — and
+ the browser's mirror asks the same question in `lib/sheetRoles.clockHolds`.
+ """
+ return int(hour or 0) <= 23 and int(minute or 0) <= 59 and int(second or 0) <= 59
+
+
+def parse_when(text: Any, role: dict[str, Any] | None = None) -> dict[str, Any] | None:
+ """A cell read as a moment, or None. Mirrors `lib/sheetRoles.parseWhen`.
+
+ Everything the three binders wrote: `dd/MM/yyyy`, `yyyy-MM-dd`, a bare `hh:mm`,
+ either of the first two with a time appended, and the full RFC form an email header
+ carries.
+
+ A bare clock stays a **time of day** rather than being pinned to some invented date:
+ the binders' `Local time` column holds `01:57` for an event whose date lives in the
+ sheet's title, and giving it a date here would be inventing evidence. ``shape`` says
+ which of the two a reading is, and what a Claim does about the missing date is
+ `claim_moment`'s business, out loud.
+ """
+ body = str(text or "").strip()
+ if not body:
+ return None
+ day_first = True if (role or {}).get("dayFirst") is None else bool((role or {})["dayFirst"])
+
+ clock = _CLOCK.match(body)
+ if clock:
+ hour, minute, second = (int(part or 0) for part in clock.groups())
+ if not _holds(hour, minute, second):
+ return None
+ return {
+ "shape": "time",
+ "date": "",
+ "clock": _clock(hour, minute, second),
+ "text": f"{hour:02d}:{minute:02d}",
+ }
+
+ rfc = _RFC.match(body)
+ if rfc and rfc.group(2).lower()[:3] in _MONTHS:
+ month = _MONTHS.index(rfc.group(2).lower()[:3]) + 1
+ return _moment(int(rfc.group(3)), month, int(rfc.group(1)), *rfc.groups()[3:])
+
+ slash = _SLASH.match(body)
+ if slash:
+ one, two, three = slash.group(1), slash.group(2), slash.group(3)
+ # A four-digit leading group can only be a year, whatever the column's convention.
+ isoish = len(one) == 4
+ year = int(one if isoish else (f"20{three}" if len(three) == 2 else three))
+ day = int(three if isoish else (one if day_first else two))
+ month = int(two if isoish else (two if day_first else one))
+ return _moment(year, month, day, *slash.groups()[3:])
+ return None
+
+
+def _moment(
+ year: int, month: int, day: int, hour: Any, minute: Any, second: Any
+) -> dict[str, Any] | None:
+ if not 1 <= month <= 12 or not 1 <= day <= 31:
+ return None
+ # The time of day, checked exactly as the bare-clock branch checks it. Without this
+ # `03/01/2026 99:00` read as a moment whose clock was `99:00:00`, and the refusal
+ # arrived one layer down as "the timestamp is not a valid Gregorian date and time" —
+ # about a value the analyst never wrote, instead of about the cell they did.
+ if hour is not None and not _holds(hour, minute, second):
+ return None
+ try:
+ datetime(year, month, day)
+ except ValueError:
+ return None
+ date = f"{year:04d}-{month:02d}-{day:02d}"
+ clock = _clock(hour, minute, second) if hour is not None else ""
+ return {
+ "shape": "moment",
+ "date": date,
+ "clock": clock,
+ "text": f"{date}T{clock[:5]}" if clock else date,
+ }
+
+
+def claim_moment(read: dict[str, Any] | None, *, day: str = "", zone: str = "") -> str | None:
+ """One reading as the temporal value a Claim stores, or None when it cannot be one.
+
+ Inside `engine/temporal`'s profile and no wider: a reduced date for a cell that named
+ only a day, a timestamp for one that named an hour. ``zone`` is empty by default,
+ which stores a **local** timestamp — the binders' column is called `Local time` and
+ stamping it `Z` would move the evidence by however many hours the event was away.
+
+ A bare clock with no ``day`` is None rather than today: the date is genuinely not in
+ the file, and the sheet is where the analyst says which one it was.
+ """
+ if read is None:
+ return None
+ date = day if read["shape"] == "time" else read["date"]
+ if not date:
+ return None
+ clock = read["clock"]
+ return f"{date}T{clock}{zone}" if clock else date
+
+
+def split_values(cell: Any, role: dict[str, Any] | None) -> list[str]:
+ """A cell as the values it holds. One, unless the column says it is a list.
+
+ Mirrors `lib/sheetRoles.splitValues`. Two kinds hold lists and for the same reason:
+ a `choice` cell holds three pieces of equipment, a `row` cell holds the three
+ companies of a brigade. Everything else is one value, whatever is in it.
+ """
+ body = str(cell or "")
+ kind = (role or {}).get("kind")
+ separator = (role or {}).get("multi") if kind in ("choice", "row") else None
+ if not separator:
+ return [body.strip()] if body.strip() else []
+ return [part.strip() for part in body.split(separator) if part.strip()]
+
+
+# -- one row pointing at another ----------------------------------------------
+
+
+def row_targets(
+ columns: list[str],
+ rows: list[list[str]],
+ column: str,
+ role: dict[str, Any],
+) -> dict[str, dict[str, Any]]:
+ """Which rows each row's ``row`` column names, by row key. Mirrors `lib/sheetRows.js`.
+
+ The binders' `Links with others` held **names**, not keys, and that is kept: a file
+ whose links read `r7f3a` is a file the collaborator opening it cannot follow. So a
+ word points at a row when exactly one other row spells it that way in the named
+ column, case and surrounding spaces aside.
+
+ ``missing`` is the other half and is the reason the binder's own version broke: a
+ word naming no row, or naming two, is reported rather than guessed. Theirs had
+ already decayed to `#REF!` because a validation cannot survive a row moving; this
+ one is re-read from the words every time, so it decays into a list of what to fix.
+ """
+ if column not in columns:
+ return {}
+ from .sheets import ID_COLUMN, key_index
+
+ key_at = key_index(columns)
+ at = columns.index(column)
+ named = role.get("of") if isinstance(role, dict) else None
+ if not isinstance(named, str) or named not in columns:
+ named = next((name for name in columns if name.casefold() != ID_COLUMN), None)
+ if named is None:
+ return {}
+ name_at = columns.index(named)
+
+ # Every word the naming column holds, and the rows holding it: a word two rows share
+ # names neither of them, which is a finding about the file rather than a coin toss.
+ holders: dict[str, list[str]] = {}
+ for row in rows:
+ word = (row[name_at] if name_at < len(row) else "").strip().casefold()
+ if word:
+ holders.setdefault(word, []).append(row[key_at] if key_at < len(row) else "")
+
+ answer: dict[str, dict[str, Any]] = {}
+ for row in rows:
+ identity = row[key_at] if key_at < len(row) else ""
+ keys: list[str] = []
+ missing: list[str] = []
+ for word in split_values(row[at] if at < len(row) else "", role):
+ found = [key for key in holders.get(word.casefold(), []) if key != identity]
+ if len(found) == 1 and found[0] not in keys:
+ keys.append(found[0])
+ elif len(found) != 1:
+ missing.append(word)
+ if keys or missing:
+ answer[identity] = {"keys": keys, "missing": missing}
+ return answer
+
+
+def _stamp_today() -> str:
+ return datetime.now(UTC).date().isoformat()
+
+
+def apply_stamped(
+ columns: list[str], rows: list[list[str]], roles: dict[str, Any], *, today: str | None = None
+) -> int:
+ """Fill the empty cells of every ``stamped`` column with today's date.
+
+ Written once and never rewritten: a stamp that moved on every save would say when
+ the sheet was last touched, which the filesystem already says, instead of when the
+ row appeared, which nothing else records.
+
+ Only the date. The binders' column read "added by + date", and the *by* half is not
+ written here because it cannot be known honestly: Azimut is one user on localhost so
+ there is no identity to record, and by the time a save arrives the server cannot
+ tell a pasted row from a typed one. A made-up provenance is worse than none.
+ """
+ at = [index for index, name in enumerate(columns) if roles.get(name, {}).get("kind") == "stamped"]
+ if not at:
+ return 0
+ stamp = today or _stamp_today()
+ filled = 0
+ for row in rows:
+ for index in at:
+ if index < len(row) and not row[index].strip():
+ row[index] = stamp
+ filled += 1
+ return filled
+
+
+def _point_of(entity: dict[str, Any] | None) -> tuple[float, float] | None:
+ attrs = (entity or {}).get("attrs") or {}
+ try:
+ lat, lon = float(attrs["lat"]), float(attrs["lon"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ return (lat, lon) if -90 <= lat <= 90 and -180 <= lon <= 180 else None
+
+
+def _points_by_entity(case: "Case") -> dict[str, set[tuple[float, float]]]:
+ """Every entity that can be put on a map, with the point or points that place it.
+
+ Three ways to be, and they are the ontology's own: the entity holds a point; it
+ points at a place through one of `PLACED_BY`; or a statement that sits at a place is
+ *about* it. The third is not a nicety — `located-at` is reserved for collected media
+ and `sited-at` for structures, so a vehicle or a unit is positioned by a dated Claim
+ and by nothing else. Without that hop the column would answer NO for exactly the
+ rows a unit registry is made of.
+
+ Two hops and no more, which is why the second pass reads a **frozen** copy of the
+ first: a statement that gained its place from a hop must not pass it on again, or the
+ answer becomes "something near this is placed".
+
+ Walked once per read rather than per row: a sheet may hold twenty thousand rows and
+ the graph is the same graph for all of them.
+ """
+ own: dict[str, set[tuple[float, float]]] = {}
+ for entity in case.list_entities():
+ point = _point_of(entity)
+ if point:
+ own.setdefault(str(entity["id"]), set()).add(point)
+ if not own:
+ return own
+ reached = {identity: set(points) for identity, points in own.items()}
+ links = case.list_links()
+ for link in links:
+ held = own.get(str(link.get("to")))
+ if held and link.get("type") in PLACED_BY:
+ reached.setdefault(str(link.get("from")), set()).update(held)
+ # Only now, and only from the statements the pass above reached.
+ placed = {identity: set(points) for identity, points in reached.items()}
+ for link in links:
+ held = placed.get(str(link.get("from")))
+ if held and link.get("type") == ABOUT:
+ reached.setdefault(str(link.get("to")), set()).update(held)
+ return reached
+
+
+def entity_points(case: "Case", ids: list[str]) -> dict[str, dict[str, float]]:
+ """Where the case puts each of these entities, for the cells that point at them.
+
+ The half of a place column the geocoder should never have been asked about: a cell
+ pointing at an entity the case has already placed has an answer that is exact,
+ offline and instant, while Nominatim is guessing from a word at one request a second
+ and cannot answer `3rd Bde` at all.
+
+ **Exactly one point, or no answer.** An entity reached by two different points is an
+ ambiguity, and picking one of them to fill a cell would be the same silent merge this
+ app refuses when two entities share a name. The row stays for the analyst.
+ """
+ reached = _points_by_entity(case)
+ answer: dict[str, dict[str, float]] = {}
+ for identity in dict.fromkeys(ids):
+ points = reached.get(identity)
+ if points and len(points) == 1:
+ lat, lon = next(iter(points))
+ answer[identity] = {"lat": lat, "lon": lon}
+ return answer
+
+
+def _relations_by_entity(case: "Case") -> dict[str, list[str]]:
+ """What the case has joined each entity to, as the labels at the far end.
+
+ One hop, and read from both ends: "is part of" and "contains" are the same edge seen
+ from its two sides, and a registry of companies wants the brigade whichever way round
+ the analyst happened to state it.
+
+ Chain edges and `mentions` are left out (`NOT_A_RELATION`): the first says how a file
+ was produced rather than what the case joined, and the second would answer with the
+ sheet being read.
+
+ Sorted by their words and capped, because the cell is one line: a subject joined to
+ sixty things says nothing in a column, and the Graph is where that is looked at.
+ Walked once per read like the points — the graph is the same graph for every row.
+ """
+ labels = {
+ str(entity["id"]): str(entity.get("label") or "").strip()
+ for entity in case.list_entities()
+ }
+ joined: dict[str, set[str]] = {}
+ for link in case.list_links():
+ if link.get("type") in NOT_A_RELATION:
+ continue
+ ends = (str(link.get("from")), str(link.get("to")))
+ for holder, other in (ends, ends[::-1]):
+ if holder not in labels or not labels.get(other):
+ continue
+ joined.setdefault(holder, set()).add(labels[other])
+ return {
+ identity: sorted(names)[:MAX_RELATION_VALUES] for identity, names in joined.items()
+ }
+
+
+def _yes_words(columns: list[str], roles: dict[str, Any], index: int) -> set[str]:
+ """What counts as a yes in the column at *index*, folded for comparison.
+
+ A declared yes/no column answers with **its own first value**, because that is the
+ word its own cells hold and the one its chips draw. Everything else falls back to the
+ spellings the binders use: a tick column somebody typed by hand holds `x`, and a
+ score that ignored it would read zero over a column that is plainly answered.
+ """
+ role = roles.get(columns[index]) or {}
+ values = role.get("values") or []
+ if role.get("kind") == "boolean" and values:
+ return {str(values[0]).strip().casefold()}
+ return set(YES_WORDS)
+
+
+def apply_computed(
+ case: "Case",
+ columns: list[str],
+ rows: list[list[str]],
+ roles: dict[str, Any],
+ links: dict[str, Any],
+ built: dict[str, Any] | None = None,
+) -> int:
+ """Restate every ``computed`` column from what the case, or the row, currently says.
+
+ Read-only in the grid and rewritten here on every save, so the answer never drifts.
+ Six natures, in four families:
+
+ ``has_point``
+ ``links`` is the sidecar's cell-to-entity table, and a row counts as placed when
+ **any** of its linked cells points at something that can be mapped, because the
+ row is the unit the column describes, not the cell.
+ ``filled_of`` / ``yes_of``
+ Counted over the row's own chosen columns. Written as the bare number, so the
+ column sorts as a number and a spreadsheet can total it; the panel is where the
+ denominator is said, since repeating `of 6` down four hundred rows would be four
+ hundred copies of one fact. A nature told to read no columns writes nothing at
+ all rather than a column of zeroes nobody chose.
+ ``point`` / ``relations``
+ What the case holds about the entity **one named column** points at. Where
+ `has_point` answers whether the case knows, these answer what it knows — which is
+ the question that was actually being retyped into the column alongside. The
+ column is named rather than swept, because a sheet may point at the case from a
+ subject column and a place column both, and "whatever this row points at" would
+ answer about whichever the walk reached first.
+ ``in_case``
+ Whether the case still holds what the row was **built** from. The only nature
+ that reads `built` instead of `links`, because it is the only one asking about an
+ entity that may be gone — and a link naming something gone is swept before it
+ gets here. A row nobody built writes nothing: the question does not apply to a
+ line somebody typed themselves.
+
+ A nature whose answer cannot be had writes an **empty cell** rather than a word: a
+ row whose subject the case does not place has no coordinates, and `unknown` spelled
+ into four hundred cells is four hundred cells a filter would then have to unlearn.
+ """
+ at = [
+ (index, name)
+ for index, name in enumerate(columns)
+ if roles.get(name, {}).get("kind") == "computed"
+ ]
+ if not at:
+ return 0
+ from .sheets import key_index
+
+ key_at = key_index(columns)
+ natures = {name: (roles.get(name) or {}).get("of", "has_point") for _, name in at}
+ # The graph is walked once, and only for what a column actually asks: a sheet whose
+ # only computed column is a score has no business listing every entity.
+ wants_points = any(nature in ("has_point", "point") for nature in natures.values())
+ reached = _points_by_entity(case) if wants_points else {}
+ placed = set(reached)
+ # One bounded lookup for the whole table rather than one per row, the same bargain
+ # every other nature here strikes: the ids are the sidecar's and the answer is the
+ # case's, so the question is asked once.
+ made = {str(key): str(value) for key, value in (built or {}).items() if value}
+ alive: set[str] = set()
+ if made and "in_case" in natures.values():
+ alive = {str(entity["id"]) for entity in case.entities_by_ids(sorted(set(made.values())))}
+ joined = _relations_by_entity(case) if "relations" in natures.values() else {}
+ # Which cells each counting column reads, what a yes looks like in each of them, and
+ # which column each linked nature follows. Resolved once rather than per row: twenty
+ # thousand rows would otherwise re-read the same roles twenty thousand times.
+ counted: dict[str, list[int]] = {}
+ accepts: dict[str, list[set[str]]] = {}
+ follows: dict[str, str] = {}
+ for _index, name in at:
+ role = roles.get(name) or {}
+ if natures[name] in COUNTING_NATURES:
+ wanted = [
+ columns.index(column) for column in role.get("columns", []) if column in columns
+ ]
+ counted[name] = wanted
+ accepts[name] = [_yes_words(columns, roles, column) for column in wanted]
+ elif natures[name] in LINKED_NATURES:
+ source = role.get("from")
+ if isinstance(source, str) and source in columns:
+ follows[name] = source
+
+ written = 0
+ for row in rows:
+ identity = row[key_at] if key_at < len(row) else ""
+ cells = links.get(identity) or {}
+ mapped = COMPUTED_YES if any(str(target) in placed for target in cells.values()) else COMPUTED_NO
+ for index, name in at:
+ if index >= len(row):
+ continue
+ nature = natures[name]
+ if nature == "has_point":
+ answer = mapped
+ elif nature == "in_case":
+ source = made.get(identity)
+ answer = "" if not source else (COMPUTED_YES if source in alive else COMPUTED_NO)
+ elif nature in COUNTING_NATURES:
+ answer = _counted(row, counted.get(name) or [], accepts.get(name) or [], nature)
+ else:
+ target = str(cells.get(follows.get(name, ""), ""))
+ if nature == "point":
+ # Exactly one point, or nothing. An entity two different points reach
+ # is an ambiguity, and picking one to fill a cell would be the silent
+ # merge this app refuses when two entities share a name.
+ points = reached.get(target) or set()
+ lat, lon = next(iter(points)) if len(points) == 1 else (None, None)
+ answer = "" if lat is None else f"{lat:.5f}, {lon:.5f}"
+ else:
+ separator = (roles.get(name) or {}).get("multi") or DEFAULT_SEPARATOR
+ answer = separator.join(joined.get(target) or [])
+ if row[index] != answer:
+ row[index] = answer
+ written += 1
+ return written
+
+
+def _counted(
+ row: list[str], columns: list[int], accepts: list[set[str]], nature: str
+) -> str:
+ """One counting nature's answer for one row, or nothing when it reads no columns."""
+ if not columns:
+ return ""
+ if nature == "filled_of":
+ return str(sum(1 for column in columns if row[column].strip()))
+ return str(
+ sum(
+ 1
+ for column, words in zip(columns, accepts, strict=True)
+ if row[column].strip().casefold() in words
+ )
+ )
diff --git a/src/azimut/engine/sheets.py b/src/azimut/engine/sheets.py
new file mode 100644
index 0000000..1b0b530
--- /dev/null
+++ b/src/azimut/engine/sheets.py
@@ -0,0 +1,1452 @@
+"""Case sheets: a table the analyst works in, stored as a real CSV.
+
+**The file is the sheet.** Not rows in the database with CSV as an import format —
+`sheets/<name>.csv` is the artifact, it opens in any spreadsheet, and a case whose
+app is gone still holds a readable table. That is the whole design, and everything
+below follows from it:
+
+- What the analyst *found* is a column of the table. A status, a reason, the date a
+ row was checked: hand the file to someone else and the work is still there.
+- What the *grid* remembers is a sidecar (`sheets/.meta/<name>.json`). Column
+ widths, hidden columns, the sort, row colours, and which entity a cell points at.
+ Losing it costs presentation, never a finding.
+
+A CSV row has no identity, which is the one hard problem here: a colour or an
+entity link hung on "row 4" moves to the wrong row the moment someone sorts the
+file in Excel. So a sheet carries an **id column**, in the file, in plain sight. A
+file that already has one keeps it — an imported export usually does, and adding a
+second key column beside it would be noise. Otherwise one is added on first open,
+and the first save is what writes it down.
+
+The other consequence of the file being the artifact is that the analyst may have
+it open in a spreadsheet at the same time as the grid. So a read hands out a
+**stamp** and a save may present it back: if the file moved on in between, the save
+is refused rather than allowed to overwrite work it never saw.
+
+Bounds are enforced here rather than at the route, because both the editor and the
+import land on the same table and one of them would drift.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+import os
+import tempfile
+import uuid
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from .. import layout
+from ..workspace import CaseError, ensure_dir
+from . import sheetroles
+
+if TYPE_CHECKING:
+ from ..workspace import Case
+
+#: The column holding each row's identity. Lowercase because a file that already
+#: has one usually spells it this way, and adopting it beats adding a second.
+ID_COLUMN = "id"
+
+#: What one sheet may hold. A worklist of a few thousand rows is the workflow;
+#: past this it is a dataset, and a grid in a browser is the wrong tool for it.
+MAX_ROWS = 20_000
+MAX_COLUMNS = 64
+#: One cell. The same bound a declared long-text attr gets: a cell holds a note,
+#: not a document.
+MAX_CELL = 4_000
+#: A column heading.
+MAX_COLUMN_NAME = 120
+#: One column's note — the line of instruction the binders drew with annotated
+#: screenshots. A line, not a paragraph: it is read in a tooltip.
+MAX_NOTE = 240
+#: The word the grid was searching when it was last left. A term, not a document.
+MAX_QUERY = 200
+#: How many chosen values one column's filter may carry. The menu offers a page of
+#: forty; a filter built by clicking chips can hold more, and nothing needs a thousand.
+MAX_FILTER_VALUES = 200
+#: What a row colour is said to mean in this sheet. A word or two — it is drawn in a
+#: legend strip, not read as prose.
+MAX_LEGEND = 40
+#: The two lines of instruction above the grid. The binders carried a whole "How to
+#: use" tab of annotated screenshots; most of what it said belongs on the columns it
+#: was about (``notes``), and what is left is what the sheet as a whole is for.
+MAX_DESCRIPTION = 400
+#: How many case files one row may hang off itself. A row is a line of work, and a
+#: dozen pieces attached to one is a folder, which the Media Library already is.
+MAX_ATTACHMENTS = 12
+#: How many of a column's words may be pointed at the case. The promotion's own bound:
+#: past it the column is prose, and prose is searched rather than promoted.
+MAX_COLUMN_VALUES = 500
+#: An uploaded CSV, before it is parsed. Generous for 20 000 rows of text, small
+#: enough that a mis-picked file is refused rather than read into memory.
+MAX_IMPORT_BYTES = 16 * 1024 * 1024
+
+#: Row colours the grid offers, by key. Stored as a key rather than a hex value so
+#: the palette can follow the theme and an old sheet still paints. Drawn from the
+#: annotation palette, never the amber accent: that one means selection.
+ROW_COLOURS = ("red", "orange", "yellow", "green", "blue", "grey")
+
+#: Delimiters worth guessing between. A European export is semicolon-separated far
+#: too often for "comma or nothing" to be an acceptable import.
+DELIMITERS = (",", ";", "\t", "|")
+
+
+class SheetError(ValueError):
+ """A table that cannot be stored as asked."""
+
+
+class SheetConflict(ValueError):
+ """The file moved on since the grid read it, so the save was not made.
+
+ Deliberately not a ``SheetError``: nothing is wrong with the table that was
+ posted, and the answer is a 409 the grid recovers from by reloading rather than
+ a 422 saying the request was bad.
+ """
+
+
+class SheetUnwritable(ValueError):
+ """The table is fine and the file would not take it.
+
+ The case this exists for is Windows: the analyst has the CSV open in Excel, which
+ holds the handle, and the rename that lands the new copy is refused by the operating
+ system. That is not a bad request and not a stale grid — it is a file that is busy,
+ and the only useful answer names it so the analyst closes the spreadsheet.
+
+ A 409 like ``SheetConflict``, because both mean "not now" rather than "not ever",
+ and neither is a reason for the grid to throw away what it is holding.
+ """
+
+
+def key_index(columns: list[str]) -> int:
+ """Where the row's handle sits in a heading row.
+
+ Matched without regard to case, because a file that already had a key column keeps
+ **its own spelling** (`normalize`) and an exported table routinely writes `ID`. Asked
+ for by every reader that has to look a row up, and it is one function rather than an
+ `.index()` at each of them: the literal lookup raised on precisely the files this
+ module promises to adopt rather than rewrite.
+ """
+ return next((at for at, name in enumerate(columns) if name.casefold() == ID_COLUMN), 0)
+
+
+def new_row_id() -> str:
+ """A fresh row key. Public because a table built elsewhere in the app — a worklist
+ made out of the catalog — has to mint the keys its own sidecar will hang on."""
+ return f"r{uuid.uuid4().hex[:10]}"
+
+
+def stamp(path: Path) -> str:
+ """What the file looked like, as one short opaque token.
+
+ Modification time and size together: a spreadsheet that rewrites a row changes
+ at least one of them, and comparing two tokens is cheaper than re-reading a
+ twenty-thousand-row CSV to find out whether it is still the one that was read.
+ A missing file stamps as the empty string, so a file appearing where the grid
+ saw none is a mismatch rather than a silent overwrite.
+ """
+ try:
+ info = path.stat()
+ except OSError:
+ return ""
+ return f"{info.st_mtime_ns}-{info.st_size}"
+
+
+def sniff_delimiter(sample: str) -> str:
+ """The delimiter a file's first non-empty line is most likely written with.
+
+ Counted outside quotes, so a comma inside `"Smith, J"` does not vote for the
+ comma. Ties go to the earliest in `DELIMITERS`, which puts the standard first.
+ """
+ line = next((row for row in sample.splitlines() if row.strip()), "")
+ best, best_count = DELIMITERS[0], 0
+ for delimiter in DELIMITERS:
+ count, quoted = 0, False
+ for char in line:
+ if char == '"':
+ quoted = not quoted
+ elif char == delimiter and not quoted:
+ count += 1
+ if count > best_count:
+ best, best_count = delimiter, count
+ return best
+
+
+def _clean_cell(value: Any) -> str:
+ """One cell, as text with no control characters and inside the length bound.
+
+ Newlines survive: a note column is the reason a cell may hold sentences, and
+ the CSV writer quotes them correctly. Everything else below 0x20 goes — a stray
+ NUL or a vertical tab in a pasted table breaks the file for the next reader.
+ """
+ text = "" if value is None else str(value)
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
+ text = "".join(char for char in text if char == "\n" or char >= " ")
+ if len(text) > MAX_CELL:
+ raise SheetError(f"a cell holds at most {MAX_CELL} characters")
+ return text
+
+
+def normalize(columns: list[Any], rows: list[Any]) -> tuple[list[str], list[list[str]]]:
+ """The table as it will be written: named columns, square rows, keyed rows.
+
+ Every route goes through this — a save, an import, a fresh sheet — so the file
+ on disk has one shape whatever wrote it. Blank and duplicate headings are named
+ rather than refused: an analyst's export routinely has both, and refusing the
+ file at the door is worse than fixing it and showing what happened.
+ """
+ names: list[str] = []
+ seen: set[str] = set()
+ for index, raw in enumerate(columns):
+ name = _clean_cell(raw).replace("\n", " ").strip()[:MAX_COLUMN_NAME]
+ if not name:
+ name = f"Column {index + 1}"
+ candidate, suffix = name, 2
+ while candidate.casefold() in seen:
+ candidate = f"{name} ({suffix})"
+ suffix += 1
+ seen.add(candidate.casefold())
+ names.append(candidate)
+
+ key = next((name for name in names if name.casefold() == ID_COLUMN), None)
+ if key is None:
+ names.insert(0, ID_COLUMN)
+ key = ID_COLUMN
+ rows = [["", *(row or [])] for row in rows]
+ if len(names) > MAX_COLUMNS:
+ raise SheetError(f"a sheet holds at most {MAX_COLUMNS} columns")
+ if len(rows) > MAX_ROWS:
+ raise SheetError(f"a sheet holds at most {MAX_ROWS} rows")
+
+ key_at = names.index(key)
+ table: list[list[str]] = []
+ taken: set[str] = set()
+ for row in rows:
+ cells = [_clean_cell(cell) for cell in (row or [])][: len(names)]
+ cells += [""] * (len(names) - len(cells))
+ identity = cells[key_at].strip()
+ if not identity or identity in taken:
+ identity = new_row_id()
+ taken.add(identity)
+ cells[key_at] = identity
+ table.append(cells)
+ return names, table
+
+
+def parse_csv(text: str, *, delimiter: str | None = None) -> tuple[list[str], list[list[str]]]:
+ """A CSV's heading row and body, normalized.
+
+ A file with no rows at all still yields its columns, and a wholly empty file
+ yields an empty sheet rather than an error: an analyst who imports the wrong
+ thing should see an empty table and delete it, not read a stack trace.
+ """
+ body = text.lstrip("")
+ if not body.strip():
+ return normalize([], [])
+ reader = csv.reader(io.StringIO(body), delimiter=delimiter or sniff_delimiter(body))
+ try:
+ table = [row for row in reader]
+ except csv.Error as exc:
+ raise SheetError(f"this file is not readable as CSV: {exc}") from exc
+ if not table:
+ return normalize([], [])
+ return normalize(table[0], table[1:])
+
+
+#: How a sheet's CSV is written. The BOM is for Excel and only for Excel: without it
+#: Excel opens a UTF-8 CSV in the legacy codepage of the machine, so a Ukrainian
+#: place name or a French street arrives as mojibake — on Windows, which is one of the
+#: three binaries we ship. Every reader here already opens files as ``utf-8-sig``, so
+#: the mark is stripped back off on the way in, and LibreOffice never needed it either
+#: way. The sidecar is plain ``utf-8``: a BOM in JSON breaks strict parsers.
+CSV_ENCODING = "utf-8-sig"
+
+
+def write_atomic(path: Path, text: str, *, encoding: str) -> None:
+ """Replace *path* with *text*, or leave it exactly as it was.
+
+ ``write_text`` truncates the file and then writes it, so a process killed in
+ between — or a disk that fills, or a laptop that sleeps badly — leaves the analyst
+ with half a table or none. The sheet is *the* artifact of this tool, which makes it
+ the one file in the app least able to afford that.
+
+ So: a temporary file beside it, flushed to the platter, then one rename. The same
+ shape `config.write_pointer` uses, for the same reason. `os.replace` is atomic on
+ POSIX and on Windows, and the temporary lands in the same directory so the rename
+ never crosses a filesystem.
+
+ `OSError` is raised as `SheetUnwritable`: a read-only folder and a spreadsheet
+ holding the file open are the two ways this fails in practice, and both deserve a
+ sentence rather than a 500.
+ """
+ # Encoded here rather than by the file handle so that `replace_atomic` owns the
+ # rename for both callers: the bytes are identical either way, since the text is
+ # written with no newline translation.
+ replace_atomic(path, text.encode(encoding))
+
+
+def replace_atomic(path: Path, data: bytes) -> None:
+ """The rename `write_atomic` is made of, over bytes rather than text.
+
+ Its own function because a rollback has to put back the exact bytes a file held,
+ and re-encoding text it had already decoded would add or drop a byte order mark.
+ """
+ try:
+ ensure_dir(path.parent)
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
+ except OSError as exc:
+ # Making the folder counts: it is where a read-only case, or a name already taken
+ # by a directory, fails — and an `OSError` escaping here is the 500 this exists
+ # to prevent.
+ raise SheetUnwritable(f"could not write beside “{path.name}”: {exc}") from exc
+ tmp_path = Path(tmp_name)
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_path, path)
+ except OSError as exc:
+ raise SheetUnwritable(f"could not write “{path.name}”: {exc}") from exc
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
+def _bytes_at(path: Path) -> bytes | None:
+ """What a file holds right now, or None when it holds nothing readable.
+
+ Half of a rollback: a write that touches two files has to be able to put the first
+ one back when the second is refused.
+ """
+ try:
+ return path.read_bytes()
+ except OSError:
+ return None
+
+
+def _put_back(path: Path, data: bytes | None) -> None:
+ """Restore a file to the bytes it held, or remove it if it held none.
+
+ Best effort: it runs while another failure is on its way up, and raising over the
+ restore would replace a sentence the analyst can act on with one they cannot.
+ """
+ try:
+ if data is None:
+ path.unlink(missing_ok=True)
+ else:
+ replace_atomic(path, data)
+ except (OSError, SheetUnwritable):
+ return
+
+
+def to_csv(columns: list[str], rows: list[list[str]]) -> str:
+ """The table as a comma-separated file with LF endings.
+
+ LF rather than the CRLF the CSV spec asks for: every spreadsheet reads both,
+ and a case folder is copied between the three platforms we ship.
+ """
+ buffer = io.StringIO(newline="")
+ writer = csv.writer(buffer, lineterminator="\n")
+ writer.writerow(columns)
+ writer.writerows(rows)
+ return buffer.getvalue()
+
+
+# -- the sidecar --------------------------------------------------------------
+
+
+#: The sidecar shape written today. Version 2 is where **roles** arrive: a column's
+#: kind, its vocabulary, its separator. Everything before it was presentation — widths,
+#: colours, a sort — and that was the first thing the sidecar knew that changes what a
+#: cell *means* to the app. Version 3 adds ``promoted``: what a cell said at the moment
+#: the case took it, which is what lets a row say it has moved on since. Version 4 adds
+#: **the question** — the search term and the filters — plus the colour legend, the
+#: pinned row, the row height and a second sort key: everything the analyst had set up
+#: and lost on the next restart. Version 5 is the bridge to the case finished:
+#: ``anchors`` (the named moments an offset column counts from), ``attachments`` (case
+#: files a row hangs off itself, referenced and never copied), ``values`` (what a
+#: column's *words* mean in the case, which is the grain a whole column is promoted at)
+#: and ``description`` (the two lines the binders' "How to use" tab was actually for).
+#: Version 6 adds ``built``: the entity a row was **made from**, which is not the same
+#: thing as the entity its cells point at. A link is dropped the moment the case stops
+#: holding what it names — that is `drop_dead_links`, and it is right to do it — so a
+#: sheet built out of the case had no way to say "this row had a proof and no longer
+#: does". ``built`` is the half that survives the sweep, and it is what the ``in_case``
+#: nature reads.
+#: Additive throughout, and `clean_meta` still reads a 1.
+META_VERSION = 6
+
+
+def empty_meta() -> dict[str, Any]:
+ return {
+ "version": META_VERSION,
+ "widths": {},
+ "hidden": [],
+ "sort": None,
+ "colours": {},
+ "links": {},
+ "frozen": None,
+ "roles": {},
+ "notes": {},
+ "progress": None,
+ "promoted": {},
+ "query": "",
+ "filters": {},
+ "legend": {},
+ "pinned": None,
+ "tall": False,
+ "anchors": {},
+ "attachments": {},
+ "values": {},
+ "description": "",
+ "built": {},
+ }
+
+
+def clean_meta(meta: Any, columns: list[str], rows: list[list[str]]) -> dict[str, Any]:
+ """The sidecar reduced to what the table it describes can still carry.
+
+ A width for a deleted column, a colour on a deleted row, a link in a column
+ nobody kept: dropped on every save. Otherwise the sidecar only ever grows, and
+ a sheet that has been reworked twice carries more dead state than table.
+ """
+ clean = empty_meta()
+ if not isinstance(meta, dict):
+ return clean
+ known = {name for name in columns}
+ identities = {row[key_index(columns)] for row in rows} if rows else set()
+
+ widths = meta.get("widths")
+ if isinstance(widths, dict):
+ for name, width in widths.items():
+ if name in known and isinstance(width, (int, float)):
+ clean["widths"][name] = max(60, min(720, int(width)))
+
+ hidden = meta.get("hidden")
+ if isinstance(hidden, list):
+ # The id column is never hidden: it is the row's handle, and a grid that
+ # hides it hides why a colour survived a re-sort.
+ clean["hidden"] = [name for name in hidden if name in known and name != ID_COLUMN]
+
+ # One key, and optionally a second one under it: a worklist is read as "by status,
+ # then by date", and a single key made the analyst re-sort by hand every time the
+ # first one tied. The second is dropped when it names the first column — one column
+ # cannot break its own tie.
+ sort = meta.get("sort")
+ if isinstance(sort, dict) and sort.get("column") in known:
+ clean["sort"] = {"column": str(sort["column"]), "desc": bool(sort.get("desc"))}
+ then = sort.get("then")
+ if (
+ isinstance(then, dict)
+ and then.get("column") in known
+ and str(then["column"]) != str(sort["column"])
+ ):
+ clean["sort"]["then"] = {
+ "column": str(then["column"]),
+ "desc": bool(then.get("desc")),
+ }
+
+ # One column may be kept beside the key while the table scrolls sideways. Never
+ # the key itself: it already stays put, so recording it would record a change
+ # that does nothing and then have to be undone by hand.
+ frozen = meta.get("frozen")
+ if isinstance(frozen, str) and frozen in known and frozen.casefold() != ID_COLUMN:
+ clean["frozen"] = frozen
+
+ colours = meta.get("colours")
+ if isinstance(colours, dict):
+ for identity, colour in colours.items():
+ if identity in identities and colour in ROW_COLOURS:
+ clean["colours"][identity] = colour
+
+ links = meta.get("links")
+ if isinstance(links, dict):
+ for identity, cells in links.items():
+ if identity not in identities or not isinstance(cells, dict):
+ continue
+ kept = {
+ name: str(entity_id)
+ for name, entity_id in cells.items()
+ if name in known and isinstance(entity_id, str) and entity_id
+ }
+ if kept:
+ clean["links"][identity] = kept
+
+ # -- version 2: what the app knows about a column ------------------------
+ clean["roles"] = sheetroles.clean_roles(meta.get("roles"), columns)
+
+ notes = meta.get("notes")
+ if isinstance(notes, dict):
+ for name, note in notes.items():
+ text = _clean_cell(note).replace("\n", " ").strip()[:MAX_NOTE]
+ if name in known and text:
+ clean["notes"][name] = text
+
+ # Which column says how far along the work is. One per sheet: "where is this
+ # chantier" is a question, not five, and two answers would need two footers.
+ progress = meta.get("progress")
+ if isinstance(progress, str) and progress in known:
+ clean["progress"] = progress
+
+ # -- version 3: what the cell said when the case took it -----------------
+ # Kept so a promoted row can say it has been edited since. The value rather than a
+ # flag, because "changed" is only worth saying when it can be compared: a flag set
+ # on every save would mark every row the analyst scrolled past.
+ promoted = meta.get("promoted")
+ if isinstance(promoted, dict):
+ for identity, cells in promoted.items():
+ if identity not in identities or not isinstance(cells, dict):
+ continue
+ kept = {
+ name: _clean_cell(said)
+ for name, said in cells.items()
+ if name in known and isinstance(said, str)
+ }
+ if kept:
+ clean["promoted"][identity] = kept
+
+ # -- version 4: the question, and the rest of the reading -----------------
+ # The sidecar already carried the sort and the hidden columns, which is half a
+ # reading; the half that decides what is on screen — the search and the filters —
+ # lived in the tab and died with it. A sheet that reopens showing all four hundred
+ # rows is a sheet whose analyst has to rebuild their question every morning.
+ query = meta.get("query")
+ if isinstance(query, str):
+ clean["query"] = _clean_cell(query).replace("\n", " ").strip()[:MAX_QUERY]
+
+ filters = meta.get("filters")
+ if isinstance(filters, dict):
+ for name, entry in filters.items():
+ if name not in known or not isinstance(entry, dict):
+ continue
+ asked = _clean_filter(entry)
+ if asked:
+ clean["filters"][name] = asked
+
+ # What a colour means in *this* sheet. Six colours with no legend is six colours
+ # whose meaning lives in one analyst's head, which is the opposite of handing the
+ # case over.
+ legend = meta.get("legend")
+ if isinstance(legend, dict):
+ for colour, label in legend.items():
+ if colour not in ROW_COLOURS or not isinstance(label, str):
+ continue
+ text = _clean_cell(label).replace("\n", " ").strip()[:MAX_LEGEND]
+ if text:
+ clean["legend"][colour] = text
+
+ # One row kept under the heading while the rest scrolls: the reference candidate a
+ # comparison grid is read against. Keyed like a colour, so a re-sort cannot move it.
+ pinned = meta.get("pinned")
+ if isinstance(pinned, str) and pinned in identities:
+ clean["pinned"] = pinned
+
+ clean["tall"] = bool(meta.get("tall"))
+
+ # -- version 5: the moments, the pieces and what the sheet is for ---------
+ # A named shot several videos are lined up on, and the time it happened once
+ # somebody works that out. Kept here rather than in the offset columns because one
+ # anchor serves several of them, and a time restated per column is a time that will
+ # disagree with itself.
+ anchors = meta.get("anchors")
+ if isinstance(anchors, dict):
+ for name, entry in anchors.items():
+ label = _clean_cell(name).replace("\n", " ").strip()[: sheetroles.MAX_ANCHOR_NAME]
+ if not label or len(clean["anchors"]) >= sheetroles.MAX_ANCHORS:
+ continue
+ at = entry.get("at") if isinstance(entry, dict) else None
+ clean["anchors"][label] = {"at": sheetroles.clean_anchor_at(at)}
+
+ # Case files a row hangs off itself: the screenshot of the message giving the hour,
+ # the emailed reply. **Referenced**, never copied — the entity is already the case's,
+ # so nothing new is filed, no artifact is owned twice and the bundle does not drift.
+ attachments = meta.get("attachments")
+ if isinstance(attachments, dict):
+ for identity, held in attachments.items():
+ if identity not in identities or not isinstance(held, list):
+ continue
+ pieces: list[str] = []
+ for entity_id in held:
+ if isinstance(entity_id, str) and entity_id and entity_id not in pieces:
+ pieces.append(entity_id)
+ if pieces:
+ clean["attachments"][identity] = pieces[:MAX_ATTACHMENTS]
+
+ # What a column's **words** mean in the case, which is not what `links` says. A link
+ # is one cell pointing at one entity, and it cannot answer a cell holding three pieces
+ # of equipment; a vocabulary pointed at the case can, and it is also the grain a whole
+ # column is promoted at — forty names out of four hundred rows.
+ values = meta.get("values")
+ if isinstance(values, dict):
+ for name, words in values.items():
+ if name not in known or not isinstance(words, dict):
+ continue
+ meant = {
+ _clean_cell(word).strip(): str(entity_id)
+ for word, entity_id in list(words.items())[:MAX_COLUMN_VALUES]
+ if _clean_cell(word).strip() and isinstance(entity_id, str) and entity_id
+ }
+ if meant:
+ clean["values"][name] = meant
+
+ description = meta.get("description")
+ if isinstance(description, str):
+ clean["description"] = _clean_cell(description).strip()[:MAX_DESCRIPTION]
+
+ # -- version 6: the entity the row was made from --------------------------
+ # Deliberately **not** run through the dead-link sweep below. An id here is a record
+ # of where the row came from, not a claim that the case still holds it, so an entity
+ # that has since been deleted must leave this exactly as it is — that is the one
+ # question `in_case` exists to answer.
+ built = meta.get("built")
+ if isinstance(built, dict):
+ for identity, entity_id in built.items():
+ if identity in identities and isinstance(entity_id, str) and entity_id:
+ clean["built"][identity] = entity_id
+ return clean
+
+
+#: What a column's filter may be asked, beyond which values it holds. Mirrors
+#: `lib/sheet.FILL_ASKS`.
+FILL_ASKS = ("blank", "filled", "unreadable")
+
+
+def _clean_filter(entry: dict[str, Any]) -> dict[str, Any] | None:
+ """One column's filter, or None when nothing is actually asked of it.
+
+ The clauses are stored as the browser holds them, with one difference that matters:
+ the chosen values are a **list** here and a Set there. JSON has no set, and a
+ sidecar that carried one would be a file no other reader could parse.
+ """
+ values: list[str] = []
+ raw = entry.get("values")
+ if isinstance(raw, list):
+ for value in raw:
+ if isinstance(value, str) and value not in values:
+ values.append(_clean_cell(value))
+ if len(values) >= MAX_FILTER_VALUES:
+ break
+ fill = entry.get("fill")
+ asked = {
+ "values": values,
+ "fill": fill if fill in FILL_ASKS else None,
+ "contains": _clean_cell(entry.get("contains") or "").strip()[:MAX_QUERY],
+ "without": _clean_cell(entry.get("without") or "").strip()[:MAX_QUERY],
+ "from": _clean_cell(entry.get("from") or "").strip()[:MAX_QUERY],
+ "to": _clean_cell(entry.get("to") or "").strip()[:MAX_QUERY],
+ }
+ if not any(asked.values()):
+ return None
+ return asked
+
+
+def linked_entity_ids(meta: dict[str, Any]) -> list[str]:
+ """Every entity a sheet points at, deduplicated, in reading order.
+
+ Cells first, then what the rows have hung on themselves. Both become the same
+ `mentions` edge, because both are the same statement: this sheet refers to that. A
+ piece attached to a row and reachable only from the sheet would be a file the case
+ holds and the subject's own panel could not see.
+ """
+ found: list[str] = []
+ for cells in (meta.get("links") or {}).values():
+ found.extend(str(value) for value in cells.values() if value)
+ for words in (meta.get("values") or {}).values():
+ found.extend(str(value) for value in words.values() if value)
+ for held in (meta.get("attachments") or {}).values():
+ found.extend(str(value) for value in held if value)
+ return list(dict.fromkeys(found))
+
+
+def sync_mentions(case: "Case", sheet_id: str, meta: dict[str, Any]) -> None:
+ """Restate the entities this sheet points at, as ``mentions`` edges.
+
+ Beside the sidecar it reads, because the edges are a *function* of it: whatever
+ wrote the sidecar — a save, a promotion, a row moved to another sheet — the sheet
+ should mention exactly what its rows now point at, and a link the analyst cleared
+ should lose its edge.
+
+ **A function of the sidecar, and only of the sidecar** (``own_only``). ``mentions``
+ is also a relation an analyst may state by hand, and a sheet is one of the documents
+ it can be stated from — so the graph holds two kinds, and reconciling over both let
+ the sidecar-only route delete a claim nobody made in a cell. That route is the one
+ behind a funnel being ticked, which is to say a click that touches no cell was
+ permanently dropping somebody's own statement.
+
+ A target the vocabulary refuses is skipped rather than raised: the cell keeps its
+ link and the grid keeps working, exactly as a note's body does with a token pointing
+ somewhere odd. The sidecar is the record either way — the edges are what make the
+ sheet visible from the other end.
+ """
+ from . import links as link_engine
+
+ source = case.get_entity(sheet_id)
+ if source is None:
+ return
+ wanted: list[str] = []
+ for entity_id in linked_entity_ids(meta):
+ try:
+ link_engine.check_relation_target(case, source, entity_id, link_engine.MENTIONS)
+ except CaseError:
+ continue
+ wanted.append(entity_id)
+ case.sync_links(sheet_id, link_engine.MENTIONS, wanted, by="sheet", own_only=True)
+
+
+# -- files --------------------------------------------------------------------
+
+
+def _sheet_entity(case: "Case", entity_id: str) -> dict[str, Any]:
+ entity = case.get_entity(entity_id)
+ if entity is None or entity.get("type") != "sheet":
+ raise CaseError(f"sheet '{entity_id}' not found")
+ return entity
+
+
+def _paths(case: "Case", entity: dict[str, Any]) -> tuple[Path, Path]:
+ rel = (entity.get("attrs") or {}).get("path")
+ if not isinstance(rel, str) or not rel:
+ raise CaseError(f"sheet '{entity['id']}' has no file")
+ stem = Path(rel).stem
+ return case.resolve_inside(rel), case.resolve_inside(layout.sheet_meta_rel(stem))
+
+
+def target(case: "Case", title: str, *, taken_by: str | None = None) -> str:
+ """A free case-relative path for a sheet called *title*.
+
+ Same rule as every other named artifact: the name is the filename. A name
+ already used gets a numbered suffix rather than a refusal, because the front
+ already proposes free names and a save is not the moment to argue about one.
+ """
+ stem = layout.slugify(title, "Sheet")
+ directory = case.resolve_inside(layout.sheet_rel(stem)).parent
+ keep = case.resolve_inside(taken_by) if taken_by else None
+ occupied = (
+ {path.name.casefold() for path in directory.iterdir() if path != keep}
+ if directory.is_dir()
+ else set()
+ )
+ candidate, index = layout.sheet_rel(stem), 2
+ while Path(candidate).name.casefold() in occupied:
+ candidate = layout.sheet_rel(f"{stem}-{index}")
+ index += 1
+ return candidate
+
+
+def create(
+ case: "Case",
+ title: str,
+ columns: list[Any] | None = None,
+ rows: list[Any] | None = None,
+) -> dict[str, Any]:
+ """File a new sheet: a graph row, a CSV on disk, and an empty sidecar.
+
+ The table is written at creation rather than on first save, so a sheet made
+ and never touched is still a real file the case owns — the same rule a note
+ follows, and what keeps the trash and the bundle able to see it.
+
+ **The file first, the row second.** A read-only folder, a full disk and a name
+ taken by a directory are the three cases `SheetUnwritable` exists for, and filing
+ the entity before the write left every one of them with a sheet the list showed
+ and nothing could open. The label is slugified here rather than read back off the
+ entity because the store keeps a label verbatim, so the path is known before the
+ row exists.
+
+ **The label is the file's own stem, suffix and all.** `target` steps a taken name to
+ `-2` rather than refusing it, and the label used to keep the name that was asked for —
+ so building the same shape twice left two sheets reading `My geolocations` in the list,
+ backed by two different files, with nothing on screen to tell them apart. Taking the
+ stem back is what makes the rule this module states hold at birth: the name *is* the
+ filename.
+ """
+ names, table = normalize(
+ columns if columns is not None else ["Subject", "Status", "Notes"],
+ rows if rows is not None else [],
+ )
+ rel = target(case, layout.slugify(title, "Sheet"))
+ write_atomic(case.resolve_inside(rel), to_csv(names, table), encoding=CSV_ENCODING)
+ return case.add_entity("sheet", Path(rel).stem, {"path": rel}, by="sheet")
+
+
+def discard(case: "Case", entity: dict[str, Any]) -> None:
+ """Undo a `create` a later step made pointless: the row and the files it owns.
+
+ Not the trash, because nothing here was ever the analyst's: a workbook whose fourth
+ tab cannot be written should leave neither three sheets nor three bin entries to
+ clean up. Best effort throughout — it runs while another failure is being raised,
+ and hiding that one behind a second would be the worse answer.
+ """
+ rel = (entity.get("attrs") or {}).get("path")
+ if isinstance(rel, str) and rel:
+ for candidate in (rel, layout.sheet_meta_rel(Path(rel).stem)):
+ try:
+ case.resolve_inside(candidate).unlink(missing_ok=True)
+ except (CaseError, OSError):
+ continue
+ try:
+ case.remove_entity(str(entity["id"]))
+ except CaseError:
+ return
+
+
+def read(case: "Case", entity_id: str) -> dict[str, Any]:
+ """One sheet: its table, its sidecar, its stamp, and whether ids were minted.
+
+ ``assigned`` is how the grid knows the file on disk does not carry the keys it
+ is showing yet. Reading never writes — a case opened to be looked at stays
+ byte-identical — so the first save is what settles it. A ``computed`` column is
+ restated into the table handed over for the same reason and with the same rule: the
+ grid shows what the case answers *now*, and the next save is what puts it on disk.
+
+ ``stamp`` is taken **before** the file is read, so a write landing between the
+ two produces a token that no longer matches the bytes returned. Stamping after
+ would hand back a token that says "this is current" for a table that is not.
+ """
+ entity = _sheet_entity(case, entity_id)
+ path, meta_path = _paths(case, entity)
+ token = stamp(path)
+ try:
+ raw = path.read_text(encoding="utf-8-sig")
+ except OSError:
+ raw = ""
+ columns, rows = parse_csv(raw)
+ try:
+ stored = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ stored = None
+ clean = clean_meta(stored, columns, rows)
+ # A link the case cannot answer for is not shown as one. In memory only: reading
+ # never writes, so the file settles on the next save.
+ clean = drop_dead_links(case, clean)
+ # Roles whose column is no longer in the file. Reported rather than dropped in
+ # silence: someone renaming a column in a spreadsheet takes the role with it, and a
+ # lens configured in ten minutes is not a colour. Same idea as `assigned`.
+ declared = (stored or {}).get("roles") if isinstance(stored, dict) else None
+ dropped = (
+ sorted(set(declared or {}) - set(clean["roles"])) if isinstance(declared, dict) else []
+ )
+ # What the case currently answers, restated into the table that is handed over — in
+ # memory, so the read still leaves the file byte-identical. Without it an `On map`
+ # column said whatever the last save said, and a place added from the map an hour ago
+ # left the sheet reading NO until somebody happened to type in it.
+ sheetroles.apply_computed(
+ case, columns, rows, clean["roles"], clean["links"], clean["built"]
+ )
+ return {
+ "id": entity_id,
+ "title": entity.get("label") or "Sheet",
+ "path": (entity.get("attrs") or {}).get("path"),
+ "columns": columns,
+ "rows": rows,
+ "meta": clean,
+ "stamp": token,
+ "dropped_roles": dropped,
+ "pieces": _pieces(case, clean),
+ "assigned": ID_COLUMN
+ not in [_clean_cell(name).strip().casefold() for name in _heading(raw)],
+ }
+
+
+def _pieces(case: "Case", meta: dict[str, Any]) -> dict[str, dict[str, str]]:
+ """What each case file a row carries is called, so the panel can name it.
+
+ The sidecar stores ids and only ids — a label copied beside one goes stale the moment
+ the entity is renamed, which is the whole reason a link is an id. But a panel listing
+ `e_58fea8e8f0` is a panel nobody can read, and there is no route that reads one entity,
+ so the read that already answers the sidecar answers the names too.
+
+ Attachments alone, and one walk of the graph rather than a lookup each: a sheet may
+ point at hundreds of entities from its cells, and none of those needs a name here —
+ a linked cell shows the words the file holds.
+ """
+ wanted = {
+ str(entity_id) for held in (meta.get("attachments") or {}).values() for entity_id in held
+ }
+ if not wanted:
+ return {}
+ return {
+ str(entity["id"]): {
+ "label": str(entity.get("label") or ""),
+ "type": str(entity.get("type") or ""),
+ }
+ for entity in case.list_entities()
+ if str(entity["id"]) in wanted
+ }
+
+
+def _heading(raw: str) -> list[str]:
+ """The heading row exactly as the file holds it, for the id-column check."""
+ body = raw.lstrip("")
+ if not body.strip():
+ return []
+ reader = csv.reader(io.StringIO(body), delimiter=sniff_delimiter(body))
+ try:
+ return next(reader, [])
+ except csv.Error:
+ return []
+
+
+def ensure_current(case: "Case", entity_id: str, expected: str | None) -> None:
+ """Raise `SheetConflict` unless the file is still the one the caller read.
+
+ The same check `write` makes, asked **before** anything else happens. Promotion is
+ why it exists: it changes the graph and then saves the sheet, so finding out at the
+ write that the file had moved on left entities behind for a save that never landed.
+ A refusal has to come before the first entity, not after the last one.
+ """
+ entity = _sheet_entity(case, entity_id)
+ path, _ = _paths(case, entity)
+ if expected is not None and stamp(path) != expected:
+ raise SheetConflict("this file changed on disk since it was opened")
+
+
+def write(
+ case: "Case",
+ entity_id: str,
+ columns: list[Any],
+ rows: list[Any],
+ meta: Any,
+ expected: str | None = None,
+) -> dict[str, Any]:
+ """Write a sheet's table and sidecar, and return what landed.
+
+ Both files are written, in that order: a sidecar describing a table that was
+ never saved would paint rows the analyst does not have.
+
+ *expected* is the stamp the caller last read. When it is given and the file no
+ longer matches it, nothing is written and `SheetConflict` is raised: the analyst
+ has the CSV open in a spreadsheet too, and the grid's twenty-minute-old copy of
+ the table must not win over what they just typed there. Omitting it writes
+ unconditionally, which is what a caller holding a table it just built — an
+ import, a fresh sheet — is entitled to do.
+ """
+ entity = _sheet_entity(case, entity_id)
+ path, meta_path = _paths(case, entity)
+ if expected is not None and stamp(path) != expected:
+ raise SheetConflict("this file changed on disk since it was opened")
+ names, table = normalize(columns, rows)
+ clean = clean_meta(meta, names, table)
+ # A grid that has been open since before a delete still holds the link it made then,
+ # and a save is exactly where that dead id would land back on disk.
+ clean = drop_dead_links(case, clean)
+ # The two columns the app fills rather than the analyst, in that order: a row that
+ # has just been stamped is a row that exists, and `computed` restates the graph for
+ # every row including it. Both write **into the table**, before it is serialised,
+ # because both are columns a collaborator opening the CSV is meant to read.
+ sheetroles.apply_stamped(names, table, clean["roles"])
+ sheetroles.apply_computed(
+ case, names, table, clean["roles"], clean["links"], clean["built"]
+ )
+ write_atomic(path, to_csv(names, table), encoding=CSV_ENCODING)
+ write_atomic(meta_path, json.dumps(clean, ensure_ascii=False, indent=2), encoding="utf-8")
+ return {"columns": names, "rows": table, "meta": clean, "stamp": stamp(path)}
+
+
+def write_meta(case: "Case", entity_id: str, meta: Any) -> dict[str, Any]:
+ """Write the sidecar alone, leaving the CSV byte-identical.
+
+ The route behind the grid's own view: a filter ticked, a column hidden, a colour
+ painted, the row kept in view. All of those are the sidecar and none of them is the
+ table — and a save that rewrote the CSV for them would move its modification time,
+ which is what the stamp is made of. Two costs followed from that: the analyst's own
+ next save answered a conflict nobody caused, and a spreadsheet open on the same file
+ was told it had been overwritten because somebody clicked a funnel.
+
+ So no stamp is presented and none is checked: nothing here can lose a cell. The
+ columns and rows are read from disk only to know what the sidecar may still refer
+ to, which is what `clean_meta` needs.
+ """
+ entity = _sheet_entity(case, entity_id)
+ path, meta_path = _paths(case, entity)
+ try:
+ raw = path.read_text(encoding="utf-8-sig")
+ except OSError:
+ raw = ""
+ columns, rows = parse_csv(raw)
+ clean = clean_meta(meta, columns, rows)
+ clean = drop_dead_links(case, clean)
+ write_atomic(meta_path, json.dumps(clean, ensure_ascii=False, indent=2), encoding="utf-8")
+ return {"meta": clean}
+
+
+#: How many sheets one page of the delete's sweep reads. A case has a handful, not a
+#: catalog of them, so this is a bound rather than a paging strategy.
+SHEET_PAGE = 200
+
+
+def forget_entities(case: "Case", gone: set[str]) -> list[str]:
+ """Drop every pointer the case's sheets keep at entities that have just gone.
+
+ A sheet points at the case through **ids in a sidecar** — a cell's link, a column's
+ vocabulary, the files a row carries — and none of those is an edge the graph takes
+ with it. Deleting the entity left the cell still marked as linked, the row still
+ carrying a file the case no longer holds, and a later save writing the dead id back.
+
+ Called by the one delete every surface goes through, so a sheet cannot outlive what
+ it points at whichever screen the click came from. The CSV is never touched: a link
+ is the sidecar's, and rewriting the table here would move the stamp under an analyst
+ who is typing in it.
+
+ Returns the sheets it rewrote.
+ """
+ if not gone:
+ return []
+ rewritten: list[str] = []
+ cursor: str | None = None
+ while True:
+ # The sheets alone, off the catalog rather than a walk of the graph: this runs
+ # inside every delete, and a case holding a hundred thousand rows must not read
+ # them to clear a link.
+ page = case.page_entities(limit=SHEET_PAGE, cursor=cursor, types=["sheet"])
+ for entity in page.get("items", []):
+ try:
+ _, meta_path = _paths(case, entity)
+ stored = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (CaseError, OSError, ValueError):
+ continue # a sheet with no readable sidecar has nothing to forget
+ if not isinstance(stored, dict):
+ continue
+ pruned = _without_entities(stored, gone)
+ if pruned is None:
+ continue
+ try:
+ write_meta(case, entity["id"], pruned)
+ except (CaseError, OSError, SheetUnwritable):
+ # One sheet whose file refuses is not a reason to fail the delete and
+ # roll the whole thing back: that sheet keeps its dead link, every other
+ # one is cleared, and nothing in the case is left half-deleted.
+ # `SheetUnwritable` is named because it is a `ValueError` and not an
+ # `OSError`, so it used to escape the sentence above and take the delete
+ # down with it.
+ continue
+ rewritten.append(str(entity["id"]))
+ cursor = page.get("next_cursor")
+ if not cursor:
+ return rewritten
+
+
+def drop_dead_links(case: "Case", meta: dict[str, Any]) -> dict[str, Any]:
+ """The sidecar with every pointer at something the case no longer holds removed.
+
+ `forget_entities` clears the sheets as a delete happens, which is the eager half of
+ this. The rule itself is here, and it runs on every read and every save, because a
+ link can go dead without a delete ever passing through this app: a sidecar carried in
+ from another case, a case restored beside sheets written against older ids, a file
+ edited by hand. A cell claiming a link to nothing is worse than a plain cell — it
+ reads as work already done, and it opens a panel about an entity nobody can see.
+
+ One bounded lookup for the whole sidecar rather than a query per cell. Unchanged
+ sidecars are handed straight back, so a read stays free of copying.
+ """
+ wanted = linked_entity_ids(meta)
+ if not wanted:
+ return meta
+ held = {str(entity["id"]) for entity in case.entities_by_ids(wanted)}
+ gone = {entity_id for entity_id in wanted if entity_id not in held}
+ return _without_entities(meta, gone) or meta
+
+
+def _without_entities(meta: dict[str, Any], gone: set[str]) -> dict[str, Any] | None:
+ """The sidecar with every pointer at *gone* removed, or None when it held none.
+
+ Answering None rather than a copy is what keeps a delete from rewriting every
+ sidecar in the case: only a sheet that actually pointed at the deleted material is
+ written, so nothing else has its file touched.
+ """
+ hit = False
+ out = dict(meta)
+
+ links = meta.get("links")
+ if isinstance(links, dict):
+ kept_rows: dict[str, Any] = {}
+ for identity, cells in links.items():
+ if not isinstance(cells, dict):
+ continue
+ kept = {name: value for name, value in cells.items() if value not in gone}
+ if len(kept) != len(cells):
+ hit = True
+ if kept:
+ kept_rows[identity] = kept
+ if hit:
+ out["links"] = kept_rows
+
+ values = meta.get("values")
+ if isinstance(values, dict):
+ kept_columns: dict[str, Any] = {}
+ touched = False
+ for name, words in values.items():
+ if not isinstance(words, dict):
+ continue
+ kept = {word: value for word, value in words.items() if value not in gone}
+ if len(kept) != len(words):
+ touched = True
+ if kept:
+ kept_columns[name] = kept
+ if touched:
+ hit = True
+ out["values"] = kept_columns
+
+ attachments = meta.get("attachments")
+ if isinstance(attachments, dict):
+ kept_held: dict[str, Any] = {}
+ touched = False
+ for identity, held in attachments.items():
+ if not isinstance(held, list):
+ continue
+ left = [value for value in held if value not in gone]
+ if len(left) != len(held):
+ touched = True
+ if left:
+ kept_held[identity] = left
+ if touched:
+ hit = True
+ out["attachments"] = kept_held
+
+ return out if hit else None
+
+
+def duplicate(
+ case: "Case", entity_id: str, title: str | None = None, *, with_rows: bool = True
+) -> dict[str, Any]:
+ """A second sheet holding the same table and the same sidecar.
+
+ The app's answer to "another reading of these rows" has always been *another sheet* —
+ that is why there are no named views — and until this existed there was no way to make
+ one without exporting the CSV and importing it back, which lost every colour, role and
+ link on the way. The copy carries the sidecar whole: it is a fork of the work, not a
+ blank grid with the same headings.
+
+ The rows keep their keys. Two sheets naming the same row is not a clash — the key is
+ the row's handle inside its own file — and it is what lets a promoted row in the copy
+ still say which entity it came from.
+
+ ``with_rows=False`` forks the **shape** instead: the same headings and everything the
+ app knows about them — the roles, the vocabularies, the notes, the progress column,
+ the anchors — with no rows under it. That is the other table the binders had, and it
+ is not a copy: an inbox, a worklist and a reference table are three sheets at one
+ schema, and a row moves up a floor as it is worked out. Everything the sidecar keyed
+ on a row goes with the rows, which `clean_meta` does on its own once there are none.
+ """
+ source = _sheet_entity(case, entity_id)
+ path, meta_path = _paths(case, source)
+ try:
+ raw = path.read_text(encoding="utf-8-sig")
+ except OSError:
+ raw = ""
+ columns, rows = parse_csv(raw)
+ if not with_rows:
+ rows = []
+ try:
+ stored = json.loads(meta_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ stored = None
+ fallback = "copy" if with_rows else "empty"
+ name = (title or "").strip() or f"{source.get('label') or 'Sheet'} {fallback}"
+ entity = create(case, name, columns, rows)
+ saved = write(case, entity["id"], columns, rows, stored)
+ return {**entity, "meta": saved["meta"]}
+
+
+#: What the sidecar keeps per row, and therefore what travels when a row moves to
+#: another sheet. Colours and links are keyed by the row key; `promoted`, `attachments`
+#: and `built` are too. Everything else in the sidecar belongs to the column or to the
+#: sheet, and staying behind is what it means for it to belong there.
+ROW_KEYED = ("colours", "links", "promoted", "attachments", "built")
+
+
+def column_pairs(
+ names: list[str], to_columns: list[str], mapping: Any = None
+) -> list[tuple[str, str]]:
+ """Which column of this sheet lands in which column of that one.
+
+ By name when nothing is said, which is what a move between two tabs of the same
+ binder wants: the schema is shared, so the names already line up. *mapping* is what
+ a dialog that has read both shapes hands over instead — `Adresse` into `Address` is
+ one column spelled twice, and the name match alone called it a loss. A source column
+ left out of it, or pointed at nothing, is dropped.
+
+ The destination's shape stays its own: a target it does not have is refused rather
+ than added, and two columns cannot be poured into one.
+ """
+ if mapping is None:
+ return [
+ (name, name) for name in names if name in to_columns and name.casefold() != ID_COLUMN
+ ]
+ if not isinstance(mapping, dict):
+ raise SheetError("the column mapping must say which column lands in which")
+ known = set(names)
+ theirs = set(to_columns)
+ pairs: list[tuple[str, str]] = []
+ taken: set[str] = set()
+ for source, target in mapping.items():
+ if not isinstance(source, str) or not isinstance(target, str) or not target:
+ continue
+ # The key column is matched without regard to case for the same reason it is
+ # everywhere else: a file that arrived spelling it `ID` keeps its own spelling.
+ if source not in known or source.casefold() == ID_COLUMN:
+ raise SheetError(f"this sheet has no column called “{source}”")
+ if target not in theirs or target.casefold() == ID_COLUMN:
+ raise SheetError(f"that sheet has no column called “{target}”")
+ if target in taken:
+ raise SheetError(f"two columns cannot both land in “{target}”")
+ taken.add(target)
+ pairs.append((source, target))
+ # In the order the source draws them, so what the answer names reads like the sheet.
+ order = {name: index for index, name in enumerate(names)}
+ return sorted(pairs, key=lambda pair: order[pair[0]])
+
+
+def move_rows(
+ case: "Case",
+ from_id: str,
+ to_id: str,
+ keys: list[str],
+ columns: list[Any],
+ rows: list[Any],
+ meta: Any,
+ mapping: Any = None,
+ expected: str | None = None,
+) -> dict[str, Any]:
+ """Take rows out of one sheet and put them in another, columns matched by name.
+
+ The gesture the binders' three tabs were built out of: an inbox, a worklist and a
+ reference table at one schema, and a row that has been worked out **moves up a
+ floor**. Copying it by hand loses the colour, the entity the cell points at and the
+ record that it was already promoted, which is exactly the state worth keeping.
+
+ Columns are matched **by name** unless *mapping* says otherwise, and a column with
+ nothing in front of it is dropped rather than added: the destination's shape is its
+ own, and a move that grew it by three columns would be an import wearing a different
+ word. What was dropped is answered, because a silent loss reads as a clean move.
+
+ The source's table travels in the request the way a promotion's does — the analyst
+ moves what is on screen, and the version on disk may be a minute behind — so the
+ source's stamp is presented and the write is refused if the file moved on. The
+ destination is read from disk immediately before it is written, which is the whole
+ window in which nothing can have touched it.
+
+ A key already taken in the destination is minted fresh, and everything the sidecar
+ hung on the old one moves with it: two sheets can hold the same key without it being
+ a clash, but one sheet holding it twice would be.
+ """
+ if from_id == to_id:
+ raise SheetError("a row cannot be moved into the sheet it is already in")
+ _sheet_entity(case, from_id)
+ target = _sheet_entity(case, to_id)
+ ensure_current(case, from_id, expected)
+
+ names, table = normalize(columns, rows)
+ clean = clean_meta(meta, names, table)
+ key_at = key_index(names)
+ wanted = [key for key in dict.fromkeys(keys) if key]
+ taking = {row[key_at] for row in table if row[key_at] in set(wanted)}
+ if not taking:
+ raise SheetError("none of these rows are in this sheet")
+
+ to_path, to_meta_path = _paths(case, target)
+ try:
+ raw = to_path.read_text(encoding="utf-8-sig")
+ except OSError:
+ raw = ""
+ to_columns, to_rows = parse_csv(raw)
+ try:
+ to_stored = json.loads(to_meta_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ to_stored = {}
+ if not isinstance(to_stored, dict):
+ to_stored = {}
+
+ pairs = column_pairs(names, to_columns, mapping)
+ landing_of = dict(pairs)
+ dropped = [name for name in names if name not in landing_of and name != ID_COLUMN]
+ to_key_at = key_index(to_columns)
+ held = {row[to_key_at] for row in to_rows}
+
+ carried: dict[str, dict[str, Any]] = {key: dict(to_stored.get(key) or {}) for key in ROW_KEYED}
+ #: The key each row is filed under over there, which is the only handle an undo has:
+ #: a key already taken in the destination is minted fresh, so the row the analyst
+ #: sent is not always the row they could ask for back by name.
+ landed: list[str] = []
+ for row in table:
+ identity = row[key_at]
+ if identity not in taking:
+ continue
+ fresh = identity if identity not in held else new_row_id()
+ held.add(fresh)
+ landing = [""] * len(to_columns)
+ landing[to_key_at] = fresh
+ for mine, theirs in pairs:
+ landing[to_columns.index(theirs)] = row[names.index(mine)]
+ to_rows.append(landing)
+ landed.append(fresh)
+ for key in ROW_KEYED:
+ was = (clean.get(key) or {}).get(identity)
+ if was is None:
+ continue
+ # A link or a promoted reading is keyed by column as well as by row, so a
+ # column the destination does not have loses it here rather than carrying a
+ # pointer into a column nobody can see.
+ if key in ("links", "promoted"):
+ was = {landing_of[name]: value for name, value in was.items() if name in landing_of}
+ if not was:
+ continue
+ carried[key][fresh] = was
+
+ # What the destination held, kept as bytes so a refused source write can put it back
+ # exactly. The order stands — the destination first — but the moment between the two
+ # writes must not become a permanent state: a row in both sheets is the duplicate an
+ # analyst cannot see, since it is in another sheet under another key. `undo_move`
+ # reasons about the same window and reaches the same conclusion.
+ to_was = (_bytes_at(to_path), _bytes_at(to_meta_path))
+ saved_to = write(case, to_id, to_columns, to_rows, {**to_stored, **carried})
+ sync_mentions(case, to_id, saved_to["meta"])
+
+ stayed = [row for row in table if row[key_at] not in taking]
+ left = {
+ **clean,
+ **{
+ key: {
+ identity: value
+ for identity, value in (clean.get(key) or {}).items()
+ if identity not in taking
+ }
+ for key in ROW_KEYED
+ },
+ }
+ try:
+ saved_from = write(case, from_id, names, stayed, left, expected=expected)
+ except Exception:
+ # The source refused — a spreadsheet holding it open, or a file that moved on
+ # under the grid. The destination goes back to the bytes it had, so the answer
+ # the route gives ("nothing moved") is the truth on disk as well.
+ _put_back(to_path, to_was[0])
+ _put_back(to_meta_path, to_was[1])
+ sync_mentions(case, to_id, to_stored)
+ raise
+ # Both ends restate, and the source's is the one easy to forget: a row that left
+ # takes its links with it, so a sheet that kept the edge would still be listed on
+ # the subject's own panel as mentioning it.
+ sync_mentions(case, from_id, saved_from["meta"])
+ return {
+ "moved": len(landed),
+ "landed": landed,
+ "dropped": dropped,
+ "to": {"id": to_id, "title": target.get("label") or "Sheet", "rows": len(to_rows)},
+ **saved_from,
+ }
+
+
+def undo_move(
+ case: "Case",
+ from_id: str,
+ to_id: str,
+ keys: list[str],
+ columns: list[Any],
+ rows: list[Any],
+ meta: Any,
+ expected: str | None = None,
+) -> dict[str, Any]:
+ """Put a move back: the source as it was, and the rows it sent taken out again.
+
+ A move writes two files and there is nothing in the grid's own undo stack that can
+ reach either, which is what made a mis-aimed one final. It is not replayed backwards
+ — a move drops the columns the destination does not have, so a reverse move would
+ hand back rows with holes in them. The **table as it stood before** is what is
+ restored, which is the copy the grid still has on screen, and it carries the colours,
+ the links and the promotion records the rows left with.
+
+ *keys* are the keys the rows landed under over there, from the move's own answer.
+ Only those are taken out, so a row somebody added to the destination in between
+ stays. The source's stamp is presented as usual: if the analyst has typed into it
+ since, the undo is refused rather than overwriting what they typed.
+ """
+ if from_id == to_id:
+ raise SheetError("a move cannot be undone into the sheet it came from")
+ _sheet_entity(case, from_id)
+ target = _sheet_entity(case, to_id)
+ ensure_current(case, from_id, expected)
+
+ to_path, to_meta_path = _paths(case, target)
+ try:
+ raw = to_path.read_text(encoding="utf-8-sig")
+ except OSError:
+ raw = ""
+ to_columns, to_rows = parse_csv(raw)
+ try:
+ to_stored = json.loads(to_meta_path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ to_stored = {}
+ if not isinstance(to_stored, dict):
+ to_stored = {}
+
+ taking = {key for key in keys if key}
+ to_key_at = key_index(to_columns)
+ kept = [row for row in to_rows if row[to_key_at] not in taking]
+ # The destination first: for the moment between the two writes a row is in neither
+ # sheet rather than in both, and a duplicate is the one of the two an analyst cannot
+ # see. Its sidecar needs no filtering, since a save drops what its table no longer
+ # holds.
+ saved_to = write(case, to_id, to_columns, kept, to_stored)
+ sync_mentions(case, to_id, saved_to["meta"])
+ saved_from = write(case, from_id, columns, rows, meta, expected=expected)
+ sync_mentions(case, from_id, saved_from["meta"])
+ return {
+ "undone": len(to_rows) - len(kept),
+ "from": {"id": to_id, "title": target.get("label") or "Sheet", "rows": len(kept)},
+ **saved_from,
+ }
+
+
+def export_csv(case: "Case", entity_id: str, columns: list[Any], rows: list[Any]) -> dict[str, str]:
+ """The table the grid is showing, serialised for the analyst to hand over.
+
+ The columns and rows are the caller's rather than the file's, and that is the whole
+ point of the route: the case folder already holds the sheet, so a byte copy of it
+ would be a button that produces a file the analyst already has. What they do not
+ have is *this reading* — the twelve rows left to check, the four columns kept, in
+ the order they were sorted into.
+
+ Serialised here because there is one CSV writer in the app and it is this one. A
+ second one in the browser would be a second answer to how a quoted newline is
+ written, on the one artifact that has to open in any spreadsheet.
+ """
+ entity = _sheet_entity(case, entity_id)
+ names, table = normalize(columns, rows)
+ stem = layout.slugify(str(entity.get("label") or "Sheet"), "Sheet")
+ return {"filename": f"{stem}.csv", "csv": to_csv(names, table)}
+
+
+def summary(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:
+ """A row for the sheet list: what it is called and how big it is.
+
+ Counted through the CSV reader rather than by counting lines, because a note
+ column holds sentences and a quoted newline is one row, not two.
+ """
+ rel = (entity.get("attrs") or {}).get("path")
+ rows = 0
+ headings: list[str] = []
+ if isinstance(rel, str) and rel:
+ try:
+ raw = case.resolve_inside(rel).read_text(encoding="utf-8-sig")
+ except (OSError, CaseError):
+ raw = ""
+ if raw.strip():
+ reader = csv.reader(io.StringIO(raw.lstrip("")), delimiter=sniff_delimiter(raw))
+ try:
+ headings = [str(name) for name in next(reader, [])]
+ rows = sum(1 for _ in reader)
+ except csv.Error:
+ headings, rows = [], 0
+ return {
+ "id": entity.get("id"),
+ "title": entity.get("label") or "Sheet",
+ "path": rel,
+ "rows": rows,
+ "columns": len(headings),
+ # The names as well as the count, because the one screen that has to know them —
+ # the move's column mapping — would otherwise read every other sheet in the case
+ # whole just to learn its headings.
+ "headings": headings,
+ "created_at": (entity.get("prov") or {}).get("at"),
+ }
diff --git a/src/azimut/engine/sheetxlsx.py b/src/azimut/engine/sheetxlsx.py
new file mode 100644
index 0000000..2422eae
--- /dev/null
+++ b/src/azimut/engine/sheetxlsx.py
@@ -0,0 +1,197 @@
+"""Read a workbook into one table per tab, so a binder arrives whole.
+
+The three binders this tool was written against have five, six and one tab. Two of the
+six hold nothing but pasted screenshots. Asking the analyst to open each one and export
+it to CSV by hand is asking them not to bother, and the tab that gets skipped is always
+the "How to use" one that says what the others mean.
+
+**Reading only, and into the same tables every other import lands in.** The case's
+artifact is a CSV — that is the whole design (`engine/sheets.py`) — so nothing here
+writes a workbook, and every tab goes through `sheets.normalize` like a dropped file.
+What comes out is a list of tables, and it is the caller that decides which of them to
+file: a tab of screenshots reads as empty, and filing an empty sheet nobody asked for is
+worse than saying it was empty.
+
+**A cell becomes the words a person would read.** A workbook has no words — it has a
+serial number and a display format — so this is the one importer that has to choose a
+spelling. It chooses **ISO 8601**, because that is the one spelling that means the same
+thing in every locale, `parse_when` reads it, and it round-trips through a spreadsheet
+unchanged. A column of `dd/MM/yyyy` is one cleaning pass away for anyone who wants it.
+
+**Formulas arrive as their last answer, not as their text.** That is what the analyst was
+looking at, and `=VLOOKUP(...)` in a cell is a reference to a workbook the case will not
+have. A formula Excel never cached reads as empty, which is honest: nothing computed it.
+"""
+
+from __future__ import annotations
+
+import io
+import zipfile
+from datetime import date, datetime, time
+from typing import Any
+
+from openpyxl import load_workbook
+from openpyxl.utils.exceptions import InvalidFileException
+
+from .sheets import MAX_COLUMNS, MAX_ROWS, SheetError
+
+#: How many tabs one workbook may be read into sheets. Six is the biggest binder seen;
+#: past a couple of dozen the file is a database export and the grid is the wrong tool.
+MAX_TABS = 24
+
+#: How large a workbook may be before it is refused unread. An .xlsx is zipped XML, so
+#: this is several times the CSV bound it expands into.
+MAX_XLSX_BYTES = 32 * 1024 * 1024
+
+#: How far a workbook may expand once unzipped. An .xlsx is compressed XML and a real one
+#: expands ten or fifteen times over, so this leaves a full-size workbook room while
+#: refusing the shape it is here for: thirty two megabytes of zeroes declaring gigabytes of
+#: `sharedStrings.xml`, which `read_only` streams no part of. The app already bounds images
+#: for exactly this reason (`MAX_IMAGE_PIXELS`), and an archive from a third party is the
+#: same class of file — the binders this reader exists for arrive by email.
+MAX_XLSX_UNZIPPED_BYTES = 512 * 1024 * 1024
+
+
+def _clock(value: datetime | time) -> str:
+ """The time of day a cell holds, to the second when it has one.
+
+ The seconds are written because ISO 8601 carries them and `parse_when` reads them: a
+ workbook's timecode column is what an offset is counted in, and cutting `00:01:23` to
+ `00:01` moved a synchronised video by twenty three seconds with nothing said. They are
+ left off when they are zero, so a column of days and hours keeps the spelling somebody
+ typed rather than gaining `:00` on every row.
+
+ Midnight is empty, which is how a `datetime` with no time in it reads as a date.
+ """
+ if not (value.hour or value.minute or value.second):
+ return ""
+ return value.strftime("%H:%M:%S" if value.second else "%H:%M")
+
+
+def _cell(value: Any) -> str:
+ """One cell as the text a reader would see.
+
+ Booleans come back as the two words a `boolean` column is born with, so a tick column
+ imported out of Excel and one typed into the grid hold the same file. A float that is
+ a whole number loses its `.0`: Excel stores every number as a double, and a column of
+ counts reading `12.0` is a column nobody would have typed.
+ """
+ if value is None:
+ return ""
+ if isinstance(value, bool):
+ return "YES" if value else "NO"
+ if isinstance(value, datetime):
+ stamp = value.strftime("%Y-%m-%d")
+ clock = _clock(value)
+ return stamp if not clock else f"{stamp} {clock}"
+ if isinstance(value, date):
+ return value.isoformat()
+ if isinstance(value, time):
+ return _clock(value) or "00:00"
+ if isinstance(value, float) and value.is_integer():
+ return str(int(value))
+ return str(value)
+
+
+def _trim(rows: list[list[str]]) -> list[list[str]]:
+ """Drop the trailing empty rows and columns a spreadsheet always reports.
+
+ Excel's idea of how far a sheet extends outlives whatever was deleted from it, so a
+ tab of eleven rows arrives claiming nine hundred and sixty-nine. The binders' own
+ timeline tab does exactly that.
+ """
+ while rows and not any(cell.strip() for cell in rows[-1]):
+ rows.pop()
+ if not rows:
+ return []
+ width = max(
+ (index + 1 for row in rows for index, cell in enumerate(row) if cell.strip()),
+ default=0,
+ )
+ return [row[:width] + [""] * max(0, width - len(row)) for row in rows]
+
+
+def _unzipped_size(data: bytes) -> int:
+ """What the archive says it expands into, read off the directory and not by unzipping.
+
+ `zipfile` stops each member at its declared size and checks the CRC, so the declaration
+ is the bound the reader will honour: refusing on it costs no decompression at all.
+ """
+ try:
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ return sum(max(0, entry.file_size) for entry in archive.infolist())
+ except (zipfile.BadZipFile, OSError, ValueError):
+ # Not a zip, which `load_workbook` is about to say in the sentence written for it.
+ return 0
+
+
+def read_book(data: bytes) -> dict[str, Any]:
+ """Every tab of a workbook, as a heading row and a body, plus what was left out.
+
+ Answers all of them, empty ones included, each with its own name: which tabs are
+ worth filing is the caller's question, and a reader that silently dropped the empty
+ ones would hide the two tabs of pasted screenshots that a timeline binder keeps its
+ proof of the hour in.
+
+ Three ceilings hold — the tabs, the rows and the columns — and each of them is
+ **answered rather than applied in silence**. A thirty thousand row export arriving as
+ twenty thousand under a toast reading "5 sheets created" is a sheet that looks whole,
+ and there is nothing on screen to suspect otherwise. So ``dropped`` names the tabs past
+ `MAX_TABS` and each tab says whether it was cut, which is what the caller says out loud.
+ """
+ if len(data) > MAX_XLSX_BYTES:
+ raise SheetError(f"a workbook is read up to {MAX_XLSX_BYTES // (1024 * 1024)} MB")
+ if _unzipped_size(data) > MAX_XLSX_UNZIPPED_BYTES:
+ raise SheetError(
+ "a workbook is read up to "
+ f"{MAX_XLSX_UNZIPPED_BYTES // (1024 * 1024)} MB once unzipped"
+ )
+ try:
+ book = load_workbook(io.BytesIO(data), read_only=True, data_only=True)
+ except (
+ # An .xlsx is a zip of XML, so a mis-picked file fails at any of three layers:
+ # not a zip at all, a zip without the parts a workbook has, or XML that does not
+ # parse. All three are the same answer to the analyst.
+ zipfile.BadZipFile,
+ InvalidFileException,
+ OSError,
+ ValueError,
+ KeyError,
+ ) as exc:
+ raise SheetError(f"this file is not readable as a workbook: {exc}") from exc
+
+ tables: list[dict[str, Any]] = []
+ dropped = [str(tab.title) for tab in book.worksheets[MAX_TABS:]]
+ try:
+ for tab in book.worksheets[:MAX_TABS]:
+ rows: list[list[str]] = []
+ over_row = False
+ over_column = False
+ # One row and one column past each ceiling, read only to know whether the tab
+ # goes further. What lies past them is never kept, so the extra pair costs a
+ # cell each and buys the sentence that says the tab was cut.
+ for line in tab.iter_rows(
+ max_row=MAX_ROWS + 2, max_col=MAX_COLUMNS + 1, values_only=True
+ ):
+ cells = [_cell(value) for value in line]
+ if any(cell.strip() for cell in cells[MAX_COLUMNS:]):
+ over_column = True
+ if len(rows) > MAX_ROWS:
+ over_row = over_row or any(cell.strip() for cell in cells[:MAX_COLUMNS])
+ continue
+ rows.append(cells[:MAX_COLUMNS])
+ rows = _trim(rows)
+ tables.append(
+ {
+ "title": str(tab.title or "Sheet"),
+ "columns": rows[0] if rows else [],
+ "rows": rows[1:] if len(rows) > 1 else [],
+ #: How many were kept, when the tab held more. `None` is a tab that
+ #: fitted, which is every tab a binder has.
+ "cut_rows": MAX_ROWS if over_row else None,
+ "cut_columns": MAX_COLUMNS if over_column else None,
+ }
+ )
+ finally:
+ book.close()
+ return {"tabs": tables, "dropped": dropped}
diff --git a/src/azimut/engine/sky.py b/src/azimut/engine/sky.py
index 4437eea..fa29e45 100644
--- a/src/azimut/engine/sky.py
+++ b/src/azimut/engine/sky.py
@@ -207,7 +207,7 @@ def _moon_ecliptic(t: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- 0.186 * np.sin(ms) # yearly equation
- 0.059 * np.sin(2 * mm - 2 * elong)
- 0.057 * np.sin(mm - 2 * elong + ms)
- + 0.053 * np.sin(2 * elong + ms)
+ + 0.053 * np.sin(2 * elong + mm)
+ 0.046 * np.sin(2 * elong - ms)
+ 0.041 * np.sin(mm - ms)
- 0.035 * np.sin(elong) # parallactic
diff --git a/src/azimut/engine/stitch.py b/src/azimut/engine/stitch.py
index b91369b..1402fd9 100644
--- a/src/azimut/engine/stitch.py
+++ b/src/azimut/engine/stitch.py
@@ -26,13 +26,19 @@ that a curved warp is not a quad: the piece's pixels are remapped (a ``remap`` o
baked into its recipe, so the full-res export re-derives it) and the piece is
placed as an upright rectangle. It stays draggable — it is no longer corner-warpable.
+Both models share one pre-filter (:func:`_static_points`): keypoints that sit at
+the same pixel of most pieces are dropped before any matching. Video frames come
+with burnt-in furniture — a platform logo, a channel bug — and those points agree
+with each other far too well to be argued with once they reach the matcher.
+
The heavy lifting is OpenCV's; the fitting math is pure so it stays testable and
honest about coordinates.
"""
from __future__ import annotations
-from collections import deque
+import math
+from collections import defaultdict, deque
from typing import Any
from PIL import Image
@@ -69,6 +75,25 @@ _MATCH_CONF = 0.3 # per-descriptor, OpenCV's default for its panorama pipeline
# wildly bigger than it started has a broken camera behind it, not a wide angle.
_MAX_WARP_AREA = 25.0
+# Frames pulled from one video carry the same burnt-in furniture — a platform logo,
+# a channel bug, a timestamp — at the same pixel of every frame. Those keypoints
+# match each other perfectly at zero displacement, and being both numerous and
+# mutually consistent they out-vote the scene: RANSAC settles on the identity
+# homography and the pieces stack instead of stitching. So find them and never hand
+# them to the matcher. Position is the whole test — an overlay is defined by *where*
+# it sits, not by what it looks like, and keypoints are sparse enough (~2000 over a
+# 1000px work image) that a chance co-location surviving across most of the set is
+# vanishingly unlikely.
+_STATIC_PX = 2.0 # work pixels: an overlay does not move, only the detector jitters
+_STATIC_SHARE = 0.6 # of the other same-sized pieces must show the point too
+# Two pieces of a still camera look exactly like two pieces sharing an overlay, and
+# there the identity *is* the answer — so never conclude anything from one peer.
+_STATIC_MIN_PEERS = 2
+# Past this share the *scene* is what stands still (a fixed camera, a slow pan), not
+# an overlay on it. Dropping those points would leave nothing to stitch with, so the
+# piece keeps all of them and the solver is no worse off than before.
+_STATIC_MAX_SHARE = 0.5
+
# Gain read-back probe level: mid-grey, so a gain up to ~2.5 stays representable
# in uint8 while quantisation keeps the recovered scalar within ~1%.
_PROBE = 100
@@ -103,24 +128,93 @@ def _detector(cv2) -> tuple[Any, int]:
return cv2.ORB_create(nfeatures=2000), cv2.NORM_HAMMING
+def _work_scale(size: tuple[int, int]) -> float:
+ """The factor that takes an image down to ``WORK_DIM`` (1.0 if already smaller)."""
+ return min(1.0, WORK_DIM / max(size))
+
+
+def _work_size(size: tuple[int, int]) -> tuple[int, int]:
+ """``size`` after :func:`_work_scale` — the pixel grid features are found on."""
+ scale = _work_scale(size)
+ return max(1, round(size[0] * scale)), max(1, round(size[1] * scale))
+
+
def _features(cv2, det, img: Image.Image):
"""Keypoints (in full-res coordinates) + descriptors, or ``(None, None)``."""
import numpy as np
gray = img.convert("L")
- scale = 1.0
- if max(gray.size) > WORK_DIM:
- scale = WORK_DIM / max(gray.size)
- gray = gray.resize(
- (max(1, round(gray.width * scale)), max(1, round(gray.height * scale))),
- Image.Resampling.BILINEAR,
- )
+ scale = _work_scale(gray.size)
+ if scale < 1.0:
+ gray = gray.resize(_work_size(gray.size), Image.Resampling.BILINEAR)
kp, desc = det.detectAndCompute(np.asarray(gray), None)
if desc is None or len(kp) < 4:
return None, None
return np.asarray([k.pt for k in kp], dtype=np.float32) / scale, desc
+def _static_points(points: list[Any], sizes: list[tuple[int, int]]) -> list[set[int]]:
+ """Per image, the indices of the keypoints that sit still across the set.
+
+ ``points`` are keypoints in *work* pixels (so the tolerance means the same thing
+ whatever the source resolution) and ``sizes`` the work sizes they were found on.
+ Only pieces of identical size are compared: an overlay lands on the same pixel
+ of every frame of one video, and that claim is meaningless across geometries.
+
+ A keypoint is called static when enough of its peers hold one within
+ :data:`_STATIC_PX` of the same spot. The two guards above — a floor on peers, a
+ ceiling on the share — draw the line between "something is pinned over the
+ scene" and "the scene itself is not moving", which the evidence inside a single
+ piece cannot tell apart.
+ """
+ out: list[set[int]] = [set() for _ in points]
+ groups: dict[tuple[int, int], list[int]] = defaultdict(list)
+ for i, (pts, size) in enumerate(zip(points, sizes)):
+ if pts is not None and len(pts):
+ groups[size].append(i)
+
+ for members in groups.values():
+ if len(members) <= _STATIC_MIN_PEERS:
+ continue
+ # Bucket every keypoint into a _STATIC_PX-wide cell, so a point's possible
+ # neighbours are the nine cells around its own — no all-pairs scan.
+ cells: dict[tuple[int, int], list[tuple[int, int]]] = defaultdict(list)
+ for i in members:
+ for k, (x, y) in enumerate(points[i]):
+ cells[(int(x // _STATIC_PX), int(y // _STATIC_PX))].append((i, k))
+
+ needed = max(_STATIC_MIN_PEERS, math.ceil(_STATIC_SHARE * (len(members) - 1)))
+ for i in members:
+ flagged: set[int] = set()
+ for k, (x, y) in enumerate(points[i]):
+ cx, cy = int(x // _STATIC_PX), int(y // _STATIC_PX)
+ peers: set[int] = set()
+ for dx in (-1, 0, 1):
+ for dy in (-1, 0, 1):
+ for j, m in cells.get((cx + dx, cy + dy), ()):
+ if j == i or j in peers:
+ continue
+ px, py = points[j][m]
+ if (px - x) ** 2 + (py - y) ** 2 <= _STATIC_PX**2:
+ peers.add(j)
+ if len(peers) >= needed:
+ flagged.add(k)
+ if len(flagged) <= _STATIC_MAX_SHARE * len(points[i]):
+ out[i] = flagged
+ return out
+
+
+def _drop_points(feat, drop: set[int]):
+ """``feat`` minus the given keypoints, or ``(None, None)`` if too few remain."""
+ pts, desc = feat
+ if pts is None or not drop:
+ return feat
+ keep = [k for k in range(len(pts)) if k not in drop]
+ if len(keep) < 4:
+ return None, None
+ return pts[keep], desc[keep]
+
+
def _pair_homography(cv2, matcher, feat_a, feat_b) -> tuple[Any, int]:
"""Homography mapping image *b* into image *a*'s plane, + its inlier count."""
import numpy as np
@@ -224,8 +318,6 @@ def quad_ok(quad: Quad) -> bool:
the quad inside out. Such a piece is worse than useless on the canvas, so it
is dropped rather than rendered.
"""
- import math
-
if any(not math.isfinite(v) for pt in quad for v in pt):
return False
# Convexity: every consecutive cross product must share a sign. A fold or a
@@ -280,6 +372,14 @@ def solve_layout(images: list[Image.Image], *, width: int, height: int) -> dict[
matcher = cv2.BFMatcher(norm)
feats = [_features(cv2, det, img) for img in images]
+ statics = _static_points(
+ [
+ None if pts is None else pts * _work_scale(img.size)
+ for (pts, _), img in zip(feats, images)
+ ],
+ [_work_size(img.size) for img in images],
+ )
+ feats = [_drop_points(f, s) for f, s in zip(feats, statics)]
edges: dict[tuple[int, int], Any] = {}
weights: dict[tuple[int, int], int] = {}
@@ -348,8 +448,32 @@ def _work_array(img: Image.Image):
def _detail_features(cv2, arrays: list[Any]) -> list[Any]:
+ """Features for the rotation model, minus whatever is pinned over the scene.
+
+ Same rejection as the planar solver, applied one step earlier: this pipeline
+ matches inside OpenCV, so the overlay's keypoints have to be gone from the
+ feature objects before the matcher ever sees them.
+ """
+ import numpy as np
+
det, _ = _detector(cv2)
- return [cv2.detail.computeImageFeatures2(det, arr) for arr in arrays]
+ feats = [cv2.detail.computeImageFeatures2(det, arr) for arr in arrays]
+
+ points = [
+ np.asarray([k.pt for k in ft.keypoints], dtype=np.float32) if len(ft.keypoints) else None
+ for ft in feats
+ ]
+ sizes = [(arr.shape[1], arr.shape[0]) for arr in arrays]
+ for ft, drop in zip(feats, _static_points(points, sizes)):
+ if not drop:
+ continue
+ keep = [k for k in range(len(ft.keypoints)) if k not in drop]
+ if len(keep) < 4:
+ continue
+ descriptors = ft.descriptors.get()
+ ft.keypoints = tuple(ft.keypoints[k] for k in keep)
+ ft.descriptors = cv2.UMat(descriptors[keep])
+ return feats
def _match_component(cv2, feats: list[Any]) -> tuple[list[Any], list[int]]:
diff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.py
index 613a097..0c96bf9 100644
--- a/src/azimut/engine/thumbnails.py
+++ b/src/azimut/engine/thumbnails.py
@@ -84,18 +84,26 @@ def _render(media_path: Path, out_path: Path, kind: str) -> bool:
if kind == "video":
if not ffmpeg_engine.ffmpeg_available():
return False
- subprocess.run(
- [
- ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error",
- "-ss", "1", "-i", str(media_path),
- "-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",
- str(out_path),
- ],
- check=True,
- timeout=30,
- capture_output=True,
- )
- return out_path.exists()
+ # One second in, because the first frame of a clip is often black or a
+ # fade-in. A video shorter than that has no such frame, and seeking past
+ # the end yields no output at all — so the seek is a preference, not a
+ # requirement, and the second pass takes whatever the clip opens with
+ # rather than letting a two-second capture retry until it is given up on.
+ for seek in ("1", "0"):
+ subprocess.run(
+ [
+ ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error",
+ "-ss", seek, "-i", str(media_path),
+ "-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",
+ str(out_path),
+ ],
+ check=True,
+ timeout=30,
+ capture_output=True,
+ )
+ if out_path.exists():
+ return True
+ return False
return False
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index 69d94d8..503daac 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -502,9 +502,14 @@ def fetch_crop(
def fetch_all(url_template: str) -> list[tuple[int, int, Image.Image | None]]:
def grab(tx: int, ty: int) -> tuple[int, int, Image.Image | None]:
- if not (0 <= tx <= max_index and 0 <= ty <= max_index):
+ # Longitude wraps and latitude does not: a crop straddling the
+ # antimeridian asks for tiles past either edge of the grid, and those
+ # are the same tiles read from the other side. Clamping them away
+ # instead left a blank band down the middle of every capture at
+ # ±180°. Rows above the pole have no such twin and stay empty.
+ if not 0 <= ty <= max_index:
return tx, ty, None
- url = tile_url(url_template, tile_z, tx, ty, provider.zoom_offset)
+ url = tile_url(url_template, tile_z, tx % (max_index + 1), ty, provider.zoom_offset)
return tx, ty, fetch(client, url)
with httpx.Client(
@@ -530,7 +535,11 @@ def fetch_crop(
px, py = int(tx * ts - left), int(ty * ts - top)
if tile is None:
missing += 1
- if 0 <= tx <= max_index and 0 <= ty <= max_index:
+ # Same bounds `grab` fetched under: x wraps, y does not. A tile past
+ # the antimeridian is a real one the provider had nothing for, so it
+ # is a coverage gap the overzoom fill should try, not an index there
+ # was never imagery for.
+ if 0 <= ty <= max_index:
gaps.append((tx, ty))
continue
served += 1
@@ -661,9 +670,15 @@ def _overzoom_fill(
if not unresolved or tile_z - up < 0 or sub < 1:
break
+ parent_span = 1 << (tile_z - up)
+
def grab(pxy: tuple[int, int]) -> tuple[tuple[int, int], Image.Image | None]:
try:
- url = tile_url(url_template, tile_z - up, pxy[0], pxy[1], zoom_offset)
+ # x wraps here as it does in the main fetch: a gap past the
+ # antimeridian has a parent, on the other side of the grid.
+ url = tile_url(
+ url_template, tile_z - up, pxy[0] % parent_span, pxy[1], zoom_offset
+ )
return pxy, fetch(client, url)
except Exception:
return pxy, None
diff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.py
index e2434a6..072b9ae 100644
--- a/src/azimut/engine/workqueue.py
+++ b/src/azimut/engine/workqueue.py
@@ -128,13 +128,16 @@ def _run_loop() -> None:
if not _pending:
_worker_running = False
return
- case_id, case = next(iter(_pending.items()))
+ # Claimed before the drain, not after it. `wake` is a no-op while the
+ # case is already pending, so a job enqueued *during* the drain — past
+ # the point this pass read the queue — would have its mark removed by
+ # a pop on the way out and never be drained at all.
+ case_id = next(iter(_pending))
+ case = _pending.pop(case_id)
try:
drain(case)
except Exception: # a worker must never die on one case's failure
pass
- with _worker_lock:
- _pending.pop(case_id, None)
def wake(case: "CaseType") -> None:
diff --git a/src/azimut/jobs.py b/src/azimut/jobs.py
index 1e5e9e6..0a83cbd 100644
--- a/src/azimut/jobs.py
+++ b/src/azimut/jobs.py
@@ -25,8 +25,15 @@ def _evict_finished() -> None:
del _jobs[jid]
-def start(kind: str, work: Callable[[Callable[[dict[str, Any]], None]], Any]) -> str:
- """Run `work(set_progress)` in a thread; returns the job id."""
+def start(kind: str, work: Callable[..., Any], *, stoppable: bool = False) -> str:
+ """Run `work(set_progress)` in a thread; returns the job id.
+
+ ``stoppable`` calls it as ``work(set_progress, stopping)`` instead, where
+ ``stopping()`` answers whether somebody has pressed cancel. A job that takes
+ it is promising to check between units of work and to leave the unit it was
+ part-way through unwritten — which is the only kind of cancellation this
+ registry can offer, since a thread cannot be interrupted from outside.
+ """
job_id = uuid.uuid4().hex[:12]
with _lock:
_evict_finished()
@@ -37,9 +44,12 @@ def start(kind: str, work: Callable[[Callable[[dict[str, Any]], None]], Any]) ->
if job_id in _jobs:
_jobs[job_id]["progress"] = progress
+ def stopping() -> bool:
+ return cancelled(job_id)
+
def runner() -> None:
try:
- result = work(set_progress)
+ result = work(set_progress, stopping) if stoppable else work(set_progress)
with _lock:
_jobs[job_id].update(status="done", result=result)
except Exception as exc: # surfaced to the UI, not swallowed
@@ -50,6 +60,25 @@ def start(kind: str, work: Callable[[Callable[[dict[str, Any]], None]], Any]) ->
return job_id
+def cancel(job_id: str) -> bool:
+ """Ask a running job to stop at its next safe point. Answers whether it heard.
+
+ A flag, never a kill: the work decides where stopping is safe, and for the one
+ job that takes it that is between two rows.
+ """
+ with _lock:
+ job = _jobs.get(job_id)
+ if not job or job["status"] != "running":
+ return False
+ job["cancelled"] = True
+ return True
+
+
+def cancelled(job_id: str) -> bool:
+ with _lock:
+ return bool((_jobs.get(job_id) or {}).get("cancelled"))
+
+
def get(job_id: str) -> dict[str, Any] | None:
with _lock:
job = _jobs.get(job_id)
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index 925387e..a6a6e58 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -31,7 +31,7 @@ from __future__ import annotations
import re
import unicodedata
-from pathlib import Path, PurePosixPath
+from pathlib import Path, PurePosixPath, PureWindowsPath
#: What the tool owns inside a case folder. Everything beside it is the
#: analyst's, and Azimut neither reads nor writes there.
@@ -70,6 +70,7 @@ ENTITY_IMAGES_DIR = "entity-images"
CASE_SUBDIRS = (
"media",
"notes",
+ "sheets",
"proofs",
"exports",
DRAFTS_DIR,
@@ -243,6 +244,21 @@ URL_HOSTILE_CHARS = "#%"
UNUSABLE_NAME_CHARS = '\\ / : * ? " < > | # %'
+def names_one_child(name: str) -> bool:
+ """Whether ``name`` addresses one directory entry and cannot climb out of it.
+
+ Asked of both path flavours rather than the host's, because the two disagree
+ about exactly the string an attacker sends: ``..\\case.json`` is a traversal
+ on Windows and an ordinary filename on Linux. A guard that only consulted the
+ running machine's `pathlib` would make the Windows binary the one place the
+ rule does not hold, and the suite — which runs on Linux too — would never see
+ it (`tests/test_regressions.py`).
+ """
+ if not name or name in {".", ".."}:
+ return False
+ return name == PurePosixPath(name).name == PureWindowsPath(name).name
+
+
def usable_case_name(name: str) -> bool:
"""Whether a folder can hold a case under the name it already has.
@@ -395,6 +411,28 @@ def note_rel(folder: str, name: str) -> str:
return "/".join(["notes", *parts, f"{name}.md"])
+def sheet_rel(name: str) -> str:
+ """A sheet's table, and deliberately a real CSV in a visible folder.
+
+ The file *is* the sheet: it opens in any spreadsheet, it travels in the bundle
+ as itself, and a case that outlives the app keeps a readable table rather than
+ rows locked in a database. Flat, like proofs and drafts — sheets have no filing
+ tree of their own, so uniqueness is scoped to the case.
+ """
+ return f"sheets/{name}.csv"
+
+
+def sheet_meta_rel(name: str) -> str:
+ """What the grid remembers about a sheet, beside it and out of the way.
+
+ Column widths, hidden columns, the sort, row colours and the entity each cell
+ points at. None of it belongs in the CSV: a width is not a finding, and a
+ column of internal ids in a file handed to someone else is noise. What *is* a
+ finding — a status, a note, a verdict — is a column of the table itself.
+ """
+ return f"sheets/{META_DIR}/{name}.json"
+
+
def draft_rel(name: str) -> str:
return f"{DRAFTS_DIR}/{name}.json"
@@ -416,7 +454,11 @@ def content_dirs(root: Path) -> tuple[Path, ...]:
keeps green (`tests/test_artifacts.py`).
"""
dirs = [tool_root(root) / name for name in CASE_SUBDIRS]
- dirs += [media(root) / META_DIR, subdir(root, "proofs") / META_DIR]
+ dirs += [
+ media(root) / META_DIR,
+ subdir(root, "proofs") / META_DIR,
+ subdir(root, "sheets") / META_DIR,
+ ]
return tuple(dirs)
diff --git a/src/azimut/repository.py b/src/azimut/repository.py
index c9ed2a8..eee20c8 100644
--- a/src/azimut/repository.py
+++ b/src/azimut/repository.py
@@ -17,6 +17,7 @@ browsing; it is not a second copy of the media bytes.
from __future__ import annotations
+from contextlib import AbstractContextManager
from typing import Any, Literal, Protocol, runtime_checkable
#: Confidence on an entity or link: an analyst's `confirmed` vs a tool's
@@ -315,6 +316,12 @@ class CaseRepository(Protocol):
def save_analysis_view(self, view: dict[str, Any]) -> dict[str, Any]:
...
+ def rename_analysis_view(
+ self, view_id: str, name: str, updated_at: str
+ ) -> dict[str, Any] | None:
+ """Relabel one reading without rewriting the recipe or capture it holds."""
+ ...
+
def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
...
@@ -472,6 +479,17 @@ class CaseRepository(Protocol):
"""Compare the derived temporal index with its graph and media authorities."""
...
+ # -- writing several things as one -------------------------------------
+
+ def batch(self) -> AbstractContextManager[None]:
+ """One transaction for every write made inside, or none of them.
+
+ For the caller that has a whole plan to write and no half of it worth
+ keeping — a sheet promotion's entities and the links between them. Short and
+ without I/O: it holds the store's write lock while it is open.
+ """
+ ...
+
# -- entity mutations --------------------------------------------------
def add_entity(
@@ -527,6 +545,7 @@ class CaseRepository(Protocol):
*,
by: str,
status: EntityStatus = "confirmed",
+ own_only: bool = False,
) -> list[dict[str, Any]]:
...
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 1e05206..787993b 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -35,35 +35,90 @@ SERVE_PORT: int | None = None
LOCAL_HOSTNAMES = frozenset({"127.0.0.1", "localhost", "::1", "[::1]"})
-class NotesPdfBodyLimit:
- """Bound the one JSON route that can carry binary images before parsing."""
+class BulkBodyLimit:
+ """Bound the JSON routes that carry a payload the browser assembled, before parsing.
+
+ Four of them: a note's PDF export posts its Mermaid diagrams, an analysis plate posts
+ the page itself, a sheet posts a whole table, and saving a proof posts the composer's
+ rendered export plus the images pasted into it. Each is bounded by its own route's
+ number, so the limit stays beside the code that knows what it is for.
+ """
+
+ #: `(method, tail, module, attribute)`, where the tail is the path segments after
+ #: `/api/cases/{case_id}/`. `*` stands for one segment of any value and a trailing
+ #: `...` for any number of further segments — which is what every road out of a
+ #: sheet's promotion needs, since each of them posts the whole table and each has a
+ #: `/preview` beside it. Spelling those out one by one is how `promote/preview` went
+ #: unbounded while `promote` was bounded, and then how `move/undo`, `proofs`, `parse`
+ #: and `meta` went the same way — and then how the composer's own save, the route this
+ #: middleware most obviously exists for, was never on the list at all. Which is why the
+ #: gate is a test rather than this list: `test_hardening.py` enumerates every router the
+ #: app mounts and fails on a body that can carry a table or a picture and answers no
+ #: limit.
+ ANY = "..."
+ ROUTES: tuple[tuple[str, tuple[str, ...], str, str], ...] = (
+ ("POST", ("notes", "pdf"), "notes", "MAX_PDF_BODY_BYTES"),
+ # The note itself, on the three roads that write one. Declared after `notes/pdf`
+ # so the export keeps its own, larger number.
+ ("POST", ("notes",), "notes", "MAX_NOTE_BODY_BYTES"),
+ ("PUT", ("notes",), "notes", "MAX_NOTE_BODY_BYTES"),
+ ("PUT", ("notes", "*"), "notes", "MAX_NOTE_BODY_BYTES"),
+ ("POST", ("plates",), "plates", "MAX_PLATE_BODY_BYTES"),
+ ("POST", ("proofs",), "proofs", "MAX_PROOF_BODY_BYTES"),
+ ("POST", ("sheets",), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "import"), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "parse"), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "promote", ANY), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "move", ANY), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "proofs", ANY), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "points"), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "refresh"), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("POST", ("sheets", "*", "csv"), "sheets", "MAX_SHEET_BODY_BYTES"),
+ ("PUT", ("sheets", "*", ANY), "sheets", "MAX_SHEET_BODY_BYTES"),
+ )
def __init__(self, app: ASGIApp) -> None:
self.app = app
- @staticmethod
- def _matches(scope: Scope) -> bool:
- parts = str(scope.get("path", "")).split("/")
- return scope.get("method") == "POST" and len(parts) == 6 and (
- parts[1], parts[2], parts[4], parts[5]
- ) == ("api", "cases", "notes", "pdf")
+ @classmethod
+ def _matches(cls, tail: tuple[str, ...], route: tuple[str, ...]) -> bool:
+ open_ended = route[-1:] == (cls.ANY,)
+ wanted = route[:-1] if open_ended else route
+ if len(tail) < len(wanted) or (not open_ended and len(tail) != len(wanted)):
+ return False
+ return all(want in ("*", have) for want, have in zip(wanted, tail))
+
+ @classmethod
+ def _limit(cls, scope: Scope) -> int | None:
+ method = str(scope.get("method", ""))
+ parts = str(scope.get("path", "")).strip("/").split("/")
+ if len(parts) < 4 or parts[0] != "api" or parts[1] != "cases":
+ return None
+ tail = tuple(parts[3:])
+ for want_method, route, module_name, attribute in cls.ROUTES:
+ if method != want_method or not cls._matches(tail, route):
+ continue
+ # Imported lazily so each route owns its limit and a test can lower it
+ # without rebuilding the application.
+ from importlib import import_module
+
+ module = import_module(f".api.{module_name}", package=__package__)
+ return int(getattr(module, attribute))
+ return None
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
- if scope["type"] != "http" or not self._matches(scope):
+ limit = self._limit(scope) if scope["type"] == "http" else None
+ if limit is None:
await self.app(scope, receive, send)
return
- # Import lazily so the route owns the limit and tests can lower it
- # without rebuilding the application.
- from .api import notes
-
headers = dict(scope.get("headers", []))
raw_length = headers.get(b"content-length", b"")
try:
content_length = int(raw_length) if raw_length else None
except ValueError:
content_length = None
- if content_length is not None and content_length > notes.MAX_PDF_BODY_BYTES:
+ if content_length is not None and content_length > limit:
await JSONResponse(
{"detail": "request body too large"}, status_code=413
)(scope, receive, send)
@@ -75,7 +130,7 @@ class NotesPdfBodyLimit:
if message["type"] != "http.request":
break
chunk = message.get("body", b"")
- if len(body) + len(chunk) > notes.MAX_PDF_BODY_BYTES:
+ if len(body) + len(chunk) > limit:
await JSONResponse(
{"detail": "request body too large"}, status_code=413
)(scope, receive, send)
@@ -233,17 +288,24 @@ def create_app() -> FastAPI:
from .api import (
analysis_views, cases, drafts, events, files, folders, ingest, inspect, media,
- notes, proofs, satellite, settings, templates,
+ notes, plates, proofimports, proofs, satellite, settings, sheetproofs, sheets,
+ templates,
)
+ from .engine import sheets as sheet_engine
app.include_router(cases.router)
app.include_router(cases.workspace_router)
app.include_router(analysis_views.router)
app.include_router(notes.router)
+ app.include_router(plates.router)
+ app.include_router(sheets.router)
+ # The one sheet road that fetches bytes, so its own module and its own job.
+ app.include_router(sheetproofs.router)
app.include_router(media.router)
app.include_router(inspect.router)
app.include_router(satellite.router)
app.include_router(proofs.router)
+ app.include_router(proofimports.router)
app.include_router(drafts.router)
app.include_router(files.router)
app.include_router(folders.router)
@@ -251,13 +313,22 @@ def create_app() -> FastAPI:
app.include_router(ingest.router)
app.include_router(events.router)
app.include_router(templates.router)
+ # A sheet's CSV that the filesystem would not take. Handled once for the app rather
+ # than at each of the ten routes that write one: the failure is the same wherever it
+ # happens — a spreadsheet holding the file open on Windows, a read-only folder — and
+ # its answer does not depend on which route hit it. A route added later cannot forget
+ # this, which a per-route `except` could.
+ @app.exception_handler(sheet_engine.SheetUnwritable)
+ async def _sheet_unwritable(_: Request, exc: sheet_engine.SheetUnwritable) -> JSONResponse:
+ return JSONResponse(status_code=409, content={"detail": str(exc)})
+
# extension-origin CORS, /api/ingest/* only (see ingest.install_cors)
ingest.install_cors(app)
# Inside the local guard: a request that isn't allowed to reach the app at
# all should not learn whether the workspace is there.
install_availability_guard(app)
- # Bound diagram-carrying JSON before FastAPI/Pydantic materialises it.
- app.add_middleware(NotesPdfBodyLimit)
+ # Bound picture-carrying JSON before FastAPI/Pydantic materialises it.
+ app.add_middleware(BulkBodyLimit)
# last, so it wraps everything: refuse non-loopback Host / cross-origin web
install_local_guard(app)
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index 944b0a4..b75072d 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -23,6 +23,7 @@ from __future__ import annotations
import json
import sqlite3
+import threading
from contextlib import closing, contextmanager
from dataclasses import dataclass, field
from pathlib import Path
@@ -331,6 +332,12 @@ class SqliteCase:
def __init__(self, db_path: Path):
self.db_path = Path(db_path)
+ # The connection a `batch()` is holding open, per thread. Thread-local rather
+ # than a plain attribute because one `SqliteCase` is shared by the request
+ # threads and the job worker, and a sqlite3 connection belongs to the thread
+ # that made it: an attribute would hand one thread's open transaction to
+ # another and raise from somewhere unrelated.
+ self._local = threading.local()
# -- lifecycle ---------------------------------------------------------
@@ -519,18 +526,49 @@ class SqliteCase:
# and there is no cross-thread connection to mismanage. Autocommit
# (isolation_level=None) leaves transaction control explicit — reads run
# bare, writes wrap in BEGIN IMMEDIATE..COMMIT via `_write`.
- conn = sqlite3.connect(self.db_path, isolation_level=None)
+ #
+ # Inside a `batch()`, that connection is lent instead. Reads have to join it
+ # or they would be looking at the file as it was before the batch started:
+ # SQLite shows uncommitted rows to the connection that wrote them and to no
+ # other, so a planner that adds an entity and then reads it back would find
+ # nothing. Never closed here — the batch owns its lifetime.
+ ambient = getattr(self._local, "conn", None)
+ if ambient is not None:
+ yield ambient
+ return
+ conn = self._open()
try:
- conn.row_factory = sqlite3.Row
- conn.execute("PRAGMA foreign_keys = ON")
- conn.execute("PRAGMA busy_timeout = 5000")
- conn.execute("PRAGMA synchronous = FULL")
yield conn
finally:
conn.close()
+ def _open(self) -> sqlite3.Connection:
+ """One configured connection. Here rather than inline because `batch()` opens
+ its own and the two must agree on every pragma."""
+ conn = sqlite3.connect(self.db_path, isolation_level=None)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA foreign_keys = ON")
+ # Long enough for a queue, not long enough to hide a deadlock: every write goes
+ # through BEGIN IMMEDIATE, so no waiter is queued behind a lock it holds itself,
+ # and what it waits on is the fsync `synchronous = FULL` charges per commit.
+ # Five seconds held on Linux and ran out on Windows. Eight concurrent downloads
+ # open eighty of these between them, ten per filed item; the whole lot costs two
+ # seconds of lock on Linux and enough more on Windows that one of the eight gave
+ # up on a queue that was still moving.
+ conn.execute("PRAGMA busy_timeout = 30000")
+ conn.execute("PRAGMA synchronous = FULL")
+ return conn
+
def _write(self, op: Callable[[sqlite3.Connection], T]) -> T:
- """Run `op` inside one immediate transaction, rolling back on error."""
+ """Run `op` inside one immediate transaction, rolling back on error.
+
+ Inside a `batch()` there is already a transaction open and it belongs to the
+ batch, so the operation joins it and neither commits nor rolls back: one
+ `COMMIT` for the whole lot is the point of the thing.
+ """
+ ambient = getattr(self._local, "conn", None)
+ if ambient is not None:
+ return op(ambient)
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
try:
@@ -541,6 +579,44 @@ class SqliteCase:
conn.execute("ROLLBACK")
raise
+ @contextmanager
+ def batch(self) -> Iterator[None]:
+ """One transaction for every store call made inside, on this thread.
+
+ What "all or nothing" costs. A promotion that writes thirty-four entities and
+ thirty-four links makes sixty-nine short transactions on its own, and a failure
+ at the fortieth leaves the first thirty-nine standing — a case half-way through
+ an operation nobody can see the shape of. Wrapped in a batch, the same calls
+ share one `BEGIN IMMEDIATE`: the last one commits them all, and any exception
+ leaves the case exactly as it was.
+
+ **Keep a batch short and keep I/O out of it.** It holds SQLite's write lock for
+ its whole duration, so every other writer — the job worker included — waits on
+ it and then fails on `busy_timeout`. That is precisely why the road that
+ downloads files is atomic per row instead: a batch around a hundred network
+ fetches would lock the case for minutes.
+
+ Not nestable, deliberately. An inner batch would either commit early, breaking
+ the outer promise, or silently do nothing, breaking its own; refusing says which
+ caller is wrong while there is still a stack trace to say it in.
+ """
+ if getattr(self._local, "conn", None) is not None:
+ raise CaseError("a batch is already open on this thread")
+ conn = self._open()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ self._local.conn = conn
+ try:
+ yield
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
+ finally:
+ self._local.conn = None
+ finally:
+ conn.close()
+
@staticmethod
def _touch(conn: sqlite3.Connection) -> None:
conn.execute("UPDATE meta SET value = ? WHERE key = 'updated_at'", (_now(),))
@@ -607,16 +683,27 @@ class SqliteCase:
# -- reads -------------------------------------------------------------
def snapshot(self) -> dict[str, Any]:
+ # One read transaction, not four bare SELECTs: the connection runs in
+ # autocommit, so without it a write landing between the entities read and
+ # the links read would produce a snapshot whose edges point at nodes it
+ # does not carry. A bundle export runs on the worker thread while the
+ # analyst keeps editing, which is exactly that window.
with self._connect() as conn:
- meta = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM meta")}
- entities = [
- self._entity(r) for r in conn.execute("SELECT * FROM entities ORDER BY rowid")
- ]
- links = [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]
- folders = [
- r["path"]
- for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
- ]
+ conn.execute("BEGIN")
+ try:
+ meta = {r["key"]: r["value"] for r in conn.execute("SELECT key, value FROM meta")}
+ entities = [
+ self._entity(r) for r in conn.execute("SELECT * FROM entities ORDER BY rowid")
+ ]
+ links = [self._link(r) for r in conn.execute("SELECT * FROM links ORDER BY rowid")]
+ folders = [
+ r["path"]
+ for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
+ ]
+ conn.execute("COMMIT")
+ except BaseException:
+ conn.execute("ROLLBACK")
+ raise
schema = int(meta.get("schema_version", SQLITE_SCHEMA))
return {
"azimut": {"schema": schema, "storage": "sqlite"},
@@ -938,6 +1025,30 @@ class SqliteCase:
raise CaseError(f"analysis view '{view['id']}' was not saved")
return saved
+ def rename_analysis_view(
+ self, view_id: str, name: str, updated_at: str
+ ) -> dict[str, Any] | None:
+ """Give one saved reading another name, leaving the reading itself alone.
+
+ The spec column is never touched here, so a snapshot keeps the exact bytes it
+ captured: a label is not evidence, and rewriting thousands of frozen rows to
+ change one is both slow and a chance to lose them.
+ """
+
+ def op(conn: sqlite3.Connection) -> bool:
+ cursor = conn.execute(
+ "UPDATE analysis_views SET name = ?, updated_at = ? WHERE id = ?",
+ (name, updated_at, view_id),
+ )
+ renamed = cursor.rowcount > 0
+ if renamed:
+ self._touch(conn)
+ return renamed
+
+ if not self._write(op):
+ return None
+ return self.get_analysis_view(view_id)
+
def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
"""Remove one view and return the recipe Trash needs to restore it."""
existing = self.get_analysis_view(view_id)
@@ -2701,6 +2812,7 @@ class SqliteCase:
*,
by: str,
status: EntityStatus = "confirmed",
+ own_only: bool = False,
) -> list[dict[str, Any]]:
def op(conn: sqlite3.Connection) -> list[dict[str, Any]]:
if conn.execute("SELECT 1 FROM entities WHERE id = ?", (from_id,)).fetchone() is None:
@@ -2725,7 +2837,13 @@ class SqliteCase:
}
# Drop edges no longer wanted; leave the survivors untouched so their
# id and timestamp are preserved (restating sources, not rebuilding).
- stale = [(r["id"],) for to_id, r in existing.items() if to_id not in wanted_set]
+ # `own_only` also leaves what another author wrote: the caller's list is
+ # then its own statement rather than the whole truth about this type.
+ stale = [
+ (r["id"],)
+ for to_id, r in existing.items()
+ if to_id not in wanted_set and not (own_only and r["prov_by"] != by)
+ ]
if stale:
conn.executemany("DELETE FROM links WHERE id = ?", stale)
for to_id in wanted:
@@ -3036,8 +3154,8 @@ class SqliteCase:
conn.execute(
"INSERT OR REPLACE INTO links"
"(id, from_id, to_id, type, prov_by, prov_at, prov_status,"
- " prov_source, confidence)"
- " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ " prov_source, confidence, nature)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
link["id"], link["from"], link["to"], link["type"],
prov.get("by", "user"), prov.get("at", _now()),
@@ -3045,6 +3163,9 @@ class SqliteCase:
# restoring an eliminated candidate must bring back the
# elimination: "I ruled these eleven out" is the finding
link.get("confidence"),
+ # and the qualifier with it: "brother of" is the analyst's
+ # own reading of the tie, not a decoration on the verb
+ link.get("nature"),
),
)
kept += 1
diff --git a/src/azimut/store/rows.py b/src/azimut/store/rows.py
index a13c80a..227e35e 100644
--- a/src/azimut/store/rows.py
+++ b/src/azimut/store/rows.py
@@ -69,7 +69,8 @@ _MEDIA_CATEGORY_SQL = {
"satellite": _SATELLITE_SQL,
# A paste and a drop are one facet: both are material the analyst brought in
# by hand, which is the question this filter asks. They stay two source types
- # because only one of them can state where it came from.
+ # because the gesture is part of the record — a screenshot is not a file that
+ # was chosen off a disk, whatever origin was stated for either.
"upload": "source_type IN ('upload', 'clipboard')",
"download": "source_type = 'download'",
"other": "kind NOT IN ('image', 'video')",
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index f0e6879..3a461fa 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -329,7 +329,15 @@ class Case(CaseStore):
Normal callers want :meth:`open`. The Case Doctor deliberately needs a
weaker primitive: a missing ``case.db`` is one of the failures it must
be able to inspect and repair.
+
+ The id names a folder in the workspace and nothing else. It arrives from
+ a URL path segment, which cannot hold a ``/`` but can hold a ``\\`` — a
+ separator on Windows — so the containment rule is stated here rather than
+ left to the caller: every case route resolves through this one method,
+ and one of them is the delete that removes the folder.
"""
+ if not layout.names_one_child(case_id):
+ raise CaseError(f"case '{case_id}' not found")
for parent in (config.cases_dir(), config.scratch_dir()):
path = parent / case_id
if layout.is_case(path):
@@ -550,9 +558,20 @@ class Case(CaseStore):
if not layout.is_case(path):
continue
case = cls(path)
- data = case.read()
- updated_at = data.get("updated_at")
health = "ok"
+ try:
+ data = case.read()
+ except (OSError, json.JSONDecodeError):
+ # An unreadable manifest must not cost the whole list: this
+ # is the switcher, and it is also what `_ensure_name_free`
+ # calls, so one corrupt case.json would otherwise block
+ # opening *and* creating every other case.
+ data = {}
+ health = "needs-attention"
+ if not isinstance(data, dict):
+ data = {}
+ health = "needs-attention"
+ updated_at = data.get("updated_at")
try:
if case._sqlite is not None:
updated_at = case._sqlite.updated_at() or updated_at
@@ -887,6 +906,7 @@ class Case(CaseStore):
"proof": ("spec", layout.proof_spec_rel, "Proof"),
"inspect-session": ("spec", layout.session_rel, "Inspect"),
"post": ("draft", layout.draft_rel, "Post"),
+ "sheet": ("path", layout.sheet_rel, "Sheet"),
}
rule = rules.get(str(entity.get("type") or ""))
if rule is None:
@@ -933,6 +953,13 @@ class Case(CaseStore):
replacements.append((old_export, new_export))
if (entity.get("attrs") or {}).get("path") == old_export:
attrs["path"] = new_export
+ if entity["type"] == "sheet":
+ # The sidecar is named after the table, so it follows it or the grid
+ # reopens with its colours and links hung on nothing.
+ old_meta = layout.sheet_meta_rel(Path(current).stem)
+ new_meta = layout.sheet_meta_rel(canonical)
+ moves.append((self.resolve_inside(old_meta), self.resolve_inside(new_meta)))
+ replacements.append((old_meta, new_meta))
moved: list[tuple[Path, Path]] = []
applied: list[tuple[str, str]] = []
diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md
new file mode 100644
index 0000000..7740d4e
--- /dev/null
+++ b/tests/fixtures/README.md
@@ -0,0 +1,16 @@
+# Sheet fixtures
+
+The pathologies of three real investigation binders, distilled into files a test can
+read. **Synthetic and anonymous on purpose**: the binders themselves are case material,
+so no name, no unit, no place and no URL from them appears here — what is kept is the
+*shape* of the mess, which is the only part a parser cares about.
+
+| File | What it is there to break |
+|---|---|
+| `binder-semicolon.csv` | A European export: semicolon-separated, comma decimals, a quoted cell holding a comma, `dd/MM/yyyy` dates, `#REF!` where a formula died. |
+| `binder-worklist.csv` | A geolocation worklist with **no status column at all** — its progress is the fill rate of `Coordinates`, and its cells hold three coordinate formats plus `To be found`. |
+| `binder-timeline.csv` | An event timeline: a bare `hh:mm` local time with no date, an hour note in prose, a multi-value equipment cell with a quantity, and mostly empty rows. |
+| `binder-states.csv` | The eight words a real binder used for one status column, so a state vocabulary is tested against words nobody would invent. |
+
+Any test asserting "the app reads the real thing" belongs here rather than against a
+table written to suit the code.
diff --git a/tests/fixtures/binder-semicolon.csv b/tests/fixtures/binder-semicolon.csv
new file mode 100644
index 0000000..91be0d0
--- /dev/null
+++ b/tests/fixtures/binder-semicolon.csv
@@ -0,0 +1,4 @@
+Date;Nature;Title;Country;Coordinates;Geolocation
+31/01/2026;strike;"Quay, south end";Atlantis;"48,8566; 2,3522";https://example.test/1
+01/02/2026;movement;North bridge;Atlantis;#REF!;https://example.test/2
+14/02/2026;strike;East station;Borduria;"50,1000; 3,0000";
diff --git a/tests/fixtures/binder-states.csv b/tests/fixtures/binder-states.csv
new file mode 100644
index 0000000..b4c6b67
--- /dev/null
+++ b/tests/fixtures/binder-states.csv
@@ -0,0 +1,10 @@
+id,Subject,Status
+r1,A,To do
+r2,B,OK en cours
+r3,C,To be found
+r4,D,pass
+r5,E,x
+r6,F,-
+r7,G,AFTER
+r8,H,?
+r9,I,
diff --git a/tests/fixtures/binder-timeline.csv b/tests/fixtures/binder-timeline.csv
new file mode 100644
index 0000000..8f5b64b
--- /dev/null
+++ b/tests/fixtures/binder-timeline.csv
@@ -0,0 +1,13 @@
+Type,Local time,Est. local time,Note hour,Code,Equipments,start synchro
+VID,01:57,,"the author told me this hour",P1,"Buk-M2E, 2x S-125",-00:01:50
+PIC,02:10,02:05,"between 2:00 and 2:10",P2,ZU23-2,00:04:04
+SAT,,,"no idea of the exact hour",P6,,
+VID,02:40,,"probably taken after 2 h",P3,"Mi-17V-5, ZU23-2",00:01:05
+,,,,,,
+,,,,,,
+,,,,,,
+,,,,,,
+,,,,,,
+,,,,,,
+,,,,,,
+,,,,,,
diff --git a/tests/fixtures/binder-worklist.csv b/tests/fixtures/binder-worklist.csv
new file mode 100644
index 0000000..1e5b443
--- /dev/null
+++ b/tests/fixtures/binder-worklist.csv
@@ -0,0 +1,7 @@
+id,Title,Country,Coordinates,Source
+r1,South quay,Atlantis,"48.85660, 2.35220",https://example.test/a
+r2,North bridge,Atlantis,To be found,https://example.test/b
+r3,East station,Borduria,"48.85, 2.35",https://example.test/c
+r4,West depot,Borduria,,https://example.test/d
+r5,Old mill,Atlantis,"48°51'24\"N 2°21'08\"E",
+r6,River lock,Atlantis,-,https://example.test/f
diff --git a/tests/fullcase.py b/tests/fullcase.py
index 28eabd9..874b313 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -19,6 +19,7 @@ import base64
import hashlib
import io
from dataclasses import dataclass, field
+from pathlib import Path
from PIL import Image
from azimut import layout
@@ -45,6 +46,9 @@ class FullCase:
draft: str = ""
note_id: str = ""
note: str = "" # its case-relative path
+ sheet_id: str = ""
+ sheet: str = "" # the CSV, which is the sheet
+ sheet_meta: str = "" # the sidecar beside it
place_id: str = ""
grid: str = ""
person_id: str = ""
@@ -256,6 +260,55 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
full.note = note.json()["attrs"]["path"]
client.put(f"/api/cases/{case_id}/notes", json={"text": "# Full case\n\nRunning notes.\n"})
+ # -- a sheet: a CSV in the case, and the sidecar that paints it ------------
+ sheet = client.post(f"/api/cases/{case_id}/sheets", json={"title": "Candidates"})
+ assert sheet.status_code == 200, sheet.text
+ full.sheet_id = sheet.json()["id"]
+ full.sheet = sheet.json()["attrs"]["path"]
+ full.sheet_meta = layout.sheet_meta_rel(Path(full.sheet).stem)
+ # The sidecar carries what the app knows about a column as well as how it looks — a
+ # role, its vocabulary, a line of instruction, and which column the progress is read
+ # off — so the bundle gates see all of it and not only the colours.
+ saved_sheet = client.put(
+ f"/api/cases/{case_id}/sheets/{full.sheet_id}",
+ json={
+ "columns": [
+ "id", "Subject", "Status", "Coordinates", "Added", "On map",
+ "Links with others", "start synchro",
+ ],
+ "rows": [
+ ["r1", "Quai sud", "ruled out", "48.85660, 2.35220", "", "", "", "-00:01:50"],
+ ["r2", "Pont nord", "to do", "", "", "", "Quai sud", "00:04:04"],
+ ],
+ "meta": {
+ "colours": {"r1": "grey"},
+ "widths": {"Subject": 220},
+ "frozen": "Subject",
+ "roles": {
+ "Status": {"kind": "state", "values": ["to do", "done", "ruled out"]},
+ "Coordinates": {"kind": "latlon"},
+ "Added": {"kind": "stamped"},
+ "On map": {"kind": "computed", "of": "has_point"},
+ "Links with others": {"kind": "row", "of": "Subject", "multi": ", "},
+ "start synchro": {"kind": "offset", "anchor": "IGLA launch"},
+ },
+ "notes": {"Status": "where this candidate got to"},
+ "progress": "Coordinates",
+ # The three tables the bridge to the case writes, each a different grain:
+ # a named moment several videos are lined up on, a case file a row carries,
+ # and what a column's words mean in the graph.
+ "anchors": {"IGLA launch": {"at": "2026-01-03T01:57:00Z"}},
+ "attachments": {"r1": [photo_entity["id"]]},
+ "values": {"Subject": {"Quai sud": full.structure_id}},
+ "description": "What is left to geolocate.",
+ },
+ },
+ )
+ assert saved_sheet.status_code == 200, saved_sheet.text
+ assert saved_sheet.json()["rows"][0][4], "a stamped column is dated by the save"
+ assert saved_sheet.json()["meta"]["anchors"]["IGLA launch"]["at"]
+ assert saved_sheet.json()["meta"]["attachments"] == {"r1": [photo_entity["id"]]}
+
# -- a claim, with its three dedicated connectors --------------------------
# The reified statement carries one confidence for the whole assertion. Its
# connectors only identify the subject, place and supporting material.
diff --git a/tests/jobwait.py b/tests/jobwait.py
new file mode 100644
index 0000000..82b1c2b
--- /dev/null
+++ b/tests/jobwait.py
@@ -0,0 +1,40 @@
+"""Wait for a background job the way the browser does.
+
+Every road that ends in a job — a download, a sheet press, a proof import, a frame
+suggestion — is polled here, and each caller used to count its own turns: a hundred turns
+of a tenth of a second in one module, two hundred of a twentieth in the next. A turn is
+not a unit of time. A poll that costs a millisecond on a developer's machine costs whole
+seconds on the Windows runner, so the same count of turns was a different budget on every
+box, and on that one it ran out while a three-row press was still filing its second row.
+
+Wall clock instead, in one place, so "long enough" is said once.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+#: Long enough for the slowest box we run on. Windows spends around twenty seconds on a
+#: three-row proofs press, against under one here, and a job that is genuinely stuck
+#: fails the shard either way — so the cost of being generous is paid only when something
+#: is already broken.
+WAIT = 60.0
+
+
+def wait_for_job(client, job_id: str, *, timeout: float = WAIT) -> dict[str, Any]:
+ """The job's record once it stops running, whatever it ended as."""
+ deadline = time.monotonic() + timeout
+ while True:
+ job = client.get(f"/api/jobs/{job_id}").json()
+ if job["status"] != "running":
+ return job
+ assert time.monotonic() < deadline, f"the job never finished: {job}"
+ time.sleep(0.05)
+
+
+def job_result(client, job_id: str, *, timeout: float = WAIT) -> Any:
+ """The result of a job that has to succeed, reporting the record if it did not."""
+ job = wait_for_job(client, job_id, timeout=timeout)
+ assert job["status"] == "done", job
+ return job["result"]
diff --git a/tests/legacy_case.py b/tests/legacy_case.py
index 8b34bc2..4e2e577 100644
--- a/tests/legacy_case.py
+++ b/tests/legacy_case.py
@@ -165,6 +165,12 @@ def _rewind_hidden_layout(case: Case) -> None:
case._sqlite_cache = workspace._UNSET
+#: Content directories the layout gained after the `azimut/` wrapper shipped. They
+#: postdate every unwrapped checkpoint, so a rewind removes them rather than putting
+#: them at the case root where they never were.
+POST_WRAPPER_DIRS = frozenset({"sheets"})
+
+
def rewind_case(case: Case, schema: int) -> None:
"""Reconstruct one folder checkpoint from the final schema-9 layout.
@@ -188,6 +194,19 @@ def rewind_case(case: Case, schema: int) -> None:
if schema < workspace.STORAGE_SCHEMA + 2:
tool = case.tool_root
for entry in sorted(tool.iterdir()):
+ if entry.name in POST_WRAPPER_DIRS and entry.is_dir():
+ # A directory the layout gained after the wrapper shipped was never
+ # at a case root, so moving one there would build a shape no real
+ # case has ever had — and the migration would rightly leave it
+ # behind as the analyst's own folder.
+ held = [path for path in entry.rglob("*") if path.is_file()]
+ if held:
+ raise AssertionError(
+ f"'{entry.name}' holds {len(held)} file(s) at this checkpoint; "
+ "rewind it deliberately instead of dropping it here"
+ )
+ shutil.rmtree(entry)
+ continue
shutil.move(str(entry), str(case.path / entry.name))
tool.rmdir()
case._sqlite_cache = workspace._UNSET
diff --git a/tests/test_analysis_views.py b/tests/test_analysis_views.py
index f4a2217..7eb8461 100644
--- a/tests/test_analysis_views.py
+++ b/tests/test_analysis_views.py
@@ -503,6 +503,91 @@ def test_a_name_is_claimed_inside_its_own_family(client):
assert names == {("board", "Week one"), ("timeline", "Week one")}
+def test_renaming_a_view_leaves_the_reading_it_holds_alone(client):
+ """A label is not a reading, so both modes accept a rename.
+
+ The `PUT` a live view saves through refuses a snapshot on purpose — its capture is
+ evidence. Renaming has to reach it anyway, or a frozen reading is stuck with the
+ name it was given, and the answer stays the menu row rather than the whole capture.
+ """
+ case_id = _case(client, "Renaming")
+ truck = _entity(client, case_id, "vehicle", "White pickup", {"plate": "AB-123-CD"})
+ live = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("Plate watch")
+ ).json()
+ body = _body("Captured plate", mode="snapshot")
+ body["spec"]["capture_ids"] = [truck["id"]]
+ snapshot = client.post(f"/api/cases/{case_id}/analysis-views", json=body).json()
+
+ renamed = client.patch(
+ f"/api/cases/{case_id}/analysis-views/{live['id']}", json={"name": " Plates "}
+ )
+ assert renamed.status_code == 200, renamed.text
+ assert renamed.json()["name"] == "Plates"
+ # The row a menu reads, not the recipe: a rename ships no spec back.
+ assert "spec" not in renamed.json()
+ assert renamed.json()["created_at"] == live["created_at"]
+ assert renamed.json()["updated_at"] >= live["updated_at"]
+ assert client.get(
+ f"/api/cases/{case_id}/analysis-views/{live['id']}"
+ ).json()["spec"] == live["spec"]
+
+ frozen = client.patch(
+ f"/api/cases/{case_id}/analysis-views/{snapshot['id']}",
+ json={"name": "Plate capture"},
+ )
+ assert frozen.status_code == 200, frozen.text
+ assert frozen.json()["name"] == "Plate capture"
+ assert frozen.json()["snapshot_count"] == 1
+ reread = client.get(f"/api/cases/{case_id}/analysis-views/{snapshot['id']}").json()
+ assert reread["spec"]["snapshot"] == snapshot["spec"]["snapshot"]
+
+ # A name still belongs to one view of the family, and a whitespace-only name is
+ # not a name.
+ taken = client.patch(
+ f"/api/cases/{case_id}/analysis-views/{snapshot['id']}", json={"name": "plates"}
+ )
+ assert taken.status_code == 409
+ assert client.patch(
+ f"/api/cases/{case_id}/analysis-views/{live['id']}", json={"name": " "}
+ ).status_code == 400
+ assert client.patch(
+ f"/api/cases/{case_id}/analysis-views/{live['id']}", json={"name": ""}
+ ).status_code == 422
+ assert client.patch(
+ f"/api/cases/{case_id}/analysis-views/v_missing", json={"name": "Nowhere"}
+ ).status_code == 404
+ # Keeping its own name is not a clash with itself.
+ assert client.patch(
+ f"/api/cases/{case_id}/analysis-views/{live['id']}", json={"name": "Plates"}
+ ).status_code == 200
+
+
+def test_a_renamed_view_keeps_its_name_across_a_family(client):
+ """The two lists are separate namespaces for a rename as much as for a save."""
+ case_id = _case(client, "Rename across families")
+ board = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("Week one")
+ ).json()
+ timeline = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Tracks", "mode": "live", "surface": "timeline",
+ "spec": {"timeline": {"tracks": []}},
+ },
+ ).json()
+
+ renamed = client.patch(
+ f"/api/cases/{case_id}/analysis-views/{timeline['id']}", json={"name": "Week one"}
+ )
+ assert renamed.status_code == 200, renamed.text
+ assert {
+ (view["surface"], view["name"])
+ for view in client.get(f"/api/cases/{case_id}/analysis-views").json()["views"]
+ } == {("board", "Week one"), ("timeline", "Week one")}
+ assert board["name"] == "Week one"
+
+
def test_a_timeline_view_keeps_the_clock_and_the_colours_it_was_read_with(client):
case_id = _case(client, "Zone and colour")
body = {
diff --git a/tests/test_bulk_trash.py b/tests/test_bulk_trash.py
index 68a6813..0fdb76f 100644
--- a/tests/test_bulk_trash.py
+++ b/tests/test_bulk_trash.py
@@ -29,6 +29,50 @@ def test_multi_delete_is_one_trash_group(tmp_workspace):
assert case.resolve_inside(second["attrs"]["path"]).read_text(encoding="utf-8") == "two"
+def test_the_route_deletes_a_selection_as_one_undoable_act(client):
+ """The Board's ticked rows and the organizer's selected tiles come this way.
+
+ One request, one trash group, one Undo: sending a row per click would put the
+ selection back a row at a time, which is the same as having no way back.
+ """
+ case_id = client.post("/api/cases", json={"name": "Ticked rows"}).json()["id"]
+ ids = [
+ client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "person", "label": name},
+ ).json()["id"]
+ for name in ("First", "Second", "Third")
+ ]
+
+ deleted = client.post(f"/api/cases/{case_id}/entities/delete", json={"ids": ids[:2]}).json()
+
+ assert set(deleted["deleted"]) == set(ids[:2])
+ listed = client.get(f"/api/cases/{case_id}/trash").json()
+ assert len(listed["groups"]) == 1
+ assert listed["items"] == 2
+
+ restored = client.post(f"/api/cases/{case_id}/trash/{deleted['trash']}/restore")
+ assert restored.status_code == 200
+ held = client.get(f"/api/cases/{case_id}/catalog/entities").json()["items"]
+ assert {row["id"] for row in held} == set(ids)
+
+
+def test_the_route_refuses_a_selection_holding_an_unknown_row(client):
+ """Nothing goes if one id does not resolve: half a delete is the worst answer,
+ since the analyst would have to work out which half."""
+ case_id = client.post("/api/cases", json={"name": "Stale tick"}).json()["id"]
+ kept = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Kept"}
+ ).json()["id"]
+
+ answer = client.post(f"/api/cases/{case_id}/entities/delete", json={"ids": [kept, "e_gone"]})
+
+ assert answer.status_code == 404
+ held = client.get(f"/api/cases/{case_id}/catalog/entities").json()["items"]
+ assert [row["id"] for row in held] == [kept]
+ assert client.get(f"/api/cases/{case_id}/trash").json()["items"] == 0
+
+
def test_recovery_rolls_back_an_interrupted_delete(tmp_workspace):
case = Case.create("Interrupted delete")
note = case.create_note("Note", "", "kept")
diff --git a/tests/test_ci_shards.py b/tests/test_ci_shards.py
new file mode 100644
index 0000000..12c8408
--- /dev/null
+++ b/tests/test_ci_shards.py
@@ -0,0 +1,87 @@
+"""The Windows shards have to add up to the suite.
+
+Windows costs roughly eight times as much per test as Linux does — every test here
+builds a case, and a case is a database, folders and files — so it is the one box that
+runs the suite in pieces (see the backend matrix in `.github/workflows/ci.yml`).
+
+Pieces are how a file goes missing. A range stopping at ``test_sc*`` beside one starting
+at ``test_se*`` runs everything except whatever ``test_sd*`` somebody adds next year, and
+nothing anywhere says so: the run is green, the shards are green, and a module is simply
+never executed on the platform it was most likely to break on. Green would mean "the
+tests we happened to name", which is not what green is for.
+
+So the ranges are read back out of the workflow and checked against the directory. The
+workflow is parsed as text rather than as YAML on purpose: this is a gate, PyYAML is not
+a declared dependency of this project, and a gate that needs a dependency to run is a
+gate that gets skipped.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+WORKFLOW = ROOT / ".github" / "workflows" / "ci.yml"
+TESTS = ROOT / "tests"
+
+#: A matrix entry's `tests:` value. The whole-suite boxes say `tests`; a shard says one
+#: or more globs, which is what makes it a shard.
+_TESTS_LINE = re.compile(r"^\s*tests:\s*(\S.*?)\s*$", re.MULTILINE)
+
+
+def _shards() -> list[list[str]]:
+ """Every sharded `tests:` value in the workflow, as its list of globs."""
+ values = _TESTS_LINE.findall(WORKFLOW.read_text(encoding="utf-8"))
+ return [value.split() for value in values if "*" in value]
+
+
[email protected](scope="module")
+def shards() -> list[list[str]]:
+ if not WORKFLOW.is_file():
+ pytest.skip("no workflow to check: not a repository checkout")
+ found = _shards()
+ assert found, "the backend matrix names no sharded `tests:` value"
+ return found
+
+
+def test_every_test_file_runs_on_windows(shards: list[list[str]]) -> None:
+ """No test file falls between two ranges."""
+ covered = {path for globs in shards for glob in globs for path in ROOT.glob(glob)}
+ missing = sorted(path.name for path in set(TESTS.glob("test_*.py")) - covered)
+ assert not missing, (
+ "these test files are in no Windows shard, so Windows never runs them: "
+ + ", ".join(missing)
+ )
+
+
+def test_no_test_file_runs_twice_on_windows(shards: list[list[str]]) -> None:
+ """No test file is claimed by two ranges.
+
+ Not a correctness problem — the same test passing twice is still passing — but it is
+ a shard paying for work another one already did, which is the whole thing the split
+ exists to avoid.
+ """
+ seen: dict[str, int] = {}
+ for globs in shards:
+ for path in {p for glob in globs for p in ROOT.glob(glob)}:
+ seen[path.name] = seen.get(path.name, 0) + 1
+ twice = sorted(name for name, times in seen.items() if times > 1)
+ assert not twice, "these test files are in more than one Windows shard: " + ", ".join(twice)
+
+
+def test_the_shards_stay_within_reach_of_each_other(shards: list[list[str]]) -> None:
+ """No range grows into the one job everything waits for.
+
+ Counted in files rather than in tests, because reading every module to count its
+ tests is the collection this gate is deliberately cheaper than. It is a coarse
+ measure and the bound is loose to match: it catches a range that has drifted into
+ holding half the suite, not a range that is merely the largest.
+ """
+ sizes = [len({p for glob in globs for p in ROOT.glob(glob)}) for globs in shards]
+ assert min(sizes) > 0, "a Windows shard matches no file at all"
+ assert max(sizes) <= 3 * (sum(sizes) / len(sizes)), (
+ f"one Windows shard holds far more files than the rest: {sizes}"
+ )
diff --git a/tests/test_cities.py b/tests/test_cities.py
new file mode 100644
index 0000000..f3563a1
--- /dev/null
+++ b/tests/test_cities.py
@@ -0,0 +1,104 @@
+"""The bundled city gazetteer: what the search bar can answer offline."""
+
+import gzip
+
+import pytest
+
+from azimut.engine import cities
+
+
[email protected](autouse=True)
+def fresh_gazetteer():
+ """Each test starts before the lazy load, and leaves nothing loaded behind."""
+ cities._reset()
+ yield
+ cities._reset()
+
+
+def _names(query, limit=8):
+ return [city["name"] for city in cities.search(query, limit)]
+
+
+def test_the_data_file_ships_with_the_package():
+ # collect_data_files("azimut") puts it in the binaries and hatchling puts it
+ # in the wheel — but only if it is committed beside the module.
+ assert cities.DATA.exists(), "run scripts/build_cities.py"
+ text = gzip.decompress(cities.DATA.read_bytes()).decode("utf-8")
+ header, columns, first = text.splitlines()[:3]
+ assert "GeoNames" in header and "CC BY 4.0" in header
+ assert columns.split("\t") == ["# name", "ascii", "country", "region", "lat", "lon", "population"]
+ assert len(first.split("\t")) == 7
+ # biggest first: the row order *is* the ranking, so nothing re-sorts on read
+ populations = [int(line.split("\t")[6]) for line in text.splitlines()[2:102]]
+ assert populations == sorted(populations, reverse=True)
+
+
+def test_a_prefix_finds_the_city():
+ found = cities.search("krama", 5)
+ assert found[0]["name"] == "Kramatorsk"
+ assert found[0]["country"] == "ua"
+ assert found[0]["country_name"] == "Ukraine"
+ assert found[0]["region"] == "Donetsk"
+ assert found[0]["lat"] == pytest.approx(48.73, abs=0.05)
+ assert found[0]["lon"] == pytest.approx(37.57, abs=0.05)
+
+
+def test_four_letters_are_enough():
+ # the whole point of shipping the file: no pause, no network, four letters
+ assert "Kyiv" in _names("kyiv")
+ assert "Mariupol" in _names("mari")
+ assert "Aleppo" in _names("alep")
+
+
+def test_the_biggest_match_leads():
+ # three Springfields and a Paris, Texas — population decides, not the file order
+ assert _names("springfield")[0] == "Springfield"
+ paris = cities.search("paris", 3)
+ assert paris[0]["country"] == "fr"
+ assert paris[0]["population"] > paris[1]["population"]
+
+
+def test_an_exact_name_beats_a_longer_one_that_starts_the_same():
+ # "York" the city outranks York University Heights, which has more people
+ assert _names("york")[0] == "York"
+
+
+def test_a_later_word_is_searchable_but_ranks_below_a_leading_one():
+ found = _names("york", 20)
+ assert "New York City" in found
+ assert found.index("York") < found.index("New York City")
+
+
+def test_accents_and_punctuation_do_not_have_to_be_typed():
+ assert "Saint-Étienne" in _names("saint etie")
+ assert "Saint-Étienne" in _names("saint-étienne")
+ assert "Malmö" in _names("malmo")
+
+
+def test_multi_word_names_match_across_the_space():
+ assert "New York City" in _names("new yo")
+ assert "Los Angeles" in _names("los ang")
+
+
+def test_limit_is_honored_and_a_blank_query_finds_nothing():
+ assert len(cities.search("s", 3)) == 3
+ assert cities.search("", 5) == []
+ assert cities.search(" ", 5) == []
+ assert cities.search("paris", 0) == []
+
+
+def test_nothing_matches_gibberish():
+ assert cities.search("zzzqx nowhere", 5) == []
+
+
+def test_a_missing_data_file_is_not_fatal(monkeypatch, tmp_path):
+ # a broken install loses suggestions, not the search bar: the geocoder layer
+ # still answers, so this must degrade quietly rather than raise
+ monkeypatch.setattr(cities, "DATA", tmp_path / "absent.tsv.gz")
+ assert cities.search("paris", 5) == []
+
+
+def test_the_gazetteer_never_reaches_the_network():
+ # the module that answers on a keystroke must have no way to make a request
+ source = (cities.__file__ and open(cities.__file__, encoding="utf-8").read()) or ""
+ assert "httpx" not in source and "urllib" not in source
diff --git a/tests/test_entities.py b/tests/test_entities.py
index 55a7b06..24538f9 100644
--- a/tests/test_entities.py
+++ b/tests/test_entities.py
@@ -333,6 +333,60 @@ def test_the_new_verbs_keep_the_approved_endpoint_matrix():
assert "equipment-type" in by_type["about"].to_types
+# -- which verbs a pair of types has at all ------------------------------------
+
+
+def test_a_pair_offers_only_the_verbs_the_registry_allows():
+ """`pair_verbs` is the type-only endpoint check, asked before either entity exists.
+
+ Two ordered pairs, two different answers: a media may be *at* a place or *show*
+ one, and a person may only be a member of an organization, own it, or be tied to
+ it. `part-of` is absent on purpose — it runs organization to organization, so a
+ person is never *part of* one.
+ """
+ assert [s.type for s in link_engine.pair_verbs("media", "place")] == [
+ "located-at", "depicts",
+ ]
+ assert [s.type for s in link_engine.pair_verbs("person", "organization")] == [
+ "owns", "member-of", "associated-with",
+ ]
+ assert [s.type for s in link_engine.pair_verbs("organization", "organization")] == [
+ "owns", "part-of", "member-of", "associated-with",
+ ]
+ assert [s.type for s in link_engine.pair_verbs("structure", "place")] == ["sited-at"]
+
+
+def test_a_person_and_a_point_have_no_verb_between_them():
+ """The witness case for a promotion that maps coordinates onto a column of people:
+ the vocabulary joins them by nothing, so the pair is never offered and a latitude
+ never lands on a person as a field nothing shows or edits."""
+ assert link_engine.pair_verbs("person", "place") == ()
+ assert link_engine.pair_verbs("place", "media") == ()
+
+
+def test_a_pair_never_offers_what_only_a_machine_may_state():
+ """`same-image-as` is enrichment's own claim and the derivation chain is recorded
+ by the save that produced it, so neither is a verb a batch of edges may pick."""
+ assert link_engine.pair_verbs("media", "media") == ()
+ offered = {
+ spec.type
+ for a in ("media", "person", "organization", "note", "proof")
+ for b in ("media", "person", "organization", "place")
+ for spec in link_engine.pair_verbs(a, b)
+ }
+ assert offered.isdisjoint({"same-image-as", *link_engine.CHAIN_TYPES})
+
+
+def test_a_pair_can_be_asked_for_one_kind_of_gesture():
+ """A document naming a place is a pointer, not a finding, and the two never share a
+ select — so the caller asks for the action it is drawing."""
+ assert [s.type for s in link_engine.pair_verbs("note", "place")] == ["mentions"]
+ assert link_engine.pair_verbs("note", "place", action="relation") == ()
+ assert [
+ s.type for s in link_engine.pair_verbs("note", "place", action="mention")
+ ] == ["mentions"]
+
+
# -- what state a thing is in, and how many of it ------------------------------
diff --git a/tests/test_export_destinations.py b/tests/test_export_destinations.py
index 491d352..767bae0 100644
--- a/tests/test_export_destinations.py
+++ b/tests/test_export_destinations.py
@@ -59,7 +59,11 @@ def test_export_destinations_are_remembered_independently(client, tmp_path):
"notes": str(notes),
"media": str(media),
"proofs": "",
+ "views": "",
+ "sheets": "",
}
+ # Every kind answers, so a new one cannot ship without a folder of its own.
+ assert set(response.json()["export_dirs"]) == set(exportdir.KINDS)
assert client.get("/api/settings").json()["export_dirs"]["notes"] == str(notes)
reset = client.put("/api/settings/prefs", json={"export_dirs": {"notes": ""}})
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index cc5fda7..8cfb9f3 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -388,3 +388,101 @@ def test_sky_never_touches_the_network(client, monkeypatch):
"/api/geo/sky", params={"lat": 48.8584, "lon": 2.2945, "date": "2026-07-30"}
)
assert response.status_code == 200
+
+
+# -- /api/geo/suggest: the search bar's instant layer, offline by construction ---------
+
+
+def test_suggest_offers_cities_without_touching_the_network(client, monkeypatch):
+ def explode(*args, **kwargs):
+ raise AssertionError("a keystroke must never reach the geocoder")
+
+ monkeypatch.setattr(geo.httpx, "get", explode)
+
+ body = client.get("/api/geo/suggest", params={"q": "krama"}).json()
+ assert body["cities"][0]["name"] == "Kramatorsk"
+ assert body["cities"][0]["country_name"] == "Ukraine"
+ assert "GeoNames" in body["attribution"]
+ assert body["coords"] is None
+
+
+def test_suggest_recognizes_coordinates_as_they_are_typed(client):
+ body = client.get("/api/geo/suggest", params={"q": "50.4501, 30.5234"}).json()
+ assert body["coords"] == {"lat": 50.4501, "lon": 30.5234}
+ # a coordinate is not a place name, so the gazetteer stays quiet
+ assert body["cities"] == []
+
+
+def test_suggest_honors_the_limit_and_survives_an_empty_query(client):
+ assert len(client.get("/api/geo/suggest", params={"q": "s", "limit": 3}).json()["cities"]) == 3
+ blank = client.get("/api/geo/suggest", params={"q": " "}).json()
+ assert blank == {"coords": None, "cities": [], "attribution": None}
+
+
+# -- /api/geo/places: the slow layer, dropped rather than queued -----------------------
+
+
+def test_places_returns_several_matches(client, monkeypatch):
+ fake, calls = _fake_get(
+ [
+ {"lat": "48.8584", "lon": "2.2945", "display_name": "Tour Eiffel, Paris", "type": "attraction"},
+ {"lat": "48.86", "lon": "2.29", "display_name": "Rue de la Tour, Paris", "type": "road"},
+ ]
+ )
+ monkeypatch.setattr(geo.httpx, "get", fake)
+
+ body = client.get("/api/geo/places", params={"q": "tour eiffel"}).json()
+ assert [place["display_name"] for place in body["places"]] == [
+ "Tour Eiffel, Paris",
+ "Rue de la Tour, Paris",
+ ]
+ assert body["places"][1]["kind"] == "road"
+ assert body["busy"] is False
+ assert "OpenStreetMap" in body["attribution"]
+ assert calls["params"]["limit"] == 10 # one request feeds any limit the UI asks for
+
+
+def test_places_is_dropped_rather_than_queued_when_the_pace_is_held(client, monkeypatch):
+ fake, _ = _fake_get([{"lat": "1", "lon": "2", "display_name": "Somewhere"}])
+ monkeypatch.setattr(geo.httpx, "get", fake)
+
+ assert client.get("/api/geo/places", params={"q": "first"}).json()["busy"] is False
+ # a second query inside the one-per-second floor waits for nothing: it says so
+ second = client.get("/api/geo/places", params={"q": "second"}).json()
+ assert second == {"places": [], "busy": True, "throttled": False, "attribution": None}
+
+
+def test_places_answers_a_repeated_query_from_memory(client, monkeypatch):
+ calls = []
+
+ def counting(url, params=None, headers=None, timeout=None):
+ calls.append(params["q"])
+ return _FakeResponse([{"lat": "50.45", "lon": "30.52", "display_name": "Kyiv"}])
+
+ monkeypatch.setattr(geo.httpx, "get", counting)
+
+ first = client.get("/api/geo/places", params={"q": "kyiv"}).json()
+ # inside the pace floor, and still answered — the cache spends no slot
+ again = client.get("/api/geo/places", params={"q": " KYIV "}).json()
+ assert again["places"] == first["places"] and again["busy"] is False
+ assert calls == ["kyiv"]
+
+
+def test_places_reports_a_throttled_geocoder_instead_of_an_empty_list(client, monkeypatch):
+ class _Throttled(_FakeResponse):
+ status_code = 429
+
+ def raise_for_status(self):
+ raise RuntimeError("429")
+
+ monkeypatch.setattr(geo.httpx, "get", lambda *a, **k: _Throttled([]))
+ assert client.get("/api/geo/places", params={"q": "paris"}).json()["busy"] is True
+
+ # the 429 is remembered for a minute, so the next query is refused before it
+ # is even sent — and says why, rather than looking like "no such place"
+ body = client.get("/api/geo/places", params={"q": "lyon"}).json()
+ assert body["busy"] is True and body["throttled"] is True
+
+
+def test_places_empty_query_is_422(client):
+ assert client.get("/api/geo/places", params={"q": " "}).status_code == 422
diff --git a/tests/test_graph.py b/tests/test_graph.py
index 6957a25..65d22f3 100644
--- a/tests/test_graph.py
+++ b/tests/test_graph.py
@@ -168,7 +168,7 @@ def test_a_reading_of_the_case_leaves_out_what_the_analyst_wrote():
are derived from the relation registry: a type added there lands in the right
readings with no edit here."""
filing = entity_engine.types_with_role(entity_engine.ANNEX, entity_engine.DELIVERABLE)
- assert filing == {"note", "inspect-session", "post"}
+ assert filing == {"note", "sheet", "inspect-session", "post"}
for lens_id in ("all", "subjects", "ground", "claims"):
assert set(graph_engine.lens(lens_id).hides) == filing, lens_id
diff --git a/tests/test_hardening.py b/tests/test_hardening.py
index e822242..c800bb2 100644
--- a/tests/test_hardening.py
+++ b/tests/test_hardening.py
@@ -1,6 +1,7 @@
-"""Local hardening: the decompression-bomb clamp and owner-only secrets file."""
+"""Local hardening: the decompression-bomb clamp, owner-only secrets, request bounds."""
import os
+import re
import stat
import sys
import warnings
@@ -34,3 +35,99 @@ def test_settings_and_workspace_are_owner_only(tmp_workspace):
assert stat.S_IMODE(os.stat(config.internal_dir()).st_mode) == 0o700
assert stat.S_IMODE(os.stat(config.settings_dir()).st_mode) == 0o700
assert stat.S_IMODE(os.stat(config.settings_path()).st_mode) == 0o600
+
+
+#: Body fields that mean "the browser assembled this and it has no natural size". A table
+#: (`columns`/`rows`/`text`/`meta`), a document (`content`) or a picture
+#: (`png_base64`/`assets`): each can arrive at tens of megabytes from an ordinary gesture,
+#: and each is parsed into memory whole. `content` is here because `text` alone let a note
+#: written through `POST /notes` past a gate that caught the same note through `PUT`.
+CARRIES = frozenset({"columns", "rows", "text", "meta", "content", "png_base64", "assets"})
+
+
+def _bounded_by_its_own_field(model, named):
+ """Whether every carrying field declares its own `max_length`.
+
+ The second acceptable answer, and the right one for a field with a natural size: a
+ coordinate is never a document, so `POST /geo/parse` is bounded where it is read rather
+ than by a middleware built for bodies too big to parse.
+ """
+ fields = getattr(model, "model_fields", {}) or {}
+ return all(
+ any(getattr(rule, "max_length", None) is not None for rule in fields[name].metadata)
+ for name in named
+ )
+
+
+def test_no_route_carrying_a_browser_built_payload_is_parsed_before_it_is_bounded():
+ """The gate that stops the next recurrence, rather than the next entry in a list.
+
+ `server.BulkBodyLimit.ROUTES` is spelled out by hand, and routes kept being added
+ without one: four roads out of a sheet's promotion first — `parse`, `move/undo`,
+ `proofs`, `meta` — and then the composer's own save, which posts a rendered PNG plus
+ every image pasted into the proof and had no limit at all, on the very middleware that
+ exists for pictures the browser draws.
+
+ So the list is not trusted: every router the application mounts is walked here, and any
+ body model holding a table or a picture must answer a limit. Asked of the app rather
+ than of two named routers, because "which routers carry tables" was itself the
+ assumption that let the proof route through.
+ """
+ from azimut.server import BulkBodyLimit, create_app
+
+ def every_route(holder):
+ """Walk the mounted tree. FastAPI keeps an included router as a wrapper around the
+ router it was given rather than flattening its routes into the app, so a single pass
+ over `app.routes` sees nineteen wrappers and no body at all."""
+ for entry in getattr(holder, "routes", ()):
+ yield entry
+ yield from every_route(entry)
+ wrapped = getattr(entry, "original_router", None)
+ if wrapped is not None:
+ yield from every_route(wrapped)
+
+ checked = 0
+ for route in every_route(create_app()):
+ body = getattr(route, "body_field", None)
+ model = getattr(getattr(body, "field_info", None), "annotation", None)
+ carried = CARRIES & set(getattr(model, "model_fields", {}) or {})
+ if not carried:
+ continue
+ for method in sorted(getattr(route, "methods", set()) & {"POST", "PUT"}):
+ path = re.sub(r"\{[^}]+\}", "x", route.path)
+ bounded = BulkBodyLimit._limit(
+ {"type": "http", "method": method, "path": path}
+ ) is not None or _bounded_by_its_own_field(model, carried)
+ assert bounded, f"{method} {route.path} carries {sorted(carried)} and answers no limit"
+ checked += 1
+ # The count is the test's own gate: a FastAPI that stopped exposing `body_field` would
+ # otherwise make this pass by checking nothing.
+ assert checked >= 16, checked
+
+
+def test_the_proof_export_is_refused_by_the_size_it_decodes_to(client, monkeypatch):
+ """The whole request is bounded by the middleware; the picture inside it by the route.
+
+ Two bounds because they answer two things. The middleware refuses a body too big to
+ parse, before parsing. This one refuses a legal-sized body whose export alone is
+ absurd — and it has to land before the rename, which deletes the old PNG and moves the
+ pasted images: a payload refused after that point would leave the proof under its old
+ name with both of them gone.
+ """
+ import base64
+
+ from azimut.api import proofs as proofs_api
+
+ monkeypatch.setattr(proofs_api, "MAX_EXPORT_BYTES", 64)
+ case_id = client.post("/api/cases", json={"name": "Bounds"}).json()["id"]
+ answer = client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={
+ "title": "Too wide",
+ "spec": {"azimut_proof": 1, "panels": [], "shapes": []},
+ "png_base64": base64.b64encode(b"x" * 200).decode("ascii"),
+ },
+ )
+ assert answer.status_code == 413
+ assert "under" in answer.json()["detail"]
+ assert client.get(f"/api/cases/{case_id}/proofs").json() == []
diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.py
index 4e676f3..81e7a31 100644
--- a/tests/test_inspect_api.py
+++ b/tests/test_inspect_api.py
@@ -9,9 +9,9 @@ import subprocess
import threading
import graph_read
-import time
import pytest
+from jobwait import job_result
from PIL import Image
from azimut.engine import inspect as inspect_engine
@@ -1004,13 +1004,7 @@ def test_frame_capture_from_video(client, tmp_path):
job_id = client.post(
f"/api/cases/{cid}/inspect/suggest", json={"path": item["path"], "bins": 4}
).json()["job_id"]
- for _ in range(100):
- job = client.get(f"/api/jobs/{job_id}").json()
- if job["status"] != "running":
- break
- time.sleep(0.1)
- assert job["status"] == "done"
- assert len(job["result"]["frames"]) >= 1
+ assert len(job_result(client, job_id)["frames"]) >= 1
def test_saved_frame_filename_follows_the_typed_name(client):
diff --git a/tests/test_layout.py b/tests/test_layout.py
index 04576ab..36629e2 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -90,6 +90,8 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:
"entity photo": len(layout.entity_image_rel("i_0123456789")),
"entity photo thumbnail": len(layout.entity_image_thumb_rel("i_0123456789")),
"note": len(layout.note_rel(longest_folder, longest_name)),
+ "sheet table": len(layout.sheet_rel(longest_name)),
+ "sheet sidecar": len(layout.sheet_meta_rel(longest_name)),
"proof asset": len(layout.proof_assets_rel(longest_name)) + 1 + ASSET_NAME,
"proof spec": len(layout.proof_spec_rel(longest_name)),
"proof export": len(layout.proof_export_rel(longest_name)),
@@ -196,7 +198,7 @@ def test_layout_answers_are_all_under_the_root(tmp_path: Path) -> None:
assert answer.is_relative_to(root)
-def test_content_dirs_covers_every_subdir_and_the_meta_pair(tmp_path: Path) -> None:
+def test_content_dirs_covers_every_subdir_and_its_meta(tmp_path: Path) -> None:
root = tmp_path / "a-case"
born = layout.content_dirs(root)
assert [d.name for d in born[: len(CASE_SUBDIRS)]] == list(CASE_SUBDIRS)
@@ -204,6 +206,7 @@ def test_content_dirs_covers_every_subdir_and_the_meta_pair(tmp_path: Path) -> N
assert set(born[len(CASE_SUBDIRS) :]) == {
layout.media(root) / layout.META_DIR,
layout.subdir(root, "proofs") / layout.META_DIR,
+ layout.subdir(root, "sheets") / layout.META_DIR,
}
assert layout.trash(root).name not in CASE_SUBDIRS
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index 158a676..b7f43ab 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -2,11 +2,14 @@
import io
import json
+import sys
+import threading
import graph_read
import pytest
import time
+from jobwait import job_result, wait_for_job
from PIL import Image
from azimut.engine.media import safe_filename
@@ -18,9 +21,11 @@ def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
return buf.getvalue()
-def _upload(client, cid, name, data):
+def _upload(client, cid, name, data, source_url=None):
return client.post(
- f"/api/cases/{cid}/media/upload", files={"file": (name, io.BytesIO(data), "image/png")}
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(data), "image/png")},
+ **({"data": {"source_url": source_url}} if source_url is not None else {}),
)
@@ -738,6 +743,101 @@ def test_update_media_clear_notes(client):
assert "notes" not in updated
+def test_import_states_where_the_file_came_from(client):
+ """A file fetched by hand elsewhere carries no address of its own, and the
+ import is the first chance to state one.
+
+ Stated, never fetched: the source type stays ``upload``, so the facet still
+ reads how the file arrived and a reader can tell this address from the one a
+ download really pulled from.
+ """
+ cid = client.post("/api/cases", json={"name": "Stated"}).json()["id"]
+ item = _upload(
+ client, cid, "shot.png", _png_bytes(), source_url="https://t.me/channel/42"
+ ).json()["item"]
+
+ assert item["source"] == {
+ "type": "upload",
+ "original_name": "shot.png",
+ "url": "https://t.me/channel/42",
+ }
+ entity = graph_read.entities(cid)[0]
+ assert entity["attrs"]["source_url"] == "https://t.me/channel/42"
+
+ # searchable like a download's address, through the same indexed field
+ hit = client.get(f"/api/cases/{cid}/media/page", params={"q": "t.me/channel"}).json()
+ assert [i["path"] for i in hit["items"]] == [item["path"]]
+
+ # and still an import, not a download
+ assert (
+ client.get(f"/api/cases/{cid}/media/page", params={"category": "upload"}).json()["total"]
+ == 1
+ )
+
+
+def test_a_stated_source_must_be_a_link(client):
+ cid = client.post("/api/cases", json={"name": "Not a link"}).json()["id"]
+ res = _upload(client, cid, "shot.png", _png_bytes(), source_url="a friend sent it")
+ assert res.status_code == 422
+ assert client.get(f"/api/cases/{cid}/media").json() == []
+
+
+def test_a_source_can_be_stated_after_the_import(client):
+ """The origin is often remembered after the files have landed — and for a batch
+ dropped in one go, stated once for all of them."""
+ cid = client.post("/api/cases", json={"name": "Later"}).json()["id"]
+ item = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]
+
+ updated = _set(client, cid, item["path"], source_url="https://example.org/post/7")
+ assert updated["source"]["url"] == "https://example.org/post/7"
+ assert updated["source"]["type"] == "upload"
+ assert graph_read.entities(cid)[0]["attrs"]["source_url"] == "https://example.org/post/7"
+
+ # and taken back, without disturbing the rest of what the sidecar records
+ cleared = _set(client, cid, item["path"], source_url="")
+ assert "url" not in cleared["source"]
+ assert cleared["source"]["original_name"] == "shot.png"
+ assert graph_read.entities(cid)[0]["attrs"]["source_url"] == ""
+
+ # typed wrong, refused at the edge like every other surface that takes one
+ assert (
+ client.patch(
+ f"/api/cases/{cid}/media", json={"path": item["path"], "source_url": "ftp://host/x"}
+ ).status_code
+ == 422
+ )
+
+
+def test_only_a_file_brought_in_by_hand_can_be_given_a_source(client):
+ """What a tool recorded about where bytes came from is not something a later
+ edit gets to write over: a case that cannot tell a fetched address from a
+ stated one is holding neither."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Fetched"}).json()["id"]
+ filed = media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (32, 24), (10, 10, 90)),
+ "post.png",
+ {
+ "type": "download",
+ "url": "https://x.com/user/status/1",
+ "webpage_url": "https://x.com/user/status/1",
+ },
+ )
+
+ res = client.patch(
+ f"/api/cases/{cid}/media",
+ json={"path": filed["item"]["path"], "source_url": "https://example.org/other"},
+ )
+ assert res.status_code == 400
+ assert "brought in by hand" in res.json()["detail"]
+
+ listed = client.get(f"/api/cases/{cid}/media").json()[0]
+ assert listed["source"]["url"] == "https://x.com/user/status/1"
+
+
def test_update_media_bad_path(client):
cid = client.post("/api/cases", json={"name": "Bad"}).json()["id"]
res = client.patch(
@@ -876,12 +976,16 @@ def test_download_reports_multi_without_downloading(client, monkeypatch):
)
result = media_engine.download_url(case, "https://x.com/user/status/123")
+ # `own` is the vouch: past the first, this extractor cannot say whether an
+ # attachment is the post's or the one it quotes.
assert result == {
"multi": True,
"items": [
- {"index": 1, "title": "photo 1", "thumbnail": "https://x.test/p1.jpg", "kind": "image"},
- {"index": 2, "title": "photo 2", "thumbnail": "https://x.test/p2.jpg", "kind": "image"},
- {"index": 3, "title": "p3", "thumbnail": None, "kind": "video"},
+ {"index": 1, "title": "photo 1", "thumbnail": "https://x.test/p1.jpg",
+ "kind": "image", "own": True},
+ {"index": 2, "title": "photo 2", "thumbnail": "https://x.test/p2.jpg",
+ "kind": "image", "own": False},
+ {"index": 3, "title": "p3", "thumbnail": None, "kind": "video", "own": False},
],
}
assert case.list_entities() == []
@@ -908,14 +1012,9 @@ def test_download_route_surfaces_multi_via_job(client, monkeypatch):
f"/api/cases/{cid}/media/download", json={"url": "https://x.com/u/status/1"}
).json()["job_id"]
- for _ in range(100):
- job = client.get(f"/api/jobs/{job_id}").json()
- if job["status"] != "running":
- break
- time.sleep(0.1)
- assert job["status"] == "done"
- assert job["result"]["multi"] is True
- assert [i["title"] for i in job["result"]["items"]] == ["a", "b"]
+ result = job_result(client, job_id)
+ assert result["multi"] is True
+ assert [i["title"] for i in result["items"]] == ["a", "b"]
def test_download_with_index_picks_entry_and_keeps_custom_title(client, monkeypatch):
@@ -982,6 +1081,11 @@ def _install_failing_ydl(monkeypatch, message="No video could be found in this t
return False
def extract_info(self, url, download=False):
+ # real yt-dlp reports the failure through its console/logger first,
+ # then raises — the report is what used to reach the terminal
+ reporter = self.opts.get("logger")
+ if reporter is not None:
+ reporter.error(f"[twitter] 1: {message}")
raise DownloadError(message)
utils = types.ModuleType("yt_dlp.utils")
@@ -1044,6 +1148,38 @@ def test_gallery_dl_fallback_downloads_single_image(client, monkeypatch):
assert result["item"]["source"]["uploader"] == "someone"
+
+def test_ytdlp_failure_does_not_print_to_the_terminal(client, monkeypatch, capsys, caplog):
+ """An image-only post makes yt-dlp report "No video could be found", then
+ gallery-dl downloads it anyway. Nothing about that working download may
+ reach the terminal; the extractor's own words stay at debug level."""
+ import logging
+
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "QuietFallback"}).json()["id"]
+ case = Case.open(cid)
+
+ _install_failing_ydl(monkeypatch)
+ items = [("https://pbs.twimg.com/media/abc.jpg", {"filename": "abc", "extension": "jpg"})]
+ monkeypatch.setattr(gdl_extractor, "find", lambda url: _FakeGalleryExtractor(items))
+
+ capsys.readouterr() # drop whatever the fixtures printed before this call
+ with caplog.at_level(logging.DEBUG, logger="azimut.engine.media"):
+ result = media_engine.download_url(case, "https://x.com/u/status/1")
+
+ assert result["item"]["source"]["downloader"] == "gallery-dl"
+ captured = capsys.readouterr()
+ assert "No video could be found" not in captured.out + captured.err
+ assert any(
+ "No video could be found" in rec.getMessage() and rec.levelno == logging.DEBUG
+ for rec in caplog.records
+ )
+
+
def test_gallery_dl_fallback_multi_images(client, monkeypatch):
"""Two photos on the same post: reported as a picker like the yt-dlp
path, downloads nothing until an ``index`` is picked."""
@@ -1066,8 +1202,9 @@ def test_gallery_dl_fallback_multi_images(client, monkeypatch):
assert result == {
"multi": True,
"items": [
- {"index": 1, "title": "a", "thumbnail": items[0][0], "kind": "image"},
- {"index": 2, "title": "b", "thumbnail": items[1][0], "kind": "image"},
+ # gallery-dl drops a quoted tweet before listing, so both are vouched for.
+ {"index": 1, "title": "a", "thumbnail": items[0][0], "kind": "image", "own": True},
+ {"index": 2, "title": "b", "thumbnail": items[1][0], "kind": "image", "own": True},
],
}
assert case.list_entities() == []
@@ -1098,10 +1235,144 @@ def test_gallery_dl_fallback_no_extractor_raises(client, monkeypatch):
assert "no extractor" in str(exc)
-def test_telegram_extra_photos_parses_embed_html(monkeypatch):
- """Unit test for the Telegram photo scraper itself: extracts photo CDN
- URLs from the embed page's markup, and never makes a network call at all
- for a non-Telegram URL (the domain check short-circuits first)."""
+def test_a_slot_that_holds_footage_takes_photographs_too(client, monkeypatch):
+ """`wants` binds one way, and only one way.
+
+ A slot that holds a **picture** has nowhere for a video: the composer lays panels out
+ on a canvas and a clip has nothing to lay out. That is a requirement.
+
+ "Footage" is not the mirror of it. A still photographed on the spot is material as
+ much as the clip beside it, so the footage roads say `wants="video"` as a
+ *preference* — which of two attachments to reach for — and a post of four
+ photographs is an ordinary geolocation. Reading it as a requirement refused those
+ rows outright, on a road whose own tests could not see it: they stub the downloader,
+ so `wants` never reaches the code that reads it.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Photos"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch)
+ monkeypatch.setattr(
+ gdl_extractor, "find",
+ lambda url: [(3, "https://cdn.test/a.jpg", {"filename": "a", "extension": "jpg"})],
+ )
+ monkeypatch.setattr(
+ media_engine, "_register_gallery_dl_item",
+ lambda *a, **k: {"multi": False, "item": {"filename": "a.jpg"}},
+ )
+
+ taken = media_engine.download_url(case, "https://x.com/u/status/7", wants="video")
+ assert taken["item"]["filename"] == "a.jpg"
+
+
+def test_a_post_holding_only_a_clip_is_refused_a_slot_that_holds_pictures(
+ client, monkeypatch
+):
+ """The road a video-only post took into a proof's picture slot.
+
+ `wants="image"` bound on the yt-dlp path — a pick of the wrong kind counted as
+ nothing found — and then fell through to gallery-dl, which registered whatever it
+ had. So a post carrying one clip came back as the proof's picture, was staged, and
+ was shown as "Proof: clip.mp4"; the refusal waited for the preview, two screens on.
+
+ This is the last road, so the wrong kind is a refusal rather than a fallback. And a
+ refusal of its own type: a wall handler that turned it into "sign in" would be
+ offering a login that could not fix what is not a permission problem.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "ClipOnly"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch)
+ monkeypatch.setattr(
+ gdl_extractor, "find",
+ lambda url: [(3, "https://cdn.test/clip.mp4", {"filename": "clip", "extension": "mp4"})],
+ )
+
+ with pytest.raises(media_engine.WrongKind, match="image"):
+ media_engine.download_url(case, "https://x.com/u/status/9", wants="image")
+ assert case.list_entities() == [] # nothing filed on the way out
+
+ # With room for it, the same address is an ordinary download.
+ monkeypatch.setattr(
+ media_engine, "_register_gallery_dl_item",
+ lambda *a, **k: {"multi": False, "item": {"filename": "clip.mp4"}},
+ )
+ assert media_engine.download_url(case, "https://x.com/u/status/9")["item"]["filename"] == (
+ "clip.mp4"
+ )
+
+
+def test_the_picker_vouches_only_for_what_the_post_itself_holds(monkeypatch):
+ """Which of a post's attachments are certainly its own, and which may be quoted.
+
+ yt-dlp's X extractor reads a tweet's media *and* the media of the tweet it quotes
+ into one list — the post's own first — and nothing in the result says which is which.
+ So the first row is vouched for and the rest are not, and every road that takes
+ attachments without asking reads that flag rather than writing the rule again.
+ gallery-dl needs no flag of its own: it drops a quoted tweet before listing anything.
+ """
+ from azimut.engine import media as media_engine
+
+ items = media_engine._picker_items([
+ {"id": "a", "title": "the post's own clip", "ext": "mp4"},
+ {"id": "b", "title": "the quoted clip", "ext": "mp4"},
+ {"id": "c", "title": "and another", "ext": "mp4"},
+ ])
+ assert [one["own"] for one in items] == [True, False, False]
+ assert [one["index"] for one in items] == [1, 2, 3]
+
+
+def test_a_mastodon_status_on_any_server_reaches_the_extractor(client, monkeypatch):
+ """gallery-dl names three Mastodon servers in its pattern, and the fediverse is the
+ one place a list of servers can never be the answer.
+
+ Its own `mastodon:<url>` prefix says "read this address with that extractor", so a
+ status nothing recognized is offered to it once before the link is refused. Only a
+ status, and only by shape: an account page is not a download, and a link of any
+ other shape is refused exactly as before.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Fediverse"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch)
+
+ asked: list[str] = []
+
+ def find(url):
+ asked.append(url)
+ return None # nothing is downloaded here; the question is what was tried
+
+ monkeypatch.setattr(gdl_extractor, "find", find)
+
+ for url, tried in (
+ ("https://infosec.exchange/@user/112233445566", ["mastodon:"]),
+ ("https://mstdn.social/users/bob/statuses/998877", ["mastodon:"]),
+ ("https://infosec.exchange/@user", []),
+ ("https://example.com/nope", []),
+ ):
+ asked.clear()
+ with pytest.raises(RuntimeError, match="no extractor"):
+ media_engine.download_url(case, url)
+ assert asked[0] == url # the address as typed is always asked first
+ assert [a[: len(t)] for a, t in zip(asked[1:], tried)] == tried
+ assert len(asked) == 1 + len(tried)
+
+
+def test_telegram_embed_media_parses_photos(monkeypatch):
+ """The Telegram embed reader extracts photo CDN URLs and reports no size
+ wall, while a non-Telegram URL makes no network call at all."""
from azimut.engine import media as media_engine
html = """
@@ -1121,17 +1392,71 @@ def test_telegram_extra_photos_parses_embed_html(monkeypatch):
monkeypatch.setattr(requests, "get", lambda *a, **kw: FakeResp())
- photos = media_engine._telegram_extra_photos("https://t.me/exilenova_plus/24988")
+ photos, too_large = media_engine._telegram_embed_media(
+ "https://t.me/exilenova_plus/24988"
+ )
assert [p["url"] for p in photos] == [
"https://cdn1.telesco.pe/file/AAA",
"https://cdn1.telesco.pe/file/BBB",
]
+ assert too_large is False
def boom(*a, **kw):
raise AssertionError("must not be called for a non-Telegram URL")
monkeypatch.setattr(requests, "get", boom)
- assert media_engine._telegram_extra_photos("https://x.com/u/status/1") == []
+ assert media_engine._telegram_embed_media("https://x.com/u/status/1") == ([], False)
+
+
+def test_telegram_embed_media_detects_video_too_large(monkeypatch):
+ """Telegram replaces the video URL with this wall for large app-only
+ videos; preserve that distinction instead of treating it as a broken URL."""
+ from azimut.engine import media as media_engine
+
+ html = """
+ <a class="tgme_widget_message_video_player not_supported js-message_video_player">
+ <div class="message_media_not_supported_label">Media is too big</div>
+ <span class="message_media_view_in_telegram">VIEW IN TELEGRAM</span>
+ </a>
+ """
+
+ class FakeResp:
+ text = html
+
+ def raise_for_status(self):
+ pass
+
+ import requests
+
+ monkeypatch.setattr(requests, "get", lambda *a, **kw: FakeResp())
+
+ assert media_engine._telegram_embed_media(
+ "https://t.me/warhistoryalconafter/104333"
+ ) == ([], True)
+
+
+def test_download_reports_large_telegram_video_without_fallback(client, monkeypatch):
+ """An app-only Telegram video is an actionable result, not the generic
+ `no extractor recognizes this link` error from the gallery-dl fallback."""
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "TelegramLarge"}).json()["id"]
+ case = Case.open(cid)
+ url = "https://t.me/warhistoryalconafter/104333"
+
+ _install_fake_ydl(monkeypatch, lambda ydl, target, download: None)
+ monkeypatch.setattr(media_engine, "_telegram_embed_media", lambda target: ([], True))
+ monkeypatch.setattr(
+ gdl_extractor,
+ "find",
+ lambda target: (_ for _ in ()).throw(AssertionError("gallery-dl must not run")),
+ )
+
+ assert media_engine.download_url(case, url) == {"telegram_only": True}
+ assert case.list_entities() == []
def test_download_merges_telegram_video_and_photos(client, monkeypatch):
@@ -1153,8 +1478,8 @@ def test_download_merges_telegram_video_and_photos(client, monkeypatch):
)
monkeypatch.setattr(
media_engine,
- "_telegram_extra_photos",
- lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ "_telegram_embed_media",
+ lambda url: ([{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}], False),
)
result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988")
@@ -1186,14 +1511,15 @@ def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):
)
monkeypatch.setattr(
media_engine,
- "_telegram_extra_photos",
- lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ "_telegram_embed_media",
+ lambda url: ([{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}], False),
)
captured = {}
- def fake_register(case_, post_url, photo, *, title=None):
+ def fake_register(case_, post_url, photo, *, title=None, stage=None):
captured["photo"] = photo
+ captured["stage"] = stage
return {"multi": False, "item": {"filename": "a.jpg"}}
monkeypatch.setattr(media_engine, "_register_telegram_photo", fake_register)
@@ -1201,6 +1527,8 @@ def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):
result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988", index=3)
assert captured["photo"]["url"] == "https://cdn/a.jpg"
assert result["item"]["filename"] == "a.jpg"
+ # No staging directory asked for, so this path files into the library as before
+ assert captured["stage"] is None
def test_download_picks_yt_dlp_video_from_mixed_post(client, monkeypatch):
@@ -1221,8 +1549,8 @@ def test_download_picks_yt_dlp_video_from_mixed_post(client, monkeypatch):
)
monkeypatch.setattr(
media_engine,
- "_telegram_extra_photos",
- lambda url: [{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}],
+ "_telegram_embed_media",
+ lambda url: ([{"url": "https://cdn/a.jpg"}, {"url": "https://cdn/b.jpg"}], False),
)
result = media_engine.download_url(case, "https://t.me/exilenova_plus/24988", index=2)
@@ -1287,11 +1615,7 @@ def test_download_job_bad_url(client):
json={"url": "https://localhost:1/nothing-here"},
).json()["job_id"]
- for _ in range(100):
- job = client.get(f"/api/jobs/{job_id}").json()
- if job["status"] != "running":
- break
- time.sleep(0.1)
+ job = wait_for_job(client, job_id)
assert job["status"] == "error"
assert job["error"]
@@ -1453,9 +1777,14 @@ def test_cookies_file_threads_absolute_cookiefile(client, monkeypatch):
assert result["item"]["title"] == "Gated via file"
-def test_apply_gallery_cookies_sets_browser_then_file(monkeypatch):
- """The gallery-dl path threads cookies through gallery_dl.config: a browser
- source as a [name] list, a file source as a path string."""
+def test_apply_gallery_config_asks_for_facets_and_threads_cookies(monkeypatch):
+ """What gallery-dl is told before it reads a link.
+
+ Cookies when there are any: a browser source as a [name] list, a file source as a
+ path string. And Bluesky's facets always — an AT Protocol post keeps its links
+ beside its words rather than in them, and the words hold an address printed with an
+ ellipsis through it.
+ """
import sys
import types
@@ -1469,17 +1798,58 @@ def test_apply_gallery_cookies_sets_browser_then_file(monkeypatch):
monkeypatch.setitem(sys.modules, "gallery_dl", gdl)
monkeypatch.setitem(sys.modules, "gallery_dl.config", config_mod)
- media_engine._apply_gallery_cookies({"browser": "firefox"})
- assert calls[-1] == (("extractor",), "cookies", ["firefox"])
+ facets = (("extractor", "bluesky"), "metadata", "facets")
- media_engine._apply_gallery_cookies({"file": "cookies.txt"})
+ media_engine._apply_gallery_config({"browser": "firefox"})
+ assert calls == [facets, (("extractor",), "cookies", ["firefox"])]
+
+ calls.clear()
+ media_engine._apply_gallery_config({"file": "cookies.txt"})
path, key, value = calls[-1]
assert (path, key) == (("extractor",), "cookies")
assert value.endswith("cookies.txt")
calls.clear()
- media_engine._apply_gallery_cookies(None)
- assert calls == [], "no cookies → no gallery-dl config mutation"
+ media_engine._apply_gallery_config(None)
+ assert calls == [facets], "no cookies → nothing about cookies is said"
+
+
+def test_a_post_is_read_for_its_words_whatever_the_platform_calls_them(monkeypatch):
+ """Where a post keeps its text, and where it keeps the links it points at.
+
+ Everything the import prefills is read from a post's own words: the name, the
+ position scanned out of it, the source it names. `content` is what X and Mastodon
+ call them and it was the only field read, so a Bluesky post — which carries `text`
+ — arrived with a filename for a title, no coordinates and no source, three symptoms
+ of one missing key.
+
+ Its links are a second reading: an AT Protocol post prints an address truncated to
+ an ellipsis and keeps the whole of it in a facet, so scanning the words gives half
+ an address with nothing to say it is half.
+ """
+ from azimut.engine import media as media_engine
+
+ bluesky = media_engine._gallery_dl_item(
+ "https://cdn.test/a.jpg",
+ {
+ "filename": "3mthgt4lups2f_1",
+ "extension": "jpg",
+ "text": "Quito, Ecuador\nSource: bsky.app/profile/x/post/…",
+ "author": {"handle": "scaratlas.bsky.social", "displayName": "Scar Atlas"},
+ "uris": ["https://x.com/atummundi/status/1"],
+ },
+ )
+ assert bluesky["title"] == "Quito, Ecuador"
+ assert bluesky["uploader"] == "Scar Atlas"
+ assert bluesky["links"] == ["https://x.com/atummundi/status/1"]
+
+ # And what already worked keeps working: `content` still wins where a site has it.
+ x = media_engine._gallery_dl_item(
+ "https://cdn.test/b.jpg",
+ {"filename": "b", "extension": "jpg", "content": "10.39, -66.89", "text": "ignored"},
+ )
+ assert x["title"] == "10.39, -66.89"
+ assert x["links"] == []
def test_cookies_from_preference_maps_each_source():
@@ -1522,12 +1892,7 @@ def test_download_use_cookies_threads_saved_preference(client, monkeypatch):
f"/api/cases/{cid}/media/download",
json={"url": "https://x.test/1", "use_cookies": use_cookies},
).json()["job_id"]
- for _ in range(100):
- job = client.get(f"/api/jobs/{job_id}").json()
- if job["status"] != "running":
- break
- time.sleep(0.05)
- assert job["status"] == "done"
+ job_result(client, job_id)
assert seen == [None, {"browser": "firefox"}]
@@ -1869,3 +2234,196 @@ def test_paste_is_bounded_at_the_edge_like_every_other_swallowed_image(client, m
assert refused.status_code == 413
assert "under" in refused.json()["detail"]
assert list(Case.open(cid).media_dir.glob("*.png")) == []
+
+
+def test_cancelling_a_job_is_a_flag_and_never_a_kill(client):
+ """A thread cannot be interrupted from outside, so a cancel is a question the work
+ answers where stopping is safe. What the route owes the caller is whether anybody
+ heard — and a job already over heard nothing, which is not an error about it."""
+ from azimut import jobs
+
+ finished = jobs.start("test", lambda set_progress: "done")
+ for _ in range(100):
+ if jobs.get(finished)["status"] != "running":
+ break
+ time.sleep(0.02)
+ assert client.post(f"/api/jobs/{finished}/cancel").json() == {"stopped": False}
+
+ held = threading.Event()
+ running = jobs.start("test", lambda set_progress, stopping: held.wait(5), stoppable=True)
+ assert client.post(f"/api/jobs/{running}/cancel").json() == {"stopped": True}
+ assert jobs.cancelled(running) is True
+ held.set()
+
+ assert client.post("/api/jobs/nope/cancel").status_code == 404
+
+
+def test_a_slot_that_needs_a_picture_is_not_handed_the_quoted_video(client, monkeypatch):
+ """A post publishing a geolocation carries the picture *and* quotes the footage.
+
+ yt-dlp reads a post for its video, so it answers with the clip and the published
+ picture stays invisible — and the slot that receives it is the one place in the app
+ that has nowhere to put a video. Saying so before the download is what lets the image
+ extractor be tried at all, where today it is only reached when yt-dlp found nothing.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "QuotedVideo"}).json()["id"]
+ case = Case.open(cid)
+ _install_fake_ydl(
+ monkeypatch,
+ lambda ydl, url, download=False: {
+ "id": "v1", "title": "the quoted clip", "ext": "mp4", "extractor": "twitter",
+ },
+ # Distinct bytes from the picture below, or the library would dedupe the two and
+ # the test would be reading the first download back twice.
+ content_fn=lambda info: _png_bytes(color=(10, 90, 200)),
+ )
+ monkeypatch.setattr(
+ gdl_extractor,
+ "find",
+ lambda url: _FakeGalleryExtractor(
+ [("https://pbs.twimg.com/media/proof.jpg",
+ {"filename": "proof", "extension": "jpg", "content": "the published proof"})]
+ ),
+ )
+
+ # Asked for nothing in particular, the clip is a perfectly good answer.
+ plain = media_engine.download_url(case, "https://x.com/u/status/1")
+ assert plain["item"]["source"]["title"] == "the quoted clip"
+ assert plain["item"]["source"]["downloader"] == "yt-dlp"
+
+ # Asked for a picture, the same post answers with the picture instead.
+ wanted = media_engine.download_url(case, "https://x.com/u/status/2", wants="image")
+ assert wanted["item"]["source"]["downloader"] == "gallery-dl"
+ assert wanted["item"]["title"] == "the published proof"
+
+
+def test_a_tombstone_is_read_as_a_wall_so_the_cookies_can_be_offered(client, monkeypatch):
+ """What a site says about content a guest cannot see is what it says about content
+ that is gone, and X says both in the same words.
+
+ Read as a plain failure, a login wall was unrecoverable: no ``needs_auth``, so no
+ prompt, so no cookie source was ever stored — and every later retry went out
+ cookie-less too, because the only thing that sets that source is the prompt.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ class AbortExtraction(Exception):
+ pass
+
+ cid = client.post("/api/cases", json={"name": "Tombstone"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch, message="No video could be found in this tweet")
+ monkeypatch.setattr(
+ gdl_extractor, "find", lambda url: (_ for _ in ()).throw(AbortExtraction("Unavailable"))
+ )
+
+ assert media_engine.download_url(case, "https://x.com/u/status/1") == {
+ "needs_auth": True,
+ "platform": sys.platform,
+ }
+
+ # Refused *with* a session is a third answer, and it is the one worth saying out loud:
+ # the platform's own wording is a tombstone nobody can act on, where "the session did
+ # not get through" names the thing to fix.
+ refused = media_engine.download_url(
+ case, "https://x.com/u/status/1", cookies={"browser": "firefox"}
+ )
+ assert refused == {"needs_auth": True, "platform": sys.platform, "refused": True}
+
+
+def test_a_session_given_once_is_not_asked_for_again(client, monkeypatch):
+ """An answer given once should not be asked for again.
+
+ The wall prompt is what *stores* a cookie source, and every road went out cookie-less,
+ hit the wall and put the question back on screen — which for a hundred rows of a binder
+ is a hundred questions with one answer. Public media still never touches the session:
+ cookie-less first, then once, on a wall, with whatever the settings hold.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Session"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch, message="No video could be found in this tweet")
+ tried: list[str] = []
+
+ def find(url):
+ tried.append(url)
+ raise RuntimeError("Unavailable")
+
+ # With nothing configured, the wall stands and the prompt is what has to appear.
+ monkeypatch.setattr(gdl_extractor, "find", find)
+ assert media_engine.fetch_url(case, "https://x.com/u/status/1")["needs_auth"] is True
+ assert len(tried) == 1, "no session to try, so one attempt"
+
+ # With one configured, the same wall is answered rather than reported — and when the
+ # session does not get past it either, the real error surfaces instead of the question
+ # being asked a second time.
+ client.put(
+ "/api/settings/prefs",
+ json={"download_cookies": {"source": "browser", "browser": "firefox"}},
+ )
+ tried.clear()
+ answer = media_engine.fetch_url(case, "https://x.com/u/status/2")
+ assert answer["needs_auth"] is True and answer["refused"] is True
+ assert len(tried) == 2, "cookie-less first, then once with the stored session"
+
+ # And a caller that named its own session is answered on its own attempt alone. A
+ # cookie file rather than a browser, because a Chromium pick is answered by the
+ # Windows guard before anything is tried and the assertion would be about that.
+ tried.clear()
+ assert media_engine.fetch_url(
+ case, "https://x.com/u/status/3", cookies={"file": "cookies.txt"}
+ )["refused"] is True
+ assert len(tried) == 1
+
+
+def test_a_link_that_only_says_unavailable_is_retried_with_the_session(client, monkeypatch):
+ """The accepted cost of reading a tombstone as a wall, stated as a test.
+
+ "Unavailable" is what X says about a post a guest cannot read *and* about one that was
+ deleted, so a dead link gets the second attempt too, and that attempt carries the
+ analyst's cookies to a host that never asked for them. Kept, because the alternative is
+ a question in the middle of a hundred-row press and because the first attempt is always
+ cookie-less — and written down here and in SPEC's security posture so it is a decision
+ rather than a surprise.
+ """
+ import gallery_dl.extractor as gdl_extractor
+
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Dead"}).json()["id"]
+ case = Case.open(cid)
+ _install_failing_ydl(monkeypatch, message="Unable to extract")
+ sessions = []
+
+ def find(_url):
+ raise RuntimeError("Unavailable")
+
+ monkeypatch.setattr(gdl_extractor, "find", find)
+ real = media_engine.download_url
+
+ def watched(case_, url, **asked): # noqa: ANN001 — a spy over one call
+ sessions.append(asked.get("cookies"))
+ return real(case_, url, **asked)
+
+ monkeypatch.setattr(media_engine, "download_url", watched)
+ client.put(
+ "/api/settings/prefs",
+ json={"download_cookies": {"source": "browser", "browser": "firefox"}},
+ )
+
+ media_engine.fetch_url(case, "https://x.com/u/status/9")
+ assert sessions[0] is None, "the first attempt is cookie-less, always"
+ assert sessions[1] == {"browser": "firefox"}, "and the wall is answered with the session"
diff --git a/tests/test_notes_pdf.py b/tests/test_notes_pdf.py
index ee7dbe4..91e2c05 100644
--- a/tests/test_notes_pdf.py
+++ b/tests/test_notes_pdf.py
@@ -519,3 +519,28 @@ def test_revealing_the_export_folder_takes_no_path_from_the_browser(client, monk
response = client.post(f"/api/cases/{cid}/{route}")
assert response.status_code == 200
assert opened and opened[0].name == "exports"
+
+
+def test_writing_a_note_is_bounded_on_all_three_roads(client, monkeypatch):
+ """The note itself, not only its PDF export.
+
+ `PUT /notes`, `PUT /notes/{id}` and `POST /notes` each carry a whole document, and each
+ was parsed into memory before anything could refuse it — the export beside them had a
+ limit from the first day, which is exactly the asymmetry a hand-written list of routes
+ produces.
+ """
+ cid = make_case(client)
+ monkeypatch.setattr(notes_api, "MAX_NOTE_BODY_BYTES", 20)
+ heavy = b"x" * 40
+ headers = {"content-type": "application/json"}
+
+ assert client.put(f"/api/cases/{cid}/notes", content=heavy, headers=headers).status_code == 413
+ assert (
+ client.put(f"/api/cases/{cid}/notes/whatever", content=heavy, headers=headers).status_code
+ == 413
+ )
+ assert client.post(f"/api/cases/{cid}/notes", content=heavy, headers=headers).status_code == 413
+
+ # And the export keeps its own, larger number rather than inheriting this one.
+ assert notes_api.MAX_PDF_BODY_BYTES > 20
+ assert client.put(f"/api/cases/{cid}/notes", json={"text": "short"}).status_code == 200
diff --git a/tests/test_placement.py b/tests/test_placement.py
index 6efee01..5f6833b 100644
--- a/tests/test_placement.py
+++ b/tests/test_placement.py
@@ -310,3 +310,40 @@ def test_a_deleted_capture_leaves_the_proof_its_frozen_point(client, sat_tiles):
proof_id = _id(cid, spec="proofs/.meta/Roofline.json")
assert _points(client, cid, proof_id) == [(50.4501, 30.5234)]
assert _points(client, cid, _id(cid, path=video)) == [(50.4501, 30.5234)]
+
+
+# ── a proof arguing several points places the footage at all of them ─────────
+
+
+def test_the_footage_behind_a_proof_reports_every_point_it_states(client):
+ """Three impacts is three placements, not the conclusion and a shrug.
+
+ The proof is what establishes each of them, so the video it was cut from
+ answers for all three — the same one-hop reading the map already does, once
+ per point.
+ """
+ cid = _new_case(client)
+ clip = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, clip)
+ _save_proof(client, cid, "Harbour strike", [frame], points=[
+ {"coords": "64.1466, -21.9426", "label": "impact 1"},
+ {"coords": "64.1481, -21.9401", "label": "impact 2"},
+ {"coords": "64.1502, -21.9350", "label": "caméra", "pov": True},
+ ])
+
+ assert sorted(_points(client, cid, _id(cid, path=clip))) == [
+ (64.1466, -21.9426), (64.1481, -21.9401), (64.1502, -21.935),
+ ]
+
+
+def test_a_proof_reports_its_own_points_and_nothing_it_overrode(client, sat_tiles):
+ """The walk stops where a point is carried, whatever the panels say."""
+ cid = _new_case(client)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Corrected", [cap], points=[
+ {"coords": "64.1466, -21.9426"},
+ {"coords": "64.1481, -21.9401"},
+ ])
+
+ proof_id = _id(cid, spec="proofs/.meta/Corrected.json")
+ assert sorted(_points(client, cid, proof_id)) == [(64.1466, -21.9426), (64.1481, -21.9401)]
diff --git a/tests/test_plates.py b/tests/test_plates.py
new file mode 100644
index 0000000..d6c7689
--- /dev/null
+++ b/tests/test_plates.py
@@ -0,0 +1,198 @@
+"""Analysis plates: writing a reading out as a page, and refusing what is not one."""
+
+from __future__ import annotations
+
+import base64
+import io
+import json
+
+from PIL import Image
+
+from azimut import layout
+from azimut.api import plates
+from azimut.workspace import Case
+
+
+SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600"'
+ ' viewBox="0 0 800 600"><text x="10" y="20">Rooftop match</text>'
+ '<circle cx="40" cy="40" r="12" fill="#3f6ea8" /></svg>'
+)
+
+
+def _case(client, name: str = "Plate case") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def exports_of(case_id: str):
+ return layout.subdir(Case.open(case_id).path, "exports")
+
+
+def _png() -> str:
+ data = io.BytesIO()
+ Image.new("RGB", (40, 30), (250, 250, 250)).save(data, "PNG")
+ return base64.b64encode(data.getvalue()).decode("ascii")
+
+
+def _write(client, case_id: str, **body):
+ return client.post(
+ f"/api/cases/{case_id}/plates",
+ json={"filename": "graph-rooftop-match-202608132010", "format": "svg", **body},
+ )
+
+
+def test_a_plate_lands_in_the_case_exports_folder(client):
+ case_id = _case(client)
+
+ response = _write(client, case_id, svg=SVG)
+
+ assert response.status_code == 200, response.text
+ assert response.json()["file"] == "graph-rooftop-match-202608132010.svg"
+ assert response.json()["path"] == str(exports_of(case_id))
+ written = exports_of(case_id) / response.json()["file"]
+ assert written.read_text(encoding="utf-8") == SVG
+
+ # Inside the case a re-export refreshes rather than accumulating copies, which is
+ # the rule the notes PDF already follows for that folder.
+ again = _write(client, case_id, svg=SVG.replace("Rooftop match", "Rooftop match 2"))
+ assert again.json()["file"] == response.json()["file"]
+ assert "Rooftop match 2" in written.read_text(encoding="utf-8")
+
+
+def test_a_plate_goes_to_the_folder_the_analyst_chose_and_never_overwrites(
+ client, tmp_path
+):
+ case_id = _case(client)
+ chosen = tmp_path / "reports"
+ chosen.mkdir()
+ assert client.put(
+ "/api/settings/prefs", json={"export_dirs": {"views": str(chosen)}}
+ ).status_code == 200
+
+ first = _write(client, case_id, svg=SVG)
+ second = _write(client, case_id, svg=SVG)
+
+ assert first.status_code == 200, first.text
+ assert first.json()["path"] == str(chosen)
+ # Their folder, their files: the second export takes a name of its own.
+ assert second.json()["file"] != first.json()["file"]
+ assert {path.name for path in chosen.iterdir()} == {
+ first.json()["file"], second.json()["file"]
+ }
+
+
+def test_a_png_plate_is_written_as_an_image(client):
+ case_id = _case(client)
+
+ response = _write(client, case_id, format="png", png=_png(), svg="")
+
+ assert response.status_code == 200, response.text
+ assert response.json()["file"].endswith(".png")
+ written = exports_of(case_id) / response.json()["file"]
+ assert written.read_bytes().startswith(b"\x89PNG\r\n\x1a\n")
+
+
+def test_what_a_plate_may_not_carry_into_a_folder_of_documents(client):
+ """The app's own generator writes none of this, so a body holding it is not ours.
+
+ A plate is written where the analyst opens documents, and an SVG a browser opens is
+ a document a browser executes. Refusing beats filing and hoping.
+ """
+ case_id = _case(client)
+
+ refused = [
+ SVG.replace("<text", "<script>alert(1)</script><text"),
+ SVG.replace("<circle", '<circle onclick="alert(1)"'),
+ SVG.replace("<text", '<foreignObject><b>hi</b></foreignObject><text'),
+ SVG.replace("<text", '<image href="https://example.com/x.png" /><text'),
+ SVG.replace("<text", '<use xlink:href="https://example.com/x.svg" /><text'),
+ ]
+ for markup in refused:
+ response = _write(client, case_id, svg=markup)
+ assert response.status_code == 422, markup[:60]
+
+ assert _write(client, case_id, svg="<html><body>no</body></html>").status_code == 422
+ assert _write(client, case_id, svg=" ").status_code == 422
+ assert _write(client, case_id, format="png", png="not base64!", svg="").status_code == 422
+ assert _write(
+ client, case_id, format="png", png=base64.b64encode(b"GIF89a").decode(), svg=""
+ ).status_code == 422
+ # A local reference is how the drawing points at its own arrowhead marker.
+ assert _write(
+ client, case_id, svg=SVG.replace("<circle", '<path marker-end="url(#plate-arrow)" /><circle')
+ ).status_code == 200
+
+
+def test_one_broken_character_does_not_take_the_export_down(client):
+ """A label cut through an emoji leaves half a surrogate pair behind.
+
+ JSON carries it and UTF-8 cannot express it, so writing the file raised and the
+ whole export failed over one entity's name. The half stands for nothing drawable,
+ so it is dropped and the plate is written.
+ """
+ case_id = _case(client)
+ # Sent the way a browser sends it: `JSON.stringify` escapes a lone surrogate to
+ # `\ud83c`, so the body is ASCII on the wire and only becomes one when parsed.
+ body = json.dumps({
+ "filename": "graph-emoji",
+ "format": "svg",
+ "svg": SVG.replace("Rooftop match", "Rooftop \ud83c match"),
+ })
+
+ response = client.post(
+ f"/api/cases/{case_id}/plates",
+ content=body.encode("ascii"),
+ headers={"content-type": "application/json"},
+ )
+
+ assert response.status_code == 200, response.text
+ written = (exports_of(case_id) / response.json()["file"]).read_text(encoding="utf-8")
+ assert "Rooftop match" in written
+
+
+def test_a_plate_larger_than_the_bound_is_refused_before_it_is_written(client, monkeypatch):
+ case_id = _case(client)
+ monkeypatch.setattr(plates, "MAX_SVG_CHARS", 200)
+
+ padded = SVG.replace("</svg>", f"<text>{'x' * 400}</text></svg>")
+ response = _write(client, case_id, svg=padded)
+
+ assert response.status_code == 413
+ assert "too large" in response.json()["detail"]
+
+
+def test_the_body_limit_covers_the_plate_route(client, monkeypatch):
+ """The picture-carrying routes are bounded before Pydantic materialises them."""
+ case_id = _case(client)
+ monkeypatch.setattr(plates, "MAX_PLATE_BODY_BYTES", 200)
+
+ response = _write(client, case_id, svg=SVG * 40)
+
+ assert response.status_code == 413
+ assert response.json()["detail"] == "request body too large"
+
+
+def test_an_unnamed_plate_still_gets_a_name(client):
+ case_id = _case(client)
+
+ response = client.post(
+ f"/api/cases/{case_id}/plates", json={"filename": "///", "svg": SVG}
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["file"].endswith(".svg")
+
+
+def test_the_reveal_route_takes_no_path_from_the_browser(client, monkeypatch):
+ case_id = _case(client)
+ opened: list[str] = []
+ monkeypatch.setattr(
+ plates.reveal_engine, "reveal",
+ lambda path, workspace_only=True: opened.append(str(path)),
+ )
+
+ response = client.post(f"/api/cases/{case_id}/plates/reveal")
+
+ assert response.status_code == 200, response.text
+ assert opened and opened[0].endswith("exports")
+ assert response.json()["path"] == opened[0]
diff --git a/tests/test_proof_import.py b/tests/test_proof_import.py
new file mode 100644
index 0000000..3a46493
--- /dev/null
+++ b/tests/test_proof_import.py
@@ -0,0 +1,989 @@
+"""Importing a geolocated post as a proof.
+
+Three promises are what these tests hold to:
+
+- **nothing enters the case until the preview is approved.** A cancelled or
+ abandoned import leaves the case byte-for-byte as it was;
+- **the graph it writes is the composer's,** not a second implementation of it:
+ the same place dedup, the same verbs, the same derivation chain, and a proof
+ that reopens, exports and travels like a hand-made one;
+- **no post format is special.** The scan reads shapes, so a post that spells
+ nothing out prefills nothing and the form is filled by hand.
+"""
+
+import io
+
+from jobwait import job_result
+from PIL import Image
+
+from azimut import layout
+from azimut.engine import geo
+from azimut.engine import links as link_engine
+from azimut.engine import media as media_engine
+from azimut.engine import proofimport as import_engine
+
+POST = """Hoyo de la Puerta, Miranda, Venezuela - 94V4+8XH
+
+Point of view - Two helicopters were spotted heading East over Hoyo de la Puerta.
+
+10.393313, -66.892504
+
+Source:
+https://instagram.com/reels/DTG728Xk"""
+
+
+def make_case(client, name="Import"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def case_of(case_id):
+ from azimut.api.cases import get_case
+
+ return get_case(case_id)
+
+
+def picture(colour=(30, 90, 140), size=(320, 200)):
+ buffer = io.BytesIO()
+ Image.new("RGB", size, colour).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def start(client, case_id):
+ response = client.post(f"/api/cases/{case_id}/proof-imports")
+ assert response.status_code == 200, response.text
+ return response.json()["token"]
+
+
+def attach(client, case_id, token, slot, content, filename, source_url=""):
+ response = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/attach",
+ files={"file": (filename, content, "application/octet-stream")},
+ data={"slot": slot, "source_url": source_url},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+
+
+FORM = {
+ "title": "Hoyo de la Puerta",
+ "coords": "10.393313, -66.892504",
+ "source_urls": ["https://instagram.com/reels/DTG728Xk"],
+ "note": "Two helicopters heading East",
+ "pov": True,
+}
+
+
+def links_between(case, from_id, to_id):
+ return {
+ link["type"] for link in case.links_of(from_id) if link["from"] == from_id and link["to"] == to_id
+ }
+
+
+# -- reading a post ----------------------------------------------------------
+#
+# The scan is the only part that touches free text, so it is the only part that
+# can be fooled by prose. Each of these is a shape, never a line or a keyword.
+
+
+def test_the_scan_reads_a_position_out_of_a_post():
+ found = geo.scan_coords(POST)
+ assert [(round(c["lat"], 6), round(c["lon"], 6)) for c in found] == [(10.393313, -66.892504)]
+ assert found[0]["format"] == "decimal"
+ assert found[0]["text"] == "10.393313, -66.892504"
+
+
+def test_the_scan_reads_every_notation_the_field_accepts():
+ formats = {
+ "48.8584, 2.2945": "decimal",
+ "48°51'30.2\"N 2°17'40.2\"E": "dms",
+ "grid 31U DQ 48250 11951 confirmed": "mgrs",
+ "code 8FW4V75V+8Q here": "plus-code",
+ "https://www.google.com/maps/@48.8584,2.2945,17z": "map-link",
+ "https://www.openstreetmap.org/#map=17/48.8584/2.2945": "map-link",
+ }
+ for text, expected in formats.items():
+ found = geo.scan_coords(text)
+ assert found, text
+ assert found[0]["format"] == expected, text
+ assert abs(found[0]["lat"] - 48.858) < 0.01, text
+
+
+def test_prose_that_merely_contains_numbers_states_no_position():
+ for text in ("2 photos, 3 videos and 4 links", "MH-47 flew 300 m at 12.5, 3 pm", ""):
+ assert geo.scan_coords(text) == []
+
+
+def test_a_short_plus_code_is_not_decoded():
+ """It needs a locality to resolve against, which a post does not carry. Read
+ as a position it would put the point in the wrong hemisphere."""
+ assert geo.scan_coords("Hoyo de la Puerta - 94V4+8XH") == []
+
+
+def test_one_position_written_twice_is_offered_once():
+ text = "10.393313, -66.892504 — https://maps.google.com/maps/@10.393313,-66.892504,17z"
+ assert len(geo.scan_coords(text)) == 1
+
+
+def test_the_scan_offers_the_post_s_links_but_not_the_post():
+ urls = import_engine.scan_urls(POST, exclude="https://x.com/a/1")
+ assert urls == ["https://instagram.com/reels/DTG728Xk"]
+ assert import_engine.scan_urls("see https://x.com/a/1", exclude="https://x.com/a/1") == []
+
+
+def test_the_links_a_platform_records_are_believed_over_the_ones_it_prints():
+ """Where a post keeps its links decides whether they can be read at all.
+
+ An AT Protocol post prints an address truncated to an ellipsis and keeps the whole
+ of it in a facet beside the words. Scanning the words there hands back half an
+ address with nothing to say it is half — so the recorded ones come first, in their
+ own order, and the scan follows for the platforms that write theirs out in full.
+ """
+ post = import_engine.read_post(
+ {
+ "title": "Quito",
+ "description": "Source: bsky.app/profile/x/post/…\nand https://t.me/chan/9",
+ "links": ["https://x.com/atummundi/status/1"],
+ },
+ "https://bsky.app/profile/scaratlas.bsky.social/post/3mthgt4lups2f",
+ )
+ assert post["urls"][0] == "https://x.com/atummundi/status/1"
+ assert "https://t.me/chan/9" in post["urls"] # the scan still runs
+
+ # The post's own address is not one of its sources, whichever half named it.
+ own = "https://bsky.app/profile/a/post/1"
+ assert import_engine.read_post({"links": [own], "description": ""}, own)["urls"] == []
+
+
+def test_a_post_that_states_nothing_prefills_nothing():
+ post = import_engine.read_post({"description": "Look at this"}, "https://x.com/a/1")
+ assert post["coords"] == []
+ assert post["urls"] == []
+ assert post["title"] == ""
+
+
+# -- the staging directory ---------------------------------------------------
+
+
+def test_a_held_file_is_not_in_the_case(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ case = case_of(case_id)
+ assert case.list_entities() == []
+ assert not any(case.media_dir.glob("*.png"))
+ assert import_engine.staged_path(case, token, "panel") is not None
+
+
+def test_cancelling_leaves_nothing_behind(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ assert client.delete(f"/api/cases/{case_id}/proof-imports/{token}").status_code == 200
+ case = case_of(case_id)
+ assert not (case.subdir("media") / ".dl").exists() or not list(
+ (case.subdir("media") / ".dl").iterdir()
+ )
+ assert case.list_entities() == []
+
+
+def test_an_abandoned_import_is_swept_by_the_next_one(client, monkeypatch):
+ case_id = make_case(client)
+ stale = start(client, case_id)
+ attach(client, case_id, stale, "panel", picture(), "panel.png")
+ case = case_of(case_id)
+ directory = import_engine.staging_dir(case, stale)
+
+ monkeypatch.setattr(import_engine, "_now", lambda: 9e9)
+ start(client, case_id)
+ assert not directory.exists()
+
+
+def test_a_download_still_writing_is_not_swept_or_discarded(client, monkeypatch):
+ """Staging shares `media/.dl/` with in-progress downloads, and shares their
+ naming so the Windows path budget does not move. The manifest is what tells
+ them apart, and getting that wrong deletes somebody's download mid-write."""
+ case_id = make_case(client)
+ case = case_of(case_id)
+ scratch = case.subdir("media") / ".dl" / ("f" * 12)
+ scratch.mkdir(parents=True)
+ (scratch / "half-a-video.mp4.part").write_bytes(b"...")
+
+ client.delete(f"/api/cases/{case_id}/proof-imports/{'f' * 12}")
+ monkeypatch.setattr(import_engine, "_now", lambda: 9e9)
+ start(client, case_id) # opening an import sweeps
+
+ assert (scratch / "half-a-video.mp4.part").is_file()
+
+
+def test_a_token_this_case_never_minted_is_refused(client):
+ """A token names a directory, so only the shape this module mints is read as
+ one — a request cannot point the import at a path of its own choosing."""
+ case_id = make_case(client)
+ for token in ("....etc", "0" * 40, "abcdef"):
+ response = client.post(f"/api/cases/{case_id}/proof-imports/{token}/preview", json=FORM)
+ assert response.status_code == 404, token
+
+
+def test_refilling_a_slot_drops_what_it_held(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture((10, 10, 10)), "first.png")
+ attach(client, case_id, token, "panel", picture((200, 30, 30)), "second.png")
+
+ case = case_of(case_id)
+ held = list(import_engine.staging_dir(case, token).glob("*.png"))
+ assert [path.name for path in held] == ["second.png"]
+
+
+# -- fetching, without a network ---------------------------------------------
+
+
+def test_the_fetch_holds_the_download_and_reads_the_post(client, monkeypatch):
+ """The one path the hand-attached tests cannot reach: a real download, with
+ the extractor faked. The file must land in staging and nowhere else, and the
+ post's text must come back scanned."""
+ from test_media_api import _install_fake_ydl
+
+ _install_fake_ydl(
+ monkeypatch,
+ lambda ydl, url, download: {
+ "id": "p1",
+ "title": "Hoyo de la Puerta",
+ "description": POST,
+ "uploader": "someone",
+ "upload_date": "20260301",
+ "ext": "png",
+ },
+ )
+ case_id = make_case(client)
+ token = start(client, case_id)
+
+ started = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/fetch",
+ json={"url": "https://x.com/a/1", "slot": "panel"},
+ )
+ assert started.status_code == 200, started.text
+ result = job_result(client, started.json()["job_id"])
+
+ assert result["staged"]["kind"] == "image"
+ assert result["post"]["coords"][0]["lat"] == 10.393313
+ assert result["post"]["urls"] == ["https://instagram.com/reels/DTG728Xk"]
+
+ case = case_of(case_id)
+ assert case.list_entities() == [] # the case is untouched
+ assert not any(case.media_dir.glob("*.png"))
+ assert import_engine.staged_path(case, token, "panel") is not None
+
+
+# -- the preview -------------------------------------------------------------
+
+
+def preview(client, case_id, token, **overrides):
+ response = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/preview", json={**FORM, **overrides}
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_the_preview_lists_what_the_import_would_create(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ attach(client, case_id, token, "source", b"video-bytes", "reel.mp4")
+
+ report = preview(client, case_id, token)
+ assert report["ready"] is True
+ assert [(e["slot"], e["type"], e["state"]) for e in report["entities"]] == [
+ ("place", "place", "new"),
+ ("source", "media", "new"),
+ ("panel", "media", "new"),
+ ("proof", "proof", "new"),
+ ]
+ edges = {(e["from"], e["type"], e["to"]) for e in report["links"]}
+ assert ("source", link_engine.LOCATED_AT, "place") in edges
+ assert ("proof", link_engine.DEPICTS, "place") in edges
+ # The proof is what the constellation hangs off: it composes the picture and rests
+ # on the material, and both are its own edges.
+ assert ("proof", link_engine.DERIVED_FROM, "source") in edges
+ assert ("proof", link_engine.DERIVED_FROM, "panel") in edges
+ assert ("panel", link_engine.DERIVED_FROM, "source") not in edges
+
+
+def test_without_the_camera_on_site_the_footage_shows_the_place(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ attach(client, case_id, token, "source", b"video-bytes", "reel.mp4")
+
+ report = preview(client, case_id, token, pov=False)
+ edges = {(e["from"], e["type"], e["to"]) for e in report["links"]}
+ assert ("source", link_engine.DEPICTS, "place") in edges
+ assert ("source", link_engine.LOCATED_AT, "place") not in edges
+
+
+def test_neither_coordinates_nor_a_source_may_be_left_out(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ assert preview(client, case_id, token, coords="")["ready"] is False
+ assert preview(client, case_id, token, source_urls=[])["ready"] is False
+ assert "Coordinates are required." in preview(client, case_id, token, coords="")["blocking"]
+
+
+def test_prose_in_the_coordinate_field_is_refused_by_name(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ report = preview(client, case_id, token, coords="somewhere near the ridge")
+ assert report["ready"] is False
+ assert any("is not a position" in line for line in report["blocking"])
+
+
+def test_the_preview_says_when_the_footage_was_not_recovered(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ report = preview(client, case_id, token)
+ assert report["ready"] is True # a dead link is information, not a blockage
+ assert any(w["code"] == "no-source-media" for w in report["warnings"])
+ assert [e["slot"] for e in report["entities"]] == ["place", "panel", "proof"]
+
+
+def test_a_missing_source_is_said_once_not_twice(client):
+ """With no address typed, the blocking line is the whole answer: repeating it
+ as a warning reads as two problems where there is one."""
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ report = preview(client, case_id, token, source_urls=[])
+ assert "A source is required." in report["blocking"]
+ assert not any(w["code"] == "no-source-media" for w in report["warnings"])
+
+
+def test_the_source_field_holds_one_address_and_says_so(client):
+ """The field is the address the footage is fetched from as much as the line the
+ proof carries, so two of them is not extra information.
+
+ Pasted as a pair it was posted to the downloader as one address, refused there,
+ and reported as a source that "was not downloaded" — the import went through and
+ filed a proof with no material and a line nothing could be traced from. The
+ preview is where that is said, as it is for the coordinates and the name.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ report = preview(client, case_id, token, source_urls=["https://x.com/a/1 https://t.me/b/2"])
+ assert report["ready"] is False
+ assert "A source is one address, and this is several." in report["blocking"]
+
+ report = preview(client, case_id, token, source_urls=["handed to me on a stick"])
+ assert report["ready"] is False
+ assert "A source is an address, and this is not one." in report["blocking"]
+
+ # Two of them, each in its own box, is the ordinary thing a thread asks for.
+ two = preview(client, case_id, token, source_urls=["https://x.com/a/1", "https://t.me/b/2"])
+ assert two["ready"] is True
+
+
+def test_a_point_the_case_already_holds_is_reused_not_pinned_twice(client):
+ case_id = make_case(client)
+ saved = client.post(
+ f"/api/cases/{case_id}/satellite/place",
+ json={"lat": 10.393313, "lon": -66.892504},
+ )
+ assert saved.status_code == 200, saved.text
+
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ report = preview(client, case_id, token)
+ place = next(e for e in report["entities"] if e["type"] == "place")
+ assert place["state"] == "existing"
+
+
+def test_the_preview_reads_the_bytes_it_holds_for_a_duplicate(client):
+ case_id = make_case(client)
+ same = picture()
+ client.post(
+ f"/api/cases/{case_id}/media/upload",
+ files={"file": ("already-here.png", same, "image/png")},
+ )
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", same, "panel.png")
+
+ report = preview(client, case_id, token)
+ panel = next(e for e in report["entities"] if e["slot"] == "panel")
+ assert panel["state"] == "existing"
+ assert any(w["code"] == "already-imported" for w in report["warnings"])
+
+
+def test_the_same_post_twice_is_noticed_by_its_address(client):
+ """Two different encodings of one picture still come from one post, so the
+ address is asked as well as the bytes."""
+ case_id = make_case(client)
+ first = start(client, case_id)
+ attach(client, case_id, first, "panel", picture(), "panel.png", source_url="https://x.com/a/1")
+ commit(client, case_id, first)
+
+ second = start(client, case_id)
+ attach(
+ client, case_id, second, "panel", picture((9, 9, 9)), "other.png",
+ source_url="https://x.com/a/1",
+ )
+ # what the fetch would have written down about the post, without the download
+ import_engine.record_post(case_of(case_id), second, {"url": "https://x.com/a/1"})
+
+ report = preview(client, case_id, second, title="Second sighting")
+ assert any(w["code"] == "already-imported" for w in report["warnings"])
+
+
+def test_a_picture_larger_than_the_clamp_is_refused(client, monkeypatch):
+ from azimut.api import proofimports
+
+ monkeypatch.setattr(proofimports, "MAX_IMAGE_BYTES", 64)
+ case_id = make_case(client)
+ token = start(client, case_id)
+ response = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/attach",
+ files={"file": ("panel.png", picture(), "image/png")},
+ data={"slot": "panel"},
+ )
+ assert response.status_code == 413
+ assert import_engine.staged_path(case_of(case_id), token, "panel") is None
+
+
+def test_the_footage_is_not_held_to_the_picture_s_clamp(client, monkeypatch):
+ """The clamp answers a decompression bomb, and a video is not one. A reel the
+ downloader could not reach is exactly the file somebody attaches by hand."""
+ from azimut.api import proofimports
+
+ monkeypatch.setattr(proofimports, "MAX_IMAGE_BYTES", 64)
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "source", b"x" * 5000, "reel.mp4")
+ assert import_engine.staged_path(case_of(case_id), token, "source") is not None
+
+
+def test_a_wall_of_text_is_read_up_to_a_bound(client):
+ """Post text is attacker-controlled input feeding patterns that backtrack, so
+ the length is capped once at the door rather than defended in each scan."""
+ long_text = ("filler " * 2000) + "10.393313, -66.892504"
+ post = import_engine.read_post({"description": long_text}, "https://x.com/a/1")
+ assert len(post["text"]) == import_engine.MAX_POST_TEXT
+ assert post["coords"] == [] # the position sat past the bound and was not read
+
+
+def test_a_file_that_contradicts_the_typed_point_is_flagged(client, monkeypatch):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ monkeypatch.setattr(
+ import_engine, "_stated_gps", lambda path, kind: {"lat": 10.40, "lon": -66.90}
+ )
+
+ report = preview(client, case_id, token)
+ conflict = next(w for w in report["warnings"] if w["code"] == "gps-conflict")
+ assert "10.400000" in conflict["text"]
+
+
+def test_a_position_the_file_agrees_with_is_not_flagged(client, monkeypatch):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ monkeypatch.setattr(
+ import_engine, "_stated_gps", lambda path, kind: {"lat": 10.393310, "lon": -66.892500}
+ )
+
+ report = preview(client, case_id, token)
+ assert not any(w["code"] == "gps-conflict" for w in report["warnings"])
+
+
+def test_a_name_another_proof_holds_is_refused(client):
+ case_id = make_case(client)
+ client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={"title": "Hoyo de la Puerta", "spec": {"panels": []}},
+ )
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ report = preview(client, case_id, token)
+ assert report["ready"] is False
+ assert any("already called" in line for line in report["blocking"])
+
+
+def test_a_video_cannot_be_the_proof_s_picture(client):
+ """Refused at the door it comes through, and refused again at the preview.
+
+ A proof is composed of pictures: the composer lays panels out on a canvas and a clip
+ has nothing to lay out. Saying so only at the preview meant the file was downloaded,
+ staged and shown as "Proof: clip.mp4" before anything said no — two screens after the
+ choice that made it, with nothing on the screen that made it hinting there was a rule.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+
+ refused = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/attach",
+ files={"file": ("clip.mp4", b"video-bytes", "application/octet-stream")},
+ data={"slot": "panel"},
+ )
+ assert refused.status_code == 422
+ assert "pictures" in refused.json()["detail"]
+ # and nothing is left holding it
+ assert import_engine.staged_pairs(case_of(case_id), token, import_engine.SLOT_PANEL) == []
+
+ # The preview keeps the line anyway: it is the invariant, whatever put a file there.
+ staged = media_engine.stage_descriptor(
+ _write(case_of(case_id), token, "clip.mp4", b"video-bytes"), {"type": "manual"}
+ )
+ import_engine.fill_slot(case_of(case_id), token, "panel", staged)
+ report = preview(client, case_id, token)
+ assert report["ready"] is False
+ assert any("pictures" in line for line in report["blocking"])
+
+
+def _write(case, token, name, data):
+ """Put bytes in the staging directory without going through a route."""
+ path = import_engine.staging_dir(case, token) / name
+ path.write_bytes(data)
+ return path
+
+
+# -- the commit --------------------------------------------------------------
+
+
+def commit(client, case_id, token, **overrides):
+ response = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/commit", json={**FORM, **overrides}
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_the_import_writes_the_graph_the_composer_would_have(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ attach(client, case_id, token, "source", b"video-bytes", "reel.mp4")
+
+ created = commit(client, case_id, token)
+ case = case_of(case_id)
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(created["proof"]["name"]))
+ place_id = created["place"]["id"]
+ panel_id = created["panel"]["id"]
+ source_id = created["source"]["id"]
+
+ assert links_between(case, source_id, place_id) == {link_engine.LOCATED_AT}
+ assert links_between(case, proof["id"], place_id) == {link_engine.DEPICTS}
+ # The proof composes the picture and rests on the material: one node the whole
+ # geolocation hangs off, which is what a hand-made proof writes too.
+ assert link_engine.DERIVED_FROM in links_between(case, proof["id"], panel_id)
+ assert link_engine.DERIVED_FROM in links_between(case, proof["id"], source_id)
+
+
+def test_the_preview_promises_exactly_the_edges_the_commit_writes(client):
+ """The gate this whole feature rests on. A preview that under-reports is
+ worse than no preview: the analyst approved a graph they were not shown."""
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ attach(client, case_id, token, "source", b"video-bytes", "reel.mp4")
+
+ promised = preview(client, case_id, token)
+ created = commit(client, case_id, token)
+
+ case = case_of(case_id)
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(created["proof"]["name"]))
+ by_slot = {
+ "place": created["place"]["id"],
+ "panel": created["panel"]["id"],
+ "source": created["source"]["id"],
+ "proof": proof["id"],
+ }
+ expected = {
+ (by_slot[edge["from"]], edge["type"], by_slot[edge["to"]]) for edge in promised["links"]
+ }
+ written = {
+ (link["from"], link["type"], link["to"])
+ for link in case.list_links()
+ if link["from"] in by_slot.values() and link["to"] in by_slot.values()
+ }
+ assert written == expected
+
+
+def test_the_proof_is_a_real_proof(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ created = commit(client, case_id, token)
+ name = created["proof"]["name"]
+
+ listed = client.get(f"/api/cases/{case_id}/proofs").json()
+ assert [p["name"] for p in listed] == [name]
+ assert listed[0]["points"] == [
+ {
+ "lat": 10.393313, "lon": -66.892504,
+ "coords": "10.393313, -66.892504", "label": "", "pov": True,
+ }
+ ]
+
+ spec = client.get(f"/api/cases/{case_id}/proofs/{name}").json()
+ assert spec["azimut_proof"] == 1
+ assert spec["pov"] is True
+ assert spec["sources"] == FORM["source_urls"]
+ assert len(spec["panels"]) == 1
+ assert spec["panels"][0]["natural"] == [320, 200]
+
+ case = case_of(case_id)
+ assert case.resolve_inside(layout.proof_export_rel(name)).is_file()
+ assert case.resolve_inside(spec["panels"][0]["src"]).is_file()
+
+
+def test_the_export_is_a_png_whatever_arrived(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ jpeg = io.BytesIO()
+ Image.new("RGB", (64, 48), (200, 120, 40)).save(jpeg, "JPEG")
+ attach(client, case_id, token, "panel", jpeg.getvalue(), "panel.jpg")
+
+ created = commit(client, case_id, token)
+ export = case_of(case_id).resolve_inside(layout.proof_export_rel(created["proof"]["name"]))
+ with Image.open(export) as img:
+ assert img.format == "PNG"
+
+
+def test_the_post_travels_with_the_picture_it_published(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png", source_url="https://x.com/a/1")
+
+ created = commit(client, case_id, token)
+ case = case_of(case_id)
+ panel = case.get_entity(created["panel"]["id"])
+ assert panel["attrs"]["source_url"] == "https://x.com/a/1"
+
+
+def test_committing_empties_the_staging_directory(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ commit(client, case_id, token)
+
+ assert not import_engine.staging_dir(case_of(case_id), token).exists()
+
+
+def test_a_refused_import_writes_nothing(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ response = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/commit", json={**FORM, "coords": ""}
+ )
+ assert response.status_code == 400
+ case = case_of(case_id)
+ assert case.list_entities() == []
+ assert import_engine.staged_path(case, token, "panel") is not None
+
+
+def test_the_place_is_filed_even_when_the_composer_would_have_asked(client):
+ """`proof_place_auto` off makes the composer ask before pinning a point. The
+ import already asked — the preview said "place: new" — so it files."""
+ client.put("/api/settings", json={"proof_place_auto": False})
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+
+ created = commit(client, case_id, token)
+ case = case_of(case_id)
+ assert case.get_entity(created["place"]["id"])["type"] == "place"
+
+
+def test_the_same_picture_twice_is_one_media(client):
+ case_id = make_case(client)
+ same = picture()
+ first = start(client, case_id)
+ attach(client, case_id, first, "panel", same, "panel.png")
+ created = commit(client, case_id, first)
+
+ second = start(client, case_id)
+ attach(client, case_id, second, "panel", same, "panel.png")
+ again = commit(client, case_id, second, title="Hoyo de la Puerta 2")
+
+ assert again["panel"]["id"] == created["panel"]["id"]
+ assert again["panel"]["duplicate"] is True
+ case = case_of(case_id)
+ assert len([e for e in case.list_entities() if e["type"] == "media"]) == 1
+ assert len([e for e in case.list_entities() if e["type"] == "proof"]) == 2
+
+
+def test_the_import_names_the_place_it_landed_on_even_when_it_reused_one(client):
+ case_id = make_case(client)
+ standing = client.post(
+ f"/api/cases/{case_id}/satellite/place",
+ json={"lat": 10.393313, "lon": -66.892504},
+ ).json()
+
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ created = commit(client, case_id, token)
+
+ assert created["place"]["id"] == standing["id"]
+
+
+def test_a_second_proof_on_one_point_does_not_pin_it_twice(client):
+ case_id = make_case(client)
+ for index, colour in enumerate(((10, 10, 10), (200, 30, 30))):
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(colour), "panel.png")
+ commit(client, case_id, token, title=f"Sighting {index}")
+
+ case = case_of(case_id)
+ assert len([e for e in case.list_entities() if e["type"] == "place"]) == 1
+
+
+def test_the_imported_proof_reopens_and_saves_like_any_other(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ created = commit(client, case_id, token)
+ name = created["proof"]["name"]
+
+ spec = client.get(f"/api/cases/{case_id}/proofs/{name}").json()
+ spec["coordsText"] = "48.8584, 2.2945"
+ again = client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={"title": name, "spec": spec, "rename_from": name},
+ )
+ assert again.status_code == 200, again.text
+
+ case = case_of(case_id)
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(name))
+ places = [e for e in case.list_entities() if e["type"] == "place"]
+ stated = [
+ link["to"]
+ for link in case.links_of(proof["id"])
+ if link["from"] == proof["id"] and link["type"] in (link_engine.DEPICTS,)
+ ]
+ assert len(stated) == 1
+ assert case.get_entity(stated[0])["attrs"]["lat"] == 48.8584
+ assert len(places) == 2 # the old point is left standing, not deleted
+
+
+def test_deleting_the_imported_proof_takes_its_files(client):
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ created = commit(client, case_id, token)
+ name = created["proof"]["name"]
+
+ case = case_of(case_id)
+ spec_path = case.resolve_inside(layout.proof_spec_rel(name))
+ export = case.resolve_inside(layout.proof_export_rel(name))
+ assert client.delete(f"/api/cases/{case_id}/proofs/{name}").status_code == 200
+ assert not spec_path.exists()
+ assert not export.exists()
+
+
+def hold_pictures(case_id, token, count):
+ """Put a set of pictures in the panel slot, the way a picker answered with several
+ ticks does. Distinct colours, because the library dedupes on the bytes."""
+ from azimut.engine import media as media_engine
+
+ case = case_of(case_id)
+ stage = import_engine.staging_dir(case, token)
+ held = []
+ for at in range(count):
+ path = stage / f"panel-{at}.png"
+ path.write_bytes(picture(colour=(20 + at * 60, 90, 140), size=(300 + at * 10, 200)))
+ held.append(media_engine.stage_descriptor(path, {"type": "test", "url": f"u{at}"}))
+ import_engine.fill_files(case, token, import_engine.SLOT_PANEL, held)
+ return held
+
+
+def test_a_post_publishing_a_set_is_one_proof_of_several_panels(client):
+ """A published geolocation is often the overhead, the ground shot and the match.
+
+ Keeping one and dropping the rest keeps a third of what was published, and the thing
+ that holds them is not new: a proof **is** a composition.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+ hold_pictures(case_id, token, 3)
+
+ report = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/preview", json=FORM
+ ).json()
+ assert report["ready"] is True
+ # Every picture is named in the preview, and named *apart*: three rows called `panel`
+ # say nothing about which one an edge is about, and the screen that renders the report
+ # is keyed on that name — so a shared one throws and blanks the whole reading.
+ slots = [entity["slot"] for entity in report["entities"] if entity["type"] == "media"]
+ assert slots == ["panel", "panel 2", "panel 3"]
+ assert len(set(slots)) == len(slots)
+ edges = [(link["from"], link["type"], link["to"]) for link in report["links"]]
+ assert len(set(edges)) == len(edges), "every stated edge is its own line"
+ chain = [link for link in report["links"] if link["from"] == "proof"]
+ assert [link["to"] for link in chain] == ["panel", "panel 2", "panel 3", "place"]
+
+ created = commit(client, case_id, token)
+ name = created["proof"]["name"]
+ spec = client.get(f"/api/cases/{case_id}/proofs/{name}").json()
+ assert len(spec["panels"]) == 3
+ assert [panel["natural"] for panel in spec["panels"]] == [[300, 200], [310, 200], [320, 200]]
+ # The note is one sentence about the proof, not a caption per picture.
+ assert [panel["caption"] for panel in spec["panels"]] == [FORM["note"], "", ""]
+
+ case = case_of(case_id)
+ for panel in spec["panels"]:
+ assert case.resolve_inside(panel["src"]).is_file()
+
+
+def test_a_picture_whose_bytes_went_missing_takes_its_own_provenance_with_it(client):
+ """A wrong origin on a proof is worse than none: the panel claims a page it never
+ came from, and nothing in the case contradicts it.
+
+ The paths that survive and the entries describing them were two lists zipped by
+ position, so one file gone from the staging directory — quarantined by an antivirus,
+ swept by hand — shifted every picture after it onto its neighbour's post, title and
+ derivation. Paired by identity now, so the second picture keeps its own `u1` or is not
+ filed at all.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+ hold_pictures(case_id, token, 3)
+ case = case_of(case_id)
+ (import_engine.staging_dir(case, token) / "panel-1.png").unlink()
+
+ created = commit(client, case_id, token)
+ filed = created.get("panels") or [created["panel"]]
+ origins = []
+ for entry in filed:
+ media = case.find_entity(attr="path", value=entry["path"])
+ origins.append((media["attrs"].get("source_url"), entry["path"]))
+
+ assert len(filed) == 2, "the picture whose bytes went is not filed"
+ assert [url for url, _ in origins] == ["u0", "u2"], origins
+
+
+def test_an_origin_that_is_not_a_link_is_refused_on_the_hand_attached_file(client):
+ """An origin is a link, refused when it is not one — and this is the surface where it
+ is typed by hand, which is the one that most needed the reading.
+
+ The other two doors, an upload and a later correction in Details, both went through
+ `stated_source`. This one wrote whatever arrived straight into the entity's own
+ `source_url`, the proof plate's source line and the lineage a lost file leaves behind,
+ all of which the rest of the app treats as an address.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+
+ refused = client.post(
+ f"/api/cases/{case_id}/proof-imports/{token}/attach",
+ files={"file": ("panel.png", picture(), "application/octet-stream")},
+ data={"slot": "panel", "source_url": "handed to me on a stick"},
+ )
+ assert refused.status_code == 422
+ assert "http(s)" in refused.json()["detail"]
+ # And nothing was staged for it: the reading happens before the bytes are streamed.
+ assert import_engine.staged_pairs(case_of(case_id), token, import_engine.SLOT_PANEL) == []
+
+ # An empty origin is still a valid answer — most hand-attached files have none.
+ attach(client, case_id, token, "panel", picture(), "panel.png")
+ stated = attach(
+ client, case_id, token, "panel", picture(colour=(1, 2, 3)), "panel.png",
+ source_url="https://t.me/chan/12",
+ )
+ assert stated["staged"]["source"]["url"] == "https://t.me/chan/12"
+
+
+def test_a_thread_states_its_point_once_and_rests_on_everything_it_hung_off_it(client):
+ """One published proof, several pieces of material, spread over several posts.
+
+ A geolocation thread states the point in its first post and hangs the photos and the
+ clips it rests on off the ones after it. The composition is the small half — often a
+ single picture the author laid out — and the material is the plural one, which is the
+ opposite of what a slot holding exactly one file could take. Keeping the first of four
+ filed one file and left the other three outside the case entirely.
+
+ Every picture records every piece of material, because which photo of four a composite
+ was laid out from is not something the post says, and a guessed pairing states one
+ edge right and three wrong. The point reaches all of them through that chain.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+ attach(client, case_id, token, "panel", picture(), "composite.png")
+ for at, url in enumerate(("https://x.com/a/2", "https://x.com/a/3", "https://x.com/a/4")):
+ attach(
+ client, case_id, token, "source", f"bytes-{at}".encode(), f"clip{at}.mp4",
+ source_url=url,
+ )
+ urls = ["https://x.com/a/2", "https://x.com/a/3", "https://x.com/a/4"]
+
+ report = preview(client, case_id, token, source_urls=urls)
+ assert report["ready"] is True
+ # One name per file, so a report about four of them can be read.
+ assert [e["slot"] for e in report["entities"]] == [
+ "place", "source", "source 2", "source 3", "panel", "proof",
+ ]
+ edges = {(e["from"], e["type"], e["to"]) for e in report["links"]}
+ for slot in ("source", "source 2", "source 3"):
+ assert ("proof", link_engine.DERIVED_FROM, slot) in edges
+ assert (slot, link_engine.LOCATED_AT, "place") in edges # POV is on in FORM
+
+ created = commit(client, case_id, token, source_urls=urls)
+ case = case_of(case_id)
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(created["proof"]["name"]))
+ panel = case.get_entity(created["panel"]["id"])
+ sources = [case.get_entity(one["id"]) for one in created["sources"]]
+
+ assert len(sources) == 3
+ assert len({one["id"] for one in sources}) == 3 # three files, not one filed thrice
+ for one in sources:
+ assert link_engine.DERIVED_FROM in links_between(case, proof["id"], one["id"])
+ # and not off the published picture, which is one file among the several rather
+ # than the thing they all hang off
+ assert links_between(case, panel["id"], one["id"]) == set()
+ assert link_engine.DERIVED_FROM in links_between(case, proof["id"], panel["id"])
+
+ # And the proof states all three addresses, so its line traces back to each post.
+ spec = client.get(f"/api/cases/{case_id}/proofs/{created['proof']['name']}").json()
+ assert spec["sources"] == urls
+
+
+def test_a_set_has_no_render_yet_and_still_draws_in_the_graph(client):
+ """A single picture is already a rendered proof, so it is filed as the export. A set
+ has no render — laying panels out is the composer's canvas, in the browser — and a
+ second renderer here would drift from it at the first change to a layout.
+
+ So the set is saved without an export and borrows the first picture's thumbnail, or it
+ would be the only blank node of its own constellation. The first save in the composer
+ writes the real one.
+ """
+ case_id = make_case(client)
+ token = start(client, case_id)
+ hold_pictures(case_id, token, 2)
+ created = commit(client, case_id, token)
+ name = created["proof"]["name"]
+
+ case = case_of(case_id)
+ assert not case.resolve_inside(layout.proof_export_rel(name)).exists()
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(name))
+ assert "path" not in proof["attrs"]
+ assert proof["attrs"].get("thumb"), "a proof with no render still draws, off a panel's"
+
+ # And one picture is unchanged: it exports, exactly as it did before.
+ other = start(client, case_id)
+ attach(client, case_id, other, "panel", picture(colour=(9, 9, 9)), "solo.png")
+ solo = commit(client, case_id, other, title="Solo proof")
+ assert case.resolve_inside(layout.proof_export_rel(solo["proof"]["name"])).is_file()
diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.py
index 8ae916a..c428a48 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -467,6 +467,69 @@ def test_index_carries_the_geography_of_the_source(client, sat_tiles, monkeypatc
assert row["country_en"] == "Ukraine"
+def test_index_carries_the_geography_of_the_place_the_proof_filed(client, monkeypatch):
+ """Panels of photos place nothing, and no Locate pass ever reaches a proof.
+ But the point the analyst typed was filed as a place and that one has a
+ country, so the proof files under it instead of under Unlocated."""
+ from azimut.engine import geo
+
+ monkeypatch.setattr(
+ geo,
+ "reverse_geocode",
+ lambda lat, lon, timeout=8, language=None: {
+ "display_name": "x",
+ "attribution": "x",
+ "address": {"country_code": "is", "country": "Ísland"},
+ },
+ )
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Photos only",
+ "spec": {**_panels("media/x.jpg"), "coordsText": "64.1466, -21.9426"},
+ },
+ )
+
+ row = _proof_index(client, cid)[0]
+ assert (row["lat"], row["lon"]) == (64.1466, -21.9426)
+ assert row["geo"]["country"] == "Ísland"
+ assert row["country_en"] == "Iceland"
+ assert row["continent"] == "Europe"
+
+
+def test_index_ignores_the_geography_of_a_place_somewhere_else(client, monkeypatch):
+ """Only the point itself answers. A place across the continent is another
+ claim about another spot, and borrowing its country would file the proof
+ under the wrong branch."""
+ from azimut.engine import geo
+
+ monkeypatch.setattr(
+ geo,
+ "reverse_geocode",
+ lambda lat, lon, timeout=8, language=None: {
+ "display_name": "x",
+ "attribution": "x",
+ "address": {"country_code": "ua", "country": "Україна"},
+ },
+ )
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 50.4501, "lon": 30.5234})
+ # the proof states a point of its own, and nothing is filed there to know it
+ client.put("/api/settings/prefs", json={"proof_place_auto": False})
+ client.post(
+ f"/api/cases/{cid}/proofs",
+ json={
+ "title": "Elsewhere",
+ "spec": {**_panels("media/x.jpg"), "coordsText": "48.8584, 2.2945"},
+ },
+ )
+
+ row = _proof_index(client, cid)[0]
+ assert (row["lat"], row["lon"]) == (48.8584, 2.2945)
+ assert row["geo"] is None # placed on the map, unlocated in the tree
+
+
def test_index_lists_the_posts_written_from_a_proof(client, sat_tiles):
cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
cap = _sat(client, cid, 50.4501, 30.5234)
@@ -623,7 +686,10 @@ def test_saving_a_proof_files_the_point_it_carries(client):
assert (places[0]["attrs"]["lat"], places[0]["attrs"]["lon"]) == (50.4501, 30.5234)
# the analyst's own answer, so there is nothing left to review
assert places[0]["provenance"]["status"] == "confirmed"
- assert saved["place"] == {"filed": True, "id": places[0]["id"], "label": places[0]["label"]}
+ assert saved["place"] == {
+ "filed": [{"id": places[0]["id"], "label": places[0]["label"]}],
+ "asking": [],
+ }
# and the proof says it shows that place
edges = _depicts(cid)
@@ -662,7 +728,7 @@ def test_a_point_the_case_already_holds_is_neither_filed_twice_nor_asked_about(c
def test_resaving_a_proof_stays_silent(client):
cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
spec = _with_coords("50.4501, 30.5234")
- assert _save(client, cid, "Roof match", spec)["place"]["filed"] is True
+ assert len(_save(client, cid, "Roof match", spec)["place"]["filed"]) == 1
# the point is in the case now: saving again must not ask, nor pin it twice
assert _save(client, cid, "Roof match", spec)["place"] is None
assert len(_places(cid)) == 1
@@ -674,15 +740,13 @@ def test_the_composer_is_asked_when_the_setting_is_off(client):
saved = _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
assert saved["place"] == {
- "filed": False, "lat": 50.4501, "lon": 30.5234, "pov": False
+ "filed": [],
+ "asking": [{"lat": 50.4501, "lon": 30.5234, "label": "", "pov": False}],
}
assert _places(cid) == [] # nothing is written until the analyst says yes
- filed = client.post(
- f"/api/cases/{cid}/proofs/Roof match/place",
- json={"lat": 50.4501, "lon": 30.5234},
- ).json()
- assert filed["type"] == "place"
+ filed = client.post(f"/api/cases/{cid}/proofs/Roof match/place").json()
+ assert len(filed) == 1
assert _depicts(cid)[0]["from"] == graph_read.entity(cid, spec=layout.proof_spec_rel("Roof match"))["id"]
@@ -692,10 +756,11 @@ def test_answering_twice_files_one_place(client):
cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
_save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
- body = {"lat": 50.4501, "lon": 30.5234}
- first = client.post(f"/api/cases/{cid}/proofs/Roof match/place", json=body).json()
- second = client.post(f"/api/cases/{cid}/proofs/Roof match/place", json=body).json()
- assert first["id"] == second["id"]
+ first = client.post(f"/api/cases/{cid}/proofs/Roof match/place").json()
+ second = client.post(f"/api/cases/{cid}/proofs/Roof match/place").json()
+ # the second answer finds the point standing and joins it: nothing new to file
+ assert first[0]["id"] == _places(cid)[0]["id"]
+ assert second == []
assert len(_places(cid)) == 1
@@ -734,6 +799,50 @@ def test_the_material_the_proof_composes_states_the_same_point(client, sat_tiles
assert stated[graph_read.entity(cid, path=cap["path"])["id"]] == "confirmed"
+def test_a_proof_rests_on_material_it_never_composed(client, sat_tiles):
+ """The clip under the photos, the second angle nobody cropped: files a geolocation
+ rests on without laying them out.
+
+ A thread states its point in the post that published it and hangs the material off
+ the ones after it. The composer can now bring those in from a stated source address,
+ and what it brings in is the proof's `material` — in the chain, and therefore on the
+ point, without ever being a panel.
+
+ Restated on every save like the panels are, so an address taken off the list takes
+ its edge with it rather than leaving a claim nothing on screen still makes.
+ """
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ case.add_entity("media", "frame.png", {"path": "media/frame.png", "kind": "image"}, by="user")
+ clip = case.add_entity(
+ "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ angle = case.add_entity(
+ "media", "angle.jpg", {"path": "media/angle.jpg", "kind": "image"}, by="user"
+ )
+ cap = _sat(client, cid, 50.4501, 30.5234)
+
+ spec = _with_coords("50.4501, 30.5234", None, "media/frame.png", cap["path"])
+ spec["material"] = ["media/clip.mp4", "media/angle.jpg"]
+ _save(client, cid, "Roof match", spec)
+
+ proof = graph_read.entity(cid, spec=layout.proof_spec_rel("Roof match"))
+ chain = {lk["to"] for lk in case.links_of(proof["id"]) if lk["type"] == "derived-from"}
+ assert {clip["id"], angle["id"]} <= chain
+
+ # And the point reaches them through that chain, with no second rule for it.
+ place = _places(cid)[0]
+ posed = {lk["from"] for lk in _depicts(cid) if lk["to"] == place["id"]}
+ assert {clip["id"], angle["id"]} <= posed
+
+ # A second save with one address dropped drops its edge, panels untouched.
+ spec["material"] = ["media/clip.mp4"]
+ _save(client, cid, "Roof match", spec)
+ chain = {lk["to"] for lk in case.links_of(proof["id"]) if lk["type"] == "derived-from"}
+ assert clip["id"] in chain
+ assert angle["id"] not in chain
+
+
def test_a_source_the_verb_does_not_accept_is_skipped(client):
cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
case = Case.open(cid)
@@ -811,13 +920,11 @@ def test_the_answer_to_the_question_reads_pov_off_the_saved_proof(client):
saved = _save(client, cid, "From the roof", _with_coords(
"50.4501, 30.5234", None, "media/clip.mp4", pov=True
))
- assert saved["place"]["pov"] is True # so the question can say what it means
+ # so the question can say what the point will mean
+ assert saved["place"]["asking"][0]["pov"] is True
- client.post(
- f"/api/cases/{cid}/proofs/From the roof/place",
- json={"lat": 50.4501, "lon": 30.5234},
- )
- # POV is a property of the proof, not of the answer: the body never carries it
+ client.post(f"/api/cases/{cid}/proofs/From the roof/place")
+ # POV is a property of the point, not of the answer: the request carries nothing
assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
@@ -953,3 +1060,398 @@ def test_a_point_another_proof_still_concludes_on_keeps_its_material(client):
holding = {lk["from"] for lk in _depicts(cid) if lk["to"] == shared["id"]}
assert video["id"] in holding
assert graph_read.entity(cid, spec=layout.proof_spec_rel("First"))["id"] in holding
+
+
+# -- a proof states several points (engine/satellite.spec_points) ---------------
+#
+# Three impacts, a building, the camera that filmed it: each is a point the
+# analyst concluded on, and the first one is the conclusion every surface that
+# can hold a single answer reads.
+
+
+def _points(*entries):
+ """A spec stating these points, `(coords, label, pov)` per entry."""
+ return {
+ "panels": [],
+ "points": [
+ {"coords": coords, "label": label, "pov": pov}
+ for coords, label, pov in entries
+ ],
+ }
+
+
+def test_a_spec_with_no_list_still_states_its_one_point(client):
+ """Nothing migrates: a proof written before the list reads as one point."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Old shape", _with_coords("50.4501, 30.5234", None, pov=True))
+
+ rows = _proof_index(client, cid)
+ assert [(r["lat"], r["lon"], r["label"]) for r in rows] == [(50.4501, 30.5234, "")]
+ assert len(_places(cid)) == 1
+
+
+def test_every_point_becomes_a_row_and_a_place(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ saved = _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1481, -21.9401", "impact 2", False),
+ ("64.1502, -21.9350", "caméra", True),
+ ))
+
+ # one row per point, all under one proof: the map is about places
+ rows = _proof_index(client, cid)
+ assert len({r["id"] for r in rows}) == 1
+ assert [r["label"] for r in rows] == ["impact 1", "impact 2", "caméra"]
+ assert len({r["key"] for r in rows}) == 3 # three marks, three render keys
+ # and the label names the ground, since a place is otherwise called by its numbers
+ assert sorted(p["label"] for p in _places(cid)) == ["caméra", "impact 1", "impact 2"]
+ assert len(saved["place"]["filed"]) == 3
+
+
+def test_the_first_point_is_the_conclusion_whatever_pov_says(client):
+ """POV does not reorder: it would move a coordinate out of a tweet in silence."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1502, -21.9350", "caméra", True),
+ ))
+ spec = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+
+ from azimut.engine import satellite
+
+ conclusion = satellite.spec_points(spec)[0]
+ assert (conclusion["lat"], conclusion["lon"]) == (64.1466, -21.9426)
+ assert conclusion["pov"] is False # the camera is the second row, and stays there
+
+
+def test_pov_is_carried_by_its_own_point(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1502, -21.9350", "caméra", True),
+ )
+ spec["panels"] = _panels("media/clip.mp4")["panels"]
+ _save(client, cid, "Harbour strike", spec)
+
+ camera = _place_by_lat(cid, 64.1502)
+ impact = _place_by_lat(cid, 64.1466)
+ # the camera stood in one place; it shows the impact from there
+ assert [lk["to"] for lk in _located_at(cid)] == [camera["id"]]
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+ assert {lk["from"] for lk in _depicts(cid) if lk["to"] == impact["id"]} == {
+ _proof(cid)["id"], video["id"]
+ }
+ # a proof was composed, never recorded: it shows the camera's point too
+ assert _proof(cid)["id"] in {lk["from"] for lk in _depicts(cid) if lk["to"] == camera["id"]}
+
+
+def test_a_second_pov_is_refused_because_a_camera_stood_in_one_place(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = _points(
+ ("64.1466, -21.9426", "one", True),
+ ("64.1502, -21.9350", "two", True),
+ )
+ spec["panels"] = _panels("media/clip.mp4")["panels"]
+ _save(client, cid, "Two cameras", spec)
+
+ # the first to claim it keeps it, whatever a hand-written spec asked for
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+ assert [lk["to"] for lk in _located_at(cid)] == [_place_by_lat(cid, 64.1466)["id"]]
+
+
+def test_moving_pov_to_another_point_restates_both_verbs(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ first = _points(("64.1466, -21.9426", "a", True), ("64.1502, -21.9350", "b", False))
+ first["panels"] = _panels("media/clip.mp4")["panels"]
+ _save(client, cid, "Harbour strike", first)
+ assert [lk["to"] for lk in _located_at(cid)] == [_place_by_lat(cid, 64.1466)["id"]]
+
+ moved = _points(("64.1466, -21.9426", "a", False), ("64.1502, -21.9350", "b", True))
+ moved["panels"] = _panels("media/clip.mp4")["panels"]
+ _save(client, cid, "Harbour strike", moved)
+
+ # the old reading goes rather than piling up beside the new one
+ assert [lk["to"] for lk in _located_at(cid)] == [_place_by_lat(cid, 64.1502)["id"]]
+ assert video["id"] in {lk["from"] for lk in _depicts(cid)
+ if lk["to"] == _place_by_lat(cid, 64.1466)["id"]}
+
+
+def test_taking_a_point_off_the_list_rends_its_place(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1481, -21.9401", "impact 2", False),
+ ))
+ dropped = _place_by_lat(cid, 64.1481)
+
+ saved = _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ))
+
+ # exactly what clearing the single field always did, one line at a time
+ assert saved["orphans"] == [{"id": dropped["id"], "label": dropped["label"]}]
+ assert [lk["to"] for lk in _depicts(cid)] == [_place_by_lat(cid, 64.1466)["id"]]
+
+
+def test_two_points_a_metre_apart_are_one_place(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Same roof", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.14660, -21.94260", "impact 1 again", False),
+ ))
+
+ assert len(_places(cid)) == 1
+ assert len(_proof_index(client, cid)) == 1
+
+
+def test_one_place_keeps_the_pov_the_second_line_ticked(client):
+ """The duplicate goes, its answer about the camera does not. Dropped with the line, a
+ POV ticked on the second of two points a metre apart was a claim the composer showed
+ and the graph never carried."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = _points(("64.1466, -21.9426", "roof", False), ("64.14660, -21.94260", "", True))
+ spec["panels"] = _panels("media/clip.mp4")["panels"]
+ _save(client, cid, "Same roof", spec)
+
+ assert len(_places(cid)) == 1
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+
+
+def test_a_line_that_reads_as_no_point_is_skipped(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Prose", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("near the harbour", "impact 2", False),
+ ))
+
+ # prose in the field is a caption, not a point
+ assert [(p["attrs"]["lat"], p["attrs"]["lon"]) for p in _places(cid)] == [(64.1466, -21.9426)]
+
+
+def test_a_spec_cannot_file_a_hundred_places_on_one_save(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Too many", _points(
+ *((f"64.{1000 + i}, -21.9426", "", False) for i in range(30))
+ ))
+
+ from azimut.engine.satellite import MAX_PROOF_POINTS
+
+ assert len(_places(cid)) == MAX_PROOF_POINTS
+
+
+def test_the_composer_is_asked_about_every_point_it_cannot_file(client):
+ client.put("/api/settings/prefs", json={"proof_place_auto": False})
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ saved = _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1502, -21.9350", "caméra", True),
+ ))
+
+ assert saved["place"]["asking"] == [
+ {"lat": 64.1466, "lon": -21.9426, "label": "impact 1", "pov": False},
+ {"lat": 64.1502, "lon": -21.9350, "label": "caméra", "pov": True},
+ ]
+ assert _places(cid) == []
+
+ filed = client.post(f"/api/cases/{cid}/proofs/Harbour strike/place").json()
+ assert sorted(one["label"] for one in filed) == ["caméra", "impact 1"]
+ # the yes reads the spec, so POV lands on the line that carries it
+ assert [lk["to"] for lk in _located_at(cid)] == [] # no material to place
+
+
+def test_only_the_conclusion_is_looked_up_at_save(client, monkeypatch):
+ """Geography is paced, so three points would hold the save for three seconds.
+ The Locate pass answers for the rest, exactly as an offline save already is."""
+ from azimut.engine import geo
+
+ asked: list[tuple[float, float]] = []
+
+ def _one(lat, lon, timeout=8, language=None):
+ asked.append((lat, lon))
+ return {
+ "display_name": "x",
+ "attribution": "x",
+ "address": {"country_code": "is", "country": "Ísland"},
+ }
+
+ monkeypatch.setattr(geo, "reverse_geocode", _one)
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Harbour strike", _points(
+ ("64.1466, -21.9426", "impact 1", False),
+ ("64.1481, -21.9401", "impact 2", False),
+ ("64.1502, -21.9350", "caméra", True),
+ ))
+
+ assert asked == [(64.1466, -21.9426)]
+ rows = {r["label"]: r["geo"] for r in _proof_index(client, cid)}
+ assert rows["impact 1"]["country"] == "Ísland"
+ assert rows["impact 2"] is None # born unlocated, for the Locate pass to pick up
+
+
+def test_stating_a_point_writes_the_list_and_the_mirror():
+ """An older build has to find the conclusion where it has always been."""
+ from azimut.engine import satellite
+
+ spec = satellite.state_points({}, [{"coords": "64.1466, -21.9426", "pov": True}])
+ assert spec["points"] == [{"coords": "64.1466, -21.9426", "pov": True}]
+ assert spec["coordsText"] == "64.1466, -21.9426"
+ assert spec["pov"] is True
+
+
+def test_stating_one_point_over_a_list_replaces_it(client):
+ """A sheet cell must not be swallowed by a list the composer left behind."""
+ from azimut.engine import satellite
+
+ spec = _points(("64.1466, -21.9426", "impact 1", False), ("64.1502, -21.9350", "b", True))
+ satellite.state_points(spec, [{"coords": "48.8584, 2.2945"}])
+
+ assert satellite.spec_points(spec) == [
+ {"lat": 48.8584, "lon": 2.2945, "coords": "48.8584, 2.2945", "label": "", "pov": False}
+ ]
+
+
+def test_a_point_filed_by_another_road_is_a_row_and_a_mark(client):
+ """A sheet row files a point for a proof it never composed. The graph knew
+ two places while the composer opened on one, so the proof said two things."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Harbour strike", _points(("48.656140, 2.371511", "impact 1", False)))
+ case = Case.open(cid)
+ proof = _proof(cid)
+ # the road the sheet takes: its own place, its own provenance, no re-composition
+ elsewhere = client.post(
+ f"/api/cases/{cid}/satellite/place", json={"lat": 48.656289, "lon": 2.371885}
+ ).json()
+ case.update_entity(elsewhere["id"], {"label": "impact 2"})
+ case.add_link(proof["id"], elsewhere["id"], "depicts", by="sheet-build")
+
+ rows = _proof_index(client, cid)
+ assert [(r["lat"], r["label"]) for r in rows] == [
+ (48.65614, "impact 1"), (48.656289, "impact 2"),
+ ]
+ # and the composer opens on both, the analyst's own row still the conclusion
+ spec = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+ assert [one["coords"] for one in spec["points"]] == ["48.656140, 2.371511", "48.656289, 2.371885"]
+ assert spec["points"][1]["label"] == "impact 2"
+
+
+def _other_road(client, cid, lat, lon, label, *, material=(), verb="depicts"):
+ """A point filed for a proof by a road that never wrote its composition.
+
+ What `api/sheetproofs._added_point` writes for the binder's cross-border shape: its
+ own place, its own provenance, the proof reaching it and the material posed on it.
+ """
+ proof = _proof(cid)
+ case = Case.open(cid)
+ place = client.post(f"/api/cases/{cid}/satellite/place", json={"lat": lat, "lon": lon}).json()
+ case.update_entity(place["id"], {"label": label})
+ case.add_link(proof["id"], place["id"], "depicts", by="sheet-proofs")
+ for entity_id in material:
+ case.add_link(entity_id, place["id"], verb, by="sheet-proofs")
+ return place
+
+
+def test_taking_off_a_point_another_road_filed_withdraws_it_for_good(client):
+ """The composer opens on a point a sheet row filed, as an editable row. So deleting
+ that row has to mean what it says: read on its own provenance, the withdrawal found
+ nothing to take back, the save reported no orphan, and the next open adopted the
+ point again — a row that could not be deleted, coming back with no way to tell why."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = {
+ **_panels("media/clip.mp4"),
+ "points": [{"coords": "48.656140, 2.371511", "label": "impact 1", "pov": False}],
+ }
+ _save(client, cid, "Harbour strike", spec)
+ elsewhere = _other_road(client, cid, 48.656289, 2.371885, "impact 2", material=[video["id"]])
+
+ opened = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+ assert [one["label"] for one in opened["points"]] == ["impact 1", "impact 2"]
+
+ kept = {**opened, "points": opened["points"][:1]}
+ saved = _save(client, cid, "Harbour strike", kept)
+
+ # the proof's own edge and the footage the road posed with it, both taken back
+ assert [lk["from"] for lk in _depicts(cid) if lk["to"] == elsewhere["id"]] == []
+ assert saved["orphans"] == [{"id": elsewhere["id"], "label": "impact 2"}]
+ again = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+ assert [one["label"] for one in again["points"]] == ["impact 1"]
+
+
+def test_a_point_kept_from_another_road_is_stated_rather_than_left_alone(client):
+ """The other half of the same rule: a row the analyst leaves standing is a row the
+ proof now states itself, so its material carries the edge the composition means."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ _save(client, cid, "Harbour strike", _with_coords("48.656140, 2.371511", None, "media/clip.mp4"))
+ elsewhere = _other_road(client, cid, 48.656289, 2.371885, "impact 2")
+
+ opened = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+ _save(client, cid, "Harbour strike", opened)
+
+ posed = {lk["from"] for lk in _depicts(cid) if lk["to"] == elsewhere["id"]}
+ assert {_proof(cid)["id"], video["id"]} <= posed
+
+
+def test_a_point_a_second_proof_concludes_on_by_another_road_keeps_its_material(client):
+ """`_other_proof_states` read one provenance, so a proof withdrawing its point took
+ the video off a place a sheet-built proof still concludes on."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = _with_coords("50.4501, 30.5234", None, "media/clip.mp4")
+ _save(client, cid, "First", spec)
+ shared = _places(cid)[0]
+ case = Case.open(cid)
+ other = case.add_entity("proof", "Built by the sheet", {"spec": "proofs/x.json"}, by="user")
+ case.add_link(other["id"], shared["id"], "depicts", by="sheet-proofs")
+
+ saved = _save(client, cid, "First", _with_coords("48.8584, 2.2945", None, "media/clip.mp4"))
+
+ assert saved["orphans"] == []
+ holding = {lk["from"] for lk in _depicts(cid) if lk["to"] == shared["id"]}
+ assert {video["id"], other["id"]} <= holding
+
+
+def test_the_pov_of_an_adopted_point_is_read_off_this_proof_material(client):
+ """POV says *this* proof's footage was recorded there. Read off any media standing
+ on the point, a second proof's video answered for this one — and the tick came back
+ on, in a composition whose own footage says nothing of the kind."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _video(cid)
+ _save(client, cid, "Harbour strike", _with_coords("48.656140, 2.371511", None, "media/clip.mp4"))
+ somebody = _video(cid, "theirs.mp4")
+ elsewhere = _other_road(
+ client, cid, 48.656289, 2.371885, "impact 2",
+ material=[somebody["id"]], verb="located-at",
+ )
+
+ opened = client.get(f"/api/cases/{cid}/proofs/Harbour strike").json()
+ adopted = next(one for one in opened["points"] if one.get("label") == "impact 2")
+ assert adopted.get("pov") is not True
+ assert [lk["from"] for lk in _located_at(cid) if lk["to"] == elsewhere["id"]] == [
+ somebody["id"]
+ ]
+
+
+def test_reopening_a_proof_never_rewrites_what_was_typed(client):
+ """Down to the format: somebody who works in DMS typed DMS."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ typed = "48°51'30.2\"N 2°17'40.2\"E"
+ _save(client, cid, "Typed", _points((typed, "", False)))
+
+ spec = client.get(f"/api/cases/{cid}/proofs/Typed").json()
+ assert [one["coords"] for one in spec["points"]] == [typed]
+
+
+def test_a_proof_the_panels_place_opens_with_an_empty_field(client, sat_tiles):
+ """Nothing was typed, so nothing is written into the row: the field shows the
+ panels' own answer and the reset arrow stays away."""
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ client.post(f"/api/cases/{cid}/proofs", json={"title": "Auto", "spec": _panels(cap["path"])})
+
+ spec = client.get(f"/api/cases/{cid}/proofs/Auto").json()
+ assert spec.get("points") in (None, [])
diff --git a/tests/test_regressions.py b/tests/test_regressions.py
new file mode 100644
index 0000000..3d6890a
--- /dev/null
+++ b/tests/test_regressions.py
@@ -0,0 +1,261 @@
+"""Bugs found by a review of the whole tree, each pinned by the case that broke.
+
+Grouped here rather than scattered into the suites they touch because what they
+have in common is the failure mode, not the module: every one of these was
+silent — a destroyed file, a dropped qualifier, a stalled queue — and none of
+them raised anything a user would have reported as an error.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import threading
+
+import pytest
+
+from azimut import config, layout, workspace
+from azimut.engine import geo, workqueue
+from azimut.engine.coords import utm_zone
+from azimut.workspace import Case, CaseError
+
+# A one-pixel PNG, and the asset name the proofs route derives from its bytes.
+PNG_BYTES = bytes.fromhex(
+ "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
+ "0000000d49444154789c6360000002000155a72b0e0000000049454e44ae426082"
+)
+PNG_B64 = base64.b64encode(PNG_BYTES).decode()
+ASSET_NAME = "126ddc670c86a4f3.png"
+
+
+def _case(client) -> str:
+ return client.post("/api/cases", json={"name": "Regression"}).json()["id"]
+
+
+# -- traversal ---------------------------------------------------------------
+#
+# The id and the artifact name both arrive as one URL path segment. A segment
+# cannot hold a `/` — the ASGI server decodes `%2F` before routing, and the route
+# stops matching — but it can hold a `\`, which is a separator on Windows and an
+# ordinary character everywhere else. So these run on every OS and would have
+# passed on Linux while the Windows binary was the one that could be walked out
+# of.
+
+
+ "case_id",
+ ["..", ".", "../elsewhere", "..\\elsewhere", "sub/case", "C:case"],
+)
+def test_case_id_names_one_folder_in_the_workspace(tmp_workspace, case_id):
+ with pytest.raises(CaseError):
+ Case.locate(case_id)
+
+
+def test_case_cannot_be_located_outside_the_workspace(tmp_workspace, tmp_path):
+ outside = tmp_path / "case-backup"
+ (outside / layout.TOOL_DIR).mkdir(parents=True)
+ (outside / layout.TOOL_DIR / "case.json").write_text(
+ json.dumps({"azimut": {"schema": 3, "storage": "sqlite"}, "name": "victim"})
+ )
+ import os
+
+ escape = os.path.relpath(outside, config.cases_dir())
+ with pytest.raises(CaseError):
+ Case.locate(escape)
+
+
+def test_grid_delete_cannot_name_the_case_manifest(client):
+ case_id = _case(client)
+ manifest = Case.locate(case_id).path / layout.TOOL_DIR / "case.json"
+ assert manifest.is_file()
+
+ client.request(
+ "DELETE", f"/api/cases/{case_id}/search-grids/..%5Ccase", follow_redirects=False
+ )
+ assert manifest.is_file()
+
+
+ ("route", "kind"),
+ [
+ ("proofs", "proof"),
+ ("drafts", "draft"),
+ ("inspect/sessions", "session"),
+ ],
+)
+def test_artifact_delete_cannot_name_the_case_manifest(client, route, kind):
+ case_id = _case(client)
+ manifest = Case.locate(case_id).path / layout.TOOL_DIR / "case.json"
+
+ client.request("DELETE", f"/api/cases/{case_id}/{route}/..%5C..%5Ccase")
+ assert manifest.is_file(), f"{kind} delete removed the manifest"
+
+
+# -- destructive-before-valid ------------------------------------------------
+
+
+def test_refused_proof_rename_keeps_the_export_and_the_pasted_images(client):
+ case_id = _case(client)
+ saved = client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={
+ "title": "Alpha",
+ "spec": {"panels": [], "pastes": [{"id": "x1", "asset": ASSET_NAME}]},
+ "png_base64": PNG_B64,
+ "assets": [{"name": ASSET_NAME, "data": PNG_B64}],
+ },
+ )
+ assert saved.status_code == 200
+ case = Case.locate(case_id)
+ export = case.resolve_inside(layout.proof_export_rel("Alpha"))
+ assets = case.resolve_inside(layout.proof_assets_rel("Alpha"))
+ assert export.is_file() and assets.is_dir()
+
+ refused = client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={
+ "title": "Beta",
+ "rename_from": "Alpha",
+ "spec": {"panels": [], "pastes": [{"id": "x1", "asset": ASSET_NAME}]},
+ "png_base64": "!!!not base64!!!",
+ "assets": [],
+ },
+ )
+ assert refused.status_code == 422
+ # The proof is still Alpha, so everything Alpha owned has to still be there.
+ assert case.resolve_inside(layout.proof_spec_rel("Alpha")).is_file()
+ assert export.is_file(), "the export was deleted before the payload was judged"
+ assert assets.is_dir(), "the pasted images were moved before the payload was judged"
+ assert not case.resolve_inside(layout.proof_assets_rel("Beta")).exists()
+
+
+# -- restore fidelity --------------------------------------------------------
+
+
+def test_trash_restore_brings_back_the_link_qualifier(client):
+ case_id = _case(client)
+ a = client.post(f"/api/cases/{case_id}/entities", json={"type": "person", "label": "A"}).json()
+ b = client.post(f"/api/cases/{case_id}/entities", json={"type": "person", "label": "B"}).json()
+ link = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": a["id"], "to_id": b["id"], "type": "associated-with"},
+ ).json()
+ qualified = client.patch(
+ f"/api/cases/{case_id}/links/{link['id']}", json={"nature": "brother of"}
+ )
+ assert qualified.json()["nature"] == "brother of"
+
+ client.request("DELETE", f"/api/cases/{case_id}/entities/{a['id']}")
+ group = client.get(f"/api/cases/{case_id}/trash").json()["groups"][0]
+ restored = client.post(f"/api/cases/{case_id}/trash/{group['id']}/restore")
+ assert restored.json()["links"] == 1
+
+ links = Case.locate(case_id).list_links()
+ assert [entry.get("nature") for entry in links] == ["brother of"]
+
+
+# -- corrupt state a user cannot get back out of -----------------------------
+
+
[email protected]("payload", ['{"schema": 0}', "null", "[]", '"x"', "123"])
+def test_unusable_settings_file_falls_back_to_defaults(tmp_workspace, payload):
+ path = config.settings_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(payload, encoding="utf-8")
+ assert config.load_settings()["schema"] == config.SETTINGS_SCHEMA
+
+
+def test_one_corrupt_manifest_does_not_hide_the_other_cases(client):
+ good = _case(client)
+ broken = client.post("/api/cases", json={"name": "Broken"}).json()["id"]
+ (Case.locate(broken).path / layout.TOOL_DIR / "case.json").write_text("{ not json")
+
+ listed = client.get("/api/cases")
+ assert listed.status_code == 200
+ by_id = {row["id"]: row for row in listed.json()}
+ assert by_id[good]["health"] == "ok"
+ assert by_id[broken]["health"] == "needs-attention"
+ # And a new case can still be created, which reads the list to check the name.
+ assert client.post("/api/cases", json={"name": "Later"}).status_code == 200
+
+
+# -- parsers that answered when they should have declined --------------------
+
+
[email protected]("text", ["2023", "1984", "0000", "12345678"])
+def test_bare_digits_are_not_a_location(text):
+ assert geo.parse_coords(text) is None
+
+
+def test_geohashes_still_parse():
+ assert geo.parse_coords("u09tvw0f") is not None
+
+
+def test_utm_zone_stops_at_the_antimeridian():
+ assert utm_zone(0, 180) == 60
+ assert utm_zone(0, 179.9) == 60
+ assert utm_zone(0, -180) == 1
+
+
+# -- queues and snapshots ----------------------------------------------------
+
+
+def test_a_job_queued_during_a_drain_is_still_drained(monkeypatch):
+ """The lost wakeup: `wake` is a no-op while a case is pending, so the mark
+ must be taken *before* the drain, not cleared after it."""
+ drained: list[int] = []
+ started = threading.Event()
+ release = threading.Event()
+
+ class FakeCase:
+ id = "case-a"
+
+ case = FakeCase()
+
+ def fake_drain(target):
+ drained.append(1)
+ if len(drained) == 1:
+ started.set()
+ release.wait(5)
+
+ monkeypatch.setattr(workqueue, "drain", fake_drain)
+ monkeypatch.setattr(workqueue, "_pending", {})
+ monkeypatch.setattr(workqueue, "_worker_running", False)
+
+ workqueue.wake(case)
+ assert started.wait(5)
+ workqueue.wake(case) # enqueued while the first drain is still running
+ release.set()
+
+ for _ in range(100):
+ if len(drained) >= 2:
+ break
+ threading.Event().wait(0.05)
+ assert len(drained) >= 2, "the job queued during the drain was never picked up"
+
+
+def test_bundle_snapshot_reads_one_consistent_state(client):
+ """Entities and links come from one transaction, so a snapshot can never
+ carry an edge whose endpoints it does not also carry."""
+ case_id = _case(client)
+ a = client.post(f"/api/cases/{case_id}/entities", json={"type": "person", "label": "A"}).json()
+ b = client.post(f"/api/cases/{case_id}/entities", json={"type": "person", "label": "B"}).json()
+ client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": a["id"], "to_id": b["id"], "type": "associated-with"},
+ )
+ snap = Case.locate(case_id).snapshot()
+ ids = {entity["id"] for entity in snap["entities"]}
+ assert all(link["from"] in ids and link["to"] in ids for link in snap["links"])
+
+
+def test_names_one_child_is_judged_on_both_path_flavours():
+ assert layout.names_one_child("Rooftop angle")
+ assert layout.names_one_child("proof.json")
+ for hostile in ("", ".", "..", "a/b", "a\\b", "..\\..\\case", "C:x", "a/"):
+ assert not layout.names_one_child(hostile), hostile
+
+
+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_repository.py b/tests/test_repository.py
index 9496f24..cc60d80 100644
--- a/tests/test_repository.py
+++ b/tests/test_repository.py
@@ -9,6 +9,7 @@ open; see tests/test_migrations.py).
from __future__ import annotations
+import threading
from contextlib import contextmanager
import pytest
@@ -110,6 +111,25 @@ def test_sync_links_restates_a_source_set(repo):
assert still["id"] == kept["id"]
+def test_sync_links_can_restate_only_what_its_own_author_wrote(repo):
+ """A caller whose list is not the whole truth about that type says so, and the edge
+ another author wrote outlives the restatement. Without it, a sheet reconciling the
+ entities its cells point at deleted the relations somebody stated by hand."""
+ sheet = repo.add_entity("sheet", "Worklist", {"path": "sheets/w.csv"}, by="user")
+ theirs = repo.add_entity("person", "Ivanov", by="user")
+ ours = repo.add_entity("person", "Petrov", by="user")
+ by_hand = repo.add_link(sheet["id"], theirs["id"], "mentions", by="user")
+ repo.sync_links(sheet["id"], "mentions", [ours["id"]], by="sheet", own_only=True)
+
+ held = {lk["id"]: lk for lk in repo.list_links()}
+ assert by_hand["id"] in held
+ assert {lk["to"] for lk in held.values()} == {theirs["id"], ours["id"]}
+
+ # and the sheet still lets go of its own
+ repo.sync_links(sheet["id"], "mentions", [], by="sheet", own_only=True)
+ assert [lk["to"] for lk in repo.list_links()] == [theirs["id"]]
+
+
def test_remove_link(repo):
a = repo.add_entity("person", "A", by="user")
b = repo.add_entity("account", "B", by="user")
@@ -790,3 +810,82 @@ def test_an_ordered_page_reads_the_case_in_order_and_pages_without_repeating(rep
assert [e["label"] for e in repo.page_entities(order="-label")["items"]] == [
"delta", "charlie", "bravo", "Alpha", "Alpha",
]
+
+
+# -- writing several things as one ---------------------------------------------
+
+
+def test_a_batch_commits_everything_inside_it(repo):
+ """The plain case: a handful of writes, one transaction, all of them there."""
+ with repo.batch():
+ person = repo.add_entity("person", "Ada", by="user")
+ unit = repo.add_entity("organization", "3rd Brigade", by="user")
+ repo.add_link(person["id"], unit["id"], "member-of", by="user")
+
+ assert [e["label"] for e in repo.list_entities()] == ["Ada", "3rd Brigade"]
+ assert [link["type"] for link in repo.list_links()] == ["member-of"]
+
+
+def test_a_failed_batch_leaves_the_case_exactly_as_it_was(repo):
+ """What the primitive exists for. Thirty-nine writes and a fortieth that raises
+ used to leave thirty-nine standing; the case is now either before or after."""
+ kept = repo.add_entity("person", "Already here", by="user")
+
+ with pytest.raises(CaseError):
+ with repo.batch():
+ for index in range(39):
+ repo.add_entity("person", f"Promoted {index}", by="user")
+ repo.add_link(kept["id"], "no-such-entity", "member-of", by="user")
+
+ assert [e["label"] for e in repo.list_entities()] == ["Already here"]
+ assert repo.list_links() == []
+
+
+def test_a_batch_sees_what_it_has_written(repo):
+ """A planner writes an entity and immediately links it, so the read has to run on
+ the batch's own connection: another one would be looking at the file as it was."""
+ with repo.batch():
+ person = repo.add_entity("person", "Ada", by="user")
+ assert repo.get_entity(person["id"])["label"] == "Ada"
+ assert repo.entity_count() == 1
+
+
+def test_a_batch_is_invisible_to_another_thread_until_it_commits(repo):
+ """Two promises in one: uncommitted rows belong to the batch and to nothing else,
+ and the batch's connection is the batch thread's own. One handle is shared by the
+ request threads and the job worker, so a batch that leaked its connection sideways
+ would hand another thread an open transaction and raise from somewhere unrelated."""
+ seen: list[int] = []
+
+ def elsewhere() -> None:
+ seen.append(repo.entity_count())
+
+ with repo.batch():
+ repo.add_entity("person", "Ada", by="user")
+ reader = threading.Thread(target=elsewhere)
+ reader.start()
+ reader.join()
+
+ assert seen == [0]
+ assert repo.entity_count() == 1
+
+
+def test_a_batch_does_not_nest(repo):
+ """An inner batch would either commit early and break the outer promise or do
+ nothing and break its own, so it says which caller is wrong instead."""
+ with pytest.raises(CaseError):
+ with repo.batch():
+ with repo.batch():
+ pass
+
+
+def test_a_batch_that_raised_can_be_followed_by_another(repo):
+ """The ambient connection is cleared on the way out however the way out went, or
+ the first failure would poison every write the case sees afterwards."""
+ with pytest.raises(CaseError):
+ with repo.batch():
+ repo.add_link("nope", "nope-either", "member-of", by="user")
+
+ with repo.batch():
+ repo.add_entity("person", "Ada", by="user")
+ assert repo.entity_count() == 1
diff --git a/tests/test_server_guard.py b/tests/test_server_guard.py
index 395c8c5..f87bd1f 100644
--- a/tests/test_server_guard.py
+++ b/tests/test_server_guard.py
@@ -42,3 +42,23 @@ def test_extension_origin_reaches_only_the_ingest_island(client):
assert client.get("/api/ingest/ping", headers={"origin": ext}).status_code == 401
# but anywhere else the extension origin is a cross-origin web page
assert client.get("/api/health", headers={"origin": ext}).status_code == 403
+
+
+def test_a_malformed_pairing_token_is_a_refusal_and_not_a_crash(client):
+ """The one authenticated surface, asked with bytes it never mints.
+
+ Starlette decodes a header as latin-1, so an octet above 0x7f reaches the comparison as
+ a non-ASCII string and `secrets.compare_digest` raises `TypeError` on one. That was a
+ 500 on the authentication edge — a refusal reported as a server fault, with a traceback
+ into the log kept for "Report an issue" — from a value any caller chooses.
+ """
+ from azimut import config
+
+ config.save_settings({**config.load_settings(), "ingest_token": "abc123"})
+ right = client.get("/api/ingest/ping", headers={"X-Azimut-Token": b"abc123"})
+ assert right.status_code == 200
+
+ for token in (b"\xe9", b"abc12\xff", b"", "é".encode()):
+ answer = client.get("/api/ingest/ping", headers={"X-Azimut-Token": token})
+ assert answer.status_code == 401, token
+ assert answer.json()["detail"] == "missing or invalid pairing token"
diff --git a/tests/test_sheet_bridge.py b/tests/test_sheet_bridge.py
new file mode 100644
index 0000000..49cf4f3
--- /dev/null
+++ b/tests/test_sheet_bridge.py
@@ -0,0 +1,955 @@
+"""The sheet as a view of the case, rather than a copy of it drifting away.
+
+A worklist built out of what the case already holds, a row moving up a floor once it has
+been worked out, a binder arriving as a workbook, and the pieces a row carries. All of
+them guard one claim: the sheet and the graph stay **two views of one case**, connected
+by links, rather than two sets of the same names nobody reconciles.
+
+The road the other way — what a column becomes in the case — is one declaration and one
+press, and it is tested in `test_sheet_pass.py` and `test_sheet_claims.py`. The helpers
+here are shared with both.
+
+What each test is really guarding:
+
+- a built sheet is a **file** like any other, with its rows keyed and its links in the
+ sidecar, so nothing about it is special afterwards;
+- the link lands where a promotion looks for one, which is what makes the round trip an
+ update instead of a twin;
+- throwing a worklist away throws the worklist away, not the subjects it established.
+"""
+
+import csv
+import io
+
+from azimut.engine import sheetfromcase as fromcase_engine
+
+
+def make_case(client, name="Bridge"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def add(client, case_id, entity_type, label, **attrs):
+ body = {"type": entity_type, "label": label}
+ if attrs:
+ body["attrs"] = attrs
+ response = client.post(f"/api/cases/{case_id}/entities", json=body)
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def read_sheet(client, case_id, sheet_id):
+ response = client.get(f"/api/cases/{case_id}/sheets/{sheet_id}")
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def case_links(case_id):
+ from azimut.api.cases import get_case
+
+ return get_case(case_id).list_links()
+
+
+def import_sheet(client, case_id, text, title="Tracker"):
+ made = client.post(f"/api/cases/{case_id}/sheets/import", json={"title": title, "text": text})
+ assert made.status_code == 200, made.text
+ return read_sheet(client, case_id, made.json()["id"])
+
+
+def post_sheet(client, case_id, sheet_id, tail, sheet, **asked):
+ return client.post(
+ f"/api/cases/{case_id}/sheets/{sheet_id}/{tail}",
+ json={
+ "columns": sheet["columns"],
+ "rows": sheet["rows"],
+ "meta": sheet["meta"],
+ "stamp": sheet["stamp"],
+ **asked,
+ },
+ )
+
+
+def case_entities(case_id, entity_type):
+ from azimut.api.cases import get_case
+
+ return [e for e in get_case(case_id).list_entities() if e.get("type") == entity_type]
+
+
+# -- a worklist out of the catalog --------------------------------------------
+
+
+def test_a_sheet_built_from_the_case_holds_one_row_per_entity(client):
+ case_id = make_case(client)
+ add(client, case_id, "person", "Ivanov", role="driver")
+ add(client, case_id, "person", "Petrov")
+ add(client, case_id, "organization", "3rd Brigade")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People to check", "type": "person", "fields": ["role"]},
+ )
+ assert made.status_code == 200, made.text
+ assert made.json()["taken"] == 2
+ assert made.json()["total"] == 2
+
+ sheet = read_sheet(client, case_id, made.json()["id"])
+ assert sheet["columns"] == ["id", "Name", "Role", "Status", "Notes"]
+ # Ordered by name, because the analyst about to work through it looks rows up by name.
+ assert [row[1] for row in sheet["rows"]] == ["Ivanov", "Petrov"]
+ assert sheet["rows"][0][2] == "driver"
+ # The two empty columns are the whole reason the rows are in a sheet.
+ assert [row[3] for row in sheet["rows"]] == ["", ""]
+
+
+def test_only_the_fields_asked_for_travel(client):
+ case_id = make_case(client)
+ add(client, case_id, "person", "Ivanov", role="driver", nationality="UA")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People", "type": "person", "fields": ["nationality", "invented"]},
+ ).json()
+
+ sheet = read_sheet(client, case_id, made["id"])
+ assert sheet["columns"] == ["id", "Name", "Nationality", "Status", "Notes"]
+ assert sheet["rows"][0][2] == "UA"
+
+
+def test_a_built_sheet_is_a_csv_on_disk_like_any_other(client):
+ case_id = make_case(client)
+ add(client, case_id, "place", "Quai sud", lat=46.6, lon=32.6)
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case", json={"title": "Places", "type": "place"}
+ ).json()
+
+ from azimut.api.cases import get_case
+
+ path = get_case(case_id).resolve_inside(
+ (get_case(case_id).get_entity(made["id"])["attrs"])["path"]
+ )
+ table = list(csv.reader(io.StringIO(path.read_text(encoding="utf-8-sig"))))
+ assert table[0] == ["id", "Name", "Status", "Notes"]
+ assert table[1][1] == "Quai sud"
+ assert table[1][0], "every row is keyed"
+
+
+def test_every_row_points_back_at_the_entity_it_came_from(client):
+ case_id = make_case(client)
+ person = add(client, case_id, "person", "Ivanov")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case", json={"title": "People", "type": "person"}
+ ).json()
+ sheet = read_sheet(client, case_id, made["id"])
+
+ key = sheet["rows"][0][0]
+ assert sheet["meta"]["links"][key] == {"Name": person["id"]}
+ # What the cell said when the case was read, which is what lets the row say later
+ # that it has moved on.
+ assert sheet["meta"]["promoted"][key] == {"Name": "Ivanov"}
+ # And the edge that makes the sheet reachable from the subject's side.
+ assert any(
+ link["type"] == "mentions" and link["from"] == made["id"] and link["to"] == person["id"]
+ for link in case_links(case_id)
+ )
+
+
+def test_a_built_worklist_can_already_count_its_own_progress(client):
+ case_id = make_case(client)
+ add(client, case_id, "person", "Ivanov")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case", json={"title": "People", "type": "person"}
+ ).json()
+ sheet = read_sheet(client, case_id, made["id"])
+
+ assert sheet["meta"]["progress"] == "Status"
+ assert sheet["meta"]["roles"]["Status"]["kind"] == "state"
+ assert sheet["meta"]["roles"]["Status"]["values"][0] == "to do"
+
+
+def test_promoting_a_built_row_back_updates_rather_than_twinning(client):
+ """The round trip. The link is written where a promotion looks for one, so a second
+ press is an update — which is the difference between a bridge and a fork."""
+ case_id = make_case(client)
+ person = add(client, case_id, "person", "Ivanov")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People", "type": "person", "fields": ["role"]},
+ ).json()
+ sheet = read_sheet(client, case_id, made["id"])
+ key = sheet["rows"][0][0]
+ sheet["rows"][0][2] = "driver"
+
+ answer = post_sheet(
+ client,
+ case_id,
+ made["id"],
+ "promote",
+ sheet,
+ keys=[key],
+ subject={"column": "Name", "type": "person", "fields": {"Role": "role"}},
+ )
+ assert answer.status_code == 200, answer.text
+ counts = answer.json()["entities"][0]["counts"]
+ assert (counts["make"], counts["update"]) == (0, 1)
+
+ from azimut.api.cases import get_case
+
+ people = [e for e in get_case(case_id).list_entities() if e["type"] == "person"]
+ assert len(people) == 1
+ assert people[0]["id"] == person["id"]
+ assert people[0]["attrs"]["role"] == "driver"
+
+
+def test_a_build_says_how_much_of_the_case_it_took(client):
+ case_id = make_case(client)
+ for index in range(4):
+ add(client, case_id, "person", f"Person {index}")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People", "type": "person", "limit": 2},
+ ).json()
+ assert (made["taken"], made["total"]) == (2, 4)
+
+
+def test_a_type_the_vocabulary_never_heard_of_builds_an_empty_worklist(client):
+ case_id = make_case(client)
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case", json={"title": "Nothing", "type": "invented"}
+ )
+ assert made.status_code == 200, made.text
+ assert made.json()["taken"] == 0
+ assert read_sheet(client, case_id, made.json()["id"])["rows"] == []
+
+
+def test_a_stored_field_lands_as_text_a_spreadsheet_can_read(client):
+ """A cell reading `["a", "b"]` is a cell nobody can filter on or hand over."""
+ assert fromcase_engine._cell(["Ivan", "Vanya"]) == "Ivan, Vanya"
+ assert fromcase_engine._cell(None) == ""
+ assert fromcase_engine._cell(True) == "YES"
+ assert fromcase_engine._cell(12) == "12"
+
+ case_id = make_case(client)
+ add(client, case_id, "person", "Ivanov", aliases="Ivan, Vanya")
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People", "type": "person", "fields": ["aliases"]},
+ ).json()
+ assert read_sheet(client, case_id, made["id"])["rows"][0][2] == "Ivan, Vanya"
+
+
+# -- a row moving up a floor ---------------------------------------------------
+
+
+def test_a_moved_row_lands_in_the_other_sheet_with_what_the_sidecar_held(client):
+ """An inbox, a worklist and a reference table at one schema: a row moves up a floor
+ once it has been worked out, and copying it by hand loses the colour, the link and
+ the record that it was already promoted."""
+ case_id = make_case(client)
+ inbox = import_sheet(
+ client, case_id, "Subject,Status\nQuai sud,to do\nPont nord,to do\n", "Inbox"
+ )
+ worklist = import_sheet(client, case_id, "Subject,Status\n", "Worklist")
+ key = inbox["rows"][0][0]
+ inbox["meta"]["colours"] = {key: "green"}
+
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["moved"] == 1 and answer.json()["dropped"] == []
+
+ left = read_sheet(client, case_id, inbox["id"])
+ assert [row[1] for row in left["rows"]] == ["Pont nord"]
+ assert left["meta"]["colours"] == {}
+
+ landed = read_sheet(client, case_id, worklist["id"])
+ assert [row[1] for row in landed["rows"]] == ["Quai sud"]
+ assert landed["meta"]["colours"] == {key: "green"}
+
+
+def test_a_column_the_destination_does_not_have_is_dropped_and_said(client):
+ """The destination's shape is its own: a move that grew it by three columns would be
+ an import wearing a different word. A silent loss reads as a clean move."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject,Status,Scratch\nQuai sud,to do,mine\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject,Status\n", "Worklist")
+
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[inbox["rows"][0][0]],
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["dropped"] == ["Scratch"]
+ assert read_sheet(client, case_id, worklist["id"])["columns"] == ["id", "Subject", "Status"]
+
+
+def test_a_promoted_row_that_moves_is_still_reachable_from_its_subject(client):
+ """Both sheets restate what they mention, so the edge follows the row."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\n", "Worklist")
+ key = inbox["rows"][0][0]
+ assert (
+ post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "promote",
+ inbox,
+ keys=[key],
+ subject={"column": "Subject", "type": "structure"},
+ ).status_code
+ == 200
+ )
+
+ inbox = read_sheet(client, case_id, inbox["id"])
+ answer = post_sheet(client, case_id, inbox["id"], "move", inbox, to=worklist["id"], keys=[key])
+ assert answer.status_code == 200, answer.text
+
+ made = case_entities(case_id, "structure")[0]["id"]
+ mentions = {link["from"] for link in case_links(case_id) if link["type"] == "mentions"}
+ assert mentions == {worklist["id"]}
+ assert read_sheet(client, case_id, worklist["id"])["meta"]["links"][key]["Subject"] == made
+
+
+def test_a_move_from_a_stale_grid_is_refused_like_any_other_write(client):
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\n", "Worklist")
+ inbox["stamp"] = "0-0"
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[inbox["rows"][0][0]],
+ )
+ assert answer.status_code == 409
+
+
+def test_a_move_whose_source_write_is_refused_leaves_no_row_in_both_sheets(client, monkeypatch):
+ """A duplicate is the one of the two failures an analyst cannot see.
+
+ The destination is written first, so a source that refuses — a spreadsheet holding the
+ CSV open, which is the case `SheetUnwritable` exists for — used to leave the rows over
+ there *and* in here, under another key in another sheet, while the route answered 409
+ and the grid went on showing that nothing had moved. The destination goes back to the
+ bytes it had now. `undo_move` reasons about the same window and reaches the same
+ conclusion in its own comment.
+ """
+ from azimut import layout
+ from azimut.api.cases import get_case
+ from azimut.engine import sheets as sheet_engine
+
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\nPont nord\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\nAlready here\n", "Worklist")
+ landing = get_case(case_id).resolve_inside(layout.sheet_rel("Worklist"))
+ before = landing.read_bytes()
+ real = sheet_engine.write_atomic
+
+ def refuse_the_source(path, text, *, encoding):
+ if path.name == "Inbox.csv":
+ raise sheet_engine.SheetUnwritable("could not write “Inbox.csv”: it is open in Excel")
+ return real(path, text, encoding=encoding)
+
+ monkeypatch.setattr(sheet_engine, "write_atomic", refuse_the_source)
+ answer = post_sheet(
+ client, case_id, inbox["id"], "move", inbox, to=worklist["id"], keys=[inbox["rows"][0][0]]
+ )
+
+ assert answer.status_code == 409, answer.text
+ assert landing.read_bytes() == before, "the destination is exactly as it was"
+ monkeypatch.setattr(sheet_engine, "write_atomic", real)
+ assert [row[1] for row in read_sheet(client, case_id, worklist["id"])["rows"]] == [
+ "Already here"
+ ]
+ assert [row[1] for row in read_sheet(client, case_id, inbox["id"])["rows"]] == [
+ "Quai sud",
+ "Pont nord",
+ ]
+
+
+def test_a_row_cannot_be_moved_into_the_sheet_it_is_already_in(client):
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\n", "Inbox")
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=inbox["id"],
+ keys=[inbox["rows"][0][0]],
+ )
+ assert answer.status_code == 422
+
+
+def test_a_mapping_lands_a_column_under_the_name_the_other_sheet_uses(client):
+ """`Adresse` into `Address` is one column spelled twice, and the name match alone
+ called it a loss. What the analyst lined up on screen is what lands."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Adresse,Statut\nQuai sud,à voir\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Address,Note\n", "Worklist")
+ key = inbox["rows"][0][0]
+ quai = add(client, case_id, "structure", "Quai sud")["id"]
+ inbox["meta"]["links"] = {key: {"Adresse": quai}}
+
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ mapping={"Adresse": "Address"},
+ )
+ assert answer.status_code == 200, answer.text
+ # Said before the press by the dialog, and answered again after it: `Statut` was
+ # pointed at nothing, so it is a drop like any other.
+ assert answer.json()["dropped"] == ["Statut"]
+
+ landed = read_sheet(client, case_id, worklist["id"])
+ assert landed["rows"][0][1] == "Quai sud" and landed["rows"][0][2] == ""
+ # The link is keyed by column as well as by row, so it follows the rename rather
+ # than pointing at a column that sheet does not have.
+ assert landed["meta"]["links"][key] == {"Address": quai}
+
+
+def test_a_column_left_out_of_the_mapping_stays_behind_even_when_the_names_match(client):
+ """The mapping is the whole answer where it is given: a column the analyst chose not
+ to send is not sent back in by the name match."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject,Scratch\nQuai sud,mine\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject,Scratch\n", "Worklist")
+
+ answer = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[inbox["rows"][0][0]],
+ mapping={"Subject": "Subject"},
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["dropped"] == ["Scratch"]
+ assert read_sheet(client, case_id, worklist["id"])["rows"][0][2] == ""
+
+
+def test_a_mapping_cannot_invent_a_column_or_pour_two_into_one(client):
+ """The destination's shape stays its own, and one column cannot hold two answers."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject,Alias\nQuai sud,QS\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\n", "Worklist")
+ key = inbox["rows"][0][0]
+
+ invented = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ mapping={"Subject": "Nowhere"},
+ )
+ assert invented.status_code == 422
+
+ both = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ mapping={"Subject": "Subject", "Alias": "Subject"},
+ )
+ assert both.status_code == 422
+ # Refused before either file was touched.
+ assert read_sheet(client, case_id, worklist["id"])["rows"] == []
+
+
+def test_a_move_can_be_put_back_from_both_ends(client):
+ """A move writes two files and the grid's undo stack reaches neither, which is what
+ made a mis-aimed one final."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject,Scratch\nQuai sud,mine\nPont nord,\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\n", "Worklist")
+ key = inbox["rows"][0][0]
+ inbox["meta"]["colours"] = {key: "green"}
+ before = read_sheet(client, case_id, inbox["id"])
+ before["meta"]["colours"] = {key: "green"}
+
+ moved = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ )
+ assert moved.status_code == 200, moved.text
+ landed = moved.json()["landed"]
+ assert landed == [key]
+
+ put_back = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move/undo",
+ {**before, "stamp": moved.json()["stamp"]},
+ to=worklist["id"],
+ keys=landed,
+ )
+ assert put_back.status_code == 200, put_back.text
+ assert put_back.json()["undone"] == 1
+
+ # The source as it stood, colour and dropped column included: the undo restores the
+ # table rather than replaying the move backwards.
+ back = read_sheet(client, case_id, inbox["id"])
+ assert [row[1] for row in back["rows"]] == ["Quai sud", "Pont nord"]
+ assert back["rows"][0][2] == "mine"
+ assert back["meta"]["colours"] == {key: "green"}
+ assert read_sheet(client, case_id, worklist["id"])["rows"] == []
+
+
+def test_an_undo_leaves_a_row_the_other_sheet_gained_in_between(client):
+ """Only the keys the move answered are taken out, so a row somebody added over there
+ afterwards is not collateral."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\nAlready here\n", "Worklist")
+ key = inbox["rows"][0][0]
+ before = read_sheet(client, case_id, inbox["id"])
+
+ moved = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[key],
+ )
+ assert moved.status_code == 200, moved.text
+ put_back = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move/undo",
+ {**before, "stamp": moved.json()["stamp"]},
+ to=worklist["id"],
+ keys=moved.json()["landed"],
+ )
+ assert put_back.status_code == 200, put_back.text
+ assert [row[1] for row in read_sheet(client, case_id, worklist["id"])["rows"]] == [
+ "Already here"
+ ]
+
+
+def test_an_undo_of_a_sheet_that_moved_on_is_refused_rather_than_overwriting_it(client):
+ """The analyst typed into the sheet after the move; the toast's button must not win
+ over what they typed."""
+ case_id = make_case(client)
+ inbox = import_sheet(client, case_id, "Subject\nQuai sud\n", "Inbox")
+ worklist = import_sheet(client, case_id, "Subject\n", "Worklist")
+ before = read_sheet(client, case_id, inbox["id"])
+ moved = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move",
+ inbox,
+ to=worklist["id"],
+ keys=[inbox["rows"][0][0]],
+ )
+ assert moved.status_code == 200, moved.text
+
+ stale = post_sheet(
+ client,
+ case_id,
+ inbox["id"],
+ "move/undo",
+ {**before, "stamp": "0-0"},
+ to=worklist["id"],
+ keys=moved.json()["landed"],
+ )
+ assert stale.status_code == 409
+ # Refused at the source, so the destination still holds the row it was sent.
+ assert len(read_sheet(client, case_id, worklist["id"])["rows"]) == 1
+
+
+def test_the_sheet_list_says_what_the_columns_are_called(client):
+ """The move's mapping needs the other sheets' headings, and reading every sheet in
+ the case whole to learn them is what this line is instead of."""
+ case_id = make_case(client)
+ import_sheet(client, case_id, "Subject,Status\nQuai sud,to do\n", "Inbox")
+ listed = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]
+ assert listed[0]["headings"] == ["id", "Subject", "Status"]
+ assert listed[0]["columns"] == 3
+
+
+def test_an_empty_fork_keeps_the_shape_and_leaves_the_rows(client):
+ """Which is the other thing an analyst wanted from a duplicate: the next floor up
+ starts as this floor's columns with nothing under them."""
+ case_id = make_case(client)
+ sheet = import_sheet(client, case_id, "Subject,Status\nQuai sud,to do\n")
+ sheet["meta"]["roles"] = {"Status": {"kind": "state", "values": ["to do", "done"]}}
+ sheet["meta"]["notes"] = {"Status": "where this one got to"}
+ sheet["meta"]["progress"] = "Status"
+ assert (
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": sheet["columns"],
+ "rows": sheet["rows"],
+ "meta": sheet["meta"],
+ "stamp": sheet["stamp"],
+ },
+ ).status_code
+ == 200
+ )
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/duplicate",
+ json={"title": "Worklist", "empty": True},
+ )
+ assert made.status_code == 200, made.text
+ forked = read_sheet(client, case_id, made.json()["id"])
+ assert forked["columns"] == ["id", "Subject", "Status"]
+ assert forked["rows"] == []
+ assert forked["meta"]["roles"]["Status"]["values"] == ["to do", "done"]
+ assert forked["meta"]["notes"] == {"Status": "where this one got to"}
+ assert forked["meta"]["progress"] == "Status"
+
+
+# -- a binder arriving whole ---------------------------------------------------
+
+
+def workbook(tabs):
+ """A real .xlsx, built here so the test reads the file format and not a stub."""
+ import io
+
+ from openpyxl import Workbook
+
+ book = Workbook()
+ book.remove(book.active)
+ for title, rows in tabs.items():
+ tab = book.create_sheet(title)
+ for row in rows:
+ tab.append(row)
+ buffer = io.BytesIO()
+ book.save(buffer)
+ return buffer.getvalue()
+
+
+def test_every_tab_of_a_workbook_lands_as_its_own_sheet(client):
+ """The binders arrive with five or six tabs. Asking the analyst to export each one to
+ CSV by hand is asking them not to bother, and the tab that gets skipped is the one
+ saying what the others mean."""
+ case_id = make_case(client)
+ data = workbook(
+ {
+ "Register": [["Unit", "On map"], ["3rd Brigade", "YES"]],
+ "Tracker": [["Unit", "Note"], ["1st Coy", "seen"]],
+ }
+ )
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 200, answer.text
+ made = answer.json()["sheets"]
+ assert [sheet["label"] for sheet in made] == ["Register", "Tracker"]
+
+ register = read_sheet(client, case_id, made[0]["id"])
+ assert register["columns"] == ["id", "Unit", "On map"]
+ assert register["rows"][0][1:] == ["3rd Brigade", "YES"]
+
+
+def test_a_tab_of_pasted_screenshots_is_named_rather_than_filed_as_an_empty_sheet(client):
+ """Two tabs of a timeline binder hold nothing but images, and two empty sheets nobody
+ asked for are worse than being told they were empty."""
+ case_id = make_case(client)
+ data = workbook({"Table": [["Unit"], ["3rd Brigade"]], "Proof of hour": []})
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(answer.json()["sheets"]) == 1
+ assert answer.json()["empty"] == ["Proof of hour"]
+
+
+def test_a_workbook_cell_becomes_the_words_a_person_would_read(client):
+ """A workbook has no words, only a serial number and a display format. ISO is the one
+ spelling that means the same thing in every locale, and Excel's every-number-is-a-
+ double is why a column of counts must not arrive reading `12.0`."""
+ from datetime import date, datetime
+
+ case_id = make_case(client)
+ data = workbook(
+ {
+ "Table": [
+ ["Day", "Moment", "Count", "Confirmed"],
+ [date(2026, 1, 3), datetime(2026, 1, 3, 6, 42), 12.0, True],
+ ]
+ }
+ )
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 200, answer.text
+ landed = read_sheet(client, case_id, answer.json()["sheets"][0]["id"])
+ assert landed["rows"][0][1:] == ["2026-01-03", "2026-01-03 06:42", "12", "YES"]
+
+
+def test_something_that_is_not_a_workbook_is_refused_rather_than_read(client):
+ case_id = make_case(client)
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("notes.txt", b"not a workbook", "text/plain")},
+ )
+ assert answer.status_code == 422
+
+
+def test_a_workbook_keeps_the_seconds_a_timecode_column_is_counted_in(client):
+ """ISO 8601 carries seconds and `parse_when` reads them, so cutting to `hh:mm` threw
+ away information both ends could handle.
+
+ The road this feeds is the one the spec sells as an absolute time *to the second*: a
+ timecode of `00:01:23` arriving as `00:01` moves a synchronised video by twenty three
+ seconds, and nothing on screen says so. A whole minute still writes no `:00`, so a
+ column of dates keeps the spelling somebody typed.
+ """
+ from datetime import datetime, time
+
+ from azimut.engine import sheetroles
+
+ case_id = make_case(client)
+ data = workbook(
+ {
+ "Table": [
+ ["Offset", "Moment", "Round"],
+ [time(0, 1, 23), datetime(2026, 1, 3, 1, 57, 33), datetime(2026, 1, 3, 6, 42)],
+ ]
+ }
+ )
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 200, answer.text
+ landed = read_sheet(client, case_id, answer.json()["sheets"][0]["id"])
+ assert landed["rows"][0][1:] == ["00:01:23", "2026-01-03 01:57:33", "2026-01-03 06:42"]
+
+ # And the round trip: what was written is what the two readers take back out.
+ assert sheetroles.parse_offset("00:01:23") == 83
+ assert sheetroles.parse_when("2026-01-03 01:57:33")["clock"] == "01:57:33"
+
+
+def test_a_workbook_says_which_tabs_and_cells_it_left_out(client, monkeypatch):
+ """Three ceilings, and each of them used to apply in silence.
+
+ A thirty thousand row export arriving as twenty thousand under a toast reading
+ "5 tabs filed" is a sheet that looks whole, with nothing on screen to suspect otherwise.
+ Lowered here rather than built at full size: the ceilings are the behaviour under test,
+ not the memory it takes to reach them.
+ """
+ from azimut.engine import sheetxlsx
+
+ monkeypatch.setattr(sheetxlsx, "MAX_TABS", 2)
+ monkeypatch.setattr(sheetxlsx, "MAX_ROWS", 2)
+ monkeypatch.setattr(sheetxlsx, "MAX_COLUMNS", 2)
+ case_id = make_case(client)
+ data = workbook(
+ {
+ "Wide": [["Unit", "Note", "Extra"], ["3rd", "seen", "dropped"]],
+ "Tall": [["Unit"], ["a"], ["b"], ["c"]],
+ "Third": [["Unit"], ["d"]],
+ }
+ )
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 200, answer.text
+ filed = answer.json()
+ assert filed["dropped"] == ["Third"], "the tab past the ceiling is named"
+ cut = {entry["title"]: entry for entry in filed["cut"]}
+ assert cut["Wide"]["columns"] == 2 and cut["Wide"]["rows"] is None
+ assert cut["Tall"]["rows"] == 2 and cut["Tall"]["columns"] is None
+
+
+def test_a_workbook_declaring_gigabytes_of_xml_is_refused_before_it_is_unzipped(client):
+ """An .xlsx is compressed XML, and `read_only` streams no part of its shared strings.
+
+ So the bound on the bytes received was not a bound at all: thirty two megabytes of
+ zeroes can declare gigabytes, and the reader would materialise them before the first
+ cell. The app already clamps images for this exact reason.
+ """
+ import zipfile
+
+ from azimut.engine import sheetxlsx
+
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("xl/sharedStrings.xml", b"\0" * (sheetxlsx.MAX_XLSX_UNZIPPED_BYTES + 1))
+ bomb = buffer.getvalue()
+ assert len(bomb) < sheetxlsx.MAX_XLSX_BYTES, "the point is that the compressed size passes"
+
+ case_id = make_case(client)
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", bomb, "application/vnd.ms-excel")},
+ )
+ assert answer.status_code == 422
+ assert "once unzipped" in answer.json()["detail"]
+
+
+def test_a_workbook_whose_tab_cannot_be_written_files_none_of_them(client, monkeypatch):
+ """All of the tabs or none.
+
+ A binder whose second tab refuses used to leave the first one standing *and* a sheet
+ with no file for the one that failed, so the retry landed a second copy of half a
+ binder beside a row nobody could open.
+ """
+ from azimut import layout
+ from azimut.api.cases import get_case
+ from azimut.engine import sheets as sheet_engine
+
+ case_id = make_case(client)
+ data = workbook({"One": [["Unit"], ["3rd"]], "Two": [["Unit"], ["1st"]]})
+ real = sheet_engine.write_atomic
+ tables: list[str] = []
+
+ def refuse_the_second(path, text, *, encoding):
+ if path.suffix == ".csv":
+ tables.append(path.name)
+ if len(tables) > 1:
+ raise sheet_engine.SheetUnwritable("could not write “Two.csv”: the disk is full")
+ return real(path, text, encoding=encoding)
+
+ monkeypatch.setattr(sheet_engine, "write_atomic", refuse_the_second)
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/import-xlsx",
+ files={"file": ("binder.xlsx", data, "application/vnd.ms-excel")},
+ )
+
+ assert answer.status_code == 409, answer.text
+ assert client.get(f"/api/cases/{case_id}/sheets").json()["sheets"] == []
+ folder = get_case(case_id).resolve_inside(layout.sheet_rel("One")).parent
+ assert not list(folder.glob("*.csv")), "and the file the first tab wrote is gone too"
+
+
+# -- a row and the file the library already downloaded -------------------------
+
+
+def test_a_row_finds_the_media_the_library_imported_from_the_same_page(client):
+ """A worklist's link column and the library's imports are the same pages twice, and
+ nothing joined them: the analyst had the video, and the row pointing at its post
+ could not say so."""
+ case_id = make_case(client)
+ video = add(client, case_id, "media", "clip.mp4", source_url="https://example.org/post/1")
+ sheet = import_sheet(
+ client, case_id, "Subject,Video\nFirst impact,https://example.org/post/1\n"
+ )
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/media",
+ json={"urls": ["https://example.org/post/1", "https://example.org/post/2"]},
+ )
+ assert answer.status_code == 200, answer.text
+ found = answer.json()["media"]
+ assert found["https://example.org/post/1"]["id"] == video["id"]
+ assert "https://example.org/post/2" not in found, "a page nobody downloaded answers nothing"
+
+
+def test_a_piece_attached_to_a_row_is_referenced_and_mentioned_never_copied(client):
+ """The screenshot of the message giving the hour, which lived in a tab of its own.
+ The entity is already the case's, so nothing new is filed and no artifact is owned
+ twice — and the edge is what makes it visible from the piece's own side."""
+ case_id = make_case(client)
+ shot = add(client, case_id, "media", "message.png")
+ sheet = import_sheet(client, case_id, "Subject\nFirst impact\n")
+ key = sheet["rows"][0][0]
+ sheet["meta"]["attachments"] = {key: [shot["id"]]}
+
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": sheet["columns"],
+ "rows": sheet["rows"],
+ "meta": sheet["meta"],
+ "stamp": sheet["stamp"],
+ },
+ )
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["meta"]["attachments"] == {key: [shot["id"]]}
+ # Ids and only ids in the sidecar — a label beside one goes stale the moment the
+ # entity is renamed — so the read answers what each of them is called. Without this
+ # the panel lists `e_58fea8e8f0`, and anything but a string is dropped in silence,
+ # which is how attaching came to look like it did nothing at all.
+ read = read_sheet(client, case_id, sheet["id"])
+ assert read["pieces"][shot["id"]] == {"label": "message.png", "type": "media"}
+ mentions = {
+ (link["from"], link["to"]) for link in case_links(case_id) if link["type"] == "mentions"
+ }
+ assert (sheet["id"], shot["id"]) in mentions
+
+
+# -- deleting a sheet that promoted --------------------------------------------
+
+
+def test_deleting_a_sheet_that_promoted_drops_its_edges_and_keeps_the_entities(client):
+ """The Trash gate this road needed and never had. A sheet says what is being checked
+ and the graph says what the case believes: throwing the worklist away is throwing the
+ worklist away, not the subjects it established."""
+ case_id = make_case(client)
+ sheet = import_sheet(client, case_id, "Subject\nQuai sud\nPont nord\n")
+ assert (
+ post_sheet(
+ client,
+ case_id,
+ sheet["id"],
+ "promote",
+ sheet,
+ keys=[row[0] for row in sheet["rows"]],
+ subject={"column": "Subject", "type": "structure"},
+ ).status_code
+ == 200
+ )
+ made = {e["id"] for e in case_entities(case_id, "structure")}
+ assert len(made) == 2
+
+ gone = client.delete(f"/api/cases/{case_id}/entities/{sheet['id']}")
+ assert gone.status_code == 200, gone.text
+
+ assert {e["id"] for e in case_entities(case_id, "structure")} == made
+ assert [link for link in case_links(case_id) if link["type"] == "mentions"] == []
diff --git a/tests/test_sheet_claims.py b/tests/test_sheet_claims.py
new file mode 100644
index 0000000..4319a0f
--- /dev/null
+++ b/tests/test_sheet_claims.py
@@ -0,0 +1,362 @@
+"""A column of hours, as dated statements about what the same press promoted.
+
+The binders hold a reasoning about a time and not a time: an established hour, an
+estimated one, the note saying how it was worked out, and — the shape nobody else has —
+ten videos carrying an offset against one shot that has yet to be dated. Copied into a
+`when` field that is one number and three lost columns, which is why the mode files a
+Claim.
+
+The engine is `engine/sheetclaims.py` and it was already general. What was missing was a
+screen saying the hours promote here, and these run through the one that now does: the
+subject column and the hours column are declared together, and the statement sees the
+subject the same press just made.
+"""
+
+from test_sheet_bridge import (
+ add,
+ case_entities,
+ case_links,
+ import_sheet,
+ make_case,
+ post_sheet,
+ read_sheet,
+)
+
+
+def timeline(client, case_id):
+ """A timeline binder's shape: an established hour, an estimated one, the note saying
+ how it was worked out, and the page it rests on."""
+ return import_sheet(
+ client,
+ case_id,
+ "Subject,Local time,Est. time,Note hour,Video\n"
+ "First impact,01:57,,the author gave me this time,https://example.org/a\n"
+ "Second impact,,02:05,between 02:00 and 02:10,\n"
+ "Third impact,,,no idea,\n",
+ title="Timeline",
+ )
+
+
+def date_rows(client, case_id, sheet, tail="promote", keys=None, **asked):
+ """The binder's whole declaration: what a row is, and what its hours state about it."""
+ return post_sheet(
+ client, case_id, sheet["id"], tail, sheet,
+ keys=[row[0] for row in sheet["rows"]] if keys is None else keys,
+ subject={"column": "Subject", "type": "structure"},
+ statement={
+ "when_column": "Local time",
+ "estimate_column": "Est. time",
+ "method_column": "Note hour",
+ "link_column": "Video",
+ "day": "2026-01-03",
+ **asked,
+ },
+ )
+
+
+def statements(answer):
+ """The statement layer of a pass, with its decisions under the key that layer used:
+ the plan calls them `rows` and the press calls them `plan`."""
+ layer = next(
+ entry for entry in answer.json()["entities"] if entry["mode"] == "statement"
+ )
+ return {**layer, "rows": layer.get("rows") or layer.get("plan") or []}
+
+
+# -- an hour, and the reasoning behind it --------------------------------------
+
+
+def test_a_column_of_hours_becomes_statements_and_not_a_field(client):
+ """A Claim carries what it is about, when it applies and what it rests on. A `when`
+ field would carry the first of those."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+
+ answer = date_rows(client, case_id, sheet, zone="Z")
+ assert answer.status_code == 200, answer.text
+ assert statements(answer)["counts"]["make"] == 2
+
+ claims = {e["label"]: e for e in case_entities(case_id, "claim")}
+ established = claims["First impact at 01:57"]
+ assert established["attrs"]["when"] == "2026-01-03T01:57:00Z"
+ assert established["attrs"]["confidence"] == "probable"
+ assert established["attrs"]["time_role"] == "occurred"
+ assert "the author gave me this time" in established["attrs"]["method"]
+ # It is about the subject the row points at, and it cites the page the row rests on.
+ edges = {(link["type"], link["from"]) for link in case_links(case_id)}
+ assert ("about", established["id"]) in edges
+ assert ("cites", established["id"]) in edges
+
+
+def test_the_plan_sees_the_subject_the_same_press_is_about_to_make(client):
+ """The screen declares both in one pass, so a plan reading only the sidecar on disk
+ would report every row "not in the case yet" and then the press would file all of
+ them. A plan the press contradicts is worse than no plan."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+
+ plan = date_rows(client, case_id, sheet, tail="promote/preview", zone="Z")
+ assert plan.status_code == 200, plan.text
+ said = statements(plan)
+ assert said["counts"]["make"] == 2
+ assert said["rows"][0]["subject_label"] == "First impact"
+ assert case_entities(case_id, "claim") == []
+
+ answer = date_rows(client, case_id, sheet, zone="Z")
+ assert answer.status_code == 200, answer.text
+ assert statements(answer)["counts"] == said["counts"], "the press does what it said"
+
+
+def test_an_estimate_is_recorded_one_rung_below_an_established_hour(client):
+ """The binders kept two columns because the difference matters, and a promotion that
+ filed both at one confidence would be the one that threw it away."""
+ case_id = make_case(client)
+ assert date_rows(client, case_id, timeline(client, case_id), zone="Z").status_code == 200
+
+ estimated = next(
+ e for e in case_entities(case_id, "claim") if e["label"].startswith("Second impact")
+ )
+ assert estimated["attrs"]["confidence"] == "possible"
+ assert "estimated in 'Est. time'" in estimated["attrs"]["method"]
+
+
+def test_a_note_saying_between_two_hours_becomes_an_interval(client):
+ """`between 02:00 and 02:10` is a more careful statement than a point, so it beats
+ one. A range of hours carries its zone because the profile can only give honest
+ bounds for one that has it — asked in those words rather than reported as a parse
+ failure the analyst cannot act on."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+
+ without = date_rows(
+ client, case_id, sheet, tail="promote/preview", keys=[sheet["rows"][1][0]],
+ link_column="",
+ )
+ assert without.status_code == 200, without.text
+ assert statements(without)["rows"][0]["reason"] == (
+ "a range of hours needs the time zone this column is written in"
+ )
+
+ assert date_rows(client, case_id, sheet, zone="Z").status_code == 200
+ estimated = next(
+ e for e in case_entities(case_id, "claim") if e["label"].startswith("Second impact")
+ )
+ assert estimated["attrs"]["when"] == "2026-01-03T02:00:00Z/2026-01-03T02:10:00Z"
+
+
+def test_a_row_with_no_readable_hour_is_left_alone_and_says_so(client):
+ case_id = make_case(client)
+ plan = date_rows(client, case_id, timeline(client, case_id), tail="promote/preview")
+ assert plan.status_code == 200, plan.text
+ third = statements(plan)["rows"][2]
+ assert third["action"] == "skip" and third["reason"] == "no time in these columns"
+
+
+def test_a_bare_clock_with_no_day_is_refused_rather_than_dated_to_today(client):
+ """The date is genuinely not in the file, and inventing one would invent evidence."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ plan = date_rows(
+ client, case_id, sheet, tail="promote/preview", keys=[sheet["rows"][0][0]], day="",
+ )
+ assert plan.status_code == 200, plan.text
+ said = statements(plan)["rows"][0]
+ assert said["action"] == "skip" and "not a time this can date" in said["reason"]
+
+
+def test_an_hour_stays_local_unless_the_column_says_otherwise(client):
+ """A column called `Local time` stamped `Z` moves the evidence by however far away
+ the event happened."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ assert date_rows(client, case_id, sheet).status_code == 200
+ local = next(e for e in case_entities(case_id, "claim") if e["label"].startswith("First"))
+ assert local["attrs"]["when"] == "2026-01-03T01:57:00", "no zone means local, not UTC"
+
+ again = read_sheet(client, case_id, sheet["id"])
+ assert date_rows(client, case_id, again, zone="Z").status_code == 200
+ utc = next(e for e in case_entities(case_id, "claim") if e["label"].startswith("First"))
+ assert utc["attrs"]["when"] == "2026-01-03T01:57:00Z"
+
+
+def test_dating_the_same_rows_twice_updates_the_statement(client):
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ assert date_rows(client, case_id, sheet, zone="Z").status_code == 200
+
+ answer = date_rows(client, case_id, read_sheet(client, case_id, sheet["id"]), zone="Z")
+ assert answer.status_code == 200, answer.text
+ counts = statements(answer)["counts"]
+ assert (counts["make"], counts["update"]) == (0, 2)
+ assert len(case_entities(case_id, "claim")) == 2
+
+
+def test_a_row_left_out_of_the_subject_layer_is_not_dated_either(client):
+ """A Claim is a statement about something the case holds. A row the analyst took out
+ of the plan is a row nothing was promoted for, so there is nothing honest to make a
+ statement about — and the second half of the pass has to see the first half's
+ decisions, not only its intentions."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ left_out = sheet["rows"][0][0]
+
+ answer = post_sheet(
+ client, case_id, sheet["id"], "promote", sheet,
+ keys=[row[0] for row in sheet["rows"]],
+ subject={"column": "Subject", "type": "structure", "skip": [left_out]},
+ statement={"when_column": "Local time", "day": "2026-01-03"},
+ )
+ assert answer.status_code == 200, answer.text
+ said = statements(answer)["rows"][0]
+ assert said["key"] == left_out
+ assert "not in the case yet" in said["reason"]
+ assert case_entities(case_id, "claim") == []
+
+
+def test_asking_for_both_a_column_of_times_and_an_anchor_is_refused(client):
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ answer = date_rows(
+ client, case_id, sheet, tail="promote/preview", keys=[],
+ offset_column="Local time",
+ )
+ assert answer.status_code == 422
+ assert "either from a column of times or from an anchor" in answer.json()["detail"]
+
+
+def test_a_day_written_the_binders_way_is_read_rather_than_pasted(client):
+ """The API takes a day from anywhere, and `03/01/2026` pasted straight into a
+ timestamp would be refused as one — with a message about the timestamp. Day-first,
+ like every other date this app reads; the picker's own ISO is unambiguous either
+ way."""
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ plan = date_rows(
+ client, case_id, sheet, tail="promote/preview", keys=[sheet["rows"][0][0]],
+ day="03/01/2026",
+ )
+ assert plan.status_code == 200, plan.text
+ assert statements(plan)["rows"][0]["when"] == "2026-01-03T01:57:00"
+
+ refused = date_rows(client, case_id, sheet, tail="promote/preview", keys=[], day="not a day")
+ assert refused.status_code == 422
+
+
+# -- an offset from an anchor --------------------------------------------------
+
+
+def synchro(client, case_id, at="2026-01-03T01:57:00Z"):
+ """Three videos lined up on one shot, the way a timeline binder holds them."""
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Subject,start synchro\nVideo A,-00:01:50\nVideo B,00:04:04\nVideo C,\n",
+ title="Synchro",
+ )
+ sheet["meta"]["roles"] = {"start synchro": {"kind": "offset", "anchor": "IGLA launch"}}
+ sheet["meta"]["anchors"] = {"IGLA launch": {"at": at}}
+ return sheet
+
+
+def anchor_rows(client, case_id, sheet, tail="promote"):
+ return post_sheet(
+ client, case_id, sheet["id"], tail, sheet,
+ keys=[row[0] for row in sheet["rows"]],
+ subject={"column": "Subject", "type": "structure"},
+ statement={"offset_column": "start synchro"},
+ )
+
+
+def test_a_dated_anchor_gives_every_offset_an_absolute_time(client):
+ """Nobody else does this. Ten videos carry an offset against one shot; the moment the
+ shot is dated, every one of them has a time to the second."""
+ case_id = make_case(client)
+ answer = anchor_rows(client, case_id, synchro(client, case_id))
+ assert answer.status_code == 200, answer.text
+ assert statements(answer)["counts"]["make"] == 2
+
+ when = {e["label"]: e["attrs"]["when"] for e in case_entities(case_id, "claim")}
+ assert when["Video A at -00:01:50"] == "2026-01-03T01:55:10Z"
+ assert when["Video B at 00:04:04"] == "2026-01-03T02:01:04Z"
+
+
+def test_an_inferred_time_is_a_statement_naming_its_anchor_and_never_a_cell(client):
+ """The ontology's own rule: an inference is a Claim. A timestamp written back into a
+ `when` cell would present a deduction as an observation."""
+ case_id = make_case(client)
+ sheet = synchro(client, case_id)
+ assert anchor_rows(client, case_id, sheet).status_code == 200
+
+ made = next(e for e in case_entities(case_id, "claim") if e["label"].startswith("Video A"))
+ assert made["attrs"]["confidence"] == "probable"
+ assert "IGLA launch" in made["attrs"]["method"]
+ # And the cell still holds exactly what the analyst typed.
+ saved = read_sheet(client, case_id, sheet["id"])
+ assert saved["rows"][0][saved["columns"].index("start synchro")] == "-00:01:50"
+
+
+def test_an_undated_anchor_dates_nothing_and_says_why(client):
+ """Relative order is usable before that, which is why an undated anchor is a normal
+ state rather than an error."""
+ case_id = make_case(client)
+ plan = anchor_rows(
+ client, case_id, synchro(client, case_id, at=""), tail="promote/preview"
+ )
+ assert plan.status_code == 200, plan.text
+ assert statements(plan)["rows"][0]["reason"] == "'IGLA launch' has no time yet"
+
+
+# -- what a statement rests on -------------------------------------------------
+
+
+def test_a_dated_statement_rests_on_the_pieces_its_row_carries(client):
+ """A URL is where the claim was published; an attached screenshot is the proof of the
+ hour somebody pasted into a tab. A statement rests on both."""
+ case_id = make_case(client)
+ shot = add(client, case_id, "media", "message.png")
+ sheet = import_sheet(client, case_id, "Subject,Local time\nFirst impact,01:57\n")
+ key = sheet["rows"][0][0]
+ sheet["meta"]["attachments"] = {key: [shot["id"]]}
+
+ answer = post_sheet(
+ client, case_id, sheet["id"], "promote", sheet,
+ keys=[key],
+ subject={"column": "Subject", "type": "structure"},
+ statement={"when_column": "Local time", "day": "2026-01-03"},
+ )
+ assert answer.status_code == 200, answer.text
+ claim = case_entities(case_id, "claim")[0]["id"]
+ cites = {link["to"] for link in case_links(case_id) if link["type"] == "cites"}
+ assert shot["id"] in cites and claim
+
+
+def test_a_citation_added_by_hand_survives_the_next_press(client):
+ """A press restates what the sheet says, not what the Claim knows.
+
+ The row's own connectors are the sheet's to reconcile — repointing a row must move
+ them rather than leave the statement pointing both ways. A source the analyst added
+ in the Claim's own panel is a different claim about the same statement, and nothing
+ holds a removed edge: re-filing one is a new id, a new date and a new author. So the
+ press restates its own and leaves theirs standing.
+ """
+ case_id = make_case(client)
+ sheet = timeline(client, case_id)
+ assert date_rows(client, case_id, sheet).status_code == 200
+ claim = case_entities(case_id, "claim")[0]
+ mine = add(client, case_id, "media", "screenshot.png")
+ stated = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": claim["id"], "to_id": mine["id"], "type": "cites"},
+ )
+ assert stated.status_code == 200, stated.text
+
+ again = date_rows(client, case_id, read_sheet(client, case_id, sheet["id"]))
+ assert again.status_code == 200, again.text
+
+ cites = [
+ link
+ for link in case_links(case_id)
+ if link["type"] == "cites" and link["from"] == claim["id"]
+ ]
+ assert mine["id"] in {link["to"] for link in cites}
+ assert {link["provenance"]["by"] for link in cites} == {"sheet", "user"}
diff --git a/tests/test_sheet_fixtures.py b/tests/test_sheet_fixtures.py
new file mode 100644
index 0000000..66475f5
--- /dev/null
+++ b/tests/test_sheet_fixtures.py
@@ -0,0 +1,120 @@
+"""The real binders, imported.
+
+`tests/fixtures/` holds the pathologies of three actual investigation binders, distilled
+into synthetic files (see the README there). This module is the gate that says the app
+reads them — as opposed to reading a table written to suit the parser, which is what every
+other sheet test necessarily does.
+
+Nothing here asserts a nice answer. It asserts that a semicolon export, a dead formula, a
+coordinate written three ways and a status column of eight invented words all **land**,
+because the alternative — refusing the file at the door — is the one failure mode a tool
+that replaces a spreadsheet cannot have.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from azimut.engine import sheets as sheet_engine
+
+FIXTURES = Path(__file__).parent / "fixtures"
+
+
+def read(name: str) -> str:
+ return (FIXTURES / name).read_text(encoding="utf-8")
+
+
+def imported(client, case_id: str, name: str, title: str) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/import", json={"title": title, "text": read(name)}
+ )
+ assert response.status_code == 200, response.text
+ return client.get(f"/api/cases/{case_id}/sheets/{response.json()['id']}").json()
+
+
+def case_id(client):
+ return client.post("/api/cases", json={"name": "Binders"}).json()["id"]
+
+
+def test_every_fixture_imports_without_being_refused(client, case_id):
+ """The one thing that must never happen: a real file turned away at the door."""
+ for path in sorted(FIXTURES.glob("*.csv")):
+ sheet = imported(client, case_id, path.name, path.stem)
+ assert sheet["rows"], f"{path.name} imported as an empty sheet"
+
+
+def test_a_european_export_lands_as_a_table(client, case_id):
+ sheet = imported(client, case_id, "binder-semicolon.csv", "Index")
+ assert sheet["columns"] == [
+ "id", "Date", "Nature", "Title", "Country", "Coordinates", "Geolocation",
+ ]
+ # The delimiter is guessed, the quoted comma stays inside its cell, and a coordinate
+ # holding the delimiter survives because the export quoted it.
+ assert sheet["rows"][0][3] == "Quay, south end"
+ assert sheet["rows"][0][5] == "48,8566; 2,3522"
+
+
+def test_a_dead_formula_is_a_value_like_any_other(client, case_id):
+ """`#REF!` is what a binder's own validation left behind. It is data now."""
+ sheet = imported(client, case_id, "binder-semicolon.csv", "Index")
+ assert sheet["rows"][1][5] == "#REF!"
+
+
+def test_a_worklist_with_no_status_column_keeps_its_gaps(client, case_id):
+ """Its progress is the fill rate of one column, which is why that reading exists."""
+ sheet = imported(client, case_id, "binder-worklist.csv", "Worklist")
+ coordinates = [row[sheet["columns"].index("Coordinates")] for row in sheet["rows"]]
+ assert len(coordinates) == 6
+ assert sum(1 for value in coordinates if value.strip()) == 5
+ assert "To be found" in coordinates and "-" in coordinates
+ # Three formats in one column, which is what the normalise action exists for.
+ assert any('°' in value for value in coordinates)
+
+
+def test_a_timeline_keeps_a_bare_clock_and_a_note_in_prose(client, case_id):
+ sheet = imported(client, case_id, "binder-timeline.csv", "Timeline")
+ at = sheet["columns"].index
+ assert sheet["rows"][0][at("Local time")] == "01:57"
+ assert sheet["rows"][1][at("Note hour")] == "between 2:00 and 2:10"
+ assert sheet["rows"][0][at("Equipments")] == "Buk-M2E, 2x S-125"
+ assert sheet["rows"][0][at("start synchro")] == "-00:01:50"
+
+
+def test_a_timeline_is_mostly_empty_and_that_is_the_normal_state(client, case_id):
+ """111 filled of 969 in the original. A tool that treats empty as broken is wrong."""
+ sheet = imported(client, case_id, "binder-timeline.csv", "Timeline")
+ filled = [row for row in sheet["rows"] if any(cell.strip() for cell in row[1:])]
+ assert len(filled) == 4
+ assert len(sheet["rows"]) > len(filled) * 2
+
+
+def test_a_status_column_of_eight_invented_words_lands_intact(client, case_id):
+ """A state vocabulary has to be built from these, not from four words we chose."""
+ sheet = imported(client, case_id, "binder-states.csv", "States")
+ at = sheet["columns"].index("Status")
+ assert [row[at] for row in sheet["rows"]] == [
+ "To do", "OK en cours", "To be found", "pass", "x", "-", "AFTER", "?", "",
+ ]
+
+
+def test_a_fixture_that_already_keys_its_rows_keeps_its_own_column(client, case_id):
+ sheet = imported(client, case_id, "binder-worklist.csv", "Worklist")
+ assert [row[0] for row in sheet["rows"]][:3] == ["r1", "r2", "r3"]
+ assert sheet["assigned"] is False
+
+
+def test_a_binder_round_trips_through_the_writer_unchanged(client, case_id):
+ """Import, save, re-read: the words a binder holds are the words it keeps."""
+ sheet = imported(client, case_id, "binder-worklist.csv", "Worklist")
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": sheet["columns"], "rows": sheet["rows"], "meta": sheet["meta"]},
+ )
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["rows"] == sheet["rows"]
+
+
+def test_the_delimiter_of_each_fixture_is_the_one_it_was_written_with(client, case_id):
+ assert sheet_engine.sniff_delimiter(read("binder-semicolon.csv")) == ";"
+ assert sheet_engine.sniff_delimiter(read("binder-worklist.csv")) == ","
diff --git a/tests/test_sheet_from_proofs.py b/tests/test_sheet_from_proofs.py
new file mode 100644
index 0000000..ad0bf0f
--- /dev/null
+++ b/tests/test_sheet_from_proofs.py
@@ -0,0 +1,336 @@
+"""A sheet built out of the proofs the case already holds, and kept level with them.
+
+The `geoloc` template and this shape carry almost the same columns and run in opposite
+directions, which is the confusion these tests exist to prevent. The template is
+**incoming**: addresses pasted in, pressed, downloaded, turned into proofs. This is
+**outgoing**: proofs the case already established, laid out as a table to read, filter
+and export. One holds the text of URLs, the other holds links to entities.
+
+What each test is really guarding:
+
+- one row per proof, and three links on it, so every proof, media and place is reachable
+ from the sheet and the sheet from each of them;
+- an incomplete proof still gets its row — a proof nobody placed is information, not an
+ error, and dropping it would let the build decide which proofs count;
+- the coordinates come off the graph on every read, so the sheet never holds a stale
+ copy of a place somebody moved;
+- pressing refresh adds and never removes, because the notes on a row are the analyst's;
+- a proof deleted afterwards leaves its row standing and says so in `In case`, which is
+ the one thing the ordinary dead-link sweep cannot express.
+"""
+
+from azimut.engine import sheetfromcase as fromcase_engine
+
+from test_sheet_bridge import add, make_case, post_sheet, read_sheet
+
+
+def get_case_(case_id):
+ from azimut.api.cases import get_case
+
+ return get_case(case_id)
+
+
+def link(case_id, from_id, to_id, type_):
+ get_case_(case_id).add_link(from_id, to_id, type_, by="test")
+
+
+def a_proof(client, case_id, label, *, media=None, place=None):
+ """A proof, and the two edges the outgoing shape reads off it."""
+ proof = add(client, case_id, "proof", label)["id"]
+ if media:
+ link(case_id, proof, media, "derived-from")
+ if place:
+ link(case_id, proof, place, "depicts")
+ return proof
+
+
+def build(client, case_id, title="My geolocations"):
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": title, "shape": "proofs"},
+ )
+ assert made.status_code == 200, made.text
+ return made.json()
+
+
+COLUMNS = ["id", "Title", "Source media", "Place", "Coordinates", "In case", "Status", "Notes"]
+
+
+# -- the shape ----------------------------------------------------------------
+
+
+def test_one_row_per_proof_carrying_its_media_and_its_place(client):
+ case_id = make_case(client)
+ media = add(client, case_id, "media", "GX010234")["id"]
+ place = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]
+ proof = a_proof(client, case_id, "Rooftop shot", media=media, place=place)
+
+ made = build(client, case_id)
+ assert made["taken"] == 1 and made["total"] == 1
+
+ sheet = read_sheet(client, case_id, made["id"])
+ assert sheet["columns"] == COLUMNS
+ assert sheet["rows"][0][1:4] == ["Rooftop shot", "GX010234", "Rooftop"]
+ # Filled off the graph rather than copied in by hand, which is what keeps it true.
+ assert sheet["rows"][0][4] == "47.10000, 37.50000"
+ assert sheet["rows"][0][5] == "YES"
+ # Every line is a proof that exists: `to do` on all of them would be a lie.
+ assert sheet["rows"][0][6] == "done"
+
+ key = sheet["rows"][0][0]
+ assert sheet["meta"]["links"][key] == {
+ "Title": proof,
+ "Source media": media,
+ "Place": place,
+ }
+ assert sheet["meta"]["built"][key] == proof
+ assert sheet["meta"]["progress"] == "Status"
+
+
+def test_the_three_case_columns_are_the_apps_and_the_two_work_columns_are_not(client):
+ case_id = make_case(client)
+ a_proof(client, case_id, "Rooftop shot")
+
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ roles = sheet["meta"]["roles"]
+ assert roles["Title"]["kind"] == "locked"
+ assert roles["Source media"]["kind"] == "locked"
+ assert roles["Place"]["kind"] == "locked"
+ assert roles["Coordinates"] == {"kind": "computed", "of": "point", "from": "Place"}
+ assert roles["In case"]["of"] == "in_case"
+ assert roles["Status"]["kind"] == "state"
+ # The analyst's own two carry no role the app writes through.
+ assert "Notes" not in roles
+
+
+def test_a_proof_with_no_place_still_gets_its_row(client):
+ case_id = make_case(client)
+ media = add(client, case_id, "media", "GX010234")["id"]
+ a_proof(client, case_id, "Unplaced", media=media)
+
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ assert sheet["rows"][0][1:5] == ["Unplaced", "GX010234", "", ""]
+ key = sheet["rows"][0][0]
+ assert "Place" not in sheet["meta"]["links"][key]
+
+
+def test_a_proof_with_no_media_still_gets_its_row(client):
+ case_id = make_case(client)
+ place = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]
+ a_proof(client, case_id, "Sourceless", place=place)
+
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ assert sheet["rows"][0][1:5] == ["Sourceless", "", "Rooftop", "47.10000, 37.50000"]
+ key = sheet["rows"][0][0]
+ assert "Source media" not in sheet["meta"]["links"][key]
+
+
+def test_a_proof_on_several_medias_takes_one_and_the_same_one_twice(client):
+ case_id = make_case(client)
+ proof = add(client, case_id, "proof", "Many sources")["id"]
+ # Filed in an order that is not the label order, so a build reading insertion order
+ # would answer differently from one reading the labels.
+ for label in ("zulu.mp4", "alpha.mp4", "mike.mp4"):
+ link(case_id, proof, add(client, case_id, "media", label)["id"], "derived-from")
+
+ first = read_sheet(client, case_id, build(client, case_id, "One")["id"])
+ second = read_sheet(client, case_id, build(client, case_id, "Two")["id"])
+ assert first["rows"][0][2] == "alpha.mp4"
+ assert second["rows"][0][2] == "alpha.mp4"
+
+
+def test_rows_are_ordered_by_the_proofs_label(client):
+ case_id = make_case(client)
+ for label in ("Zulu", "Alpha", "Mike"):
+ a_proof(client, case_id, label)
+
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ assert [row[1] for row in sheet["rows"]] == ["Alpha", "Mike", "Zulu"]
+
+
+def test_the_sheet_mentions_the_proof_the_media_and_the_place(client):
+ case_id = make_case(client)
+ media = add(client, case_id, "media", "GX010234")["id"]
+ place = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]
+ proof = a_proof(client, case_id, "Rooftop shot", media=media, place=place)
+
+ sheet_id = build(client, case_id)["id"]
+ mentioned = {
+ str(edge["to"])
+ for edge in get_case_(case_id).list_links()
+ if edge["type"] == "mentions" and str(edge["from"]) == sheet_id
+ }
+ assert mentioned == {proof, media, place}
+
+
+def test_the_generic_shape_is_untouched(client):
+ case_id = make_case(client)
+ add(client, case_id, "person", "Ivanov", role="driver")
+
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/from-case",
+ json={"title": "People", "type": "person", "fields": ["role"]},
+ )
+ assert made.status_code == 200, made.text
+ sheet = read_sheet(client, case_id, made.json()["id"])
+ assert sheet["columns"] == ["id", "Name", "Role", "Status", "Notes"]
+
+
+def test_a_generic_build_still_needs_a_type(client):
+ case_id = make_case(client)
+ refused = client.post(f"/api/cases/{case_id}/sheets/from-case", json={"title": "Nothing"})
+ assert refused.status_code == 422
+
+
+# -- kept level with the case -------------------------------------------------
+
+
+def test_refresh_files_the_proofs_added_since_the_build(client):
+ case_id = make_case(client)
+ a_proof(client, case_id, "Alpha")
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ a_proof(client, case_id, "Bravo")
+
+ answer = post_sheet(client, case_id, sheet["id"], "refresh", sheet)
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["added"] == 1
+ assert answer.json()["gone"] == 0
+
+ fresh = read_sheet(client, case_id, sheet["id"])
+ # Appended rather than re-sorted: inserting in place reshuffles a table somebody is
+ # working down, and the sheet's own sort is where order is decided.
+ assert [row[1] for row in fresh["rows"]] == ["Alpha", "Bravo"]
+
+
+def test_refresh_leaves_the_analysts_own_columns_alone(client):
+ case_id = make_case(client)
+ a_proof(client, case_id, "Alpha")
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ sheet["rows"][0][6] = "in progress"
+ sheet["rows"][0][7] = "waiting on the second angle"
+ saved = post_sheet(client, case_id, sheet["id"], "refresh", sheet)
+ assert saved.status_code == 200, saved.text
+
+ fresh = read_sheet(client, case_id, sheet["id"])
+ assert fresh["rows"][0][6] == "in progress"
+ assert fresh["rows"][0][7] == "waiting on the second angle"
+
+
+def test_refresh_restates_a_proof_renamed_since_without_filing_a_second_row(client):
+ case_id = make_case(client)
+ proof = a_proof(client, case_id, "Alpha")
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+
+ client.patch(f"/api/cases/{case_id}/entities/{proof}", json={"label": "Alpha, revised"})
+ answer = post_sheet(client, case_id, sheet["id"], "refresh", sheet)
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["added"] == 0
+
+ fresh = read_sheet(client, case_id, sheet["id"])
+ assert len(fresh["rows"]) == 1
+ assert fresh["rows"][0][1] == "Alpha, revised"
+
+
+def test_refresh_never_removes_a_row_and_says_the_proof_is_gone(client):
+ case_id = make_case(client)
+ kept = a_proof(client, case_id, "Alpha")
+ dropped = a_proof(client, case_id, "Bravo")
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ sheet_id = sheet["id"]
+ sheet["rows"][1][7] = "worth keeping"
+ assert post_sheet(client, case_id, sheet_id, "refresh", sheet).status_code == 200
+
+ client.delete(f"/api/cases/{case_id}/entities/{dropped}")
+
+ fresh = read_sheet(client, case_id, sheet_id)
+ assert len(fresh["rows"]) == 2
+ # The row keeps its text and the note nobody else wrote.
+ assert fresh["rows"][1][1] == "Bravo"
+ assert fresh["rows"][1][7] == "worth keeping"
+ # The link is swept, as it is on every sheet — and `built` is what survives to answer.
+ assert fresh["rows"][0][5] == "YES"
+ assert fresh["rows"][1][5] == "NO"
+ assert "Title" not in fresh["meta"]["links"].get(fresh["rows"][1][0], {})
+ assert fresh["meta"]["built"][fresh["rows"][1][0]] == dropped
+ assert fresh["meta"]["built"][fresh["rows"][0][0]] == kept
+
+ answer = post_sheet(client, case_id, sheet_id, "refresh", fresh)
+ assert answer.json()["gone"] == 1
+ assert answer.json()["added"] == 0
+
+
+def test_a_row_nobody_built_is_left_out_of_the_in_case_column(client):
+ case_id = make_case(client)
+ a_proof(client, case_id, "Alpha")
+ sheet = read_sheet(client, case_id, build(client, case_id)["id"])
+ # A line the analyst adds for a place not yet proven: it arrives as work to do, and
+ # the question `In case` asks does not apply to it.
+ sheet["rows"].append(["", "A place still to prove", "", "", "", "", "to do", ""])
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={k: sheet[k] for k in ("columns", "rows", "meta", "stamp")},
+ )
+ assert saved.status_code == 200, saved.text
+
+ fresh = read_sheet(client, case_id, sheet["id"])
+ assert fresh["rows"][1][5] == ""
+ assert fresh["rows"][1][6] == "to do"
+
+
+def test_the_coordinates_follow_a_place_that_moves(client):
+ case_id = make_case(client)
+ place = add(client, case_id, "place", "Rooftop", lat=47.1, lon=37.5)["id"]
+ a_proof(client, case_id, "Rooftop shot", place=place)
+ sheet_id = build(client, case_id)["id"]
+
+ client.patch(
+ f"/api/cases/{case_id}/entities/{place}",
+ json={"attrs": {"lat": 48.9, "lon": 24.7}},
+ )
+ fresh = read_sheet(client, case_id, sheet_id)
+ assert fresh["rows"][0][4] == "48.90000, 24.70000"
+
+
+def test_the_build_is_bounded(client):
+ assert fromcase_engine.MAX_FROM_CASE == 2_000
+
+
+def test_refresh_is_refused_on_a_sheet_that_was_not_built_this_way(client):
+ case_id = make_case(client)
+ a_proof(client, case_id, "Alpha")
+ # A binder that happens to hold a column called Title. Nothing stops that, and pouring
+ # every proof in the case into it would file rows of empty cells nobody asked for.
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/import",
+ json={"title": "Imported", "text": "Title,Notes\nSomething,\n"},
+ ).json()
+ sheet = read_sheet(client, case_id, made["id"])
+
+ refused = post_sheet(client, case_id, sheet["id"], "refresh", sheet)
+ assert refused.status_code == 422
+ assert "not built out of the case" in refused.text
+
+
+def test_two_sheets_built_the_same_way_are_told_apart(client):
+ """The name is the filename, suffix and all.
+
+ `target` steps a taken name to `-2` rather than refusing it, and the label used to keep
+ the name that was asked for — so building this shape twice left two rows reading `My
+ geolocations` in the list, backed by two different files, with nothing on screen to
+ say which was which.
+ """
+ case_id = make_case(client)
+ a_proof(client, case_id, "Alpha")
+
+ build(client, case_id)
+ build(client, case_id)
+ build(client, case_id)
+
+ listed = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]
+ assert [entry["title"] for entry in listed] == [
+ "My geolocations",
+ "My geolocations-2",
+ "My geolocations-3",
+ ]
+ # And each one is its own file, which is what the names now say.
+ assert len({entry["path"] for entry in listed}) == 3
diff --git a/tests/test_sheet_pass.py b/tests/test_sheet_pass.py
new file mode 100644
index 0000000..c944f63
--- /dev/null
+++ b/tests/test_sheet_pass.py
@@ -0,0 +1,839 @@
+"""One pass of a sheet into the case: every column's mode, and the edges between them.
+
+What the six older roads could not do between them. Each of them promoted one thing —
+rows, a column's words, a column of hours, a column of row names — and none could draw an
+edge, because an edge needs *two* columns and they only ever saw one. A binder's line says
+*this person, in that unit, with these sources*; the case used to get the nodes and lose
+the sentence.
+
+So these guard the two layers and the seam between them: the entities each mode makes,
+the edges the vocabulary allows between the columns that made them, one scope for the
+whole press, and all of it or none of it.
+"""
+
+from test_sheet_bridge import add, case_links, import_sheet, make_case, post_sheet, read_sheet
+
+
+def entities(case_id, entity_type):
+ from azimut.api.cases import get_case
+
+ return [e for e in get_case(case_id).list_entities() if e.get("type") == entity_type]
+
+
+def links_between(case_id, verb):
+ return [link for link in case_links(case_id) if link["type"] == verb]
+
+
+def roster(client, case_id, **roles):
+ """Two people, their units, and the pages they rest on."""
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Name,Unit,Source\n"
+ "Ivanov,3rd Brigade,https://example.org/a\n"
+ "Petrov,3rd Brigade,\n",
+ title="Roster",
+ )
+ if roles:
+ sheet["meta"] = {**sheet["meta"], "roles": roles}
+ return sheet
+
+
+def send(client, case_id, sheet, **asked):
+ return post_sheet(
+ client, case_id, sheet["id"], "promote", sheet,
+ keys=[row[0] for row in sheet["rows"]],
+ **asked,
+ )
+
+
+def preview(client, case_id, sheet, **asked):
+ return post_sheet(
+ client, case_id, sheet["id"], "promote/preview", sheet,
+ keys=[row[0] for row in sheet["rows"]],
+ **asked,
+ )
+
+
+# -- the two layers, in one press ---------------------------------------------
+
+
+def test_a_pass_makes_the_subject_the_values_and_the_edge_between_them(client):
+ """The whole point, in one press: two people, one unit, and each person a member of
+ it — where before this took three screens and drew no edge at all."""
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ addresses="Source",
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert answer.status_code == 200, answer.text
+
+ assert sorted(e["label"] for e in entities(case_id, "person")) == ["Ivanov", "Petrov"]
+ assert [e["label"] for e in entities(case_id, "organization")] == ["3rd Brigade"]
+ # One bookmark for the one page, and the page is a bookmark and never a file.
+ assert [e["attrs"]["url"] for e in entities(case_id, "bookmark")] == [
+ "https://example.org/a"
+ ]
+
+ unit = entities(case_id, "organization")[0]["id"]
+ members = {link["from"] for link in links_between(case_id, "member-of")}
+ assert members == {e["id"] for e in entities(case_id, "person")}
+ assert {link["to"] for link in links_between(case_id, "member-of")} == {unit}
+ assert answer.json()["joins"] == [
+ {"from": "Name", "to": "Unit", "verb": "member-of", "drawn": 2, "failed": []}
+ ]
+
+
+def test_the_plan_counts_both_layers_and_writes_nothing(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ plan = preview(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert plan.status_code == 200, plan.text
+ read = plan.json()
+
+ assert [layer["mode"] for layer in read["entities"]] == ["row", "value"]
+ assert read["entities"][0]["counts"]["make"] == 2, "two people"
+ assert read["entities"][1]["counts"]["make"] == 1, "and the one unit both are in"
+ assert read["joins"] == [{
+ "from": "Name", "to": "Unit", "verb": "member-of",
+ "label": "is a member of", "ratable": True, "rows": 2, "blocked": [],
+ }]
+ assert entities(case_id, "person") == [] and entities(case_id, "organization") == []
+
+
+def test_a_pair_the_vocabulary_has_no_verb_for_is_refused_at_the_door(client):
+ """The witness case. A person and a point have no verb between them, so the pair is
+ never offered — and asking for one anyway is refused before anything is written,
+ rather than putting a latitude on a person as a field nothing shows."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client, case_id, "Name,Coordinates\nIvanov,\"48.5, 35.1\"\n", title="People"
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ point="Coordinates",
+ )
+ assert answer.status_code == 422
+ assert "no way to put a person at a place" in answer.json()["detail"]
+ assert entities(case_id, "person") == []
+
+
+def test_a_join_the_registry_refuses_names_the_verbs_it_allows(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "part-of"}],
+ )
+ assert answer.status_code == 422
+ detail = answer.json()["detail"]
+ assert "joins a person to a organization by" in detail
+ assert "member-of" in detail and "part-of" not in detail.split("by")[1]
+ assert entities(case_id, "person") == []
+
+
+def test_a_cell_holding_three_values_draws_three_edges(client):
+ """`meta.values` already holds a meaning per word, so the fan is free."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Name,Unit\nIvanov,\"3rd Brigade, 5th Regiment, HQ\"\n",
+ title="Roster",
+ )
+ sheet["meta"] = {**sheet["meta"], "roles": {"Unit": {"kind": "choice", "multi": ","}}}
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "organization")) == 3
+ assert answer.json()["joins"][0]["drawn"] == 3
+ assert {
+ link["to"] for link in links_between(case_id, "member-of")
+ } == {e["id"] for e in entities(case_id, "organization")}
+
+
+def test_a_row_whose_end_is_ambiguous_keeps_its_entities_and_loses_its_edges(client):
+ """A name is not an identity: two units spelled the same are offered, never picked.
+ The row still becomes a person — losing that too would punish it twice."""
+ case_id = make_case(client)
+ add(client, case_id, "organization", "3rd Brigade")
+ add(client, case_id, "organization", "3rd Brigade")
+ sheet = roster(client, case_id)
+
+ plan = preview(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ ).json()
+ assert plan["joins"][0]["rows"] == 0
+ assert [entry["reason"] for entry in plan["joins"][0]["blocked"]] == [
+ "the case holds 2 of this name", "the case holds 2 of this name",
+ ]
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "person")) == 2, "the people are still made"
+ assert len(entities(case_id, "organization")) == 2, "and no third unit was minted"
+ assert links_between(case_id, "member-of") == []
+
+
+def test_a_second_press_adds_neither_an_entity_nor_an_edge(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+ declaration = {
+ "subject": {"column": "Name", "type": "person"},
+ "values": [{"column": "Unit", "type": "organization"}],
+ "addresses": "Source",
+ "joins": [{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ }
+
+ first = send(client, case_id, sheet, **declaration)
+ assert first.status_code == 200, first.text
+ before = len(case_links(case_id))
+
+ again = send(
+ client, case_id, read_sheet(client, case_id, sheet["id"]), **declaration
+ )
+ assert again.status_code == 200, again.text
+ assert len(entities(case_id, "person")) == 2
+ assert len(entities(case_id, "organization")) == 1
+ assert len(entities(case_id, "bookmark")) == 1
+ assert len(case_links(case_id)) == before
+
+
+def test_the_confidence_of_the_pass_lands_on_the_ratable_edges_and_no_others(client):
+ """`member-of` is a reading the analyst can be more or less sure of; the sheet's own
+ `mentions` edges are not, and a confidence on those would be an opinion nobody
+ holds."""
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ confidence=2,
+ )
+ assert answer.status_code == 200, answer.text
+ assert [link["confidence"] for link in links_between(case_id, "member-of")] == [2, 2]
+ assert all(
+ link.get("confidence") is None
+ for link in case_links(case_id)
+ if link["type"] == "mentions"
+ )
+
+
+def test_a_confidence_the_vocabulary_does_not_know_is_refused(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ confidence=9,
+ )
+ assert answer.status_code == 422
+ assert "not a confidence" in answer.json()["detail"]
+
+
+# -- one scope, and one refusal per confusion ---------------------------------
+
+
+def test_the_scope_is_the_ticked_rows_for_every_mode(client):
+ """The older column promotion read the whole table whatever was ticked, so a pass
+ whose halves disagreed about scope produced a count nobody could account for."""
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = post_sheet(
+ client, case_id, sheet["id"], "promote", sheet,
+ keys=[sheet["rows"][0][0]],
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert [e["label"] for e in entities(case_id, "person")] == ["Ivanov"]
+ assert answer.json()["joins"][0]["drawn"] == 1
+
+
+def test_a_column_cannot_be_both_the_subject_and_a_column_of_values(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Name", "type": "organization"}],
+ )
+ assert answer.status_code == 422
+ assert "cannot both be the subject and a column of values" in answer.json()["detail"]
+
+
+def test_a_join_needs_two_columns_that_designate_something(client):
+ """A column left on `ignore` designates nothing, so there is no end to draw to."""
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person"},
+ joins=[{"from": "Name", "to": "Source", "verb": "member-of"}],
+ )
+ assert answer.status_code == 422
+ assert "between two columns that designate something" in answer.json()["detail"]
+
+
+def test_addresses_and_statements_need_a_subject_to_be_about(client):
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+
+ without = send(client, case_id, sheet, addresses="Source")
+ assert without.status_code == 422
+ assert "needs the column naming what they are about" in without.json()["detail"]
+
+ dated = send(client, case_id, sheet, statement={"when_column": "Source"})
+ assert dated.status_code == 422
+ assert "needs the column naming what it is about" in dated.json()["detail"]
+
+
+def test_no_mode_of_this_screen_creates_anything_that_owns_a_file(client):
+ """The line between the two roads is the file, not the type. A `media`, a `capture`,
+ a `proof` and a `post` hold bytes; this screen holds a cell, so it does not offer
+ those types at all and an address becomes a bookmark."""
+ from azimut.engine import sheetpromote
+
+ offered = set(sheetpromote.promotable_types())
+ assert offered.isdisjoint({"media", "capture", "proof", "post", "inspect-session"})
+
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "media"},
+ )
+ assert answer.status_code == 422
+ assert "not a type a row can become" in answer.json()["detail"]
+
+
+# -- all of it, or none of it -------------------------------------------------
+
+
+def test_a_sheet_that_moved_under_the_analyst_leaves_the_case_untouched(client):
+ """The primitive earning its place. The entities are written, the save is then refused
+ because the file moved, and the way out of the batch takes the whole graph back —
+ where the older roads had to hand their ids to a compensating undo."""
+ case_id = make_case(client)
+ sheet = roster(client, case_id)
+ stale = {**sheet, "stamp": "0-0"}
+
+ answer = send(
+ client, case_id, stale,
+ subject={"column": "Name", "type": "person"},
+ values=[{"column": "Unit", "type": "organization"}],
+ joins=[{"from": "Name", "to": "Unit", "verb": "member-of"}],
+ )
+ assert answer.status_code == 409, answer.text
+ assert entities(case_id, "person") == []
+ assert entities(case_id, "organization") == []
+ assert links_between(case_id, "member-of") == []
+
+
+# -- the modes that used to be their own screens ------------------------------
+
+
+def test_a_point_column_joins_the_subject_by_the_verb_the_registry_gives(client):
+ """A structure is *sited at* its ground, and the verb is read out of the registry
+ rather than asked for. The place is deduplicated on the coordinates themselves."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Site,Coordinates\nBridge,\"48.5, 35.1\"\nQuay,\"48.5, 35.1\"\n",
+ title="Sites",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Site", "type": "structure"},
+ point="Coordinates",
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "place")) == 1, "two rows on one point pin one place"
+ assert len(links_between(case_id, "sited-at")) == 2
+
+
+def test_a_point_column_is_an_end_a_join_can_reach(client):
+ """A point is an end like any other column's, which is the one case the sidecar cannot
+ answer for: a cell holds coordinates, not the entity they became. So the row promotion
+ hands back the place it filed, and a *second* column can be joined to it.
+
+ Here the guard post stands on the ground the bridge was located on, and the analyst
+ said so once for the whole column."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Site,Annex,Coordinates\nBridge,Guard post,\"48.5, 35.1\"\n",
+ title="Sites",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Site", "type": "structure"},
+ values=[{"column": "Annex", "type": "structure"}],
+ point="Coordinates",
+ joins=[{"from": "Annex", "to": "Coordinates", "verb": "sited-at"}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "place")) == 1
+ assert answer.json()["joins"][0]["drawn"] == 1
+
+ place = entities(case_id, "place")[0]["id"]
+ sited = {link["from"] for link in links_between(case_id, "sited-at")}
+ assert sited == {e["id"] for e in entities(case_id, "structure")}
+ assert {link["to"] for link in links_between(case_id, "sited-at")} == {place}
+
+
+def test_a_column_the_registry_cannot_join_to_a_point_is_refused(client):
+ """The other half of the same rule: the vocabulary puts a structure on the ground and
+ a unit nowhere, so the pair is not offered and asking anyway is refused at the door."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Site,Unit,Coordinates\nBridge,3rd Brigade,\"48.5, 35.1\"\n",
+ title="Sites",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Site", "type": "structure"},
+ values=[{"column": "Unit", "type": "organization"}],
+ point="Coordinates",
+ joins=[{"from": "Unit", "to": "Coordinates", "verb": "sited-at"}],
+ )
+ assert answer.status_code == 422
+ assert "joins a organization to a place by nothing" in answer.json()["detail"]
+ assert entities(case_id, "structure") == []
+
+
+def test_a_column_of_hours_rides_along_as_a_statement(client):
+ """The engine was already general and what was missing was the screen. So the mode is
+ a passthrough, and what it proves is that the statement sees the subject the *same
+ press* promoted."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Subject,Local time,Note hour\nFirst impact,01:57,the author gave me this time\n",
+ title="Timeline",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Subject", "type": "structure"},
+ statement={
+ "when_column": "Local time",
+ "method_column": "Note hour",
+ "day": "2026-01-03",
+ },
+ )
+ assert answer.status_code == 200, answer.text
+ claims = entities(case_id, "claim")
+ assert len(claims) == 1
+ assert claims[0]["attrs"]["when"].startswith("2026-01-03T01:57")
+ subject = entities(case_id, "structure")[0]["id"]
+ assert [link["to"] for link in links_between(case_id, "about")] == [subject]
+
+
+def test_an_orbat_draws_its_edges_in_the_press_that_makes_its_units(client):
+ """What the threading of the sidecar buys. Row-to-row edges read what a row points at,
+ so this used to need two presses: promote the units, then draw the edges. In one pass
+ the modes run in dependency order and the edge layer sees what the subject layer just
+ wrote, so an order of battle lands in one press."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Unit,Links\n3rd Brigade,\n1st Coy,3rd Brigade\n2nd Coy,3rd Brigade\n",
+ title="ORBAT",
+ )
+ sheet["meta"] = {**sheet["meta"], "roles": {"Links": {"kind": "row", "of": "Unit"}}}
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Unit", "type": "organization"},
+ row_edges=[{"column": "Links", "verb": "part-of"}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "organization")) == 3
+ brigade = next(e for e in entities(case_id, "organization") if e["label"] == "3rd Brigade")
+ assert {link["to"] for link in links_between(case_id, "part-of")} == {brigade["id"]}
+ assert len(links_between(case_id, "part-of")) == 2
+
+
+def test_only_the_columns_mapped_onto_a_field_travel(client):
+ """A worklist's private notes have no business in the case's record of a subject, so a
+ column travels only where the analyst mapped it onto a declared field."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Name,Role,Private note\nIvanov,driver,do not call before Monday\n",
+ title="People",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Name", "type": "person", "fields": {"Role": "role"}},
+ )
+ assert answer.status_code == 200, answer.text
+ attrs = entities(case_id, "person")[0]["attrs"]
+ assert attrs["role"] == "driver"
+ assert "do not call before Monday" not in str(attrs)
+
+
+def test_the_grouped_case_stays_one_entity_with_a_point_per_row(client):
+ """Two lines of one cross-border event are one thing with two places, which row by row
+ is a twin nobody maintains. The mode is a case in this screen and its engine is
+ untouched — what is tested here is that the pass hands it through."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Site,Coordinates\nThe crossing,\"48.5, 35.1\"\nThe crossing,\"48.6, 35.2\"\n",
+ title="Crossing",
+ )
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Site", "type": "structure", "group": True},
+ point="Coordinates",
+ )
+ assert answer.status_code == 200, answer.text
+ assert len(entities(case_id, "structure")) == 1, "one subject"
+ assert len(entities(case_id, "place")) == 2, "and a place per row"
+ assert len(links_between(case_id, "sited-at")) == 2
+
+
+def test_a_column_of_words_becomes_one_entity_per_word_and_not_per_row(client):
+ """The grain of the value mode is the word. A tracker's four hundred rows hold forty
+ pieces of kit, and a mode working on rows would file `Buk-M2E, ZU23-2` as one thing
+ called exactly that."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Unit,Kit\n1st Bty,\"Buk-M2E, ZU23-2\"\n2nd Bty,\"Buk-M2E, S-125\"\n",
+ title="Tracker",
+ )
+ sheet["meta"] = {**sheet["meta"], "roles": {"Kit": {"kind": "choice", "multi": ", "}}}
+
+ answer = send(
+ client, case_id, sheet, values=[{"column": "Kit", "type": "equipment-type"}]
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["entities"][0]["counts"]["make"] == 3
+
+ kit = sorted(e["label"] for e in entities(case_id, "equipment-type"))
+ assert kit == ["Buk-M2E", "S-125", "ZU23-2"]
+ # What a word means is kept per column, because a cell holding three values cannot
+ # hold three links — and it is what makes the sheet mention all three.
+ meant = read_sheet(client, case_id, sheet["id"])["meta"]["values"]["Kit"]
+ assert set(meant) == {"Buk-M2E", "ZU23-2", "S-125"}
+ mentioned = {link["to"] for link in case_links(case_id) if link["type"] == "mentions"}
+ assert mentioned == set(meant.values())
+
+
+def test_a_single_valued_column_also_points_its_rows_at_what_it_made(client):
+ """Which is what the computed natures read: a link is per row, and a column with no
+ separator has exactly one answer per cell to give them."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client, case_id, "Unit,Parent\n1st Coy,3rd Brigade\n2nd Coy,3rd Brigade\n"
+ )
+
+ answer = send(client, case_id, sheet, values=[{"column": "Parent", "type": "organization"}])
+ assert answer.status_code == 200, answer.text
+ saved = read_sheet(client, case_id, sheet["id"])
+ made = entities(case_id, "organization")[0]["id"]
+ assert [cells.get("Parent") for cells in saved["meta"]["links"].values()] == [made, made]
+
+
+def test_a_word_the_case_holds_twice_is_offered_and_never_picked(client):
+ """A name is not an identity, and the rule does not weaken because there are forty of
+ them instead of one. The plan offers both and leaves the row alone."""
+ case_id = make_case(client)
+ add(client, case_id, "organization", "HQ")
+ add(client, case_id, "organization", "HQ")
+ sheet = import_sheet(client, case_id, "Unit,Parent\n1st Coy,HQ\n")
+
+ plan = preview(client, case_id, sheet, values=[{"column": "Parent", "type": "organization"}])
+ assert plan.status_code == 200, plan.text
+ said = plan.json()["entities"][0]["rows"][0]
+ assert said["action"] == "skip"
+ assert len(said["candidates"]) == 2
+ assert "holds 2" in said["reason"]
+
+
+def test_a_word_attached_to_what_the_case_holds_is_never_recreated(client):
+ """The half of the old *link these cells* screen that survives: the analyst answers
+ the plan's question, and the answer is read on the next look."""
+ case_id = make_case(client)
+ held = add(client, case_id, "organization", "HQ")
+ sheet = import_sheet(client, case_id, "Unit,Parent\n1st Coy,HQ\n")
+
+ answer = send(
+ client, case_id, sheet,
+ values=[{"column": "Parent", "type": "organization", "attach": {"HQ": held["id"]}}],
+ )
+ assert answer.status_code == 200, answer.text
+ assert [e["id"] for e in entities(case_id, "organization")] == [held["id"]]
+ assert read_sheet(client, case_id, sheet["id"])["meta"]["values"]["Parent"] == {
+ "HQ": held["id"]
+ }
+
+
+def test_a_place_is_made_from_coordinates_and_never_from_a_column_of_words(client):
+ """A place is its coordinates, and a word has none. Which is why the type is absent
+ from the value mode's own list rather than refused after it was picked."""
+ case_id = make_case(client)
+ sheet = import_sheet(client, case_id, "Unit,Parent\n1st Coy,HQ\n")
+
+ answer = preview(client, case_id, sheet, values=[{"column": "Parent", "type": "place"}])
+ assert answer.status_code == 422
+ assert "coordinates" in answer.json()["detail"]
+
+
+def test_a_group_keeps_the_first_answer_and_says_which_field_disagreed(client):
+ """Rows grouped on purpose differ in the detail — that is why there are two of them —
+ so refusing the group over it would refuse the shape it exists for."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client, case_id, "Title,Kind\nBridge strike,road bridge\nBridge strike,rail bridge\n"
+ )
+
+ plan = preview(
+ client, case_id, sheet,
+ subject={
+ "column": "Title", "type": "structure", "fields": {"Kind": "kind"}, "group": True,
+ },
+ )
+ assert plan.status_code == 200, plan.text
+ said = plan.json()["entities"][0]["rows"]
+ assert len(said) == 1 and said[0]["rows"] == 2
+ assert said[0]["attrs"]["kind"] == "road bridge"
+ assert said[0]["conflicts"] == ["Kind"]
+
+
+def test_the_plan_of_an_orbat_draws_the_edges_the_press_will_draw(client):
+ """The row-edges layer reads what a row points at, so a plan reading only the sidecar
+ on disk would report both edges without an end and then the press would draw them. A
+ plan the press contradicts is worse than no plan."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client,
+ case_id,
+ "Unit,Links\n3rd Brigade,\n1st Coy,3rd Brigade\n2nd Coy,3rd Brigade\n",
+ title="ORBAT",
+ )
+ sheet["meta"] = {**sheet["meta"], "roles": {"Links": {"kind": "row", "of": "Unit"}}}
+ declaration = {
+ "subject": {"column": "Unit", "type": "organization"},
+ "row_edges": [{"column": "Links", "verb": "part-of"}],
+ }
+
+ plan = preview(client, case_id, sheet, **declaration)
+ assert plan.status_code == 200, plan.text
+ edges = next(layer for layer in plan.json()["entities"] if layer["mode"] == "row-edges")
+ assert edges["counts"]["make"] == 2
+ assert entities(case_id, "organization") == []
+
+ answer = send(client, case_id, sheet, **declaration)
+ assert answer.status_code == 200, answer.text
+ assert len(links_between(case_id, "part-of")) == 2
+
+
+def test_a_row_naming_a_unit_nobody_promoted_is_said_rather_than_invented(client):
+ """There is no honest way to invent the entity a name refers to at the moment an edge
+ is being drawn to it — so the row that named it keeps its own entity and says why the
+ edge is missing."""
+ case_id = make_case(client)
+ sheet = import_sheet(client, case_id, "Unit,Links\n3rd Brigade,\n1st Coy,3rd Brigade\n")
+ sheet["meta"] = {**sheet["meta"], "roles": {"Links": {"kind": "row", "of": "Unit"}}}
+
+ plan = post_sheet(
+ client, case_id, sheet["id"], "promote/preview", sheet,
+ keys=[sheet["rows"][1][0]],
+ subject={"column": "Unit", "type": "organization"},
+ row_edges=[{"column": "Links", "verb": "part-of"}],
+ )
+ assert plan.status_code == 200, plan.text
+ edges = next(layer for layer in plan.json()["entities"] if layer["mode"] == "row-edges")
+ assert [row["action"] for row in edges["rows"]] == ["skip"]
+ assert "not in the case yet" in edges["rows"][0]["reason"]
+
+
+def test_a_name_reaching_no_row_is_reported_and_a_verb_outside_the_two_is_refused(client):
+ """A column of row names is not a column of words: it names *rows*, and a spelling
+ that reaches none of them is a broken reference and not a new entity."""
+ case_id = make_case(client)
+ sheet = import_sheet(
+ client, case_id, "Unit,Links\n3rd Brigade,\n1st Coy,3rd Bde\n", title="ORBAT"
+ )
+ sheet["meta"] = {**sheet["meta"], "roles": {"Links": {"kind": "row", "of": "Unit"}}}
+
+ plan = preview(
+ client, case_id, sheet,
+ subject={"column": "Unit", "type": "organization"},
+ row_edges=[{"column": "Links", "verb": "part-of"}],
+ )
+ assert plan.status_code == 200, plan.text
+ edges = next(layer for layer in plan.json()["entities"] if layer["mode"] == "row-edges")
+ broken = [row for row in edges["rows"] if row["action"] == "error"]
+ assert broken and "no single row is called '3rd Bde'" in broken[0]["reason"]
+
+ refused = preview(
+ client, case_id, sheet,
+ subject={"column": "Unit", "type": "organization"},
+ row_edges=[{"column": "Links", "verb": "owns"}],
+ )
+ assert refused.status_code == 422
+
+
+# -- a place, which is the one entity that is a number -------------------------
+
+
+def index_of_points(client, case_id):
+ """A geolocation index: a title, a country and the point that is the whole subject."""
+ return import_sheet(
+ client,
+ case_id,
+ "Title,Country,Coordinates\n"
+ "Quai sud,A,\"48.85, 2.35\"\n"
+ "Pont nord,B,\"48.90, 2.40\"\n",
+ title="Index",
+ )
+
+
+def test_a_column_of_coordinates_promoted_as_places_is_its_own_point(client):
+ """The shape a geolocation index actually has. The point *is* the entity, so asking
+ which column holds the coordinates once the coordinates column is the subject is a
+ question with one possible answer — and refusing the pass over it was refusing the
+ ordinary case."""
+ case_id = make_case(client)
+ sheet = index_of_points(client, case_id)
+
+ answer = send(client, case_id, sheet, subject={"column": "Coordinates", "type": "place"})
+ assert answer.status_code == 200, answer.text
+ points = sorted(
+ (e["attrs"]["lat"], e["attrs"]["lon"]) for e in entities(case_id, "place")
+ )
+ assert points == [(48.85, 2.35), (48.9, 2.4)]
+
+
+def test_a_place_is_named_by_the_column_that_is_its_subject(client):
+ """And that is how a point gets a name rather than a label reading `48.85, 2.35`: the
+ name column is the subject, the coordinates column is the point."""
+ case_id = make_case(client)
+ sheet = index_of_points(client, case_id)
+
+ answer = send(
+ client, case_id, sheet,
+ subject={"column": "Title", "type": "place"},
+ point="Coordinates",
+ )
+ assert answer.status_code == 200, answer.text
+ named = {e["label"]: (e["attrs"]["lat"], e["attrs"]["lon"]) for e in entities(case_id, "place")}
+ assert named == {"Quai sud": (48.85, 2.35), "Pont nord": (48.9, 2.4)}
+
+
+def test_a_press_reads_the_graph_a_fixed_number_of_times_whatever_the_row_count(client, monkeypatch):
+ """A walk of the whole catalog per row, inside the lock that holds every other writer.
+
+ `_place` built its own index of the places the case holds, and it was called once per
+ decision — so five hundred rows over twenty thousand entities materialised ten million
+ rows while the job worker waited on `busy_timeout` and then failed. The module states the
+ opposite rule everywhere else (`_labels_held` is commented "read once rather than once a
+ row"); this was the exception, and it was the one in the loop.
+ """
+ from azimut.api.cases import get_case
+ from azimut.workspace import Case
+
+ case_id = make_case(client)
+ rows = "".join(f'Point {n},"48.{80 + n}, 2.35"\n' for n in range(12))
+ sheet = import_sheet(client, case_id, f"Title,Coordinates\n{rows}", title="Index")
+ subject = {"column": "Title", "type": "structure"}
+
+ walks: list[int] = []
+ counting = {"on": True}
+ real = Case.list_entities
+
+ def counted(self, *args, **kwargs):
+ if counting["on"]:
+ walks.append(1)
+ return real(self, *args, **kwargs)
+
+ monkeypatch.setattr(Case, "list_entities", counted)
+ answer = send(client, case_id, sheet, subject=subject, point="Coordinates")
+ assert answer.status_code == 200, answer.text
+ counting["on"] = False
+
+ # Two: the labels the case already holds, and the places it already holds. Never a
+ # third per row — the twelve rows above would have been fourteen walks.
+ assert len(walks) <= 3, walks
+ assert len(entities(case_id, "place")) == 12
+ assert len(links_between(case_id, "sited-at")) == 12
+
+ # And the deduplication the walk used to give is still there, including between two
+ # rows of the same press: the index is added to as places are minted.
+ same = import_sheet(
+ client, case_id, 'Title,Coordinates\nOne,"48.99, 2.99"\nTwo,"48.99, 2.99"\n', title="Twice"
+ )
+ assert send(client, case_id, same, subject=subject, point="Coordinates").status_code == 200
+ at_one_point = [
+ e for e in get_case(case_id).list_entities()
+ if e.get("type") == "place" and e["attrs"].get("lat") == 48.99
+ ]
+ assert len(at_one_point) == 1, "two rows at one point are one place"
+
+
+def test_a_place_whose_subject_column_holds_names_still_asks_for_the_point(client):
+ """The door keeps the one refusal worth keeping: a column of names is not a column of
+ coordinates, and 468 rows each saying so is not an answer."""
+ case_id = make_case(client)
+ sheet = index_of_points(client, case_id)
+
+ answer = send(client, case_id, sheet, subject={"column": "Title", "type": "place"})
+ assert answer.status_code == 422
+ assert "a place needs the column holding its coordinates" in answer.json()["detail"]
+ assert entities(case_id, "place") == []
diff --git a/tests/test_sheet_proofs.py b/tests/test_sheet_proofs.py
new file mode 100644
index 0000000..fa4807f
--- /dev/null
+++ b/tests/test_sheet_proofs.py
@@ -0,0 +1,1096 @@
+"""A geolocation index into proofs: the one road out of a sheet that fetches bytes.
+
+Every other road from a sheet reads what the analyst typed. This one downloads what two
+of the columns point at, so what these guard is the pair of promises that separates it
+from the pass: **the plan touches the network never**, and **the press is atomic per row**
+— a dead link on line 12 costs line 12 and nothing else.
+
+The downloads are stubbed, deliberately and everywhere: what is under test is which rows
+become what, not yt-dlp. The one thing the stub is faithful about is the three shapes
+`download_url` really answers with — a held file, a login wall, a post with several
+attachments — because each of those is a different word beside a row.
+"""
+
+import base64
+import io
+import json
+import random
+import zlib
+
+from jobwait import job_result
+from PIL import Image
+
+from test_sheet_bridge import (
+ add,
+ case_entities,
+ case_links,
+ import_sheet,
+ make_case,
+ read_sheet,
+)
+
+INDEX = (
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Bridge strike,https://ex.org/clip,https://ex.org/pic,48.8566 2.3522,done,south bank\n"
+)
+
+
+def geoloc(client, case_id, text=INDEX, title="Geolocations"):
+ """A geolocation index at the template's own schema, roles and all."""
+ sheet = import_sheet(client, case_id, text, title=title)
+ sheet["meta"] = {
+ **sheet["meta"],
+ "roles": {
+ "Source media": {"kind": "url"},
+ "Geolocation proof": {"kind": "url"},
+ "Coordinates": {"kind": "latlon"},
+ "Status": {"kind": "state"},
+ },
+ }
+ return sheet
+
+
+DECLARED = {
+ "title": "Title",
+ "source": "Source media",
+ "proof": "Geolocation proof",
+ "point": "Coordinates",
+ "note": "Notes",
+ "status": "Status",
+}
+
+
+def build_body(sheet, **asked):
+ return {
+ "columns": sheet["columns"],
+ "rows": sheet["rows"],
+ "keys": [row[0] for row in sheet["rows"]],
+ **DECLARED,
+ **asked,
+ }
+
+
+def plan(client, case_id, sheet, **asked):
+ return client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/proofs/preview",
+ json=build_body(sheet, **asked),
+ )
+
+
+def press(client, case_id, sheet, **asked):
+ """Start the build and poll the job to its end, as the grid does."""
+ started = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/proofs", json=build_body(sheet, **asked)
+ )
+ assert started.status_code == 200, started.text
+ return job_result(client, started.json()["job_id"])
+
+
+def actions(answer):
+ return {row["key"]: row["action"] for row in answer["rows"]}
+
+
+def reasons(answer):
+ return {row["key"]: row["reason"] for row in answer["rows"]}
+
+
+# -- the plan, which downloads nothing ----------------------------------------
+
+
+def test_the_plan_answers_the_six_readings_of_a_row_without_fetching_anything(
+ client, monkeypatch
+):
+ """The table of what a row becomes, all six lines of it, in one plan.
+
+ The stub is a tripwire: a plan that reached the network would call it and the test
+ would say so. Reading a binder must never be an act that leaves the machine.
+ """
+ from azimut.engine import media as media_engine
+
+ def refuse(*args, **kwargs):
+ raise AssertionError("a plan must not download anything")
+
+ monkeypatch.setattr(media_engine, "download_url", refuse)
+
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Full,https://ex.org/clip,https://ex.org/pic,48.85 2.35,done,\n"
+ "Footage,https://ex.org/two,,48.86 2.36,done,\n"
+ "Point,,,48.87 2.37,done,\n"
+ "No source,,https://ex.org/pic2,48.88 2.38,done,\n"
+ "No point,https://ex.org/three,https://ex.org/pic3,,done,\n"
+ ",https://ex.org/four,https://ex.org/pic4,48.89 2.39,done,\n",
+ )
+ answer = plan(client, case_id, sheet)
+ assert answer.status_code == 200, answer.text
+ said = answer.json()
+
+ keys = [row[0] for row in sheet["rows"]]
+ assert [row["action"] for row in said["rows"]] == [
+ "make", "make", "make", "error", "error", "error",
+ ]
+ assert [row["writes"] for row in said["rows"][:3]] == [
+ "a proof, its two files and its point",
+ "the footage, posed on its point",
+ "a place",
+ ]
+ told = reasons(said)
+ assert told[keys[3]] == "a proof needs the footage it was read from"
+ assert told[keys[4]] == "a geolocation needs a point"
+ assert told[keys[5]] == "a proof needs a name"
+ assert said["counts"] == {"make": 3, "join": 0, "update": 0, "skip": 0, "error": 3}
+
+
+def test_a_row_ruled_out_is_left_out_and_the_plan_says_so(client):
+ """A status filter that hid rows silently would be the app deciding which lines of a
+ binder count. It says how many and which word, and the press can be told otherwise."""
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Kept,,,48.85 2.35,in progress,\n"
+ "Dropped,,,48.86 2.36,ruled out,\n",
+ )
+ said = plan(client, case_id, sheet).json()
+ assert [row["action"] for row in said["rows"]] == ["make", "skip"]
+ assert "ruled out" in said["rows"][1]["reason"]
+
+ # And the analyst can hand them back, which is the whole point of saying it out loud.
+ kept = plan(client, case_id, sheet, skip_states=[]).json()
+ assert [row["action"] for row in kept["rows"]] == ["make", "make"]
+
+
+def test_an_unreadable_or_impossible_position_is_a_refusal_not_a_guess(client):
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Prose,,,somewhere near the bridge,,\n"
+ "Transposed,,,148.85 2.35,,\n"
+ "Blank,,,,,\n",
+ )
+ said = plan(client, case_id, sheet).json()
+ assert [row["action"] for row in said["rows"]] == ["error", "error", "skip"]
+ told = [row["reason"] for row in said["rows"]]
+ assert "is not a position Azimut can read" in told[0]
+ assert "is not a position on the earth" in told[1]
+ assert told[2] == "nothing to build from"
+
+
+def test_two_rows_under_one_title_are_two_geolocations_over_one_file(client):
+ """A proof's name is its filename, so the second row would overwrite the first. The
+ single-post import refuses a name already taken; this refuses it for the same reason,
+ row by row, rather than inventing a suffix nobody asked for."""
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Same name,https://ex.org/a,https://ex.org/b,48.85 2.35,,\n"
+ "Same name,https://ex.org/c,https://ex.org/d,48.86 2.36,,\n",
+ )
+ said = plan(client, case_id, sheet).json()
+ assert [row["action"] for row in said["rows"]] == ["make", "error"]
+ assert "already" in said["rows"][1]["reason"]
+
+
+def test_a_hundred_and_one_rows_are_refused_at_the_door_with_what_is_left(client):
+ """A cap that only refuses reads as a breakdown. This one names the remainder, so it
+ reads as the queue it is."""
+ case_id = make_case(client)
+ rows = "".join(
+ f"Row {n},https://ex.org/{n},,48.{n:03d} 2.35,,\n" for n in range(101)
+ )
+ sheet = geoloc(
+ client, case_id, "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n" + rows
+ )
+ answer = plan(client, case_id, sheet)
+ assert answer.status_code == 422
+ detail = answer.json()["detail"]
+ assert "100 rows a press" in detail and "other 1" in detail
+
+ # And far past it, so the sentence is the engine's and not the model's "list too long".
+ many = plan(client, case_id, sheet, keys=[f"r{n}" for n in range(400)])
+ assert many.status_code == 422
+ assert "other 300" in many.json()["detail"]
+
+
+def test_the_door_refuses_a_declaration_that_names_one_column_twice(client):
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+ answer = plan(client, case_id, sheet, note="Title")
+ assert answer.status_code == 422
+ assert "only be one thing" in answer.json()["detail"]
+
+
+# -- the press, row by row ----------------------------------------------------
+
+
+def stub_downloads(monkeypatch, *, missing=(), gated=(), several=None, before=None):
+ """Stand in for yt-dlp, in the shapes it really answers with.
+
+ Answers with a held file by default; ``gated`` walls a URL until cookies are sent,
+ ``missing`` makes it unreachable, and ``several`` maps a URL to the attachments a post
+ carries — the picker's own items, each with its `kind`, answered until an ``index``
+ picks one. ``before`` runs on each call, which is what lets a test cancel a press while
+ a row is on the network. The list it returns is every call, with the index and the kind
+ it asked for, so a test can prove which attachment a slot went for.
+ """
+ from azimut.engine import media as media_engine
+
+ several = several or {}
+ calls = []
+
+ def download(
+ case, url, progress_hook=None, *, index=None, title=None, cookies=None, stage=None,
+ wants="",
+ ):
+ calls.append({"url": url, "cookies": bool(cookies), "index": index, "wants": wants})
+ if before is not None:
+ before(url)
+ if url in gated and not cookies:
+ return {"needs_auth": True}
+ if url in several and index is None:
+ return {"multi": True, "items": several[url]}
+ if url in missing:
+ raise RuntimeError("that address could not be reached")
+ url = f"{url}#{index}" if index is not None else url
+ path = stage / (url.rsplit("/", 1)[-1].replace("#", "-") + ".png")
+ # A different *picture* per address, not just different bytes. The library dedupes
+ # on sha256 and enrichment draws `same-image-as` between two pictures that look
+ # alike, so two flat rectangles would come back joined and the test would be about
+ # the deduplication rather than about the build.
+ noise = random.Random(zlib.crc32(url.encode()))
+ picture = Image.new("RGB", (32, 32))
+ picture.putdata([
+ (noise.randrange(256), noise.randrange(256), noise.randrange(256))
+ for _ in range(32 * 32)
+ ])
+ picture.save(path)
+ return {"staged": media_engine.stage_descriptor(path, {"type": "test", "url": url})}
+
+ monkeypatch.setattr(media_engine, "download_url", download)
+ return calls
+
+
+def edges(case_id):
+ """Every edge in the case as `from-type verb to-type`, which is what the constellation
+ is actually a claim about."""
+ from azimut.api.cases import get_case
+
+ case = get_case(case_id)
+ named = {entity["id"]: entity for entity in case.list_entities()}
+ return sorted(
+ f"{named[link['from']]['type']} {link['type']} {named[link['to']]['type']}"
+ for link in case_links(case_id)
+ if link["from"] in named and link["to"] in named
+ )
+
+
+def test_a_full_row_writes_the_whole_constellation(client, monkeypatch):
+ """The five edges an import writes by hand, written by a row of a binder instead.
+
+ `derived-from` is honest here and only here: the app fetched the file and composed the
+ proof, so it observed the derivation. A pass that merely read two addresses could not
+ state it.
+ """
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Bridge strike"]
+ assert len(case_entities(case_id, "media")) == 2
+ assert len(case_entities(case_id, "place")) == 1
+ # The proof composes the picture and rests on the footage: both are its own edges,
+ # so the whole geolocation hangs off one node.
+ assert edges(case_id) == [
+ "media depicts place",
+ "media depicts place",
+ "proof depicts place",
+ "proof derived-from media",
+ "proof derived-from media",
+ ]
+ # And the row says what it made, which is what the grid logs beside it.
+ made = result["rows"][0]["made"]
+ assert set(made) == {"source", "panel", "proof", "place"}
+
+ # The sidecar the browser writes back points each cell at what that cell produced, so
+ # the built row carries chips rather than four addresses nobody can follow.
+ key = sheet["rows"][0][0]
+ assert set(result["links"][key]) == {
+ "Title", "Source media", "Geolocation proof", "Coordinates",
+ }
+ assert result["links"][key]["Title"] == made["proof"]
+
+ # And the row's note is carried onto the proof it named, which is the only thing the
+ # Notes column is for on this road.
+ from azimut.api.cases import get_case
+
+ proof = case_entities(case_id, "proof")[0]
+ spec = json.loads(
+ get_case(case_id).resolve_inside(proof["attrs"]["spec"]).read_text(encoding="utf-8")
+ )
+ assert spec["panels"][0]["caption"] == "south bank"
+ assert spec["pov"] is False
+ assert spec["sources"] == ["https://ex.org/clip"]
+
+
+def test_pov_moves_the_two_files_onto_the_ground_instead_of_showing_it(client, monkeypatch):
+ """`located-at` says the camera was there and `depicts` says the frame shows it. The
+ proof itself never takes the first: it was composed, never recorded anywhere."""
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+
+ press(client, case_id, sheet, pov=True)
+ assert edges(case_id) == [
+ "media located-at place",
+ "media located-at place",
+ "proof depicts place",
+ "proof derived-from media",
+ "proof derived-from media",
+ ]
+
+
+def test_a_row_of_footage_alone_puts_the_media_on_its_point(client, monkeypatch):
+ """The middle line of the table: no published picture, so no proof — but the footage
+ and the ground it was filmed on are worth having on their own."""
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Clip,https://ex.org/clip,,48.85 2.35,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"]["built"] == 1
+ assert not case_entities(case_id, "proof")
+ assert len(case_entities(case_id, "media")) == 1
+ assert edges(case_id) == ["media depicts place"]
+
+
+def test_a_row_of_coordinates_alone_pins_a_place_and_fetches_nothing(client, monkeypatch):
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Just a point,,,48.85 2.35,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert calls == []
+ assert result["counts"]["built"] == 1
+ assert len(case_entities(case_id, "place")) == 1
+
+
+def test_two_rows_on_the_same_point_pin_one_place(client, monkeypatch):
+ """A place is the one entity in this app whose identity is a number. Two rows about
+ the same spot are one pin, or the map grows unreadable a row at a time."""
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "One,https://ex.org/a,https://ex.org/b,48.8566 2.3522,,\n"
+ "Two,https://ex.org/c,https://ex.org/d,48.8566 2.3522,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"]["built"] == 2
+ assert len(case_entities(case_id, "place")) == 1
+ assert len(case_entities(case_id, "proof")) == 2
+
+
+def test_a_row_whose_source_cannot_be_reached_writes_nothing_and_stops_nobody(
+ client, monkeypatch
+):
+ """Atomic per row, which is the opposite of the pass and for the opposite reason:
+ failing at row 2 is no reason to hand back rows 1 and 3."""
+ stub_downloads(monkeypatch, missing={"https://ex.org/dead"})
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "First,https://ex.org/a,https://ex.org/b,48.85 2.35,,\n"
+ "Broken,https://ex.org/dead,https://ex.org/c,48.86 2.36,,\n"
+ "Third,https://ex.org/d,https://ex.org/e,48.87 2.37,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 2, "restated": 0, "failed": 1}
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["First", "Third"]
+ # The broken row left nothing of itself, not even the picture it did reach.
+ assert len(case_entities(case_id, "media")) == 4
+ failed = next(row for row in result["rows"] if row["outcome"] == "failed")
+ assert "could not be reached" in failed["reason"]
+ assert failed["made"] == {}
+
+
+def test_a_row_behind_a_login_says_what_to_do_and_the_next_press_walks_through(
+ client, monkeypatch
+):
+ """A hundred login prompts being impossible, the wall is a word beside the row — and
+ the word says which of the two things it is, because a stored session has already been
+ tried by the time a row still comes back walled."""
+ calls = stub_downloads(monkeypatch, gated={"https://ex.org/gated"})
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Open,https://ex.org/a,https://ex.org/b,48.85 2.35,,\n"
+ "Walled,https://ex.org/gated,https://ex.org/c,48.86 2.36,,\n",
+ )
+
+ first = press(client, case_id, sheet)
+ assert first["counts"] == {"built": 1, "restated": 0, "failed": 1}
+ walled = next(row for row in first["rows"] if row["outcome"] == "failed")
+ assert walled["reason"] == "needs a login: pick your browser in Settings → Downloads"
+ assert not any(call["cookies"] for call in calls)
+
+ # Named once, it is used without being asked for again — no checkbox, no second press
+ # to arm it. The rows already built are not fetched a second time.
+ client.put(
+ "/api/settings/prefs", json={"download_cookies": {"source": "browser", "browser": "firefox"}}
+ )
+ calls.clear()
+ second = press(client, case_id, sheet)
+ assert second["counts"]["built"] == 1
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Open", "Walled"]
+ assert {call["url"] for call in calls} == {"https://ex.org/gated", "https://ex.org/c"}
+ assert any(call["cookies"] for call in calls), "the stored session was used on its own"
+
+
+def test_a_post_of_several_attachments_is_answered_by_what_the_slot_holds(
+ client, monkeypatch
+):
+ """The ordinary shape of the thing this road is for, not an exception.
+
+ A published geolocation is a picture and the post carries the footage beside it, so a
+ picker would fire on nearly every row — and a hundred rows cannot each raise one. The
+ slot's own kind is the answer: the panel takes the pictures, the source takes the clip.
+ """
+ calls = stub_downloads(
+ monkeypatch,
+ several={
+ "https://ex.org/album": [
+ {"index": 1, "kind": "video", "title": "the clip"},
+ {"index": 2, "kind": "image", "title": "the proof"},
+ ]
+ },
+ )
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Album,https://ex.org/clip,https://ex.org/album,48.85 2.35,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Album"]
+ # Asked twice: once to see what the post holds, once for the picture in it. The clip
+ # beside it is the footage, and the footage has a column of its own.
+ picks = [call for call in calls if call["url"] == "https://ex.org/album"]
+ assert [call["index"] for call in picks] == [None, 2]
+ assert {call["wants"] for call in picks} == {"image"}
+
+
+def test_a_source_cell_of_several_addresses_is_one_proof_resting_on_all_of_them(
+ client, monkeypatch
+):
+ """A geolocation states one point and rests on whatever was shot at it.
+
+ A thread hangs the photos and the clips off several posts, so the cell lists them —
+ there is no `+` in a spreadsheet, and a column that read only the first address filed
+ one file and left the rest of the case's own evidence outside it.
+
+ One proof, one point, and every file in its chain. The published picture stays one:
+ a row builds one proof, and a second picture would be a second.
+ """
+ import json
+
+ from azimut.api.cases import get_case
+
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Fuerte Tiuna,https://ex.org/photos https://ex.org/clip1 https://ex.org/clip2,"
+ "https://ex.org/pic,10.467771 -66.886490,,\n",
+ )
+
+ # The plan says what it is about to do, and it says it before a byte moves.
+ said = plan(client, case_id, sheet).json()
+ assert said["rows"][0]["action"] == "make"
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ media = case_entities(case_id, "media")
+ assert len(media) == 4 # three pieces of material and the picture composed of them
+
+ proof = case_entities(case_id, "proof")[0]
+ spec = json.loads(
+ get_case(case_id).resolve_inside(proof["attrs"]["spec"]).read_text(encoding="utf-8")
+ )
+ assert spec["sources"] == [
+ "https://ex.org/photos", "https://ex.org/clip1", "https://ex.org/clip2",
+ ]
+
+ links = case_links(case_id)
+ panel = next(one for one in media if one["attrs"].get("source_url") == "https://ex.org/pic")
+ material = {one["id"] for one in media} - {panel["id"]}
+ # The proof composes the picture and rests on the three files: one node the whole
+ # geolocation hangs off, rather than a media node the rest is strung from.
+ from_proof = {
+ link["to"] for link in links
+ if link["from"] == proof["id"] and link["type"] == "derived-from"
+ }
+ assert from_proof == material | {panel["id"]}
+ assert not [
+ link for link in links
+ if link["from"] == panel["id"] and link["type"] == "derived-from"
+ ]
+
+
+def test_a_post_that_quotes_another_gives_up_only_its_own(client, monkeypatch):
+ """The clip a post quotes belongs to the post it quotes.
+
+ yt-dlp's X extractor reads a tweet's media and the media of the tweet it quotes into
+ one list, and nothing in what comes back says which is which past the first. A press
+ that took both would file a stranger's video and, on a road that poses material on a
+ point, claim it was recorded there — a wrong statement where a missing one is merely
+ incomplete. A hundred rows cannot each be asked, so the rule takes what is vouched
+ for and leaves the rest to the two screens that have somebody in front of them.
+ """
+ calls = stub_downloads(
+ monkeypatch,
+ several={
+ "https://ex.org/quoting": [
+ {"index": 1, "kind": "video", "title": "the post's own clip", "own": True},
+ {"index": 2, "kind": "video", "title": "the quoted clip", "own": False},
+ ]
+ },
+ )
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Quito,https://ex.org/quoting,,-0.22 -78.51,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ assert len(case_entities(case_id, "media")) == 1
+ # Asked twice: once to see what the post holds, once for the one file it vouches for.
+ assert [call["index"] for call in calls] == [None, 1]
+
+
+def test_a_post_publishing_several_pictures_is_one_proof_of_several_panels(
+ client, monkeypatch
+):
+ """A published geolocation is often a set — the overhead, the ground shot, the match —
+ and keeping the first of three keeps a third of what was published.
+
+ They become the panels of one composition, which is what a proof already is. And the
+ set has no render: laying panels out is the composer's canvas, in the browser, so a
+ second renderer here would drift from it. It is filed without an export, borrowing the
+ first picture's thumbnail so it still draws in the graph.
+ """
+ import json
+
+ from azimut.api.cases import get_case
+
+ stub_downloads(
+ monkeypatch,
+ several={
+ "https://ex.org/set": [
+ {"index": 1, "kind": "image", "title": "overhead"},
+ {"index": 2, "kind": "image", "title": "ground"},
+ {"index": 3, "kind": "image", "title": "match"},
+ ]
+ },
+ )
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Published set,https://ex.org/clip,https://ex.org/set,48.85 2.35,,south bank\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ proofs_held = case_entities(case_id, "proof")
+ assert [entity["label"] for entity in proofs_held] == ["Published set"]
+ # Three pictures and the footage, and the proof composes the three.
+ assert len(case_entities(case_id, "media")) == 4
+
+ case = get_case(case_id)
+ spec = json.loads(case.resolve_inside(proofs_held[0]["attrs"]["spec"]).read_text("utf-8"))
+ assert len(spec["panels"]) == 3
+ # The note is one sentence about the proof, not a caption per picture.
+ assert [panel["caption"] for panel in spec["panels"]] == ["south bank", "", ""]
+
+ attrs = proofs_held[0]["attrs"]
+ assert "path" not in attrs, "a set has no render, so it has no export to point at"
+ assert attrs.get("thumb"), "and it borrows the first picture's, so it is not a blank node"
+
+ # The proof composes all three and rests on the footage: four edges of its own, and
+ # that closure is what makes the point reach every one of them.
+ from test_sheet_bridge import case_links
+
+ named = {entity["id"]: entity for entity in case.list_entities()}
+ chain = [
+ link for link in case_links(case_id)
+ if link["type"] == "derived-from" and named[link["from"]]["type"] == "proof"
+ ]
+ assert len(chain) == 4
+
+
+def test_a_post_holding_nothing_of_the_kind_is_a_row_to_do_by_hand(client, monkeypatch):
+ """Where the rule stops being one a rule can make. A post of four videos has no
+ published picture in it, and guessing which frame is the proof is not the app's call."""
+ stub_downloads(
+ monkeypatch,
+ several={
+ "https://ex.org/album": [
+ {"index": 1, "kind": "video", "title": "one"},
+ {"index": 2, "kind": "video", "title": "two"},
+ ]
+ },
+ )
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Album,https://ex.org/clip,https://ex.org/album,48.85 2.35,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"]["failed"] == 1
+ assert result["rows"][0]["reason"] == (
+ "that post holds 2 files and no image, so pick one by hand"
+ )
+ assert not case_entities(case_id, "proof")
+
+
+def test_the_footage_slot_takes_the_stills_rather_than_refusing_the_row(client, monkeypatch):
+ """The footage is only *usually* a video. A photograph taken on the spot is material
+ too, so a preference is not a reason to lose the row — where a proof composed of no
+ picture really is nothing to compose.
+
+ And a post carrying two of them carries two things that were shot there. The panel
+ road already answers a set by taking all of it, for the reason that keeping the first
+ of two keeps half; the material road has no reason to answer differently, and a
+ hundred rows cannot each be asked which photograph counted.
+ """
+ calls = stub_downloads(
+ monkeypatch,
+ several={
+ "https://ex.org/stills": [
+ {"index": 1, "kind": "image", "title": "on the spot"},
+ {"index": 2, "kind": "image", "title": "and again"},
+ ]
+ },
+ )
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Stills,https://ex.org/stills,,48.85 2.35,,\n",
+ )
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ media = case_entities(case_id, "media")
+ assert len(media) == 2
+ assert [call["index"] for call in calls] == [None, 1, 2]
+ # Both of them state the point, or the second would be in the case and off the map.
+ place = case_entities(case_id, "place")[0]
+ posed = {
+ link["from"]
+ for link in case_links(case_id)
+ if link["to"] == place["id"] and link["type"] in ("located-at", "depicts")
+ }
+ assert {one["id"] for one in media} <= posed
+
+
+def test_a_second_press_refreshes_the_point_and_the_note_and_downloads_nothing(
+ client, monkeypatch
+):
+ """What makes a build safe to press twice, and it is the case that remembers rather
+ than the sheet: a proof is found under the name it was saved as."""
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+ press(client, case_id, sheet)
+ assert len(calls) == 2
+ calls.clear()
+
+ moved = read_sheet(client, case_id, sheet["id"])
+ moved["meta"] = sheet["meta"]
+ row = list(moved["rows"][0])
+ row[moved["columns"].index("Coordinates")] = "50.4501 30.5234"
+ row[moved["columns"].index("Notes")] = "second reading"
+ moved["rows"] = [row]
+
+ said = plan(client, case_id, moved).json()
+ assert [entry["action"] for entry in said["rows"]] == ["update"]
+
+ result = press(client, case_id, moved)
+ assert calls == []
+ assert result["counts"] == {"built": 0, "restated": 1, "failed": 0}
+ assert len(case_entities(case_id, "proof")) == 1
+ assert len(case_entities(case_id, "media")) == 2
+
+ # The proof states the new point and nothing states the old one any more: a corrected
+ # geolocation is a withdrawal, not a second claim.
+ places = case_entities(case_id, "place")
+ standing = [
+ place for place in places if any(link["to"] == place["id"] for link in case_links(case_id))
+ ]
+ assert len(standing) == 1
+ assert round(standing[0]["attrs"]["lat"], 4) == 50.4501
+
+ from azimut.api.cases import get_case
+
+ proof = case_entities(case_id, "proof")[0]
+ spec = get_case(case_id).resolve_inside(proof["attrs"]["spec"]).read_text(encoding="utf-8")
+ assert "second reading" in spec
+
+
+def test_a_cancelled_press_keeps_the_rows_it_finished_and_leaves_no_half_row(
+ client, monkeypatch
+):
+ """Cancelling is a promise about the row in flight: its bytes are held outside the
+ case until the last moment, so dropping them leaves nothing to clean up."""
+ import threading
+
+ held = threading.Event()
+ reached = threading.Event()
+
+ def wait(url):
+ if url == "https://ex.org/slow":
+ reached.set()
+ held.wait(10)
+
+ stub_downloads(monkeypatch, before=wait)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Done first,https://ex.org/a,https://ex.org/b,48.85 2.35,,\n"
+ "Interrupted,https://ex.org/slow,https://ex.org/c,48.86 2.36,,\n"
+ "Never started,https://ex.org/d,https://ex.org/e,48.87 2.37,,\n",
+ )
+
+ started = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/proofs", json=build_body(sheet)
+ )
+ job_id = started.json()["job_id"]
+ assert reached.wait(10)
+ assert client.post(f"/api/jobs/{job_id}/cancel").json() == {"stopped": True}
+ held.set()
+ result = job_result(client, job_id)
+
+ assert result["stopped"] is True
+ assert result["counts"] == {"built": 1, "restated": 0, "failed": 0}
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Done first"]
+ # The interrupted row downloaded two files and filed neither.
+ assert len(case_entities(case_id, "media")) == 2
+
+
+def test_the_rows_the_analyst_put_aside_are_not_built(client, monkeypatch):
+ """The plan is read, not obeyed. A row the analyst leaves out stays out."""
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Wanted,https://ex.org/a,https://ex.org/b,48.85 2.35,,\n"
+ "Not now,https://ex.org/c,https://ex.org/d,48.86 2.36,,\n",
+ )
+ keys = [row[0] for row in sheet["rows"]]
+
+ result = press(client, case_id, sheet, skip=[keys[1]])
+ assert result["counts"]["built"] == 1
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Wanted"]
+
+
+def test_a_bookmark_of_that_page_is_not_the_footage(client, monkeypatch):
+ """A press before this one may have filed the address as a `bookmark` — a page, not a
+ file. Reading it as the footage would leave the row believing it holds a video nobody
+ ever downloaded, so the build fetches it and the case ends up holding both."""
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ add(client, case_id, "bookmark", "ex.org/clip", url="https://ex.org/clip",
+ source_url="https://ex.org/clip")
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Clip,https://ex.org/clip,,48.85 2.35,,\n",
+ )
+
+ assert [row["action"] for row in plan(client, case_id, sheet).json()["rows"]] == ["make"]
+ press(client, case_id, sheet)
+ assert [call["url"] for call in calls] == ["https://ex.org/clip"]
+ assert len(case_entities(case_id, "media")) == 1
+
+
+def test_a_second_press_over_footage_alone_restates_its_point_without_fetching(
+ client, monkeypatch
+):
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(
+ client,
+ case_id,
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Clip,https://ex.org/clip,,48.85 2.35,,\n",
+ )
+ press(client, case_id, sheet)
+ calls.clear()
+
+ assert [row["action"] for row in plan(client, case_id, sheet).json()["rows"]] == ["join"]
+ result = press(client, case_id, sheet)
+ assert calls == []
+ assert result["counts"] == {"built": 0, "restated": 1, "failed": 0}
+ assert len(case_entities(case_id, "media")) == 1
+ assert len(case_links(case_id)) == 1
+
+
+CROSS_BORDER = (
+ "Title,Source media,Geolocation proof,Coordinates,Status,Notes\n"
+ "Border attack (2),https://ex.org/clip,https://ex.org/pub,\"37.149836, 69.355336\",,AFGHANISTAN\n"
+ "Border attack,https://ex.org/clip,https://ex.org/pub,\"37.152061, 69.350817\",,TAJIKISTAN\n"
+)
+
+
+def test_one_published_proof_seen_at_two_points_is_one_proof(client, monkeypatch):
+ """The binder's cross-border shape: two lines because it happened at two places, and
+ one picture published about it.
+
+ Filing it row by row put two exports of one image in the case under two names and
+ fetched both files twice. And a proof **concludes on one point** by design — reopening
+ it with other coordinates withdraws the first — so the second point cannot be a second
+ conclusion. It is the material that is seen at both, which is what the material is for.
+ """
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id, CROSS_BORDER)
+
+ said = plan(client, case_id, sheet).json()
+ assert [row["action"] for row in said["rows"]] == ["make", "join"]
+ assert said["rows"][1]["writes"] == "its point, on the proof the row above builds"
+ assert "the same published proof" in said["rows"][1]["reason"]
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 1, "restated": 1, "failed": 0}
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == ["Border attack (2)"]
+ assert len(case_entities(case_id, "place")) == 2
+ # Two downloads, not four: the second row has nothing to fetch that the first did not.
+ assert len(calls) == 2
+
+ # The published proof is what establishes *both* positions — that is what writing two
+ # lines about one picture says — so it reaches both. Only the composer's own field
+ # still states one, and only the composer's own edges are reconciled by a later save.
+ assert edges(case_id) == [
+ "media depicts place",
+ "media depicts place",
+ "media depicts place",
+ "media depicts place",
+ "proof depicts place",
+ "proof depicts place",
+ "proof derived-from media",
+ "proof derived-from media",
+ ]
+ # And the second row's cell still points at the proof it is about, so the line reads as
+ # part of it rather than as a stray point.
+ second = sheet["rows"][1][0]
+ assert set(result["links"][second]) == {"Title", "Source media", "Geolocation proof",
+ "Coordinates"}
+
+
+def test_a_second_point_whose_first_row_never_built_says_so_instead_of_passing(
+ client, monkeypatch
+):
+ """A row that puts its point on nothing is not a row that succeeded.
+
+ The join reads the proof and the media the row above filed, and it skipped whatever was
+ absent — so when the first row failed on a dead link or a login wall, the second wrote a
+ place, attached nothing to it, and reported `restated`. The grid logged it as done and no
+ later press took it again: the second position of a cross-border strike disappeared
+ without a red line, on the very shape the join exists for.
+ """
+ stub_downloads(monkeypatch, missing=["https://ex.org/pub"])
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id, CROSS_BORDER)
+
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 0, "restated": 0, "failed": 2}
+ assert result["rows"][1]["reason"] == "the row this one joins did not build"
+ assert result["rows"][1]["made"] == {}
+ # And no bare pin is left standing for a row that produced nothing else.
+ assert case_entities(case_id, "place") == []
+
+ # The ordinary case is untouched: with the first row built, the second restates.
+ stub_downloads(monkeypatch)
+ again = press(client, case_id, sheet)
+ assert again["counts"] == {"built": 1, "restated": 1, "failed": 0}
+
+
+def test_a_title_corrected_since_moves_the_proof_instead_of_twinning_it(client, monkeypatch):
+ """A built proof is identified by **where it was published**, never by its name.
+
+ The name is a cell somebody edits. Keyed on it, a corrected title built a second proof
+ beside the first and left the old one standing under the old name — which is the one
+ duplicate nobody notices, since both look right in the list.
+ """
+ calls = stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+ press(client, case_id, sheet)
+ calls.clear()
+
+ moved = read_sheet(client, case_id, sheet["id"])
+ moved["meta"] = sheet["meta"]
+ row = list(moved["rows"][0])
+ row[moved["columns"].index("Title")] = "Bridge strike, south bank"
+ moved["rows"] = [row]
+
+ said = plan(client, case_id, moved).json()
+ assert said["rows"][0]["action"] == "update"
+ assert "renamed" in said["rows"][0]["reason"]
+
+ result = press(client, case_id, moved)
+ assert calls == []
+ assert result["counts"] == {"built": 0, "restated": 1, "failed": 0}
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == [
+ "Bridge strike, south bank"
+ ]
+
+
+def compose_by_hand(client, case_id, title, points):
+ """A proof written in the composer, which is the one this road must not overwrite.
+
+ Saved through the composer's own route so it carries exactly what a hand-made proof
+ carries: a spec holding its list of points, and no panel tracing back to a published
+ address.
+ """
+ spec = {
+ "azimut_proof": 1,
+ "panels": [],
+ "shapes": [],
+ "points": points,
+ "coordsText": points[0]["coords"],
+ }
+ picture = Image.new("RGB", (24, 18), (12, 34, 56))
+ held = io.BytesIO()
+ picture.save(held, "PNG")
+ answer = client.post(
+ f"/api/cases/{case_id}/proofs",
+ json={
+ "title": title,
+ "spec": spec,
+ "png_base64": base64.b64encode(held.getvalue()).decode("ascii"),
+ },
+ )
+ assert answer.status_code == 200, answer.text
+ return answer.json()["name"]
+
+
+def read_spec(case_id, name):
+ from azimut.api.cases import get_case
+ from azimut import layout
+
+ path = get_case(case_id).resolve_inside(layout.proof_spec_rel(name))
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_a_name_another_proof_holds_is_a_collision_and_not_an_already_built(
+ client, monkeypatch
+):
+ """A row must never adopt a proof on the strength of its title alone.
+
+ Keyed on the name as well as on the address, a binder line landed on whatever proof
+ happened to share its title: the plan announced *already built* about a published
+ address the case had never downloaded, and the press then wrote that row's single point
+ over the composition. A proof concludes on one point, so the list was replaced — three
+ impacts and a camera came back as one address nobody had typed, with no undo, because
+ the press's own Undo is about the sheet.
+
+ Refused instead, in the words the single-post import already uses.
+ """
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ stated = [
+ {"coords": "50.0, 30.0", "label": "impact"},
+ {"coords": "50.1, 30.1", "label": "camera", "pov": True},
+ ]
+ name = compose_by_hand(client, case_id, "Bridge strike", stated)
+ before = read_spec(case_id, name)
+
+ sheet = geoloc(client, case_id) # its one row is titled "Bridge strike" too
+ said = plan(client, case_id, sheet).json()
+ assert [row["action"] for row in said["rows"]] == ["error"]
+ assert said["rows"][0]["reason"] == "another proof is already called 'Bridge strike'"
+ assert said["counts"]["error"] == 1
+
+ # And the press honours the plan: nothing fetched, nothing filed, nothing rewritten.
+ result = press(client, case_id, sheet)
+ assert result["counts"] == {"built": 0, "restated": 0, "failed": 0}
+ assert read_spec(case_id, name) == before
+ assert len(case_entities(case_id, "proof")) == 1
+ assert case_entities(case_id, "media") == []
+
+
+def test_a_rename_onto_a_name_another_proof_holds_is_refused_by_the_plan(client, monkeypatch):
+ """The other half of one rule: the row owns its proof, and still cannot take a name.
+
+ Found by its address, a proof follows a corrected title — but not onto a name somebody
+ else is standing on. That used to be refused by the save, two minutes into a press, as
+ one red line among a hundred; the plan is where a refusal an analyst can act on belongs.
+ """
+ stub_downloads(monkeypatch)
+ case_id = make_case(client)
+ sheet = geoloc(client, case_id)
+ press(client, case_id, sheet)
+ compose_by_hand(client, case_id, "Second reading", [{"coords": "50.0, 30.0"}])
+
+ moved = read_sheet(client, case_id, sheet["id"])
+ moved["meta"] = sheet["meta"]
+ row = list(moved["rows"][0])
+ row[moved["columns"].index("Title")] = "Second reading"
+ moved["rows"] = [row]
+
+ said = plan(client, case_id, moved).json()
+ assert said["rows"][0]["action"] == "error"
+ assert "already called 'Second reading'" in said["rows"][0]["reason"]
+ assert [entity["label"] for entity in case_entities(case_id, "proof")] == [
+ "Bridge strike",
+ "Second reading",
+ ]
diff --git a/tests/test_sheets.py b/tests/test_sheets.py
new file mode 100644
index 0000000..0818a62
--- /dev/null
+++ b/tests/test_sheets.py
@@ -0,0 +1,2748 @@
+"""Case sheets: the CSV on disk, the sidecar beside it, and the routes.
+
+The gate this file exists for is the first one: **a sheet is a file**. Every test
+that reads `sheets/<name>.csv` back with the standard library is checking the
+promise the feature is built on — that a case outlives the app holding it.
+"""
+
+import csv
+import io
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from azimut import layout
+from azimut.engine import artifacts, entities as entity_engine
+from azimut.engine import sheetlinks, sheetpromote, sheetroles
+from azimut.engine import sheets as sheet_engine
+
+
+def make_case(client, name="Sheets"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def new_sheet(client, case_id, title="Candidates"):
+ response = client.post(f"/api/cases/{case_id}/sheets", json={"title": title})
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def case_file(client, case_id, rel):
+ from azimut.api.cases import get_case
+
+ return get_case(case_id).resolve_inside(rel)
+
+
+def case_links(client, case_id):
+ from azimut.api.cases import get_case
+
+ return get_case(case_id).list_links()
+
+
+def held(case_id, entity_id):
+ """One entity as the case holds it, or None. There is no route that reads one."""
+ from azimut.api.cases import get_case
+
+ return get_case(case_id).get_entity(entity_id)
+
+
+def case_entities(client, case_id, entity_type):
+ from azimut.api.cases import get_case
+
+ return [e for e in get_case(case_id).list_entities() if e.get("type") == entity_type]
+
+
+# -- the table, without a case around it -------------------------------------
+
+
+def test_a_file_with_no_id_column_gets_one_in_front():
+ columns, rows = sheet_engine.parse_csv("name,plate\nQuai sud,AB-123\n")
+ assert columns == ["id", "name", "plate"]
+ assert rows[0][1:] == ["Quai sud", "AB-123"]
+ assert rows[0][0], "every row is keyed"
+
+
+def test_a_file_that_already_keys_its_rows_keeps_its_own_column():
+ """An export usually carries an id, and a second key column beside it is noise."""
+ columns, rows = sheet_engine.parse_csv("id,name\n42,Quai sud\n43,Pont nord\n")
+ assert columns == ["id", "name"]
+ assert [row[0] for row in rows] == ["42", "43"]
+
+
+def test_blank_and_duplicate_keys_are_filled_rather_than_refused():
+ columns, rows = sheet_engine.parse_csv("id,name\n,A\n7,B\n7,C\n")
+ keys = [row[0] for row in rows]
+ assert len(set(keys)) == 3, "a key is never shared"
+ assert keys[1] == "7", "the first holder of a value keeps it"
+
+
+def test_a_semicolon_export_is_read_as_a_table():
+ """European exports are semicolon-separated far too often to refuse."""
+ columns, rows = sheet_engine.parse_csv("name;plate\nQuai sud;AB-123\n")
+ assert columns == ["id", "name", "plate"]
+ assert rows[0][1:] == ["Quai sud", "AB-123"]
+
+
+def test_a_delimiter_inside_quotes_does_not_vote():
+ assert sheet_engine.sniff_delimiter('name;note\n"Smith, J";ok\n') == ";"
+
+
+def test_blank_and_repeated_headings_are_named():
+ columns, _ = sheet_engine.parse_csv("name,,name\nx,y,z\n")
+ assert columns == ["id", "name", "Column 2", "name (2)"]
+
+
+def test_an_empty_file_is_an_empty_sheet_rather_than_an_error():
+ columns, rows = sheet_engine.parse_csv("")
+ assert columns == ["id"] and rows == []
+
+
+def test_a_cell_keeps_its_newlines_and_loses_its_control_characters():
+ columns, rows = sheet_engine.normalize(["id", "notes"], [["r1", "two\r\nlines\x07"]])
+ assert rows[0][1] == "two\nlines"
+
+
+def test_a_table_wider_or_longer_than_the_bound_is_refused():
+ import pytest
+
+ with pytest.raises(sheet_engine.SheetError):
+ sheet_engine.normalize([f"c{i}" for i in range(sheet_engine.MAX_COLUMNS + 1)], [])
+ with pytest.raises(sheet_engine.SheetError):
+ sheet_engine.normalize(["id"], [[""]] * (sheet_engine.MAX_ROWS + 1))
+ with pytest.raises(sheet_engine.SheetError):
+ sheet_engine.normalize(["id", "n"], [["r1", "x" * (sheet_engine.MAX_CELL + 1)]])
+
+
+def test_a_written_table_reads_back_through_the_standard_library():
+ """The whole design in one assertion: the file is the sheet."""
+ text = sheet_engine.to_csv(["id", "note"], [["r1", 'he said "no", twice\nthen left']])
+ back = list(csv.reader(io.StringIO(text)))
+ assert back[0] == ["id", "note"]
+ assert back[1][1] == 'he said "no", twice\nthen left'
+
+
+# -- the sidecar --------------------------------------------------------------
+
+
+def test_the_sidecar_drops_what_the_table_no_longer_carries():
+ columns, rows = ["id", "Status"], [["r1", "checked"]]
+ clean = sheet_engine.clean_meta(
+ {
+ "widths": {"Status": 200, "Gone": 120},
+ "hidden": ["Gone", "id"],
+ "sort": {"column": "Gone", "desc": True},
+ "colours": {"r1": "red", "r9": "red", "r1x": "not-a-colour"},
+ "links": {"r1": {"Status": "e_1", "Gone": "e_2"}, "r9": {"Status": "e_3"}},
+ },
+ columns,
+ rows,
+ )
+ assert clean["widths"] == {"Status": 200}
+ assert clean["hidden"] == [], "the id column is never hidden"
+ assert clean["sort"] is None
+ assert clean["colours"] == {"r1": "red"}
+ assert clean["links"] == {"r1": {"Status": "e_1"}}
+
+
+def test_a_corrupt_sidecar_costs_presentation_and_nothing_else():
+ assert sheet_engine.clean_meta("not a dict", ["id"], []) == sheet_engine.empty_meta()
+
+
+# -- what the app knows about a column ----------------------------------------
+
+
+def test_the_sidecar_keeps_roles_notes_and_the_progress_column():
+ clean = sheet_engine.clean_meta(
+ {
+ "roles": {
+ "Status": {"kind": "state", "values": ["seen", "geolocated"]},
+ "Coordinates": {"kind": "latlon"},
+ "Gone": {"kind": "when"},
+ "Odd": {"kind": "invented"},
+ },
+ "notes": {"Status": "where this row got to", "Gone": "dropped with its column"},
+ "progress": "Coordinates",
+ },
+ ["id", "Status", "Coordinates"],
+ [],
+ )
+ assert clean["version"] == sheet_engine.META_VERSION == 6
+ assert set(clean["roles"]) == {"Status", "Coordinates"}, "a role needs its column"
+ assert clean["roles"]["Status"]["values"] == ["seen", "geolocated"], "the order is the ranking"
+ assert clean["notes"] == {"Status": "where this row got to"}
+ assert clean["progress"] == "Coordinates"
+
+
+def test_a_role_keeps_only_the_fields_its_kind_uses():
+ """A column that was a choice and became a when must not keep a vocabulary."""
+ role = sheet_engine.clean_meta(
+ {"roles": {"When": {"kind": "when", "values": ["a"], "multi": ", "}}}, ["id", "When"], []
+ )["roles"]["When"]
+ assert role == {"kind": "when", "shape": "date", "dayFirst": True}
+
+
+def test_a_state_column_with_no_vocabulary_gets_the_default_one_painted():
+ """The four words and the four colours together: a worklist is read at a glance."""
+ role = sheet_engine.clean_meta({"roles": {"S": {"kind": "state"}}}, ["id", "S"], [])["roles"]["S"]
+ assert role["values"] == list(sheetroles.STATE_DEFAULTS)
+ assert role["colours"] == dict(sheetroles.STATE_COLOURS)
+
+
+def test_the_birth_colours_lose_to_what_the_column_says():
+ """Removing a colour from a line has to stick, or a value can never be un-painted."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"S": {"kind": "state", "values": list(sheetroles.STATE_DEFAULTS)}}},
+ ["id", "S"],
+ [],
+ )["roles"]
+ assert roles["S"]["colours"] == {}, "a vocabulary that says no colour has no colour"
+ # A colour the column does state wins over the one it was born with, value by value.
+ repainted = sheet_engine.clean_meta(
+ {"roles": {"S": {"kind": "state", "colours": {"to do": "orange"}}}}, ["id", "S"], []
+ )["roles"]["S"]
+ assert repainted["colours"]["to do"] == "orange"
+ assert repainted["colours"]["done"] == sheetroles.STATE_COLOURS["done"]
+ # And a vocabulary the column brought itself is not painted at all: `done` among an
+ # imported binder's own words means what the binder meant, not what the app assumes.
+ own = sheet_engine.clean_meta(
+ {"roles": {"S": {"kind": "state", "values": ["pass", "done"]}}}, ["id", "S"], []
+ )["roles"]["S"]
+ assert own["colours"] == {}
+
+
+def test_a_boolean_column_holds_exactly_two_words():
+ """Two words is what makes one click a toggle rather than a menu."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"Seen": {"kind": "boolean", "values": ["oui", "non", "peut-être"]}}},
+ ["id", "Seen"],
+ [],
+ )["roles"]
+ assert roles["Seen"]["values"] == ["oui", "non"]
+ assert sheet_engine.clean_meta({"roles": {"S": {"kind": "boolean"}}}, ["id", "S"], [])["roles"][
+ "S"
+ ]["values"] == list(sheetroles.BOOLEAN_DEFAULTS)
+
+
+def test_a_value_colour_is_kept_apart_from_the_value():
+ """The value is what a cell is matched against, so it stays the word the file holds."""
+ roles = sheet_engine.clean_meta(
+ {
+ "roles": {
+ "Status": {
+ "kind": "state",
+ "values": ["to do", "done"],
+ "colours": {"done": "green", "gone": "red", "to do": "chartreuse"},
+ }
+ }
+ },
+ ["id", "Status"],
+ [],
+ )["roles"]
+ assert roles["Status"]["values"] == ["to do", "done"]
+ assert roles["Status"]["colours"] == {"done": "green"}
+
+
+def test_a_number_column_carries_its_unit_and_where_it_is_written():
+ """The sidecar has to survive the round trip, or the choice is made once per session."""
+ roles = sheet_engine.clean_meta(
+ {
+ "roles": {
+ "Share": {"kind": "number", "unit": " % ", "unitInCells": 1, "summary": "mean"},
+ "Range": {"kind": "number", "unit": "km", "summary": "invented"},
+ }
+ },
+ ["id", "Share", "Range"],
+ [],
+ )["roles"]
+ assert roles["Share"] == {
+ "kind": "number",
+ "unit": "%",
+ "unitInCells": True,
+ "summary": "mean",
+ }
+ assert roles["Range"]["unitInCells"] is False, "the heading carries it until asked"
+ assert roles["Range"]["summary"] == "sum", "a column of counts wants a total"
+
+
+def test_a_when_column_is_told_which_of_the_three_it_holds():
+ """Declared, not inferred: a column that is still empty has to be tellable."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"At": {"kind": "when", "shape": "time"}, "On": {"kind": "when", "shape": "odd"}}},
+ ["id", "At", "On"],
+ [],
+ )["roles"]
+ assert roles["At"]["shape"] == "time"
+ assert roles["On"]["shape"] == "date"
+
+
+def test_a_picture_column_is_stored_as_a_kind_and_nothing_else():
+ """A picture is a lens like the others: the file keeps the address, and the grid is
+ the only thing that draws anything from it."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"Shot": {"kind": "picture", "values": ["a"]}}}, ["id", "Shot"], []
+ )["roles"]
+ assert roles["Shot"] == {"kind": "picture"}
+
+
+def test_a_column_of_values_no_longer_stores_a_way_to_count_them():
+ """Reading `2x S-125` as two of `S-125` kept a count in a column of values. A count
+ belongs in a number column beside a column naming what is counted."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"Equipments": {"kind": "choice", "multi": ", ", "quantities": True}}},
+ ["id", "Equipments"],
+ [],
+ )["roles"]
+ assert roles["Equipments"] == {
+ "kind": "choice",
+ "values": [],
+ "colours": {},
+ "multi": ", ",
+ }
+
+
+def test_a_computed_column_is_pinned_to_a_nature_the_server_knows():
+ roles = sheet_engine.clean_meta(
+ {"roles": {"On map": {"kind": "computed", "of": "invented"}}}, ["id", "On map"], []
+ )["roles"]
+ assert roles["On map"]["of"] == "has_point"
+
+
+def test_a_row_column_names_the_column_whose_words_point_at_the_other_row():
+ """Names and not keys: the file keeps the words, so a link a reader can follow."""
+ roles = sheet_engine.clean_meta(
+ {"roles": {"Links": {"kind": "row", "of": "Unit", "multi": ", "}}},
+ ["id", "Unit", "Links"],
+ [],
+ )["roles"]
+ assert roles["Links"] == {"kind": "row", "of": "Unit", "multi": ", "}
+ # A naming column that left the file loses its pointer rather than keeping one into
+ # a column nobody can see.
+ gone = sheet_engine.clean_meta(
+ {"roles": {"Links": {"kind": "row", "of": "Renamed"}}}, ["id", "Unit", "Links"], []
+ )["roles"]
+ assert gone["Links"]["of"] is None
+
+
+def test_an_offset_column_names_its_anchor_even_before_the_anchor_is_dated():
+ """Relative order is worth having long before anybody works out when the shot was."""
+ clean = sheet_engine.clean_meta(
+ {
+ "roles": {"start synchro": {"kind": "offset", "anchor": "IGLA launch"}},
+ "anchors": {"IGLA launch": {"at": ""}},
+ },
+ ["id", "start synchro"],
+ [],
+ )
+ assert clean["roles"]["start synchro"]["anchor"] == "IGLA launch"
+ assert clean["anchors"] == {"IGLA launch": {"at": ""}}
+
+
+def test_an_anchor_takes_a_timestamp_and_never_a_bare_date():
+ """A date read as midnight would hand ten videos a moment nobody claimed."""
+ clean = sheet_engine.clean_meta(
+ {
+ "anchors": {
+ "IGLA launch": {"at": "2026-01-03T01:57:00Z"},
+ "second impact": {"at": "2026-01-03"},
+ " ": {"at": "2026-01-03T02:00:00Z"},
+ }
+ },
+ ["id"],
+ [],
+ )
+ assert clean["anchors"]["IGLA launch"] == {"at": "2026-01-03T01:57:00Z"}
+ assert clean["anchors"]["second impact"] == {"at": ""}
+ assert " " not in clean["anchors"]
+
+
+def test_a_linked_nature_names_the_column_whose_link_it_follows():
+ """A sheet may point at the case from two columns, so "whatever this row points at"
+ would answer about whichever one the walk reached first."""
+ roles = sheet_engine.clean_meta(
+ {
+ "roles": {
+ "Point": {"kind": "computed", "of": "point", "from": "Subject"},
+ "Ties": {"kind": "computed", "of": "relations", "from": "Subject"},
+ "Lost": {"kind": "computed", "of": "point", "from": "Renamed"},
+ }
+ },
+ ["id", "Subject", "Point", "Ties", "Lost"],
+ [],
+ )["roles"]
+ assert roles["Point"] == {"kind": "computed", "of": "point", "from": "Subject"}
+ assert roles["Ties"]["multi"] == ", "
+ assert roles["Lost"]["from"] is None
+
+
+def test_a_row_keeps_the_case_files_it_carries_and_a_column_keeps_what_its_words_mean():
+ """Two tables, two grains. A link is one cell pointing at one entity and cannot
+ answer a cell holding three pieces of equipment; a vocabulary pointed at the case
+ can, and it is the grain a whole column is promoted at."""
+ clean = sheet_engine.clean_meta(
+ {
+ "attachments": {"r1": ["e_shot", "e_shot", ""], "r9": ["e_ghost"]},
+ "values": {"Kit": {"Buk-M2E": "e_buk", " ": "e_blank"}, "Gone": {"x": "e_x"}},
+ "description": " What is left to geolocate. ",
+ },
+ ["id", "Kit"],
+ [["r1", "Buk-M2E"]],
+ )
+ assert clean["attachments"] == {"r1": ["e_shot"]}, "a row that left takes its pieces"
+ assert clean["values"] == {"Kit": {"Buk-M2E": "e_buk"}}
+ assert clean["description"] == "What is left to geolocate."
+
+
+def test_a_sheet_mentions_what_its_words_mean_and_what_its_rows_carry():
+ """All three are the same statement — this sheet refers to that — so all three earn
+ the edge. A piece reachable only from the sheet would be a file the subject's own
+ panel could not see."""
+ found = sheet_engine.linked_entity_ids(
+ {
+ "links": {"r1": {"Subject": "e_unit"}},
+ "values": {"Kit": {"Buk-M2E": "e_buk"}},
+ "attachments": {"r1": ["e_shot", "e_unit"]},
+ }
+ )
+ assert found == ["e_unit", "e_buk", "e_shot"]
+
+
+def test_the_key_column_is_found_whatever_case_the_file_spells_it_in():
+ """An exported table routinely writes `ID`, and `normalize` keeps a file's own
+ spelling — so every reader has to match without regard to case or the sidecar of the
+ very files this module promises to adopt raises instead of cleaning."""
+ columns, rows = sheet_engine.parse_csv("ID,Name\n42,Quai sud\n")
+ assert columns == ["ID", "Name"]
+ assert sheet_engine.key_index(columns) == 0
+ clean = sheet_engine.clean_meta({"colours": {"42": "red"}}, columns, rows)
+ assert clean["colours"] == {"42": "red"}
+
+
+def test_an_older_sidecar_still_reads_and_is_written_as_the_current_one():
+ """Reopening a sheet from before roles existed costs nothing."""
+ clean = sheet_engine.clean_meta(
+ {"version": 1, "widths": {"Status": 200}, "colours": {"r1": "red"}},
+ ["id", "Status"],
+ [["r1", "seen"]],
+ )
+ assert clean["version"] == sheet_engine.META_VERSION
+ assert clean["widths"] == {"Status": 200}
+ assert clean["colours"] == {"r1": "red"}
+ assert clean["roles"] == {}
+ assert clean["promoted"] == {}
+
+
+def test_the_sidecar_keeps_what_a_promoted_cell_said_and_drops_the_rest():
+ """A link cannot say a row has moved on: it is the same link after an edit."""
+ clean = sheet_engine.clean_meta(
+ {"promoted": {"r1": {"Unit": "3rd Brigade", "Gone": "x"}, "r9": {"Unit": "ghost"}}},
+ ["id", "Unit"],
+ [["r1", "3rd Separate Brigade"]],
+ )
+ assert clean["promoted"] == {"r1": {"Unit": "3rd Brigade"}}
+
+
+def test_the_two_role_vocabularies_are_the_same_list_on_both_sides():
+ """The browser draws chips from its own copy, so the two copies have to agree.
+
+ Same gate as `ROW_COLOURS`: a role the grid offers and the server drops would be a
+ column the analyst configures and the file never remembers.
+ """
+ source = (
+ Path(__file__).resolve().parents[1] / "frontend" / "src" / "lib" / "sheetRoles.js"
+ ).read_text(encoding="utf-8-sig")
+
+ def js_list(name: str) -> list[str]:
+ match = re.search(rf"export const {name} = \[(.*?)\]", source, re.S)
+ assert match, f"{name} not found in sheetRoles.js"
+ return re.findall(r"'([^']+)'", match.group(1))
+
+ def js_map(name: str) -> dict[str, str]:
+ match = re.search(rf"export const {name} = \{{(.*?)\n\}}", source, re.S)
+ assert match, f"{name} not found in sheetRoles.js"
+ return dict(re.findall(r"'([^']+)':\s*'([^']+)'", match.group(1)))
+
+ assert js_list("ROLE_KINDS") == list(sheetroles.ROLE_KINDS)
+ assert js_list("STATE_DEFAULTS") == list(sheetroles.STATE_DEFAULTS)
+ assert js_map("STATE_COLOURS") == dict(sheetroles.STATE_COLOURS)
+ assert js_list("BOOLEAN_DEFAULTS") == list(sheetroles.BOOLEAN_DEFAULTS)
+ assert js_list("WHEN_SHAPES") == list(sheetroles.WHEN_SHAPES)
+ assert js_list("COMPUTED_NATURES") == list(sheetroles.COMPUTED_NATURES)
+ assert js_list("NUMBER_SUMMARIES") == list(sheetroles.NUMBER_SUMMARIES)
+ assert js_list("ROW_COLOURS") == list(sheet_engine.ROW_COLOURS)
+
+
+def test_the_server_reads_the_same_moment_out_of_a_cell_as_the_browser_does():
+ """Promotion dates a Claim off a cell, so the reading cannot be the browser's alone.
+
+ The impossible date is the one that matters: `Date.UTC` rolls 29 February in a common
+ year forward to 1 March, so a column holding one used to sort as though it were the
+ day after. Both sides refuse it now.
+ """
+ assert sheetroles.parse_when("01:57")["clock"] == "01:57:00"
+ assert sheetroles.parse_when("31/01/2026")["date"] == "2026-01-31"
+ assert sheetroles.parse_when("01/02/2026", {"dayFirst": False})["date"] == "2026-01-02"
+ assert sheetroles.parse_when("Sat, 03 Jan 2026 06:42:02 GMT")["clock"] == "06:42:02"
+ assert sheetroles.parse_when("29/02/2025") is None
+ assert sheetroles.parse_when("?") is None
+
+
+#: The cells both readers are held to, and the reading they must agree on. Lives beside the
+#: browser's copy of the reader so one file cannot be edited without the other being seen.
+READING_FIXTURE = (
+ Path(__file__).resolve().parents[1] / "frontend" / "src" / "lib" / "sheetReading.fixture.json"
+)
+
+
+def shared_cells() -> dict[str, Any]:
+ return json.loads(READING_FIXTURE.read_text(encoding="utf-8"))
+
+
+def test_both_readers_answer_the_same_thing_about_a_shared_list_of_cells():
+ """The parity gate the vocabulary lists had and the readings did not.
+
+ Comparing `ROLE_KINDS` to `ROLE_KINDS` proves the two sides offer the same words, never
+ that they *read* a cell the same way — and they had drifted where it counts: the server
+ took `03/01/2026 99:00` for an hour and the browser took `12:30:75` for a time, so a
+ cell the grid sorted without a word was refused at the promotion with a message about a
+ value nobody had typed. The other half of this test is `lib/sheetRoles.test.js`, over
+ this same file.
+ """
+ shared = shared_cells()
+ assert shared["when"] and shared["point"], "the fixture is the gate; an empty one is none"
+
+ for case in shared["when"]:
+ read = sheetroles.parse_when(case["cell"], case.get("role"))
+ wanted = case["reads"]
+ if wanted is None:
+ assert read is None, f"{case['cell']!r} should not read as a moment"
+ continue
+ assert read is not None, f"{case['cell']!r} should read as a moment"
+ assert read["shape"] == wanted["shape"], case["cell"]
+ assert read["text"] == wanted["text"], case["cell"]
+
+ for case in shared["point"]:
+ point = sheetroles.parse_latlon(case["cell"])
+ wanted = case["reads"]
+ if wanted is None:
+ assert point is None, f"{case['cell']!r} should not read as a point"
+ continue
+ assert point is not None, f"{case['cell']!r} should read as a point"
+ assert point["lat"] == pytest.approx(wanted["lat"], abs=1e-6), case["cell"]
+ assert point["lon"] == pytest.approx(wanted["lon"], abs=1e-6), case["cell"]
+ assert point["decimals"] == wanted["decimals"], case["cell"]
+
+
+def test_the_types_that_own_a_file_are_the_same_list_on_both_sides():
+ """The delete dialog promises what it is about to take, so it has to know.
+
+ `artifacts.KINDS` is where a type declares its files and `lib/trash.FILE_BACKED` is what
+ the confirmation reads to choose its sentence — two lists of one fact, and they drifted
+ at the moment `sheet` gained a file: deleting the artifact whose whole design is "the
+ file is the sheet" announced that only the item was going. Gated here like the role
+ vocabularies, so the next type to gain a file cannot forget the dialog.
+ """
+ source = (
+ Path(__file__).resolve().parents[1] / "frontend" / "src" / "lib" / "trash.js"
+ ).read_text(encoding="utf-8-sig")
+ match = re.search(r"export const FILE_BACKED = new Set\(\[(.*?)\]\)", source, re.S)
+ assert match, "FILE_BACKED not found in trash.js"
+ assert sorted(re.findall(r"'([^']+)'", match.group(1))) == sorted(artifacts.KINDS)
+
+
+def test_a_comma_is_read_as_a_decimal_mark_and_never_as_a_thousands_separator():
+ """One reading of a comma across the app, and it is the European one.
+
+ A number and a point are the two places a comma is ambiguous, and guessing per column
+ would be two answers to one question. So `1,234` is one and a bit, `1 234,5` is a
+ thousand, `1,234,567` is refused rather than read as a million, and `48,8` is a number
+ and not a pair of coordinates. Written down in UI.md where `dayFirst` is explained,
+ because it is the same class of decision and the only other one the analyst cannot see.
+ """
+ field = entity_engine.Attr(key="count", label="Count", kind="number")
+ assert sheetpromote.read_attr(field, "1,234") == (1.234, None)
+ assert sheetpromote.read_attr(field, "1 234,5") == (1234.5, None)
+ assert sheetpromote.read_attr(field, "12,5")[0] == 12.5
+ # Two commas cannot be two decimal marks, so the cell is refused rather than guessed.
+ assert sheetpromote.read_attr(field, "1,234,567")[0] is None
+ assert "not a number" in str(sheetpromote.read_attr(field, "1,234,567")[1])
+
+
+def test_a_bare_clock_is_dated_by_the_sheet_and_never_by_the_server():
+ """The binders' `Local time` is `01:57` for an event whose date is in the title, and
+ a moment invented for it would be invented evidence. Local by default, too: stamping
+ `Z` on it would move the evidence by however far away it happened."""
+ clock = sheetroles.parse_when("01:57")
+ assert sheetroles.claim_moment(clock) is None
+ assert sheetroles.claim_moment(clock, day="2026-01-03") == "2026-01-03T01:57:00"
+ assert sheetroles.claim_moment(clock, day="2026-01-03", zone="Z") == "2026-01-03T01:57:00Z"
+ # A cell that named only a day stays a day: a reduced date is inside the profile.
+ assert sheetroles.claim_moment(sheetroles.parse_when("31/01/2026")) == "2026-01-31"
+
+
+def test_an_offset_is_read_in_the_four_spellings_a_player_produces():
+ assert sheetroles.parse_offset("-00:01:50") == -110
+ assert sheetroles.parse_offset("00:04:04") == 244
+ assert sheetroles.parse_offset("1:05") == 65
+ assert sheetroles.parse_offset("-110") == -110
+ assert sheetroles.parse_offset("00:00:61") is None
+ assert sheetroles.parse_offset("then") is None
+ assert sheetroles.format_offset(-110) == "-00:01:50"
+ assert sheetroles.offset_moment("2026-01-03T01:57:00Z", -110) == "2026-01-03T01:55:10Z"
+ assert sheetroles.offset_moment("", -110) is None, "an undated anchor dates nothing"
+
+
+def test_a_row_column_reaches_a_row_only_where_one_row_answers_to_the_name():
+ """The binders' own version had already decayed to `#REF!`. Read from the words every
+ time, the same decay becomes a list of what to fix."""
+ columns = ["id", "Unit", "Links"]
+ rows = [
+ ["r1", "3rd Brigade", "1st Coy, 2nd Coy"],
+ ["r2", "1st Coy", "3rd Brigade"],
+ ["r3", "2nd Coy", "3rd Brigade"],
+ ["r4", "Recon Coy", "3rd Bde"],
+ ]
+ found = sheetroles.row_targets(
+ columns, rows, "Links", {"kind": "row", "of": "Unit", "multi": ", "}
+ )
+ assert found["r1"]["keys"] == ["r2", "r3"]
+ assert found["r2"]["keys"] == ["r1"]
+ assert found["r4"] == {"keys": [], "missing": ["3rd Bde"]}
+
+
+def test_the_server_reads_the_three_shapes_a_point_is_written_in():
+ """Promotion writes places, so the server reads a point rather than trusting one."""
+ plain = sheetroles.parse_latlon("48.8566, 2.3522")
+ assert (plain["lat"], plain["lon"]) == (48.8566, 2.3522)
+ assert plain["decimals"] == 4 and not plain["out_of_bounds"]
+
+ # A pair written with no hemisphere is northern and eastern. It came out mirrored
+ # into the south Atlantic while an empty hemisphere counted as a match for "S".
+ assert sheetroles.parse_latlon("48.8566 2.3522")["lat"] > 0
+
+ hemispheres = sheetroles.parse_latlon("48.8566N, 2.3522W")
+ assert (hemispheres["lat"], hemispheres["lon"]) == (48.8566, -2.3522)
+
+ dms = sheetroles.parse_latlon("48°51'24\"N 2°21'08\"E")
+ assert round(dms["lat"], 4) == 48.8567 and round(dms["lon"], 4) == 2.3522
+
+ assert sheetroles.parse_latlon("1 234,5")["out_of_bounds"] is True
+ assert sheetroles.parse_latlon("To be found") is None
+ assert sheetroles.parse_latlon("") is None
+ # Two decimals is about a kilometre, which is the claim the cell actually made.
+ assert sheetroles.precision_metres(2) == 1113
+ assert sheetroles.precision_metres(5) == 1
+
+
+def test_a_claim_is_the_one_manual_type_a_row_cannot_become():
+ from azimut.engine import sheetpromote
+
+ promotable = sheetpromote.promotable_types()
+ assert "person" in promotable and "place" in promotable
+ assert "claim" not in promotable
+ assert "media" not in promotable, "a media is born from an import, not from a row"
+
+
+# -- the routes ---------------------------------------------------------------
+
+
+def test_a_new_sheet_is_a_real_csv_in_the_case(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+
+ assert sheet["type"] == "sheet"
+ rel = sheet["attrs"]["path"]
+ assert rel == layout.sheet_rel("Candidates")
+ path = case_file(client, case_id, rel)
+ assert path.is_file()
+ assert path.read_text(encoding="utf-8-sig").splitlines()[0] == "id,Subject,Status,Notes"
+
+
+def test_the_csv_carries_a_byte_order_mark_so_excel_reads_it(client):
+ """Excel opens a UTF-8 CSV with no mark in the machine's legacy codepage, which turns
+ every accent in a case into mojibake. We ship a Windows binary, so the mark goes in —
+ and every reader in the engine opens files as `utf-8-sig`, which takes it back off."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id", "Subject"], "rows": [["r1", "Rue de l'Égalité"]], "meta": {}},
+ )
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+
+ assert path.read_bytes().startswith(b"\xef\xbb\xbf"), "Excel needs the mark"
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["columns"] == ["id", "Subject"], "and the grid never sees it"
+ assert read["rows"][0][1] == "Rue de l'Égalité"
+
+
+def test_the_sidecar_carries_no_mark(client):
+ """A BOM in JSON breaks strict parsers, and nothing opens the sidecar in Excel."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id"], "rows": [["r1"]], "meta": {"widths": {"id": 120}}},
+ )
+ meta_path = case_file(client, case_id, layout.sheet_meta_rel("Candidates"))
+
+ assert not meta_path.read_bytes().startswith(b"\xef\xbb\xbf")
+ assert json.loads(meta_path.read_text(encoding="utf-8"))["widths"] == {"id": 120}
+
+
+def test_a_write_that_fails_leaves_the_previous_table_untouched(tmp_path):
+ """`write_text` truncates and then writes, so dying in between costs the analyst the
+ table. The sheet is *the* artifact here, so the new copy lands by rename or not at
+ all."""
+ path = tmp_path / "Candidates.csv"
+ sheet_engine.write_atomic(path, "id,Subject\nr1,Quai sud\n", encoding=sheet_engine.CSV_ENCODING)
+ before = path.read_bytes()
+
+ with pytest.raises(sheet_engine.SheetUnwritable):
+ sheet_engine.write_atomic(path / "not-a-directory", "x", encoding="utf-8")
+
+ assert path.read_bytes() == before, "the table that was there is still there"
+ assert not list(tmp_path.glob(".*.tmp")), "and nothing is left lying beside it"
+
+
+def test_a_file_the_system_refuses_is_a_409_naming_it(client, monkeypatch):
+ """The Windows case: the analyst has the CSV open in Excel, which holds the handle.
+ That is not a bad request and not a stale grid — it is a file that is busy, and a 500
+ reading `HTTP 500` in a toast tells the analyst nothing they can act on."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+
+ def refuse(path, text, *, encoding):
+ raise sheet_engine.SheetUnwritable("could not write “Candidates.csv”: it is open elsewhere")
+
+ monkeypatch.setattr(sheet_engine, "write_atomic", refuse)
+ answer = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id"], "rows": [["r1"]], "meta": {}},
+ )
+
+ assert answer.status_code == 409
+ assert "open elsewhere" in answer.json()["detail"]
+
+
+def test_a_file_the_system_refuses_leaves_no_sheet_in_the_case(client, monkeypatch):
+ """A sheet the list shows and nothing can open is worse than no sheet at all.
+
+ The row used to be filed first and the path written last, so the three cases
+ `SheetUnwritable` exists for — a read-only folder, a full disk, a name taken by a
+ directory — each left an entity with no `path`: it appeared in the list as an empty
+ sheet, answered 404 on open, and the analyst could only delete it. The file is written
+ first now, so a refusal leaves the case as it was.
+ """
+ case_id = make_case(client)
+
+ def refuse(path, text, *, encoding):
+ raise sheet_engine.SheetUnwritable("could not write “Candidates.csv”: the folder is read-only")
+
+ monkeypatch.setattr(sheet_engine, "write_atomic", refuse)
+ answer = client.post(f"/api/cases/{case_id}/sheets", json={"title": "Candidates"})
+
+ assert answer.status_code == 409
+ assert client.get(f"/api/cases/{case_id}/sheets").json()["sheets"] == []
+
+
+def test_a_new_sheet_can_be_born_with_the_columns_a_template_names(client):
+ """A template is a list of headings; what the app knows about them is the sidecar's,
+ and it arrives by the save that follows."""
+ case_id = make_case(client)
+ made = client.post(
+ f"/api/cases/{case_id}/sheets",
+ json={"title": "Geo", "columns": ["Subject", "Picture", "Coordinates", "Status"]},
+ )
+ assert made.status_code == 200, made.text
+ path = case_file(client, case_id, made.json()["attrs"]["path"])
+ assert (
+ path.read_text(encoding="utf-8-sig").splitlines()[0]
+ == "id,Subject,Picture,Coordinates,Status"
+ )
+
+
+def test_two_sheets_with_one_name_do_not_share_a_file(client):
+ case_id = make_case(client)
+ first = new_sheet(client, case_id, "Candidates")
+ second = new_sheet(client, case_id, "Candidates")
+ assert first["attrs"]["path"] != second["attrs"]["path"]
+
+
+def test_an_imported_csv_lands_as_a_sheet_and_keeps_its_rows(client):
+ case_id = make_case(client)
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/import",
+ json={"title": "Members", "text": "handle;seen\n@a;yes\n@b;no\n"},
+ )
+ assert response.status_code == 200, response.text
+ sheet_id = response.json()["id"]
+
+ table = client.get(f"/api/cases/{case_id}/sheets/{sheet_id}").json()
+ assert table["columns"] == ["id", "handle", "seen"]
+ assert [row[1] for row in table["rows"]] == ["@a", "@b"]
+
+
+def test_an_import_writes_its_keys_down_straight_away(client):
+ case_id = make_case(client)
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/import",
+ json={"title": "Plates", "text": "plate\nAB-123\n"},
+ )
+ path = case_file(client, case_id, response.json()["attrs"]["path"])
+ assert path.read_text(encoding="utf-8-sig").startswith("id,plate")
+
+ read = client.get(f"/api/cases/{case_id}/sheets/{response.json()['id']}").json()
+ assert read["assigned"] is False
+
+
+def test_a_file_edited_outside_is_re_keyed_without_being_written_to(client):
+ """The analyst's own copy of the file is never rewritten behind their back.
+
+ Someone edits the CSV in a spreadsheet and drops the id column. The grid gets
+ keys so colours and links have something to hang on, the file on disk stays
+ exactly as they left it, and `assigned` is what tells the grid to say so.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Plates")
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ path.write_text("plate,seen\nAB-123,yes\n", encoding="utf-8")
+ before = path.read_bytes()
+
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["assigned"] is True
+ assert read["columns"] == ["id", "plate", "seen"]
+ assert read["rows"][0][0], "the grid has a key to work with"
+ assert path.read_bytes() == before, "reading wrote nothing"
+
+
+def test_saving_writes_the_table_and_the_sidecar(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ sheet_id = sheet["id"]
+
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet_id}",
+ json={
+ "columns": ["id", "Subject", "Verdict"],
+ "rows": [["r1", "Quai sud", "ruled out"]],
+ "meta": {"colours": {"r1": "red"}, "widths": {"Subject": 240}},
+ },
+ )
+ assert saved.status_code == 200, saved.text
+
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ assert list(csv.reader(io.StringIO(path.read_text(encoding="utf-8-sig")))) == [
+ ["id", "Subject", "Verdict"],
+ ["r1", "Quai sud", "ruled out"],
+ ]
+ meta_path = case_file(client, case_id, layout.sheet_meta_rel("Candidates"))
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
+ assert meta["colours"] == {"r1": "red"}
+ assert meta["widths"] == {"Subject": 240}
+
+
+def test_a_finding_is_a_column_and_presentation_is_not(client):
+ """Hand the file to someone else and the work survives; the colours do not."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Worklist")
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Status", "Why"],
+ "rows": [["r1", "ruled out", "too blurry to tell"]],
+ "meta": {"colours": {"r1": "grey"}},
+ },
+ )
+ text = case_file(client, case_id, sheet["attrs"]["path"]).read_text(encoding="utf-8-sig")
+ assert "ruled out" in text and "too blurry to tell" in text
+ assert "grey" not in text
+
+
+def test_a_linked_cell_becomes_a_mention_the_other_side_can_see(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ person = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "person", "label": "Witness A"},
+ ).json()
+
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness A"]],
+ "meta": {"links": {"r1": {"Subject": person["id"]}}},
+ },
+ )
+ links = case_links(client, case_id)
+ assert any(
+ link["from"] == sheet["id"] and link["to"] == person["id"] and link["type"] == "mentions"
+ for link in links
+ )
+
+
+def test_clearing_a_link_drops_its_edge_on_the_next_save(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ person = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ body = {
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness A"]],
+ "meta": {"links": {"r1": {"Subject": person["id"]}}},
+ }
+ client.put(f"/api/cases/{case_id}/sheets/{sheet['id']}", json=body)
+ client.put(f"/api/cases/{case_id}/sheets/{sheet['id']}", json={**body, "meta": {}})
+
+ links = case_links(client, case_id)
+ assert not [link for link in links if link["type"] == "mentions"]
+
+
+def test_a_mention_stated_by_hand_outlives_a_funnel_being_clicked(client):
+ """The sidecar answers for the cells, and for nothing else.
+
+ `mentions` is a relation the analyst may state, and the sheet is one of the
+ documents it can be stated from — so the graph holds two kinds of them, and only
+ one of them is a function of the sidecar. Reconciling over both meant a filter
+ ticked (the sidecar-only route, which touches no cell) deleted a claim somebody
+ made by hand, with no Trash behind it and nothing said about it.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ person = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ stated = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": sheet["id"], "to_id": person["id"], "type": "mentions"},
+ )
+ assert stated.status_code == 200, stated.text
+
+ client.put(f"/api/cases/{case_id}/sheets/{sheet['id']}/meta", json={"meta": {}})
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id", "Subject"], "rows": [["r1", "Witness A"]], "meta": {}},
+ )
+
+ kept = [link for link in case_links(client, case_id) if link["type"] == "mentions"]
+ assert [link["provenance"]["by"] for link in kept] == ["user"]
+ assert kept[0]["to"] == person["id"]
+
+
+def test_deleting_an_entity_clears_the_cells_that_pointed_at_it(client):
+ """A sheet cannot outlive what it points at.
+
+ The link is an id in a sidecar rather than an edge, so nothing in the graph delete
+ reaches it: the cell stayed marked as linked to a row the case no longer held, and
+ the next save wrote the dead id back.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ going = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ staying = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness B"}
+ ).json()
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness A"], ["r2", "Witness B"]],
+ "meta": {
+ "links": {"r1": {"Subject": going["id"]}, "r2": {"Subject": staying["id"]}},
+ "values": {"Subject": {"Witness A": going["id"]}},
+ "colours": {"r1": "grey"},
+ },
+ },
+ )
+
+ client.delete(f"/api/cases/{case_id}/entities/{going['id']}")
+
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["meta"]["links"] == {"r2": {"Subject": staying["id"]}}
+ assert read["meta"]["values"] == {}
+ # only the pointers go: the reading built around them is not what was deleted
+ assert read["meta"]["colours"] == {"r1": "grey"}
+ assert read["rows"] == [["r1", "Witness A"], ["r2", "Witness B"]]
+
+
+def test_a_selection_deleted_at_once_clears_every_sheet_it_was_read_in(client):
+ case_id = make_case(client)
+ first = new_sheet(client, case_id, "Candidates")
+ second = new_sheet(client, case_id, "Sightings")
+ going = [
+ client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": name}
+ ).json()
+ for name in ("Witness A", "Witness B")
+ ]
+ for sheet, entity in zip((first, second), going, strict=True):
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", entity["label"]]],
+ "meta": {"links": {"r1": {"Subject": entity["id"]}}},
+ },
+ )
+
+ client.post(
+ f"/api/cases/{case_id}/entities/delete", json={"ids": [row["id"] for row in going]}
+ )
+
+ for sheet in (first, second):
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["meta"]["links"] == {}
+
+
+def test_a_sheet_untouched_by_a_delete_keeps_its_file_as_it_was(client):
+ """Only the sheets that pointed at the deleted material are rewritten."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ kept = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness B"}
+ ).json()
+ other = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Nobody"}
+ ).json()
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness B"]],
+ "meta": {"links": {"r1": {"Subject": kept["id"]}}},
+ },
+ )
+ meta_path = case_file(client, case_id, layout.sheet_meta_rel("Candidates"))
+ before = meta_path.read_bytes()
+ written = meta_path.stat().st_mtime_ns
+
+ client.delete(f"/api/cases/{case_id}/entities/{other['id']}")
+
+ assert meta_path.read_bytes() == before
+ assert meta_path.stat().st_mtime_ns == written
+
+
+def test_a_delete_that_fails_gives_the_sheets_back_along_with_the_entities(client, monkeypatch):
+ """The rollback restores the graph and the trash. It cannot restore a sidecar.
+
+ So clearing the sheets inside the `try` meant a refused delete handed the entities back
+ with the cells' links, the columns' vocabularies and the rows' attached pieces already
+ gone for good, across every sheet in the case — an analyst looking at intact entities
+ and vanished chips, with nothing to say why. Cleared after the commit now, where there
+ is nothing left to roll back.
+ """
+ from azimut.engine import trash as trash_engine
+
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ going = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness A"]],
+ "meta": {
+ "links": {"r1": {"Subject": going["id"]}},
+ "values": {"Subject": {"Witness A": going["id"]}},
+ },
+ },
+ )
+ meta_path = case_file(client, case_id, layout.sheet_meta_rel("Candidates"))
+ before = meta_path.read_bytes()
+
+ def refuse(case, group_id):
+ raise OSError("the trash could not be committed")
+
+ monkeypatch.setattr(trash_engine, "commit", refuse)
+ with pytest.raises(OSError, match="could not be committed"):
+ client.delete(f"/api/cases/{case_id}/entities/{going['id']}")
+
+ assert meta_path.read_bytes() == before, "the sidecar is byte-identical"
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["meta"]["links"] == {"r1": {"Subject": going["id"]}}
+ assert held(case_id, going["id"]) is not None, "and the entity came back"
+
+
+def test_a_sheet_whose_sidecar_refuses_does_not_take_the_delete_down_with_it(client, monkeypatch):
+ """One sheet whose file is busy is not a reason to fail a delete, which is what the
+ sweep says it does — and `SheetUnwritable` is a `ValueError`, so it used to escape the
+ sentence that was written to swallow exactly this."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ going = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness A"]],
+ "meta": {"links": {"r1": {"Subject": going["id"]}}},
+ },
+ )
+
+ def refuse(path, text, *, encoding):
+ raise sheet_engine.SheetUnwritable("could not write “Candidates.json”: it is open")
+
+ monkeypatch.setattr(sheet_engine, "write_atomic", refuse)
+ answer = client.delete(f"/api/cases/{case_id}/entities/{going['id']}")
+
+ assert answer.status_code == 200, answer.text
+ assert held(case_id, going["id"]) is None, "the delete went through"
+
+
+def test_a_link_the_case_cannot_answer_for_is_dropped_rather_than_refused(client):
+ """The save lands and the dead link does not.
+
+ A cell pointing at nothing is worse than a plain cell: it reads as work already
+ done, and its mark opens a panel about an entity nobody can see. The words in the
+ cell are the analyst's and stay — the link is what the case knows, the text is what
+ the file says.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "somewhere"]],
+ "meta": {"links": {"r1": {"Subject": "e_does_not_exist"}}},
+ },
+ )
+ assert saved.status_code == 200
+ assert saved.json()["meta"]["links"] == {}
+ assert saved.json()["rows"] == [["r1", "somewhere"]]
+
+
+def test_a_sheet_stops_showing_a_link_the_case_no_longer_holds(client):
+ """The rule holds however the dead id got there, not only through a delete.
+
+ A sidecar carried in from another case, a case restored beside sheets written
+ against older ids, a file edited by hand: none of those passes through the delete,
+ and all of them leave a cell claiming a link to nothing.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ kept = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness B"}
+ ).json()
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Witness B"], ["r2", "Nobody"]],
+ "meta": {"links": {"r1": {"Subject": kept["id"]}}},
+ },
+ )
+ # straight into the sidecar, behind the app's back
+ meta_path = case_file(client, case_id, layout.sheet_meta_rel("Candidates"))
+ stored = json.loads(meta_path.read_text(encoding="utf-8"))
+ stored["links"]["r2"] = {"Subject": "e_from_another_case"}
+ meta_path.write_text(json.dumps(stored), encoding="utf-8")
+ csv_path = case_file(client, case_id, sheet["attrs"]["path"])
+ before = csv_path.read_bytes()
+
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+
+ assert read["meta"]["links"] == {"r1": {"Subject": kept["id"]}}
+ # reading never writes: the table is byte-identical and the sidecar still says what
+ # it said, so a case opened to be looked at is left as it was found
+ assert csv_path.read_bytes() == before
+ assert "e_from_another_case" in meta_path.read_text(encoding="utf-8")
+
+
+def test_the_list_says_how_big_each_sheet_is(client):
+ case_id = make_case(client)
+ client.post(
+ f"/api/cases/{case_id}/sheets/import",
+ json={"title": "Members", "text": 'handle,note\n@a,"two\nlines"\n@b,x\n'},
+ )
+ listed = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]
+ assert len(listed) == 1
+ assert listed[0]["title"] == "Members"
+ assert listed[0]["rows"] == 2, "a quoted newline is one row, not two"
+ assert listed[0]["columns"] == 3
+
+
+def test_renaming_a_sheet_moves_its_table_and_its_sidecar(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id"], "rows": [["r1"]], "meta": {"colours": {"r1": "red"}}},
+ )
+ client.patch(
+ f"/api/cases/{case_id}/entities/{sheet['id']}", json={"label": "Shortlist"}
+ )
+
+ assert case_file(client, case_id, layout.sheet_rel("Shortlist")).is_file()
+ assert case_file(client, case_id, layout.sheet_meta_rel("Shortlist")).is_file()
+ assert not case_file(client, case_id, layout.sheet_rel("Candidates")).exists()
+ assert not case_file(client, case_id, layout.sheet_meta_rel("Candidates")).exists()
+
+
+def test_deleting_a_sheet_takes_both_of_its_files(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id"], "rows": [["r1"]], "meta": {"colours": {"r1": "red"}}},
+ )
+ client.delete(f"/api/cases/{case_id}/entities/{sheet['id']}")
+
+ assert not case_file(client, case_id, layout.sheet_rel("Candidates")).exists()
+ assert not case_file(client, case_id, layout.sheet_meta_rel("Candidates")).exists()
+
+
+# -- the two columns the app fills, not the analyst ---------------------------
+#
+# Both land **in the CSV** rather than beside it. `On map: YES/NO` is precisely the
+# column a collaborator opening the spreadsheet reads, and a sidecar copy of it would
+# vanish at the moment the file is handed over.
+
+
+def save(client, case_id, sheet, columns, rows, meta):
+ return client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": columns, "rows": rows, "meta": meta},
+ )
+
+
+def test_a_stamped_column_dates_a_row_once_and_never_again(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Worklist")
+ meta = {"roles": {"Added": {"kind": "stamped"}}}
+
+ first = save(client, case_id, sheet, ["id", "Added", "Note"], [["r1", "", "a"]], meta)
+ stamped = first.json()["rows"][0][1]
+ assert stamped, "a new row is dated"
+
+ # A stamp that moved on every save would say when the sheet was last touched, which
+ # the filesystem already says, instead of when the row appeared.
+ again = save(
+ client, case_id, sheet, ["id", "Added", "Note"], [["r1", stamped, "b"], ["r2", "", "c"]], meta
+ )
+ rows = again.json()["rows"]
+ assert rows[0][1] == stamped
+ assert rows[1][1] == stamped, "and the new row is dated too"
+
+
+def test_a_stamp_is_a_column_of_the_file(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Worklist")
+ save(
+ client, case_id, sheet, ["id", "Added"], [["r1", ""]], {"roles": {"Added": {"kind": "stamped"}}}
+ )
+ text = case_file(client, case_id, sheet["attrs"]["path"]).read_text(encoding="utf-8-sig")
+ assert "id,Added" in text
+ assert text.strip().splitlines()[1].startswith("r1,20"), "the date is in the CSV"
+
+
+def test_a_computed_column_answers_from_the_case_and_not_from_the_cell(client):
+ """`On map` is the binders' column, and what it meant was *this has a place*."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ unit = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Subject", "On map"],
+ [["r1", "Quai sud", "whatever was typed"], ["r2", "3rd Brigade", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Subject": place["id"]}, "r2": {"Subject": unit["id"]}},
+ },
+ )
+ rows = answer.json()["rows"]
+ assert rows[0][2] == "YES", "the place has a point"
+ # The brigade points at an entity and has no place: `linked` would have said YES
+ # here, which is not what the binder's column says.
+ assert rows[1][2] == "NO"
+
+
+def test_a_counting_column_answers_from_the_row_and_never_walks_the_graph(client):
+ """The one kind of formula this tool has: how many of the chosen columns are answered.
+
+ A comparison grid is candidates down and criteria across, and the number the analyst
+ wants at the end of the row is how many criteria this candidate meets. It reads the
+ row's own cells, so a sheet whose only computed column is a score has no business
+ listing every entity the case holds.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Plate", "Face", "Time", "Complete"],
+ [
+ ["r1", "AB-123", "seen", "14:20", "whatever was typed"],
+ ["r2", "AB-123", "", "", ""],
+ ["r3", "", "", "", "3"],
+ ],
+ {
+ "roles": {
+ "Complete": {
+ "kind": "computed",
+ "of": "filled_of",
+ "columns": ["Plate", "Face", "Time"],
+ }
+ }
+ },
+ )
+ assert [row[4] for row in answer.json()["rows"]] == ["3", "1", "0"]
+ # The denominator is said in the panel and in the heading, never in four hundred
+ # cells: the file holds the bare number a spreadsheet can add up.
+ assert answer.json()["meta"]["roles"]["Complete"]["columns"] == ["Plate", "Face", "Time"]
+
+
+def test_a_score_counts_a_yes_the_way_each_column_spells_one(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Plate", "Face", "Score"],
+ [
+ # `oui` is this column's own first value; `x` is what a hand-typed tick holds.
+ ["r1", "oui", "x", ""],
+ ["r2", "non", "no", ""],
+ # `yes` is not this column's word for yes, so the column's own vocabulary wins.
+ ["r3", "yes", "TRUE", ""],
+ ],
+ {
+ "roles": {
+ "Plate": {"kind": "boolean", "values": ["oui", "non"]},
+ "Score": {"kind": "computed", "of": "yes_of", "columns": ["Plate", "Face"]},
+ }
+ },
+ )
+ assert [row[3] for row in answer.json()["rows"]] == ["2", "0", "1"]
+
+
+def test_a_counting_column_told_to_count_nothing_writes_nothing(client):
+ """Not every column: a score over the whole sheet is a number nobody asked for, and it
+ would change under the analyst every time a column is added."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Plate", "Complete"],
+ [["r1", "AB-123", "9"]],
+ {"roles": {"Complete": {"kind": "computed", "of": "filled_of", "columns": []}}},
+ )
+ assert answer.json()["rows"][0][2] == ""
+
+
+def test_a_counting_column_forgets_a_column_that_left_the_file(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Plate", "Complete"],
+ [["r1", "AB-123", ""]],
+ {
+ "roles": {
+ "Complete": {"kind": "computed", "of": "filled_of", "columns": ["Plate", "Gone"]}
+ }
+ },
+ )
+ assert answer.json()["meta"]["roles"]["Complete"]["columns"] == ["Plate"]
+ assert answer.json()["rows"][0][2] == "1", "counted over what is there"
+
+
+def link(client, case_id, from_id, to_id, type_):
+ made = client.post(
+ f"/api/cases/{case_id}/links", json={"from_id": from_id, "to_id": to_id, "type": type_}
+ )
+ assert made.status_code == 200, made.text
+
+
+def test_a_linked_column_writes_the_point_the_case_holds_and_not_a_yes(client):
+ """What `has_point` is not. It answers *whether* the case knows; this answers **what**
+ it knows, which is the number that was being copied by hand into the column along."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.8566, "lon": 2.3522}},
+ ).json()
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Subject", "Point"],
+ [["r1", "Quai sud", ""], ["r2", "Pont nord", "stale"]],
+ {
+ "links": {"r1": {"Subject": place["id"]}},
+ "roles": {"Point": {"kind": "computed", "of": "point", "from": "Subject"}},
+ },
+ )
+ assert [row[2] for row in answer.json()["rows"]] == ["48.85660, 2.35220", ""]
+ # Written into the CSV like every other computed column: the collaborator opening the
+ # file is owed the coordinates, not an empty column.
+ written = case_file(client, case_id, sheet["attrs"]["path"]).read_text(encoding="utf-8-sig")
+ assert "48.85660, 2.35220" in written
+
+
+def test_a_linked_column_writes_what_the_case_joined_that_entity_to(client):
+ """One hop and both directions: "is part of" and "contains" are one edge read from
+ two ends, and a registry wants the brigade whichever way it was stated."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ made = {}
+ for label in ("3rd Brigade", "1st Coy", "2nd Coy"):
+ made[label] = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": label}
+ ).json()
+ link(client, case_id, made["1st Coy"]["id"], made["3rd Brigade"]["id"], "part-of")
+ link(client, case_id, made["2nd Coy"]["id"], made["3rd Brigade"]["id"], "part-of")
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Unit", "Ties"],
+ [["r1", "3rd Brigade", ""], ["r2", "1st Coy", ""]],
+ {
+ "links": {
+ "r1": {"Unit": made["3rd Brigade"]["id"]},
+ "r2": {"Unit": made["1st Coy"]["id"]},
+ },
+ "roles": {
+ "Ties": {"kind": "computed", "of": "relations", "from": "Unit", "multi": ", "}
+ },
+ },
+ )
+ assert [row[2] for row in answer.json()["rows"]] == ["1st Coy, 2nd Coy", "3rd Brigade"]
+
+
+def test_a_linked_column_says_nothing_where_the_case_has_nothing_to_say(client):
+ """An empty cell rather than a word: a row whose subject the case does not place has
+ no coordinates, and `unknown` written down four hundred rows is four hundred cells a
+ filter would then have to unlearn. Two points reaching one entity is the same answer,
+ because choosing between them would be the silent merge this app refuses."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ unit = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+ for label, lat in (("North", 48.0), ("South", 49.0)):
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": label, "attrs": {"lat": lat, "lon": 2.0}},
+ ).json()
+ claim = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "claim", "label": f"seen {label}"}
+ ).json()
+ link(client, case_id, claim["id"], place["id"], "at")
+ link(client, case_id, claim["id"], unit["id"], "about")
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Unit", "Point"],
+ [["r1", "3rd Brigade", ""], ["r2", "Nobody", ""]],
+ {
+ "links": {"r1": {"Unit": unit["id"]}},
+ "roles": {"Point": {"kind": "computed", "of": "point", "from": "Unit"}},
+ },
+ )
+ assert [row[2] for row in answer.json()["rows"]] == ["", ""]
+
+
+def test_a_linked_column_told_to_follow_no_column_answers_nothing(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Subject", "Point"],
+ [["r1", "Quai sud", ""]],
+ {"roles": {"Point": {"kind": "computed", "of": "point"}}},
+ )
+ assert answer.json()["rows"][0][2] == ""
+
+
+def test_a_structure_is_on_the_map_through_the_site_it_sits_at(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ depot = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "structure", "label": "Dépôt"}
+ ).json()
+ link(client, case_id, depot["id"], place["id"], "sited-at")
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Subject", "On map"],
+ [["r1", "Dépôt", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Subject": depot["id"]}},
+ },
+ )
+ assert answer.json()["rows"][0][2] == "YES"
+
+
+def test_a_unit_is_on_the_map_through_the_claim_that_places_it(client):
+ """The hop a unit registry lives on.
+
+ `located-at` is for collected media and `sited-at` for structures, so an
+ organization or a vehicle is positioned by a dated Claim and by nothing else.
+ Without that hop the column would answer NO for exactly the rows the binders' unit
+ registry is made of.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Tracker")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ unit = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+ claim = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "claim", "label": "Seen at the quay"}
+ ).json()
+ link(client, case_id, claim["id"], place["id"], "at")
+ link(client, case_id, claim["id"], unit["id"], "about")
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Unit", "On map"],
+ [["r1", "3rd Brigade", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Unit": unit["id"]}},
+ },
+ )
+ assert answer.json()["rows"][0][2] == "YES"
+
+
+def test_the_walk_stops_at_two_hops(client):
+ """Three hops would answer "something near this is placed", which is not the column."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Tracker")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ company = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "1st Company"}
+ ).json()
+ brigade = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+ claim = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "claim", "label": "Seen at the quay"}
+ ).json()
+ link(client, case_id, claim["id"], place["id"], "at")
+ link(client, case_id, claim["id"], company["id"], "about")
+ link(client, case_id, company["id"], brigade["id"], "part-of")
+
+ answer = save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Unit", "On map"],
+ [["r1", "1st Company", ""], ["r2", "3rd Brigade", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Unit": company["id"]}, "r2": {"Unit": brigade["id"]}},
+ },
+ )
+ rows = answer.json()["rows"]
+ assert rows[0][2] == "YES", "the company is where the claim puts it"
+ assert rows[1][2] == "NO", "its brigade is not, and saying otherwise would be a guess"
+
+
+def test_a_computed_column_is_restated_when_the_case_changes(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "place", "label": "Somewhere"}
+ ).json()
+ body = (
+ ["id", "Subject", "On map"],
+ [["r1", "Somewhere", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Subject": place["id"]}},
+ },
+ )
+ assert save(client, case_id, sheet, *body).json()["rows"][0][2] == "NO"
+
+ client.patch(
+ f"/api/cases/{case_id}/entities/{place['id']}",
+ json={"attrs": {"lat": 48.85, "lon": 2.35}},
+ )
+ assert save(client, case_id, sheet, *body).json()["rows"][0][2] == "YES"
+
+
+def test_a_computed_column_answers_on_a_read_too_and_still_writes_nothing(client):
+ """It only moved on a save, so a place added an hour ago left the sheet reading NO."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "place", "label": "Somewhere"}
+ ).json()
+ save(
+ client,
+ case_id,
+ sheet,
+ ["id", "Subject", "On map"],
+ [["r1", "Somewhere", ""]],
+ {
+ "roles": {"On map": {"kind": "computed", "of": "has_point"}},
+ "links": {"r1": {"Subject": place["id"]}},
+ },
+ )
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ before = path.read_bytes()
+
+ client.patch(
+ f"/api/cases/{case_id}/entities/{place['id']}",
+ json={"attrs": {"lat": 48.85, "lon": 2.35}},
+ )
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert read["rows"][0][2] == "YES", "the grid shows what the case answers now"
+ assert path.read_bytes() == before, "a case opened to be looked at stays byte-identical"
+
+
+def test_a_promotion_records_what_the_cell_said_so_a_later_edit_shows(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ first = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit",
+ ).json()
+ assert first["meta"]["promoted"] == {"r1": {"Unit": "3rd Brigade"}}
+
+ # The link cannot say the row has moved on: it is the same link after the edit.
+ saved = save(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Separate Brigade"]], first["meta"]
+ ).json()
+ assert saved["meta"]["promoted"] == {"r1": {"Unit": "3rd Brigade"}}
+ assert saved["meta"]["links"]["r1"]["Unit"] == first["meta"]["links"]["r1"]["Unit"]
+
+
+# -- the place the case already holds -----------------------------------------
+#
+# The half of a place column that must never leave the machine: a cell pointing at
+# something the case has placed is answered off the graph, exactly, instead of being
+# guessed from a word by a geocoder paced at a request a second.
+
+
+def points(client, case_id, sheet, ids):
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/points", json={"ids": ids}
+ )
+ assert response.status_code == 200, response.text
+ return response.json()["points"]
+
+
+def test_the_case_answers_the_place_of_an_entity_it_holds(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Index")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+
+ answer = points(client, case_id, sheet, [place["id"]])
+ assert answer[place["id"]] == {"lat": 48.85, "lon": 2.35}
+
+
+def test_the_case_answers_through_the_claim_that_places_a_unit(client):
+ """The hop `has_point` walks: a unit is positioned by a dated Claim and by nothing else."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Registry")
+ place = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "Quai sud", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ company = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "1st Company"}
+ ).json()
+ brigade = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+ claim = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "claim", "label": "Seen at the quay"}
+ ).json()
+ link(client, case_id, claim["id"], place["id"], "at")
+ link(client, case_id, claim["id"], company["id"], "about")
+ link(client, case_id, company["id"], brigade["id"], "part-of")
+
+ answer = points(client, case_id, sheet, [company["id"], brigade["id"]])
+ assert answer[company["id"]] == {"lat": 48.85, "lon": 2.35}
+ assert brigade["id"] not in answer, "a third hop would answer for something merely near"
+
+
+def test_an_entity_two_points_reach_is_left_to_the_analyst(client):
+ """Picking one of them would be the silent merge this app refuses everywhere else."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Index")
+ first = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "North bank", "attrs": {"lat": 48.85, "lon": 2.35}},
+ ).json()
+ second = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "place", "label": "South bank", "attrs": {"lat": 48.86, "lon": 2.36}},
+ ).json()
+ depot = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "structure", "label": "A depot"}
+ ).json()
+ link(client, case_id, depot["id"], first["id"], "sited-at")
+ link(client, case_id, depot["id"], second["id"], "sited-at")
+
+ assert points(client, case_id, sheet, [depot["id"]]) == {}
+
+
+def test_an_unplaced_or_unknown_entity_answers_nothing_rather_than_a_zero(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Index")
+ nowhere = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "place", "label": "To be found"}
+ ).json()
+
+ assert points(client, case_id, sheet, [nowhere["id"], "no-such-entity"]) == {}
+
+
+def test_the_places_route_refuses_an_id_that_is_not_a_sheet(client):
+ case_id = make_case(client)
+ place = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "place", "label": "Quai sud"}
+ ).json()
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/{place['id']}/points", json={"ids": [place["id"]]}
+ )
+ assert response.status_code == 404
+
+
+def test_a_sheet_with_no_role_is_written_exactly_as_it_was_sent(client):
+ """The columns the app fills are opt-in: without a role, nothing is touched."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Plain")
+ rows = [["r1", "", ""]]
+ assert save(client, case_id, sheet, ["id", "A", "B"], rows, {}).json()["rows"] == rows
+
+
+# -- two writers on one file --------------------------------------------------
+#
+# The file is the artifact, so the analyst may have it open in a spreadsheet while
+# the grid holds it too. These are the gates that keep the grid from winning a race
+# it cannot see.
+
+
+def test_a_read_hands_out_a_stamp_and_a_save_moves_it_on(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ first = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert first["stamp"], "a read says which file it read"
+
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "Quai sud"]],
+ "meta": {},
+ "stamp": first["stamp"],
+ },
+ )
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["stamp"] != first["stamp"], "the grid can keep saving"
+
+
+def test_a_save_from_a_stale_grid_is_refused_rather_than_allowed_to_overwrite(client):
+ """Someone edits the CSV in a spreadsheet; the grid's copy must not win."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ path.write_text("id,Subject\nr1,typed in LibreOffice\n", encoding="utf-8")
+
+ response = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": ["id", "Subject"],
+ "rows": [["r1", "typed in the grid"]],
+ "meta": {},
+ "stamp": read["stamp"],
+ },
+ )
+ assert response.status_code == 409
+ assert "typed in LibreOffice" in path.read_text(encoding="utf-8-sig"), "nothing was written"
+
+
+def test_reloading_after_a_conflict_gets_a_stamp_that_saves(client):
+ """The way out of a 409 is a fresh read, and it has to actually work."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ stale = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()["stamp"]
+ case_file(client, case_id, sheet["attrs"]["path"]).write_text(
+ "id,Subject\nr1,elsewhere\n", encoding="utf-8"
+ )
+
+ fresh = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert fresh["stamp"] != stale
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={
+ "columns": fresh["columns"],
+ "rows": fresh["rows"],
+ "meta": {},
+ "stamp": fresh["stamp"],
+ },
+ )
+ assert saved.status_code == 200, saved.text
+
+
+def test_a_save_with_no_stamp_writes_unconditionally(client):
+ """A caller holding a table it built itself is not made to invent a stamp."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ case_file(client, case_id, sheet["attrs"]["path"]).write_text(
+ "id,Subject\nr1,moved on\n", encoding="utf-8"
+ )
+ saved = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id", "Subject"], "rows": [["r1", "written anyway"]], "meta": {}},
+ )
+ assert saved.status_code == 200, saved.text
+
+
+def test_a_missing_file_stamps_as_nothing_and_its_appearance_is_a_conflict():
+ from pathlib import Path
+
+ assert sheet_engine.stamp(Path("/does/not/exist.csv")) == ""
+
+
+# -- rows into what the case believes -----------------------------------------
+#
+# The bridge the whole plan pays for. A sheet says what is being checked; the graph says
+# what the case believes, and this is the one road between them.
+
+
+def promote(client, case_id, sheet, columns, rows, meta, **body):
+ """The pass, asked for its row mode in the words these tests are about.
+
+ One screen sends a whole sheet now, and a declaration says what every column becomes.
+ What these tests exercise is the **row** mode of it — a name is not an identity, a field
+ is checked before it is stored, only the mapped columns travel — so the declaration is
+ assembled here rather than restated at twenty call sites. The shape of the request is
+ `tests/test_sheet_pass.py`'s subject.
+ """
+ subject = {
+ "column": body.pop("label_column", ""),
+ "type": body.pop("type", ""),
+ "fields": body.pop("attr_columns", {}) or {},
+ "attach": body.pop("attach", {}) or {},
+ "skip": body.pop("skip", []) or [],
+ "group": body.pop("group", False),
+ "group_label": body.pop("group_label", None),
+ }
+ return client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/promote",
+ json={
+ "columns": columns,
+ "rows": rows,
+ "meta": meta,
+ "subject": subject,
+ "point": body.pop("point_column", None) or "",
+ "addresses": body.pop("link_column", None) or "",
+ **body,
+ },
+ )
+
+
+def counts(answer, mode="row"):
+ """One layer's five words. Every road out of a sheet answers in the same five."""
+ for layer in answer.get("entities", []):
+ if layer["mode"] == mode:
+ return layer["counts"]
+ return dict.fromkeys(("make", "join", "update", "skip", "error"), 0)
+
+
+def plan_rows(answer, mode="row"):
+ """What one layer decided, row by row."""
+ for layer in answer.get("entities", []):
+ if layer["mode"] == mode:
+ return layer["plan"]
+ return []
+
+
+def test_a_promoted_row_becomes_an_entity_the_sheet_points_at(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client,
+ case_id,
+ sheet,
+ ["id", "Unit", "Notes"],
+ [["r1", "3rd Brigade", "seen at the quay"]],
+ {},
+ keys=["r1"],
+ type="organization",
+ label_column="Unit",
+ )
+ assert answer.status_code == 200, answer.text
+ assert counts(answer.json())["make"] == 1
+
+ made = case_entities(client, case_id, "organization")
+ assert [e["label"] for e in made] == ["3rd Brigade"]
+ # The cell now points at what it made, which is what makes a second press an update.
+ assert answer.json()["meta"]["links"]["r1"]["Unit"] == made[0]["id"]
+ # And the sheet mentions it, so the row is visible from the brigade's side.
+ assert any(
+ link["from"] == sheet["id"] and link["to"] == made[0]["id"] and link["type"] == "mentions"
+ for link in case_links(client, case_id)
+ )
+ assert made[0]["provenance"]["by"] == "sheet", "the case records where the row came from"
+
+
+def test_promoting_twice_updates_instead_of_making_a_twin(client):
+ """The mechanism is the sidecar link, which was already there for hand-made ones."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ columns = ["id", "Unit"]
+ first = promote(
+ client, case_id, sheet, columns, [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit",
+ ).json()
+
+ second = promote(
+ client, case_id, sheet, columns, [["r1", "3rd Separate Brigade"]], first["meta"],
+ keys=["r1"], type="organization", label_column="Unit",
+ ).json()
+ assert counts(second)["make"] == 0 and counts(second)["update"] == 1
+
+ made = case_entities(client, case_id, "organization")
+ assert len(made) == 1, "one brigade, not two"
+ assert made[0]["label"] == "3rd Separate Brigade", "the name followed the cell"
+
+
+def test_a_name_the_case_already_holds_is_offered_rather_than_merged(client):
+ """Two people share a name. A same label is a candidate, never a match."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ existing = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit",
+ ).json()
+ assert counts(answer)["join"] == 0 and counts(answer)["make"] == 1
+ assert answer["meta"]["links"]["r1"]["Unit"] != existing["id"]
+ # And the plan said the case already held the name, so the analyst could have said
+ # otherwise before pressing.
+ assert plan_rows(answer)[0]["candidates"] == [{"id": existing["id"], "label": "3rd Brigade"}]
+
+
+def test_a_row_joins_the_entity_the_analyst_attached_it_to(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ existing = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "organization", "label": "3rd Brigade"}
+ ).json()
+
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit", "Echelon"], [["r1", "3rd Bde", "brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit",
+ attr_columns={"Echelon": "echelon"},
+ attach={"r1": existing["id"]},
+ ).json()
+ assert counts(answer)["join"] == 1 and counts(answer)["make"] == 0
+ assert answer["meta"]["links"]["r1"]["Unit"] == existing["id"]
+ joined = case_entities(client, case_id, "organization")
+ assert len(joined) == 1, "no twin was minted beside the one it joined"
+ assert joined[0]["attrs"]["echelon"] == "brigade", "the mapped columns still landed"
+ assert joined[0]["label"] == "3rd Brigade", "joining does not rename what was there"
+
+
+def test_an_identifier_is_joined_on_its_value_because_the_value_is_the_identity(client):
+ """The one family where ONTOLOGY §2 does not hold: one address is one email."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Contacts")
+ existing = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "email", "label": "[email protected]"}
+ ).json()
+
+ answer = promote(
+ client, case_id, sheet, ["id", "Address"], [["r1", "[email protected]"]], {},
+ keys=["r1"], type="email", label_column="Address",
+ ).json()
+ assert counts(answer)["join"] == 1 and counts(answer)["make"] == 0
+ assert answer["meta"]["links"]["r1"]["Address"] == existing["id"]
+
+
+def test_two_rows_with_one_name_are_flagged_rather_than_folded_together(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"], ["r2", "3RD BRIGADE"]], {},
+ keys=["r1", "r2"], type="organization", label_column="Unit",
+ ).json()
+ assert counts(answer)["make"] == 2
+ assert [row["repeat"] for row in plan_rows(answer)] == [False, True]
+
+
+def test_a_row_the_analyst_left_out_of_the_preview_is_not_promoted(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "A"], ["r2", "B"]], {},
+ keys=["r1", "r2"], type="organization", label_column="Unit", skip=["r2"],
+ ).json()
+ assert (counts(answer)["make"], counts(answer)["skip"]) == (1, 1)
+ assert set(answer["meta"]["links"]) == {"r1"}
+
+
+def test_a_cell_that_cannot_be_read_as_its_field_stops_that_row(client):
+ """Promotion was the one write that reached the store without passing a form."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Places")
+ answer = promote(
+ client, case_id, sheet, ["id", "Name", "Precision"],
+ [["r1", "Quai sud", "about 30"], ["r2", "Pont nord", "50"]], {},
+ keys=["r1", "r2"], type="place", label_column="Name",
+ point_column="Name", attr_columns={"Precision": "radius_m"},
+ )
+ assert answer.status_code == 200, answer.text
+ read = answer.json()
+ assert counts(read)["error"] == 2, "neither row holds a point in the column named"
+ assert not case_entities(client, case_id, "place")
+ # Every reason, not the first one: a row is fixed in one pass or not at all.
+ assert plan_rows(read)[0]["problems"] == [
+ "Uncertainty radius (m): 'about 30' is not a number",
+ "no point could be read in 'Name'",
+ ]
+ assert plan_rows(read)[1]["problems"] == ["no point could be read in 'Name'"]
+
+
+def test_a_number_field_refuses_prose_and_reads_a_european_spelling(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Places")
+ answer = promote(
+ client, case_id, sheet, ["id", "Name", "Point", "Precision"],
+ [
+ ["r1", "Quai sud", "48.8566, 2.3522", "1 234,5"],
+ ["r2", "Pont nord", "48.8570, 2.3530", "roughly 30"],
+ ],
+ {},
+ keys=["r1", "r2"], type="place", label_column="Name",
+ point_column="Point", attr_columns={"Precision": "radius_m"},
+ ).json()
+ assert (counts(answer)["make"], counts(answer)["error"]) == (1, 1)
+ made = case_entities(client, case_id, "place")
+ assert made[0]["attrs"]["radius_m"] == 1234.5
+ assert "is not a number" in plan_rows(answer)[1]["reason"]
+
+
+def test_a_cell_already_pointing_at_another_type_is_left_alone(client):
+ """A cell pointing at a place is not a person waiting to be overwritten."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ place = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "place", "label": "Quai sud"}
+ ).json()
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]],
+ {"links": {"r1": {"Unit": place["id"]}}},
+ keys=["r1"], type="organization", label_column="Unit",
+ ).json()
+ assert (counts(answer)["make"], counts(answer)["skip"]) == (0, 1)
+ assert "already points at a place" in plan_rows(answer)[0]["reason"]
+ assert answer["meta"]["links"]["r1"]["Unit"] == place["id"], "the hand-made link stands"
+
+
+def test_a_point_column_promotes_into_places_carrying_their_precision(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Sites")
+ answer = promote(
+ client, case_id, sheet, ["id", "Name", "Point"],
+ [["r1", "Quai sud", "48.8566, 2.3522"], ["r2", "Vague", "48.86, 2.35"]], {},
+ keys=["r1", "r2"], type="place", label_column="Name", point_column="Point",
+ )
+ assert answer.status_code == 200, answer.text
+ made = {entity["label"]: entity for entity in case_entities(client, case_id, "place")}
+ assert round(made["Quai sud"]["attrs"]["lat"], 4) == 48.8566
+ assert round(made["Quai sud"]["attrs"]["lon"], 4) == 2.3522
+ # Four decimals is about eleven metres; two is about a kilometre. A place stored
+ # without saying so reads on the map as a pinpoint somebody established.
+ assert made["Quai sud"]["attrs"]["radius_m"] == 11
+ assert made["Vague"]["attrs"]["radius_m"] == 1113
+
+
+def test_a_place_without_a_point_column_is_refused_at_the_door(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Sites")
+ answer = promote(
+ client, case_id, sheet, ["id", "Name"], [["r1", "Quai sud"]], {},
+ keys=["r1"], type="place", label_column="Name",
+ )
+ assert answer.status_code == 422
+ assert "coordinates" in answer.json()["detail"]
+
+
+def test_a_claim_is_not_a_thing_a_bare_row_can_become(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Notes")
+ answer = promote(
+ client, case_id, sheet, ["id", "What"], [["r1", "Seen at the quay"]], {},
+ keys=["r1"], type="claim", label_column="What",
+ )
+ assert answer.status_code == 422
+
+
+def test_a_link_column_files_its_pages_as_sources_that_mention_the_row(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit", "Source"],
+ [
+ ["r1", "3rd Brigade", "https://example.org/a"],
+ ["r2", "4th Brigade", "https://example.org/a"],
+ ],
+ {},
+ keys=["r1", "r2"], type="organization", label_column="Unit", link_column="Source",
+ )
+ assert answer.status_code == 200, answer.text
+ bookmarks = case_entities(client, case_id, "bookmark")
+ assert len(bookmarks) == 1, "a page cited by two rows is one bookmark"
+ assert bookmarks[0]["attrs"]["url"] == "https://example.org/a"
+ units = {entity["label"]: entity["id"] for entity in case_entities(client, case_id, "organization")}
+ mentioned = {
+ link["to"]
+ for link in case_links(client, case_id)
+ if link["from"] == bookmarks[0]["id"] and link["type"] == "mentions"
+ }
+ assert mentioned == set(units.values())
+
+
+def test_a_preview_says_what_would_happen_and_changes_nothing(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/promote/preview",
+ json={
+ "columns": ["id", "Unit"],
+ "rows": [["r1", "3rd Brigade"], ["r2", " "]],
+ "meta": {},
+ "keys": ["r1", "r2"],
+ "subject": {"column": "Unit", "type": "organization"},
+ },
+ )
+ assert answer.status_code == 200, answer.text
+ read = answer.json()
+ layer = read["entities"][0]
+ assert [row["action"] for row in layer["rows"]] == ["make", "skip"]
+ assert layer["counts"] == {"make": 1, "join": 0, "update": 0, "skip": 1, "error": 0}
+ assert not case_entities(client, case_id, "organization"), "a preview writes nothing"
+
+
+def test_a_promotion_refused_by_the_file_leaves_no_entity_behind(client, monkeypatch):
+ """The 409 used to arrive after the case had already gained forty subjects."""
+ from azimut.engine import sheets as sheet_engine
+
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+
+ real_write = sheet_engine.write
+
+ def losing_write(*args, **kwargs):
+ raise sheet_engine.SheetConflict("this file changed on disk since it was opened")
+
+ monkeypatch.setattr(sheet_engine, "write", losing_write)
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit", stamp=read["stamp"],
+ )
+ monkeypatch.setattr(sheet_engine, "write", real_write)
+ assert answer.status_code == 409
+ assert not case_entities(client, case_id, "organization"), "the promotion was taken back"
+
+
+def test_only_the_columns_asked_for_travel_into_the_case(client):
+ """A promotion that swept every column would put a worklist's notes in the graph."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "People")
+ answer = promote(
+ client,
+ case_id,
+ sheet,
+ ["id", "Name", "Role", "Private"],
+ [["r1", "Witness A", "driver", "do not contact"]],
+ {},
+ keys=["r1"],
+ type="person",
+ label_column="Name",
+ attr_columns={"Role": "role", "Private": "Private"},
+ )
+ assert answer.status_code == 200, answer.text
+ person = case_entities(client, case_id, "person")[0]
+ assert person["attrs"].get("role") == "driver"
+ # `Private` is not a declared field of a person, so it stays in the sheet where it
+ # was written rather than becoming a field of the case's vocabulary.
+ assert "Private" not in person["attrs"]
+
+
+def test_a_row_with_no_label_is_left_alone(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", " "], ["r2", "3rd Brigade"]], {},
+ keys=["r1", "r2"], type="organization", label_column="Unit",
+ ).json()
+ assert counts(answer)["make"] == 1
+ assert "r1" not in answer["meta"]["links"]
+
+
+def test_only_the_ticked_rows_are_promoted(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "A"], ["r2", "B"]], {},
+ keys=["r2"], type="organization", label_column="Unit",
+ ).json()
+ assert counts(answer)["make"] == 1
+ assert set(answer["meta"]["links"]) == {"r2"}
+
+
+def test_a_promotion_saves_the_table_it_was_given(client):
+ """The analyst promotes what is on screen, which may hold unsaved edits."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit",
+ )
+ text = case_file(client, case_id, sheet["attrs"]["path"]).read_text(encoding="utf-8-sig")
+ assert "3rd Brigade" in text
+
+
+def test_a_promotion_is_refused_when_the_file_moved_on(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ case_file(client, case_id, sheet["attrs"]["path"]).write_text(
+ "id,Unit\nr1,elsewhere\n", encoding="utf-8"
+ )
+ answer = promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "3rd Brigade"]], {},
+ keys=["r1"], type="organization", label_column="Unit", stamp=read["stamp"],
+ )
+ assert answer.status_code == 409
+
+
+def test_a_type_or_a_column_the_sheet_does_not_have_is_refused(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Units")
+ body = dict(keys=["r1"], type="organization", label_column="Unit")
+ assert promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "A"]], {}, **{**body, "type": "invented"}
+ ).status_code == 422
+ assert promote(
+ client, case_id, sheet, ["id", "Unit"], [["r1", "A"]], {}, **{**body, "label_column": "Gone"}
+ ).status_code == 422
+
+
+def test_a_body_over_the_limit_is_refused_before_it_is_parsed(client, monkeypatch):
+ from azimut.api import sheets as sheets_api
+
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ monkeypatch.setattr(sheets_api, "MAX_SHEET_BODY_BYTES", 200)
+ response = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}",
+ json={"columns": ["id", "n"], "rows": [["r1", "x" * 500]], "meta": {}},
+ )
+ assert response.status_code == 413
+
+
+# -- the question the sheet was left on ---------------------------------------
+#
+# The sort and the hidden columns were always in the sidecar; the half that decides
+# which rows are on screen lived in the browser tab and died with it. On a tool whose
+# answer to saved views is *a sheet is its own saved reading*, that was the gap.
+
+
+def test_the_sidecar_remembers_the_question_the_rows_were_left_under():
+ clean = sheet_engine.clean_meta(
+ {
+ "query": "kherson",
+ "filters": {
+ "Status": {"values": ["to do", "to do", "done"], "fill": "blank"},
+ "Subject": {"contains": "quai"},
+ "Gone": {"values": ["anything"]},
+ "Notes": {"values": [], "fill": "invented"},
+ },
+ },
+ ["id", "Status", "Subject", "Notes"],
+ [],
+ )
+ assert clean["query"] == "kherson"
+ # A filter on a column somebody deleted in a spreadsheet is a question about nothing.
+ assert set(clean["filters"]) == {"Status", "Subject"}
+ assert clean["filters"]["Status"]["values"] == ["to do", "done"], "said twice is said once"
+ assert clean["filters"]["Status"]["fill"] == "blank"
+ # A clause naming nothing is not a clause, and a filter of nothing is not a filter.
+ assert "Notes" not in clean["filters"], "an ask nobody can answer is dropped whole"
+
+
+def test_a_query_longer_than_a_search_is_cut_rather_than_stored():
+ clean = sheet_engine.clean_meta({"query": "x" * 400}, ["id"], [])
+ assert len(clean["query"]) == sheet_engine.MAX_QUERY
+
+
+def test_a_second_sort_key_is_dropped_when_it_names_the_first():
+ """Breaking a column's ties with itself is not a sort, it is a loop."""
+ same = sheet_engine.clean_meta(
+ {"sort": {"column": "Status", "desc": False, "then": {"column": "Status", "desc": True}}},
+ ["id", "Status", "Subject"],
+ [],
+ )
+ assert same["sort"] == {"column": "Status", "desc": False}
+
+ kept = sheet_engine.clean_meta(
+ {"sort": {"column": "Status", "desc": False, "then": {"column": "Subject", "desc": True}}},
+ ["id", "Status", "Subject"],
+ [],
+ )
+ assert kept["sort"]["then"] == {"column": "Subject", "desc": True}
+
+
+def test_a_legend_names_a_colour_the_palette_has_and_a_pin_names_a_row_that_exists():
+ clean = sheet_engine.clean_meta(
+ {
+ "legend": {"red": "ruled out", "puce": "invented", "blue": " "},
+ "pinned": "r_gone",
+ "tall": 1,
+ },
+ ["id", "Subject"],
+ [["r1", "Quai sud"]],
+ )
+ assert clean["legend"] == {"red": "ruled out"}
+ assert clean["pinned"] is None, "a reference row that is not in the file is not a reference"
+ assert clean["tall"] is True
+
+ kept = sheet_engine.clean_meta({"pinned": "r1"}, ["id", "Subject"], [["r1", "Quai sud"]])
+ assert kept["pinned"] == "r1"
+
+
+def test_the_grid_own_state_is_written_without_touching_the_file(client):
+ """The whole reason the second route exists.
+
+ Rewriting the CSV to record that a funnel was clicked moved the modification time the
+ stamp is made of, so the analyst's own next save answered a conflict nobody caused.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ save(client, case_id, sheet, ["id", "Subject"], [["r1", "Quai sud"]], {})
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ before = path.read_bytes()
+ stamp = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}/stamp").json()["stamp"]
+
+ written = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/meta",
+ json={"meta": {"colours": {"r1": "red"}, "query": "quai", "pinned": "r1"}},
+ )
+ assert written.status_code == 200, written.text
+ assert written.json()["meta"]["colours"] == {"r1": "red"}
+ assert written.json()["meta"]["pinned"] == "r1"
+ assert path.read_bytes() == before, "the artifact is byte-identical"
+ assert client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}/stamp").json()["stamp"] == stamp
+
+
+def test_the_meta_route_cleans_against_the_file_on_disk(client):
+ """It is the file that says which columns exist, not the body being written."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ save(client, case_id, sheet, ["id", "Subject"], [["r1", "Quai sud"]], {})
+
+ written = client.put(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/meta",
+ json={"meta": {"widths": {"Subject": 200, "Invented": 200}}},
+ )
+ assert written.json()["meta"]["widths"] == {"Subject": 200}
+
+
+def test_the_stamp_route_answers_what_a_save_would_be_asked_to_present(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ read = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}").json()
+ assert client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}/stamp").json() == {
+ "stamp": read["stamp"]
+ }
+
+ path = case_file(client, case_id, sheet["attrs"]["path"])
+ path.write_text("id,Subject\nr1,Written elsewhere\n", encoding="utf-8")
+ moved = client.get(f"/api/cases/{case_id}/sheets/{sheet['id']}/stamp").json()["stamp"]
+ assert moved != read["stamp"], "the grid can tell it is showing an old table"
+
+
+def test_the_stamp_of_a_sheet_that_is_not_one_is_refused(client):
+ case_id = make_case(client)
+ other = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "subject", "label": "Someone"}
+ ).json()
+ assert client.get(f"/api/cases/{case_id}/sheets/{other['id']}/stamp").status_code == 404
+
+
+# -- a batch of rows, and a second reading of them ----------------------------
+
+
+def test_a_table_is_parsed_without_anything_being_filed(client):
+ """One CSV parser in the app. A second one in the browser would guess the delimiter
+ differently, and the file it disagreed about is the one being imported."""
+ case_id = make_case(client)
+ before = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]
+
+ read = client.post(
+ f"/api/cases/{case_id}/sheets/parse", json={"text": "handle;seen\n@a;yes\n@b;no\n"}
+ )
+ assert read.status_code == 200, read.text
+ # Keyed by the same parser that keys an import, so the mapping screen and the append
+ # both see the table the way the app always sees one.
+ assert read.json()["columns"] == ["id", "handle", "seen"]
+ assert [row[1:] for row in read.json()["rows"]] == [["@a", "yes"], ["@b", "no"]]
+ assert client.get(f"/api/cases/{case_id}/sheets").json()["sheets"] == before
+
+
+def test_a_duplicate_carries_the_whole_sidecar_and_its_own_edges(client):
+ """Forking meant exporting the CSV and importing it back, which arrives stripped of
+ every colour, role, note and link."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ person = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ meta = {
+ "roles": {"Status": {"kind": "state", "values": ["to do", "done"]}},
+ "notes": {"Status": "where this row got to"},
+ "colours": {"r1": "red"},
+ "links": {"r1": {"Subject": person["id"]}},
+ "legend": {"red": "ruled out"},
+ "query": "quai",
+ }
+ save(client, case_id, sheet, ["id", "Subject", "Status"], [["r1", "Quai sud", "done"]], meta)
+
+ made = client.post(f"/api/cases/{case_id}/sheets/{sheet['id']}/duplicate", json={})
+ assert made.status_code == 200, made.text
+ copy = made.json()
+ assert copy["id"] != sheet["id"]
+ assert copy["label"] == "Candidates copy"
+ assert copy["meta"]["roles"]["Status"]["values"] == ["to do", "done"]
+ assert copy["meta"]["notes"] == {"Status": "where this row got to"}
+ assert copy["meta"]["colours"] == {"r1": "red"}
+ assert copy["meta"]["legend"] == {"red": "ruled out"}
+ assert copy["meta"]["query"] == "quai"
+
+ # Two files, and the copy is a real one.
+ assert copy["attrs"]["path"] != sheet["attrs"]["path"]
+ rows = list(csv.reader(io.StringIO(case_file(client, case_id, copy["attrs"]["path"]).read_text())))
+ assert rows[1][1] == "Quai sud", "the rows keep their keys and their words"
+
+ # Its cells point where the original's did, so the case knows both sheets rest on it.
+ mentions = [
+ link
+ for link in case_links(client, case_id)
+ if link["type"] == "mentions" and link["to"] == person["id"]
+ ]
+ assert {link["from"] for link in mentions} == {sheet["id"], copy["id"]}
+
+
+def test_a_duplicate_can_be_named_and_a_sheet_that_is_not_one_cannot_be_forked(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ made = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/duplicate", json={"title": "Second pass"}
+ )
+ assert made.json()["label"] == "Second pass"
+
+ other = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "subject", "label": "Someone"}
+ ).json()
+ assert (
+ client.post(f"/api/cases/{case_id}/sheets/{other['id']}/duplicate", json={}).status_code
+ == 404
+ )
+
+
+# -- whether a column of sources still answers --------------------------------
+#
+# The only part of a sheet that reaches the network, and it goes on a press. The five
+# states are the point: a checker reporting true/false would put "this page is gone"
+# and "this machine is offline" in one bucket.
+
+
+def fake_http(monkeypatch, answers):
+ """A real httpx client over a transport that answers from a table of addresses.
+
+ The client is the real one — not a stand-in — because what it does with a redirect is
+ exactly what is under test: a `Location` pointing at the loopback is refused, and that
+ refusal lives in how the hops are followed.
+
+ A table value is a status, an exception to raise, or a `("redirect", url)` pair.
+ """
+ asked: list[str] = []
+
+ def handle(request):
+ url = str(request.url)
+ asked.append(url)
+ answer = answers[url]
+ if isinstance(answer, Exception):
+ raise answer
+ if isinstance(answer, tuple):
+ return sheetlinks.httpx.Response(302, headers={"Location": answer[1]})
+ return sheetlinks.httpx.Response(answer)
+
+ monkeypatch.setattr(
+ sheetlinks,
+ "_client",
+ lambda: sheetlinks.httpx.Client(
+ transport=sheetlinks.httpx.MockTransport(handle), follow_redirects=False
+ ),
+ )
+ return asked
+
+
+def test_a_link_sweep_tells_gone_from_refused_from_unreachable(client, monkeypatch):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ answers = {
+ "https://a.org/live": 200,
+ "https://a.org/deleted": 404,
+ "https://a.org/behind-a-login": 403,
+ "https://a.org/nowhere": sheetlinks.httpx.ConnectError("no route"),
+ }
+ fake_http(monkeypatch, answers)
+
+ checked = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check", json={"urls": list(answers)}
+ )
+ assert checked.status_code == 200, checked.text
+ links = checked.json()["links"]
+ assert links["https://a.org/live"]["state"] == "ok"
+ assert links["https://a.org/deleted"] == {"state": "gone", "code": 404, "reason": ""}
+ # A 403 behind a login says nothing about whether the page is there, so it is not dead.
+ assert links["https://a.org/behind-a-login"]["state"] == "refused"
+ assert links["https://a.org/nowhere"]["state"] == "unreachable"
+
+
+def test_one_address_said_eleven_times_is_asked_once(client, monkeypatch):
+ """Eleven rows sourced to one channel hold one address eleven times, and asking that
+ host eleven times would be the rudest way to learn one fact."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ asked = fake_http(monkeypatch, {"https://a.org/one": 200})
+
+ checked = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check",
+ json={"urls": ["https://a.org/one"] * 11},
+ )
+ assert asked == ["https://a.org/one"]
+ assert list(checked.json()["links"]) == ["https://a.org/one"]
+
+
+def test_something_that_is_not_an_address_is_answered_rather_than_fetched(client, monkeypatch):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ asked = fake_http(monkeypatch, {})
+
+ checked = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check",
+ json={"urls": ["file:///etc/passwd", "not a link at all"]},
+ )
+ assert asked == [], "nothing left the machine"
+ assert all(entry["state"] == "refused" for entry in checked.json()["links"].values())
+
+
+def test_a_sweep_that_runs_out_of_its_budget_says_which_addresses_it_never_asked(
+ client, monkeypatch
+):
+ """The per-address timeout never bounded the batch.
+
+ Twenty five addresses, each taking a HEAD and then a GET at six seconds, is five minutes
+ of one held request and one occupied thread — the same hung screen the six seconds were
+ chosen to avoid. Past the budget the rest come back `skipped`, which is a different
+ answer from `unreachable`: nobody asked, so nothing was learnt about the page.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ urls = [f"https://a.org/{n}" for n in range(4)]
+ fake_http(monkeypatch, dict.fromkeys(urls, 200))
+ ticks = iter([0.0, 0.0, 1.0, sheetlinks.BUDGET + 1, sheetlinks.BUDGET + 2])
+ monkeypatch.setattr(sheetlinks, "_now", lambda: next(ticks))
+
+ links = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check", json={"urls": urls}
+ ).json()["links"]
+
+ assert [links[url]["state"] for url in urls] == ["ok", "ok", "skipped", "skipped"]
+ assert links[urls[2]]["reason"] == "the batch ran out of time"
+
+
+def test_the_check_does_not_follow_a_redirect_onto_the_machine_itself(client, monkeypatch):
+ """The addresses come from the sheet, and a sheet arrives by import, paste or workbook.
+
+ A column of links from a third party could otherwise make this app knock on its own
+ ports and report which of them answered: the loopback guard asks only that the Host be a
+ loopback name, so a remote host answering `Location: 127.0.0.1:8000` walked straight
+ through it. What leaks is only "this port answered" — the checker reads a status and
+ never a body — which is why this is a refusal with its own reason rather than a 500.
+ """
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ asked = fake_http(
+ monkeypatch,
+ {
+ "https://a.org/redirect": ("redirect", "http://127.0.0.1:8000/api/cases"),
+ "https://a.org/onward": ("redirect", "https://b.org/landed"),
+ "https://b.org/landed": 200,
+ },
+ )
+
+ links = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check",
+ json={
+ "urls": [
+ "https://a.org/redirect",
+ "https://a.org/onward",
+ "http://localhost:8000/api/cases",
+ "http://192.168.1.4/router",
+ ]
+ },
+ ).json()["links"]
+
+ assert links["https://a.org/redirect"]["state"] == "refused"
+ assert links["https://a.org/redirect"]["reason"] == "redirected to a local address"
+ # A redirect that stays outside is followed as it always was.
+ assert links["https://a.org/onward"]["state"] == "ok"
+ # And a local address written in the cell itself never leaves at all.
+ assert links["http://localhost:8000/api/cases"]["reason"] == "a local address"
+ assert links["http://192.168.1.4/router"]["reason"] == "a local address"
+ assert "http://127.0.0.1:8000/api/cases" not in asked
+ assert "http://192.168.1.4/router" not in asked
+
+
+def test_a_batch_over_the_cap_is_refused_at_the_door(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ over = [f"https://a.org/{n}" for n in range(sheetlinks.MAX_LINKS + 1)]
+ response = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/links/check", json={"urls": over}
+ )
+ assert response.status_code == 422
+
+
+# -- the reading, written out --------------------------------------------------
+
+
+def test_an_export_lands_in_the_case_exports_folder(client):
+ """A file, not a download. Every other finished thing in this app lands in a folder
+ the analyst chose, and a table in the browser's downloads was the one export nobody
+ could find twice."""
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/csv",
+ json={"columns": ["id", "Subject"], "rows": [["r1", "Quai sud"]]},
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["file"] == "Candidates.csv"
+
+ written = case_file(client, case_id, "exports/Candidates.csv")
+ assert written.is_file()
+ assert written.read_text(encoding="utf-8-sig") == "id,Subject\nr1,Quai sud\n"
+ # No byte of the file goes back to the browser: what it gets is where it went.
+ assert "csv" not in answer.json()
+
+
+def test_a_second_export_inside_the_case_overwrites_rather_than_piling_up(client):
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+ body = {"columns": ["id", "Subject"], "rows": [["r1", "Quai sud"]]}
+ client.post(f"/api/cases/{case_id}/sheets/{sheet['id']}/csv", json=body)
+ client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/csv",
+ json={**body, "rows": [["r1", "Pont nord"]]},
+ )
+
+ from azimut.api.cases import get_case
+
+ exports = get_case(case_id).resolve_inside("exports")
+ assert [path.name for path in sorted(exports.iterdir())] == ["Candidates.csv"]
+ assert "Pont nord" in (exports / "Candidates.csv").read_text(encoding="utf-8-sig")
+
+
+def test_an_export_writes_to_the_folder_saved_for_sheets(client, tmp_path):
+ chosen = tmp_path / "tables"
+ chosen.mkdir()
+ client.put("/api/settings/prefs", json={"export_dirs": {"sheets": str(chosen)}})
+ case_id = make_case(client)
+ sheet = new_sheet(client, case_id, "Candidates")
+
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/csv",
+ json={"columns": ["id"], "rows": [["r1"]]},
+ )
+ assert answer.json()["path"] == str(chosen)
+ assert (chosen / "Candidates.csv").is_file()
+
+ # Outside the case nothing is ever overwritten: the files there are the analyst's.
+ client.post(
+ f"/api/cases/{case_id}/sheets/{sheet['id']}/csv",
+ json={"columns": ["id"], "rows": [["r2"]]},
+ )
+ assert len(list(chosen.iterdir())) == 2
+
+
+def test_exporting_a_sheet_that_is_not_one_is_refused(client):
+ case_id = make_case(client)
+ person = client.post(
+ f"/api/cases/{case_id}/entities", json={"type": "person", "label": "Witness A"}
+ ).json()
+ answer = client.post(
+ f"/api/cases/{case_id}/sheets/{person['id']}/csv",
+ json={"columns": ["id"], "rows": [["r1"]]},
+ )
+ assert answer.status_code == 404
diff --git a/tests/test_sky.py b/tests/test_sky.py
index e0ec91b..121b425 100644
--- a/tests/test_sky.py
+++ b/tests/test_sky.py
@@ -60,6 +60,30 @@ def test_moon_matches_meeus_example_47a():
assert abs(distance[0] - 368409.7) < 400
+def test_moon_longitude_tracks_the_full_series_across_decades():
+ """Example 47.a is one instant, and this series has 0.02 deg of its own
+ error — so a wrong perturbation term can sit *closer* to the truth there by
+ luck. These four epochs are picked where the terms do not cancel, and the
+ references are ELP-2000/82 (Meeus table 47.A, leading terms) rather than the
+ truncation under test.
+
+ The one that made this necessary: the 0.053 inequality is `sin(2D + M')`,
+ the Moon's mean anomaly. Spelled with the Sun's it costs up to 0.1 deg of
+ moon direction, which lands squarely in what a shadow reading is judged on.
+ """
+ references = {
+ 2459983.2200: 160.026647,
+ 2460579.2900: 105.295233,
+ 2462218.3900: 87.547067,
+ 2463410.5300: 325.029664,
+ }
+ for julian_day, expected in references.items():
+ t = np.array([(julian_day - 2451545.0) / 36525.0])
+ lon, _lat, _distance = sky._moon_ecliptic(t)
+ error = abs((lon[0] - expected + 180) % 360 - 180)
+ assert error < 0.07, f"JD {julian_day}: {error:.4f} deg off"
+
+
def test_obliquity_is_current_at_j2000():
"""23.4392911° mean at J2000, shifted by the nutation term in obliquity."""
obliquity = sky._obliquity(np.array([0.0]), np.array([125.04]))
diff --git a/tests/test_stitch.py b/tests/test_stitch.py
index 4d218fc..550d69a 100644
--- a/tests/test_stitch.py
+++ b/tests/test_stitch.py
@@ -58,6 +58,23 @@ def _pan(angles, width=520, height=420, focal=520.0, seed=5) -> list[Image.Image
return out
+def _overlaid(images, box=(18, 18, 138, 88), seed=41) -> list[Image.Image]:
+ """The same textured patch burnt into every image at the same pixel.
+
+ Stands in for what a video actually carries: a platform logo, a channel bug, a
+ timestamp. Textured rather than flat, because a flat patch has no keypoints and
+ would prove nothing.
+ """
+ x0, y0, x1, y1 = box
+ logo = _scene(x1 - x0, y1 - y0, seed=seed, blobs=90)
+ out = []
+ for img in images:
+ copy = img.copy()
+ copy.paste(logo, (x0, y0))
+ out.append(copy)
+ return out
+
+
def _widths(quads):
return [max(p[0] for p in q) - min(p[0] for p in q) for q in quads]
@@ -241,6 +258,102 @@ def test_rotation_layout_rejects_an_unknown_warp():
stitch.solve_rotation_layout(_pan([0, 20]), width=800, height=600, warp="planar")
+# --- fixed overlays --------------------------------------------------------
+
+
+def _points(*groups):
+ """Keypoint arrays from ``(x, y)`` lists, as the solvers hand them over."""
+ import numpy as np
+
+ return [np.asarray(g, dtype=np.float32) for g in groups]
+
+
+def test_static_points_flags_what_sits_in_the_same_place():
+ pinned = [(10.0, 10.0), (12.0, 40.0), (60.0, 15.0)]
+ moving = [[(100.0 + 30 * i, 20.0 * k) for k in range(12)] for i in range(4)]
+ points = _points(*[pinned + m for m in moving])
+
+ static = stitch._static_points(points, [(400, 300)] * 4)
+
+ assert [sorted(s) for s in static] == [[0, 1, 2]] * 4
+
+
+def test_static_points_says_nothing_from_a_single_peer():
+ """Two frames of a still camera and two frames sharing a logo are the same
+ picture — and there the identity the overlay pushes for is the right answer."""
+ points = _points([(10.0, 10.0), (12.0, 40.0)], [(10.0, 10.0), (12.0, 40.0)])
+
+ assert stitch._static_points(points, [(400, 300)] * 2) == [set(), set()]
+
+
+def test_static_points_leaves_a_scene_that_simply_does_not_move():
+ """Everything pinned means the camera is what stands still. Strip that and the
+ solver has nothing left to match with, so the piece keeps all of it."""
+ shared = [(10.0 * i, 20.0 + i) for i in range(30)]
+ points = _points(shared, shared, shared)
+
+ assert stitch._static_points(points, [(400, 300)] * 3) == [set()] * 3
+
+
+def test_static_points_only_compares_pieces_of_the_same_geometry():
+ """Same pixel on a different canvas is not the same place, so no overlay claim."""
+ shared = [(10.0, 10.0), (12.0, 40.0), (60.0, 15.0)]
+ noise = [[(100.0 + 30 * i, 20.0 * k) for k in range(12)] for i in range(3)]
+ points = _points(*[shared + n for n in noise])
+
+ static = stitch._static_points(points, [(400, 300), (400, 300), (640, 480)])
+
+ assert static == [set(), set(), set()]
+
+
+def test_solve_layout_refuses_a_stitch_only_the_overlay_supports():
+ """The regression this rejection exists for, and the reason it is worth having.
+
+ Three unrelated scenes wearing the same logo: the overlay matches itself
+ perfectly, so unfiltered it clears every guard here and glues the three into
+ one confident panorama — geometry invented out of nothing, which is exactly
+ what an analyst must never be handed.
+ """
+ pieces = _overlaid([_scene(width=500, height=500, seed=s) for s in (1, 2, 3)])
+
+ with pytest.raises(RuntimeError, match="no overlap"):
+ stitch.solve_layout(pieces, width=900, height=900)
+
+
+def test_rotation_layout_refuses_a_stitch_only_the_overlay_supports():
+ pieces = _overlaid([_scene(width=500, height=500, seed=s) for s in (4, 5, 6)])
+
+ with pytest.raises(RuntimeError, match="no overlap"):
+ stitch.solve_rotation_layout(pieces, width=900, height=900)
+
+
+def test_solve_layout_still_stitches_pieces_that_wear_a_logo():
+ """The other half of the bargain: dropping those keypoints must not cost the
+ real overlap. Same known offset as the plain planar test, logo and all."""
+ scene = _scene()
+ pieces = _overlaid([scene.crop((x, 0, x + 500, 500)) for x in (0, 130, 260, 390)])
+
+ solved = stitch.solve_layout(pieces, width=1600, height=800)
+
+ assert solved["dropped"] == []
+ width_a = solved["quads"][0][1][0] - solved["quads"][0][0][0]
+ xs = [_centroid(solved["quads"][i])[0] for i in range(4)]
+ for a, b in zip(xs, xs[1:]):
+ assert (b - a) / width_a == pytest.approx(130 / 500, abs=0.06)
+
+
+def test_rotation_layout_still_stitches_pieces_that_wear_a_logo():
+ views = _overlaid(_pan([-30, -15, 0, 15, 30]))
+
+ solved = stitch.solve_rotation_layout(views, width=1600, height=800)
+
+ assert solved["dropped"] == []
+ xs = [_centroid(solved["quads"][i])[0] for i in range(5)]
+ assert xs == sorted(xs)
+ widths = _widths(solved["quads"].values())
+ assert max(widths) / min(widths) == pytest.approx(1.0, abs=0.1)
+
+
# --- the remap op ----------------------------------------------------------
diff --git a/tests/test_templates_api.py b/tests/test_templates_api.py
index f42dd4c..8f7740e 100644
--- a/tests/test_templates_api.py
+++ b/tests/test_templates_api.py
@@ -108,6 +108,8 @@ def test_templates_live_beside_settings_not_in_a_case(client, monkeypatch):
{"signature": {"scale": 2}},
{"signatureText": {"size": 0}},
{"footerEnabled": "false"},
+ {"footerText": "false"},
+ {"footerCoords": 1},
],
)
def test_invalid_proof_render_values_are_rejected(client, data):
@@ -178,3 +180,24 @@ def test_invalid_hand_edited_template_is_not_returned(client):
}
)
assert client.get("/api/templates").json()["proof"] == []
+
+
+def test_a_style_stored_before_the_footer_switches_reads_as_it_looked(client):
+ """The credit line goes on printing, the coordinates go on not printing."""
+ saved = client.post(
+ "/api/templates/proof",
+ json={"name": "Old house style", "data": {"bg": "#101418"}},
+ ).json()
+
+ assert saved["data"]["footerText"] is True
+ assert saved["data"]["footerCoords"] is False
+
+
+def test_a_style_carries_what_the_plate_prints(client):
+ saved = client.post(
+ "/api/templates/proof",
+ json={"name": "Points on the plate", "data": {"footerText": False, "footerCoords": True}},
+ ).json()
+
+ assert saved["data"]["footerText"] is False
+ assert saved["data"]["footerCoords"] is True
diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.py
index 98eaf3f..7275dc8 100644
--- a/tests/test_thumbnails.py
+++ b/tests/test_thumbnails.py
@@ -208,3 +208,56 @@ def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):
refreshed = media_engine.read_item(c, item["path"])
assert refreshed["thumbnail"] and c.resolve_inside(refreshed["thumbnail"]).exists()
assert workqueue.wait_until_idle()
+
+
+# -- videos shorter than the seek -----------------------------------------
+
+
+def test_a_video_shorter_than_the_seek_still_gets_a_thumbnail(case, monkeypatch, tmp_path):
+ """`-ss 1` skips a fade-in, but a clip under a second has no frame there and
+ ffmpeg writes nothing at all. That is not a broken file, so the render falls
+ back to the opening frame instead of burning the job's retries."""
+ from azimut.engine import ffmpeg as ffmpeg_engine
+
+ seeks: list[str] = []
+
+ def fake_run(argv, **kwargs):
+ seek = argv[argv.index("-ss") + 1]
+ seeks.append(seek)
+ if seek != "0":
+ return None # ffmpeg seeks past the end and produces no file
+ Image.new("RGB", (32, 24), (5, 5, 5)).save(argv[-1], "JPEG")
+ return None
+
+ monkeypatch.setattr(ffmpeg_engine, "ffmpeg_available", lambda: True)
+ monkeypatch.setattr(ffmpeg_engine, "ffmpeg_exe", lambda: "ffmpeg")
+ monkeypatch.setattr(thumbnails.subprocess, "run", fake_run)
+
+ source = tmp_path / "blink.mp4"
+ source.write_bytes(b"short clip")
+ out = tmp_path / "thumb.jpg"
+
+ assert thumbnails._render(source, out, "video") is True
+ assert out.exists()
+ assert seeks == ["1", "0"], "the opening frame was never tried"
+
+
+def test_a_normal_video_is_read_one_second_in(case, monkeypatch, tmp_path):
+ """The fallback must not cost a second ffmpeg run on every ordinary clip."""
+ from azimut.engine import ffmpeg as ffmpeg_engine
+
+ seeks: list[str] = []
+
+ def fake_run(argv, **kwargs):
+ seeks.append(argv[argv.index("-ss") + 1])
+ Image.new("RGB", (32, 24), (5, 5, 5)).save(argv[-1], "JPEG")
+ return None
+
+ monkeypatch.setattr(ffmpeg_engine, "ffmpeg_available", lambda: True)
+ monkeypatch.setattr(ffmpeg_engine, "ffmpeg_exe", lambda: "ffmpeg")
+ monkeypatch.setattr(thumbnails.subprocess, "run", fake_run)
+
+ source = tmp_path / "clip.mp4"
+ source.write_bytes(b"a longer clip")
+ assert thumbnails._render(source, tmp_path / "thumb.jpg", "video") is True
+ assert seeks == ["1"]
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index baebce3..85656fa 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -707,3 +707,46 @@ def test_esri_capture_date_network_failure_returns_none():
raise OSError("down")
assert tiles.esri_capture_date(0, 0, 17, get=boom) is None
+
+
+def test_crop_across_the_antimeridian_is_not_half_blank():
+ """Longitude wraps, so the tiles past ±180° are the ones on the other side.
+
+ Clamping them away instead left a blank band down the middle of every
+ capture near the date line — the one place on the planet where a crop is
+ guaranteed to straddle the edge of the grid.
+ """
+ provider = tiles.BUILTIN_PROVIDERS[0]
+ asked: list[int] = []
+ zoom = 6
+ max_index = (1 << zoom) - 1
+
+ def fake_fetch(client, url):
+ # the x the template was filled with, read back off the URL
+ asked.append(int(url.split("/")[-2]))
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+ img, prov = tiles.fetch_crop(
+ 0.0, 179.98, zoom, 900, 600, provider, fetch_tile=fake_fetch
+ )
+
+ assert prov["tiles_missing"] == 0, "a tile past the antimeridian went unfetched"
+ assert asked, "no tile was requested at all"
+ assert all(0 <= x <= max_index for x in asked), f"out-of-grid tile index: {sorted(set(asked))}"
+ # and the canvas holds imagery edge to edge, not the fill colour
+ assert img.getpixel((2, 300)) == (10, 120, 10)
+ assert img.getpixel((897, 300)) == (10, 120, 10)
+
+
+def test_crop_still_leaves_the_poles_empty():
+ """Latitude does not wrap: above the top row there is no imagery to read from
+ the other side, and inventing some would be a picture of nowhere."""
+ provider = tiles.BUILTIN_PROVIDERS[0]
+
+ def fake_fetch(client, url):
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+ _img, prov = tiles.fetch_crop(
+ 85.0, 0.0, 3, 700, 700, provider, fetch_tile=fake_fetch
+ )
+ assert prov["tiles_missing"] > 0
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 190f680..37ed0d5 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -143,8 +143,8 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# The pair below is the contract, and it moves in one direction only: when a
# shipped file really changes, set the manifest to the current __version__ and
# record the new digest here (the failing test prints it).
-EXTENSION_VERSION = "0.2.5"
-EXTENSION_PAYLOAD = "f8141fe57fed06b98f373446d8fc19e932a988d1cc27fdcc7d632ae1b65bb198"
+EXTENSION_VERSION = "0.2.9"
+EXTENSION_PAYLOAD = "783876649d02d0b8b06f34fb10d01bbb23633601e86cdff5adcd7d79fda2be1c"
# Text is digested by its line content: a Windows checkout can carry CRLF, and
# the gate has to reach the same verdict on the three CI platforms.
diff --git a/uv.lock b/uv.lock
index 0a04f15..5656463 100644
--- a/uv.lock
+++ b/uv.lock
@@ -105,6 +105,7 @@ dependencies = [
{ name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" },
{ name = "numpy", version = "2.5.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" },
{ name = "opencv-python-headless" },
+ { name = "openpyxl" },
{ name = "pillow" },
{ name = "pydantic" },
{ name = "python-multipart" },
@@ -125,6 +126,7 @@ dev = [
{ name = "pypdf" },
{ name = "pytest" },
{ name = "pytest-asyncio" },
+ { name = "pytest-xdist" },
{ name = "ruff" },
]
@@ -149,11 +151,13 @@ requires-dist = [
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=2.3,<3" },
{ name = "numpy", specifier = ">=1.26,<3" },
{ name = "opencv-python-headless", specifier = ">=4.9,<5" },
+ { name = "openpyxl", specifier = ">=3.1,<4" },
{ name = "pillow", specifier = ">=10.3,<13" },
{ name = "pydantic", specifier = ">=2.7,<3" },
{ name = "pypdf", marker = "extra == 'dev'", specifier = ">=6,<7" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8,<10" },
{ name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.23,<2" },
+ { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6,<4" },
{ name = "python-multipart", specifier = ">=0.0.9,<1.0" },
{ name = "requests", specifier = ">=2.31,<3" },
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.15,<0.16" },
@@ -478,6 +482,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" },
]
+[[package]]
+name = "et-xmlfile"
+version = "2.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d3/38/af70d7ab1ae9d4da450eeec1fa3918940a5fafb9055e934af8d6eb0c2313/et_xmlfile-2.0.0.tar.gz", hash = "sha256:dab3f4764309081ce75662649be815c4c9081e88f0837825f90fd28317d4da54", size = 17234, upload-time = "2024-10-25T17:25:40.039Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" },
+]
+
+[[package]]
+name = "execnet"
+version = "2.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/bf/89/780e11f9588d9e7128a3f87788354c7946a9cbb1401ad38a48c4db9a4f07/execnet-2.1.2.tar.gz", hash = "sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd", size = 166622, upload-time = "2025-11-12T09:56:37.75Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ab/84/02fc1827e8cdded4aa65baef11296a9bbe595c474f0d6d758af082d849fd/execnet-2.1.2-py3-none-any.whl", hash = "sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec", size = 40708, upload-time = "2025-11-12T09:56:36.333Z" },
+]
+
[[package]]
name = "fastapi"
version = "0.139.0"
@@ -1048,6 +1070,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4a/90/b338326131ccb2aaa3c2c85d00f41822c0050139a4bfe723cfd95455bd2d/opencv_python_headless-4.13.0.92-cp37-abi3-win_amd64.whl", hash = "sha256:77a82fe35ddcec0f62c15f2ba8a12ecc2ed4207c17b0902c7a3151ae29f37fb6", size = 40070414, upload-time = "2026-02-05T07:02:26.448Z" },
]
+[[package]]
+name = "openpyxl"
+version = "3.1.5"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "et-xmlfile" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3d/f9/88d94a75de065ea32619465d2f77b29a0469500e99012523b91cc4141cd1/openpyxl-3.1.5.tar.gz", hash = "sha256:cf0e3cf56142039133628b5acffe8ef0c12bc902d2aadd3e0fe5878dc08d1050", size = 186464, upload-time = "2024-06-28T14:03:44.161Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" },
+]
+
[[package]]
name = "packaging"
version = "26.2"
@@ -1391,6 +1425,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930, upload-time = "2026-05-26T09:56:02.576Z" },
]
+[[package]]
+name = "pytest-xdist"
+version = "3.8.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "execnet" },
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/78/b4/439b179d1ff526791eb921115fca8e44e596a13efeda518b9d845a619450/pytest_xdist-3.8.0.tar.gz", hash = "sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1", size = 88069, upload-time = "2025-07-01T13:30:59.346Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" },
+]
+
[[package]]
name = "python-dotenv"
version = "1.2.2"