The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Draw the map on MapLibre behind the façade, and the work that rode with it (#71)
OsintMeThatc178c4a38867
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1abfc7f..1f94a85 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -187,10 +187,10 @@ jobs:runs-on: ubuntu-latesttimeout-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.+ # single Playwright worker on purpose — canvas startup times out when+ # MapLibre 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: falsematrix:diff --git a/README.md b/README.mdindex d7ff256..9816a4d 100644--- a/README.md+++ b/README.md@@ -63,7 +63,7 @@ to fix a point on the map.*| **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, 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. |+| **Geo Report** | Turn a proof into a prepared thread for X or Bluesky: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. || **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. |Under the hood: reusable proof and thread templates, per-case SQLite with a@@ -195,7 +195,23 @@ py scripts\relaunch.py # WindowsThe tool rebuilds the frontend, stops the previous Azimut instance startedthrough the same tool, and launches the fresh build. It never kills unrelated-processes by name. Use `--no-browser` to keep it from opening a new tab.+processes by name. Use `--no-browser` to keep it from opening a new tab, and+`--ext` to bring the capture extension along (see below).++Working on the extension:++```bash+python3 scripts/devext.py # load it into a dev Chrome and Firefox+python3 scripts/devext.py --watch # and reload it on every save+python3 scripts/relaunch.py --ext # app + extension in one command+```++It opens a Chrome and a Firefox of its own, loads `extension/` from disk and+writes the pairing token into it, so an edit needs no reinstall and no paste.+Each dev browser keeps its profile between runs, and the everyday browsers are+left alone. Every pass reports when the extension's background restarted, which+is how you see the new code was taken. `--fresh` starts from an empty profile,+`python3 scripts/devext.py chrome` (or `firefox`) drives just one.Frontend development (hot reload, proxied API):diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdindex 11f872d..fdc210a 100644--- a/docs/IMAGERY_PROVIDERS.md+++ b/docs/IMAGERY_PROVIDERS.md@@ -69,7 +69,7 @@ EEA, so Azimut supports both products:| | Google Satellite (tiles) | Google Satellite (Maps JS) ||---|---|---|| Works in the EEA | **no** (403) | yes |-| Rendering | XYZ tiles through our proxy | a real `google.maps.Map` under Leaflet (GoogleMutant plugin, Beerware licence) |+| Rendering | XYZ tiles through our proxy | a real `google.maps.Map` under our own map, which is transparent where nothing is drawn || Captures | stitched crop, attribution burned | **screen pixels only** from one tab screenshot taken by the capture extension; attribution burned, `method:"screenshot"`, `framed:true` || Capture frame | any size (tiles are fetched) | limited to the map view; no resolution multiplier || Rotation / oversample / marquee | yes | **rotation + marquee yes**, oversample no |@@ -78,21 +78,28 @@ EEA, so Azimut supports both products:Both keys can be saved at once: each lights its own basemap, and the EEA failurepath benches the tiles one automatically (below) leaving the widget on offer.-Leaflet keeps all interaction, so measure tools, places, reference windows and-the labels overlay work unchanged over the widget.+Our own map keeps all interaction, so measure tools, places, reference windows+and the labels overlay work unchanged over the widget.### Maps JS widget behavior-GoogleMutant runs a hidden `google.maps.Map` and clones its `<img>` tiles into a-Leaflet `GridLayer`.--- **Rotation works.** The visible tiles are Leaflet tiles in the rotatable tile- pane, and leaflet-rotate already asks the grid for the rotated bounding box.- The hidden map renders the unrotated viewport, so a turned view can otherwise- expose blank corners.- `lib/gmaps.js` sizes the hidden map to a **square of the container's diagonal,- centred**, which covers every bearing at once. Extra tile renders inside one- map load are free; the billing is per `google.maps.Map`.+Google's own map renders in its own element **under** ours, and ours is+transparent where nothing is drawn (`lib/map/gmaps.js`, "under glass"). It takes+no pointer events: every gesture and every control is ours, and Google's camera+is moved to follow ours on each frame.++- **Rotation works.** Google has no bearing of its own on a raster satellite+ map, so its element is turned by CSS. A turned rectangle would expose blank+ corners, so the element is a **square of the container's diagonal, centred**,+ which covers every bearing at once — a rotated W×H rectangle always fits+ inside the circle of its own diagonal. Extra tile renders inside one map load+ are free; the billing is per `google.maps.Map`.+- **The credit line is moved upright.** Google renders it inside that oversized,+ turned element, where a bearing would rotate it off screen. It is re-homed+ into a fixed holder at the bottom right, which is the one part of the layer+ that does take the pointer, so the terms link stays clickable. If Google's+ markup ever stops offering that node, the same credit and a terms link are+ stated by us instead — the imagery is never shown bare.- **Cloned tiles remain off-limits.** Reading them through canvas, html2canvas ortheir URLs is programmatic extraction forbidden by Google's terms. Thecapture path therefore goes through the **capture extension** (`extension/`,@@ -260,7 +267,8 @@ ship at 10 m/px from three levels out, so the view runs to z18 while requestsstop at 14 and magnify the last native tile without extra requests. AskingSentinel Hub for z18 would bill 16 times as many tiles for server-side upsampling.-Leaflet's `maxNativeZoom` does it on the live map; `fetch_crop` mirrors it so a+The live map stops its tile requests at that level and scales the last one up;+`fetch_crop` mirrors it so acapture matches the screen, and records `native_zoom` +`native_meters_per_pixel` next to `zoom`. This records that the native resolutionis lower than the display zoom implies. The tile proxy@@ -312,7 +320,7 @@ in evidence imagery.**Billing units.** Both bill per tile served. Google's 2D Map Tiles SKU is"Request that returns a 2D map tile" (session and viewport requests are free);-Mapbox Static Tiles bills per tile request when used with Leaflet. Free tiers:+Mapbox Static Tiles bills per tile request on a live map. Free tiers:Google 100k/month then $0.60/1k (plus hard limits of 15k tiles/day and 6k/min perproject), Mapbox 200k/month then $0.50/1k (alerts only, no hard cap). Meteredtiles are proxied through the backend so the counter matches billing exactly;diff --git a/docs/SPEC.md b/docs/SPEC.mdindex b4ce174..ee1c279 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -125,7 +125,7 @@ proof for publication.|------|--------------|| ✅ **Coordinates & sky** | Converts coordinates and reads sun, moon, twilight and local time for a saved point on charts or the map. || ✅ **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. |+| ✅ **Reports & templates** | Stores reusable proof and post structures, then prepares sourced Markdown for X or Bluesky. || ✅ **Case Notebook** | Edits linked Markdown notes with local media, Mermaid diagrams, PDF output and remembered export folders. || ✅ **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. |@@ -155,6 +155,13 @@ proof for publication.| ✅ **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. |+### v3 GEOINT expansion (unreleased)++| Tool | What it does |+|------|--------------|+| ✅ **Map engine** | Draws the map on MapLibre GL behind `lib/map`'s façade, at parity: same providers, same captures, same bearing, and the Google widget basemap kept alive under the map's own transparent canvas. |+| ✅ **Composer hand-off** | Fills X's or Bluesky's own composer with a prepared thread: each post in its own box with its pictures, the thread button pressed between them, every box read back afterwards, and Post left to the analyst. |+---## 6. Roadmap@@ -167,11 +174,11 @@ Each version delivers one complete daily workflow. Firm ideas move here from| Tool | What it does ||------|--------------|-| **Map engine (MapLibre)** | Replaces Leaflet with MapLibre GL at 2D parity: same providers, same captures, and the capture tests still verify the pixels. Ships before the 3D map, which builds on it. || **3D map** | Pitch, public DEM terrain and extruded OSM buildings on the MapLibre map. An oblique capture records its pitch beside the bearing, so the view can be reproduced. || **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. Its photo canvas and pixel↔angle camera frame are built for two callers: Sky Clock fills the same frame by hand. |-| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. Follows the map engine, which redraws what a capture is made of. |-| **Footprint tracing** | Draws a place's uncertainty as the shape it really is, for a quay, a treeline or an L-shaped block the circle describes badly. The field, its validation and its drawing already ship; only the gesture is missing, and it follows the map engine rather than being written twice. |+| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. |+| **Extension map overlays** | Draws the app's own layers over the maps the extension rides on — Google Maps, Earth, Apple, Bing: the search grid, the sun and moon arcs, the measure tools. The geometry is already pure and shared; what is missing is drawing it over a map the app does not own. |+| **Footprint tracing** | Draws a place's uncertainty as the shape it really is, for a quay, a treeline or an L-shaped block the circle describes badly. The field, its validation and its drawing already ship; only the gesture is missing. || **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. || **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. || **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |@@ -209,8 +216,7 @@ can be rebuilt from the spec alone:The result is one track per source file over the render's timecode, withGPS-tagged clips promotable to places.-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+Toward v3: GIF maker; curated tool links; full-text case search; clipboardimage/URL capture with provenance; EXIF/GPS import suggestions for place andtime; sun and moon times read against the terrain horizon the 3D map's DEMsupplies, since a ridge ends the day well before the flat horizon does.@@ -276,6 +282,7 @@ stops making sense.- **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.- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.+- **A front door for the app:** a home surface saying what Azimut is, how a case works and where to start, then keeping the open case in view with recent items, notes and a mini-map of its places, in panels the analyst arranges. The first half is missing today, since a fresh install lands in a workspace with no case and no guidance; the second has to earn its place beside Board, Graph and Timeline, which already read the case.- **A deleted case waits before it is gone:** artifacts, entities and bulk deletes are all recoverable, while removing a case is the one act with no way back and only a typed DELETE in front of it. Move the folder aside instead, and empty it later.## 8. Explicit non-goals@@ -293,9 +300,11 @@ stops making sense.- **Backend**: Python 3.11+, FastAPI on `localhost`; current processing (ffmpeg,yt-dlp, gallery-dl, OpenCV) runs server-side.-- **Frontend**: Svelte + Leaflet (→ MapLibre) + Konva/canvas, served by the- backend, opened in the default browser. Rail = workspaces in pipeline order,- tools are tabs inside them (see [UI.md](UI.md)).+- **Frontend**: Svelte + Konva/canvas, served by the backend, opened in the+ default browser. The map is MapLibre GL behind `lib/map`'s façade, so tools+ speak points, positions and view events and never the engine. Rail =+ workspaces in pipeline order, tools are tabs inside them (see+ [UI.md](UI.md)).- **Settings and secrets:** in-app tabs group general preferences, publishing,imagery, templates, the capture extension, storage and system tools; keysstored locally and never bundled into a shared case, monthly usage counters,@@ -318,7 +327,14 @@ stops making sense.- **Security posture** (single-user localhost): `127.0.0.1` bind + Host/Originguard (DNS rebinding), 0600/0700 perms, hard 100 MP Pillow limit, content-hashednames for images pasted into a proof (no client-chosen path), token-gated- ingest island for the extension. A case id and an artifact name each address+ ingest island for the extension. The one route that reads a case file back out+ of that island — the attachments a composer hand-off carries — fences on the+ **resolved** path, so `media/../case.json` is refused where a prefix read off+ the request would have served it. Filling a composer is the extension's only+ reach past localhost — three social hosts, declared, where it types what the app+ handed it and reads nothing — and the switch that uses it is in the app+ (Settings → Publishing), where the analyst already decides how a thread is+ published. A case id and an artifact name each addressone directory entry, checked against POSIX *and* Windows path rules so theseparator only one of them honours cannot walk out of the workspace. The workspace pointer is the one file writtenoutside the workspace, 0600 and holding a path; deleting the copy a move setdiff --git a/docs/UI.md b/docs/UI.mdindex c291d05..4537892 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -612,7 +612,9 @@ single root to expand from. Expansion is the drill-down.The card names the act instead of the kind — *Frame*, *Collage* — and the panel addsone line saying it was made out of material the case already holds. Only the toolsthat compose case material mark their output: an upload carries nothing, since- "upload" on an upload says nothing about it.+ "upload" on an upload says nothing about it. A capture is not one of them — it has+ no parents to draw, and the ontology files it as collected — though the Media+ Library still holds it back as a file the app produced.- **Previews are the cached thumbnails** the Media Library uses, loaded only for thecards actually on screen and only once each. The graph never generates one: a readthat draws does no CPU work, so an entity whose picture was never cached shows its@@ -1021,17 +1023,24 @@ for a reload that will never come.## Sources-The Media Library toolbar keeps explicit maintenance actions beside Import:-**Thumbnails** repairs missing previews; **Enrich** queues local image+The Media Library toolbar keeps its explicit maintenance actions behind a `⋮`+beside Import, because both are repairs pressed once in a while and read as a+step of importing when they sit next to Download: **Regenerate missing+thumbnails** repairs missing previews; **Read file metadata** queues local imageEXIF/perceptual-hash and video metadata backfill for files not processed by the-current version. A **GPS** toggle beside the type and folder filters narrows the+current version. The `⋮` stays put on a case with no media, its rows disabled,+and closes on Escape or a click outside.++A **GPS** toggle beside the type and folder filters narrows thelist to the files whose own metadata states a position, and appears only in a casethat holds some; how many is in its tooltip, not in its label. Those rows carryone pin glyph — coordinates in the tooltip, not in the title — and clicking itflies the map there. **Show N working files** sits on the same independent axis: aswitch rather than another chip, because the chips answer *show me only X* and aresingle-select where this one is *put X back*. The library opens on what the case-collected, the frames and collages it made itself held back, and the switch says how+collected, the frames, collages and captures it produced itself held back — a capture+is a map the app drew out of tiles or the extension grabbed off the screen, where an+upload, a paste and a download came from outside — and the switch says howmany those are rather than leaving them unannounced; the counts and the paging arecomputed with it so the facets never disagree with the list, and toggling it refetchesbecause the loaded page is already the collected subset. It reads how the file@@ -1040,7 +1049,7 @@ found identical to an extracted frame stays on the side it came in by. A case honothing but working files says so instead of offering to import. Thumbnail polling follows all pending case jobs, includingfiles beyond the loaded page after a case import. Thumbnail failures are scopedto their case, so switching cases always reloads previews even when relative-paths match. Enrich respects an existing confirmed GPS relation during backfill.+paths match. Enrichment respects an existing confirmed GPS relation during backfill.**Import asks where the files came from.** A file fetched by hand elsewhere andthen dropped here carries no address of its own, so a drop or a pick opens one@@ -1142,7 +1151,7 @@ from the map.Map controls sit in two clusters. **Tools** (measure, sun & moon, grid search,reference image) float top-left. A tool with settings opens its panel beside that-cluster, never beneath it, because beneath it is where Leaflet's own controls+cluster, never beneath it, because beneath it is where the map's own controlslive. **View** — fullscreen, OSM labels, saved work — continues the zoom columnbeneath `+`/`−`, because none of them changes what you are doing, only what yousee.@@ -1239,14 +1248,17 @@ 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 answersthe 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+dragging the old one, and while the tool is held 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 atan opacity you choose. Shapes start hollow: a fill hides what is under it, so itis 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+legend reads colour as the feature. **A shape puts the pen down when it lands**:+it is picked and Select comes back with it, so the colour, the width and the note+go onto what was just drawn. What follows a stroke is nearly always a word about+it, and every one of those used to draw a second box first. Three boxes in a row+is the shortcut pressed three times. Text does the same and opens its editor where+the label was placed, because placing it and saying what it says are oneact. A label holds more than one line — Shift+Enter opens the second, Enter endsthe edit.@@ -1257,8 +1269,8 @@ points-based kinds: it has too many samples to show, so it takes the frame andthe 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.+drone, a camera, an antenna, a north arrow — stamped with one click. The one tool+that 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 legendby colour and claims no vocabulary the legend cannot say. It resizes from itscorners with the ratio locked: the box is square and there is one side to change,diff --git a/extension/README.md b/extension/README.mdindex cab0761..c24ada8 100644--- a/extension/README.md+++ b/extension/README.md@@ -8,7 +8,7 @@ The extension sends the screenshot and page URL. Azimut parses supported sites,coordinates, place names and imagery dates, so URL-format fixes ship with theapp.-It supports three flows:+It supports four flows:- On a supported map site, the popup can capture a selected area or save itscoordinates as a place.@@ -16,6 +16,9 @@ It supports three flows:downloading the page.- On Azimut's Google basemap, the in-app Capture button requests the currenttab image without a screen-share prompt.+- When Geo Report publishes, it can open X or Bluesky with the thread already+ typed and the proof attached. It never presses Post: the composer is left+ filled, and publishing stays a human act. Off until you switch it on.## Install@@ -39,17 +42,38 @@ folder directly from a repo checkout), unzip it somewhere permanent, then:token → **Save & test**.The token allows this extension to file captures through the local Azimut-server. Rotate it in Settings to revoke existing pairings.+server, and to read back the media and proofs a thread attaches. Rotate it in+Settings to revoke existing pairings.++## Fill the composer++Geo Report's **Publish** opens the site's full composer, types each post of the+thread and attaches its pictures. Nothing is posted: the composer is left filled+and the button is yours.++There is one switch and it is in the app — **Settings → Publishing → Let the+extension fill the composer**, on by default. Nothing to set here.++The filling runs in the page's own world, which is the only place a composer+accepts what it is given. That needs Firefox 128 or later; on an older Firefox+this one flow reports that it could not run, and everything else works as before.++If the site has changed its markup, or a file is too large to hand over, it+fills what it can and says so. Each post is read back after it is typed, and one+the composer will not take cleanly is left empty rather than half-written. The+whole thread is on your clipboard either way, which is what Publish did before+this existed.## Permissions| Permission | Why ||---|---|| `activeTab` | Reads the current URL and captures the tab only after you click the extension. |-| `scripting` | Shows the area-selection overlay. |+| `scripting` | Shows the area-selection overlay, and fills a composer you allowed. || `storage` | Stores the local app URL, pairing token and last-used case. || `notifications` | Reports an area capture after the popup closes. || `http://127.0.0.1/*`, `http://localhost/*` | Connects to the local Azimut app. |+| `https://x.com/*`, `https://twitter.com/*`, `https://bsky.app/*` | Types a prepared thread into the composer, when Azimut asks. Never reads those pages, never posts. |The in-app Capture button may require one initial toolbar click for a new tab.Browsers require that gesture before allowing a tab screenshot. The extensiondiff --git a/extension/background.js b/extension/background.jsindex 75290ef..6c50099 100644--- a/extension/background.js+++ b/extension/background.js@@ -83,6 +83,127 @@ async function ingest(blob, meta) {return body;}+// --- post hand-off: fill a composer the app prepared ----------------------------+//+// The app never posts, and neither does this: the thread is typed into the site's+// own composer and left there. Everything below is a layer over the path that+// already worked (the app opens the intent page, the thread is on the clipboard),+// so every failure returns rather than throws a user into a dead end.+//+// There is one switch and it lives in Azimut (Settings → Publishing): the app+// asks or it does not, and this side has no opinion to add. A second box here+// would be two answers to one question, and the pair that disagrees is the one+// nobody can find.++/** One handed-over file, fetched from the app and carried as base64: what+ * crosses into the page is a string, and the page turns it back into a file.+ * Base64 rather than a `data:` URL because the page rebuilds it with `atob` —+ * a fetch over there answers to the site's CSP, and X refuses that one. */+async function fetchAttachment(backendUrl, token, caseId, path) {+ const url =+ `${backendUrl}/api/ingest/file?case_id=${encodeURIComponent(caseId)}` ++ `&path=${encodeURIComponent(path)}`;+ const r = await fetch(url, { headers: { "X-Azimut-Token": token } });+ // Gone, too big, refused: the file is skipped and counted, never fatal. It is+ // in the case, and attaching it by hand is what the analyst did before.+ if (!r.ok) return null;+ const blob = await r.blob();+ const bytes = new Uint8Array(await blob.arrayBuffer());+ let binary = "";+ const CHUNK = 0x8000; // fromCharCode takes an argument list: chunk it or blow the stack+ for (let i = 0; i < bytes.length; i += CHUNK) {+ binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));+ }+ return {+ name: path.split("/").pop(),+ type: blob.type || "application/octet-stream",+ data: btoa(binary),+ };+}++/** Resolve once the tab has finished loading, so the injection lands on a page. */+function tabLoaded(tabId, timeoutMs = 20000) {+ return new Promise((resolve) => {+ const done = () => {+ api.tabs.onUpdated.removeListener(onUpdated);+ clearTimeout(timer);+ resolve();+ };+ // Not an error path: the composer is an app that keeps loading after the+ // document does, and the injected script waits for it anyway.+ const timer = setTimeout(done, timeoutMs);+ function onUpdated(id, info) {+ if (id === tabId && info.status === "complete") done();+ }+ api.tabs.onUpdated.addListener(onUpdated);+ });+}++/**+ * Say yes or no, now, and do the work afterwards.+ *+ * The app is holding a click while it waits for this, and a browser only lets a+ * page open a tab for a few seconds after one. So the answer here has to be about+ * whether the hand-off is *taken* — one cheap check — and never about how it+ * went: opening a tab, waiting for a composer to mount and attaching six files is+ * tens of seconds, and waiting that long to say no would spend the click on+ * nothing and leave the analyst pressing a dead button.+ *+ * Everything after the answer reports itself through notifications.+ */+async function handOff(payload) {+ const { backendUrl, token } = await settings();+ if (!token) throw new Error("not paired");+ fillComposer(payload, backendUrl, token).catch((e) =>+ notify("Azimut hand-off", `${e.message} The thread is on your clipboard.`)+ );+ return { ok: true, accepted: true };+}++async function fillComposer(payload, backendUrl, token) {+ let skipped = 0;+ const posts = [];+ for (const post of payload.posts ?? []) {+ const files = [];+ for (const path of post.files ?? []) {+ const file = await fetchAttachment(backendUrl, token, payload.caseId, path);+ if (file) files.push(file);+ else skipped += 1;+ }+ posts.push({ text: post.text ?? "", files });+ }+ if (skipped) {+ notify(+ "Azimut hand-off",+ `${skipped} file${skipped > 1 ? "s" : ""} could not be handed over. Attach ${skipped > 1 ? "them" : "it"} from the case.`+ );+ }++ const tab = await api.tabs.create({ url: payload.url, active: true });+ await tabLoaded(tab.id);+ // Both injections run in the page's own world, which is the only place a+ // composer accepts what we make (see handoff.js). Nothing over there can call+ // an extension API, so the thread goes in on a global and the report comes back+ // as the script's return value.+ const target = { tabId: tab.id };+ await api.scripting.executeScript({+ target,+ world: "MAIN",+ func: (thread) => {+ window.__AZIMUT_HANDOFF__ = thread;+ },+ args: [{ posts }],+ });+ const [done] = await api.scripting.executeScript({+ target,+ world: "MAIN",+ files: ["handoff.js"],+ });+ if (done?.result?.error) {+ notify("Azimut hand-off", `${done.result.error} The thread is on your clipboard.`);+ }+}+function notify(title, message) {// fire-and-forget: a failed toast must never fail a filed capturetry {@@ -147,6 +268,17 @@ async function handle(msg, sender) {}}+ // The app's Publish button, relayed by bridge.js: open the composer and fill+ // the thread. Same origin check as the capture route — only the app may ask.+ if (msg.type === "post-handoff") {+ if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };+ try {+ return await handOff(msg.payload ?? {});+ } catch (e) {+ return { ok: false, error: e.message };+ }+ }+return { ok: false, error: `unknown message '${msg.type}'` };}diff --git a/extension/bridge.js b/extension/bridge.jsindex 347590c..eecb22e 100644--- a/extension/bridge.js+++ b/extension/bridge.js@@ -5,8 +5,8 @@* 1. announces the extension to the app (a dataset marker, set at* document_start so it is there before the app mounts, plus a ping* answer for later checks);- * 2. relays the app's Capture requests to the background worker and hands- * the captured frame back.+ * 2. relays the app's Capture and Publish requests to the background worker and+ * hands its answer back.** The app keeps all judgment: registration, cropping, filing. The bridge* never touches the backend and never sees the pairing token — the app files@@ -55,5 +55,21 @@location.origin);}++ // Geo Report's Publish button: the thread, as paths and text. The worker+ // reads the files from the app itself, so nothing of the case and nothing of+ // the pairing token passes through here.+ if (msg.type === "post-handoff") {+ let result;+ try {+ result = await api.runtime.sendMessage({ type: "post-handoff", payload: msg.payload });+ } catch (e) {+ result = { ok: false, error: e.message };+ }+ window.postMessage(+ { channel: CHANNEL, type: "post-handoff-result", id: msg.id, ...result },+ location.origin+ );+ }});})();diff --git a/extension/handoff.js b/extension/handoff.jsnew file mode 100644index 0000000..4ee0276--- /dev/null+++ b/extension/handoff.js@@ -0,0 +1,563 @@+/**+ * Fill a social composer with the thread Azimut prepared, and stop there.+ *+ * Injected into the composer tab by the background worker, once, after the app's+ * Publish button asked for it. It writes and attaches; it never submits. The+ * button that publishes is the analyst's, exactly as it is when they paste the+ * thread by hand — which is still what happens whenever this script gives up.+ *+ * **Runs in the page's own world**, which is the only place this works. An+ * extension's scripts live in a separate world by default: the events they make+ * are untrusted and the `DataTransfer` they build belongs to the other side of+ * that boundary, so a composer is free to ignore both — and X did, in silence.+ * Here the caret, the events and the files are the page's own objects. The price+ * is that there is no extension API on this side: the thread arrives on+ * `window.__AZIMUT_HANDOFF__`, set by the injection before this one, and the+ * report is this script's own return value.+ *+ * **This is the one file in the repo that knows another site's DOM**, and it will+ * age: X and Bluesky move their markup without notice. So it is written to fail+ * shallow — every step reports how far it got, nothing throws into the page, and+ * the thread the app copied to the clipboard is the answer to all of it.+ */++(() => {++ /**+ * Bluesky's "+", by the only thing about it that is not translated or generated.+ *+ * It carries no test id, its class comes out of a stylesheet nobody wrote, and+ * its label goes through the site's translations: in French it reads *Ajouter+ * un autre post au fil de discussion*, which holds none of the words a+ * selector was asking for — so the thread stopped at post 1, in every language+ * but English. The label is also where this turns dangerous, and it is worth+ * saying why the obvious loosening is not here: *post* on its own is in the+ * button that publishes, and *add* plus *post* is also **Add media to post**,+ * one seat along in the same footer.+ *+ * What is left is the glyph. A plus is a plus in every language, and no button+ * that posts anything wears one. Both sizes of it, since the icon set draws+ * two, and either element the composer's button library renders as.+ */+ const PLUS =+ ':is(button, [role="button"]):has(' ++ 'path[d^="M12 3a1 1 0 0 1 1 1v7h7"], path[d^="M12 6a1 1 0 0 1 1 1v4h4"])';++ // Per site: where the text goes, where a file goes, and what opens the next+ // post under it. Several selectors per role, oldest last: a renamed test id+ // costs the run, and a spare that still matches saves it.+ const SITES = [+ {+ match: /(^|\.)(x|twitter)\.com$/,+ // Scoped to the dialog first: opening the composer by URL draws it over+ // the timeline, and the timeline keeps a composer of its own — so the+ // first box in the document is not always the one on screen. The add+ // button answers to the same rule, for the same reason.+ editors: ['[role="dialog"] [data-testid^="tweetTextarea_"]', '[data-testid^="tweetTextarea_"]'],+ add: ['[role="dialog"] [data-testid="addButton"]', '[data-testid="addButton"]'],+ // Pasted first here, typed only if that is refused — the reverse of+ // everywhere else. This editor rebuilds itself around what `insertText`+ // wrote and comes back holding the post several times over, every time.+ // The loop below caught it and cleared it, and the thread did come out+ // right; what the analyst watched was a post being written six times and+ // wiped. Its paste handler takes the post once, first ask.+ roads: ["paste", "type"],+ files: [+ '[role="dialog"] input[data-testid="fileInput"]',+ 'input[data-testid="fileInput"]',+ 'input[type="file"]',+ ],+ },+ {+ match: /(^|\.)bsky\.app$/,+ // Its web composer is a rich-text editor with no test id of its own: the+ // class its library puts on the box, then plain contenteditable.+ editors: ['[role="dialog"] .ProseMirror', '.ProseMirror', 'div[contenteditable="true"]'],+ // The glyph first (see PLUS), then the English label as the spare — with+ // the media button next to it excluded by name, since "Add media to post"+ // answers to the same words. Neither asks for a `button` tag: this+ // composer is React Native for Web, where a button is whatever element+ // that library felt like rendering.+ add: [+ `[role="dialog"] ${PLUS}`,+ '[aria-label*="add" i][aria-label*="post" i]:not([aria-label*="media" i])',+ '[aria-label*="thread" i]',+ ],+ // No input to hand a file to: it picks files through one it creates,+ // clicks and throws away. See `drop` below for the door it does leave open.+ files: [],+ dropOnBody: true,+ },+ ];++ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++ /**+ * Whether a paste made here carries the `DataTransfer` it was built with.+ *+ * Text can go over either spelling (see `paste`), but a file only travels on+ * the object itself — and Gecko does not take the object, it builds its own+ * out of text. So there is no such thing as pasting a picture in on Firefox,+ * and the door that site leaves open is the one below. Asked of a throwaway+ * event rather than of a browser name.+ */+ const CARRIES_FILES = (() => {+ try {+ const probe = new DataTransfer();+ return new ClipboardEvent("paste", { clipboardData: probe }).clipboardData === probe;+ } catch {+ return false;+ }+ })();++ const found = (selectors, keep = () => true) => {+ for (const selector of selectors) {+ let nodes = [];+ // A selector this browser cannot parse is one spare gone, not the run.+ try {+ nodes = [...document.querySelectorAll(selector)].filter(keep);+ } catch {+ continue;+ }+ if (nodes.length) return nodes;+ }+ return [];+ };++ /**+ * The boxes, in document order, and only the boxes.+ *+ * Matching the selector is not the same question as being the editor: X hangs+ * an empty post's placeholder on a sibling carrying the same test id with+ * `_label` on the end. It counted as a box, so post 2 was "already filled" by+ * the words *What is happening?!* and its text went nowhere. A composer box is+ * contenteditable; a placeholder never is.+ */+ const editable = (node) => {+ const attr = node.getAttribute?.("contenteditable");+ return attr === "" || attr === "true" || attr === "plaintext-only" || node.isContentEditable === true;+ };++ const boxes = (site) => found(site.editors, editable);++ /**+ * A control the composer is offering, rather than one it is holding back.+ *+ * X takes its "+" away — or refuses it — while it is still reading what was+ * just handed over, and a video is read for far longer than a picture ever+ * was. Pressing what is refused is how a thread carrying a clip stopped at+ * the post after it.+ */+ const pressable = (node) => node.disabled !== true && node.getAttribute?.("aria-disabled") !== "true";++ /** Poll for what the page has not drawn yet. A composer is an app inside an+ * app: "load finished" says nothing about the box existing. */+ async function waitFor(predicate, timeoutMs = 15000) {+ const until = Date.now() + timeoutMs;+ for (;;) {+ const hit = predicate();+ if (hit) return hit;+ if (Date.now() > until) return null;+ await sleep(200);+ }+ }++ /**+ * Make this post the one the composer is listening to.+ *+ * A composer with several boxes open takes a keystroke into the one it thinks+ * is active, and hands a picture to that one too — so every road below starts+ * here. A click and a focus, and nothing more: what a button needs (`press`)+ * is not what an editor needs, and the events an editor did not ask for are+ * the ones that get interpreted.+ */+ function focusBox(box) {+ box.click();+ box.focus();+ }++ /**+ * Press a control the way a mouse does.+ *+ * `click()` is one event, and it is not the one every composer listens for:+ * Bluesky's "+" is a React Native for Web pressable, which hangs its press on+ * the pointer sequence around the click. It sat there unpressed, so post 2 was+ * never opened and the thread stopped at one. The full sequence costs nothing+ * on a site that only ever wanted the click, and `click()` still ends it so+ * that a plain button gets its own activation.+ */+ function press(node) {+ node.focus?.();+ for (const kind of ["pointerdown", "mousedown", "pointerup", "mouseup"]) {+ const Kind = kind.startsWith("pointer") && typeof PointerEvent === "function" ? PointerEvent : MouseEvent;+ node.dispatchEvent(new Kind(kind, { bubbles: true, cancelable: true, composed: true, button: 0 }));+ }+ node.click();+ }++ /**+ * A paste, for text or for files.+ *+ * The obvious way in, and the one that has to be checked afterwards: a paste+ * is an event the editor is free to ignore, and it did — dispatched from the+ * extension's own world it carried a `DataTransfer` built on the other side of+ * that boundary, and what came of it was a box that looked filled and was+ * empty. In the page's world it is the site's own kind of object, which is why+ * it is worth a second road rather than a last resort. Nothing here says+ * whether it landed; the box does, above.+ */+ function paste(target, transfer, text) {+ target.focus();+ return target.dispatchEvent(+ // Spelled both ways, because the two engines read different members and+ // each ignores the other's. Chromium takes the `DataTransfer` handed to+ // `clipboardData`; Gecko has no such member in its `ClipboardEventInit`+ // and builds its own out of `data`. Sent only one way, Firefox's composer+ // got an empty clipboard, fell to the typed road, and **never registered+ // the post**: the text was in the box, X still called it empty, and the+ // "+" it draws over a written post was not there — so the thread stopped+ // at the post after it, on a composer that looked filled.+ new ClipboardEvent("paste", {+ bubbles: true,+ cancelable: true,+ clipboardData: transfer,+ data: text,+ dataType: text === undefined ? undefined : "text/plain",+ })+ );+ }++ /**+ * Put the caret inside this box, at the end of what it holds. Collapsed, always.+ *+ * `insertText` writes wherever the *selection* is, not into whatever element+ * was asked to focus — and a composer holding three posts keeps one selection+ * between them, so without this the second post's text was inserted into the+ * first. What the range must never do is **span** the editor's own structure:+ * the contents of an "empty" X box are the block scaffolding DraftJS keeps in+ * there, and writing over that had it rebuild the post out of a DOM it no+ * longer recognised — six copies deep. Emptying a box is `clear`'s job, and it+ * asks the editor rather than the nodes.+ */+ function placeCaret(box) {+ const range = document.createRange();+ range.selectNodeContents(box);+ range.collapse(false);+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ }++ // What a composer keeps is never character for character what was sent: X+ // wraps a post in bidi isolates, and an editor holding one post per block+ // hands them back with no line break between. So both sides are read with+ // every space and mark taken out — enough to tell empty from filled, and one+ // copy of the post from six.+ const NOISE = /[\u200b-\u200f\u061c\u2066-\u2069]/g;+ const squeeze = (value) => String(value ?? "").replace(NOISE, "").replace(/\s+/g, "");+ const holdsText = (box) => squeeze(box.textContent).length > 0;+ const occurrences = (holds, want) => (want ? holds.split(want).length - 1 : 0);++ /**+ * What the box holds once it has stopped changing.+ *+ * An editor does not write the keystroke, it *records* it: the text appears+ * when its own state has been through a render, which is not when the command+ * returns. Reading once, straight after, found post 2 empty and put it in a+ * second time — on top of the copy that arrived a moment later. Two readings+ * that agree is the earliest this can be answered.+ */+ async function settled(box, { emptyMs = 600, timeoutMs = 2000 } = {}) {+ let last = null;+ const start = Date.now();+ for (;;) {+ const holds = squeeze(box.textContent);+ if (holds && holds === last) return holds;+ last = holds;+ const waited = Date.now() - start;+ // A box still empty this long after the command is a box that took+ // nothing: waiting out the full patience owed to a slow render would only+ // spend it three times over on the attempts below.+ if (!holds && waited >= emptyMs) return "";+ if (waited >= timeoutMs) return holds;+ await sleep(100);+ }+ }++ /**+ * Empty the box, and say whether it is empty.+ *+ * Through the editor's own commands: `selectAll` in a focused editor is the+ * browser's idea of "everything in here", and `delete` is a keystroke every+ * editor implements — where a range built by hand spans nodes the editor put+ * there for itself. Asked before every attempt below, because an attempt that+ * starts on a box still holding the last one is how a post ends up doubled.+ */+ async function clear(box) {+ if (!holdsText(box)) return true;+ focusBox(box);+ placeCaret(box);+ document.execCommand?.("selectAll");+ document.execCommand?.("delete");+ const until = Date.now() + 1000;+ while (holdsText(box)) {+ if (Date.now() > until) return false;+ await sleep(100);+ }+ return true;+ }++ /**+ * Point this post's box out to the composer, and give it a moment to look.+ *+ * Both roads write wherever the editor believes the caret is, and the editors+ * that keep their own copy of the selection read it on their own schedule — so+ * arriving before they have looked puts the post in the one before it.+ */+ async function aim(box) {+ focusBox(box);+ placeCaret(box);+ await sleep(250);+ }++ /**+ * Type the post in, the way a keyboard does.+ *+ * `insertText` is executed by the browser on the current selection, so the+ * editor gets the same `beforeinput`/`input` sequence a keystroke produces and+ * updates its own state — where a paste asks it to trust an event it did not+ * see the user make. The first road on a site that has not said otherwise.+ */+ async function written(box, text) {+ await aim(box);+ document.execCommand?.("insertText", false, text);+ return settled(box);+ }++ /** The other road: hand the editor a paste, and let it read the text off. */+ async function pasted(box, text) {+ await aim(box);+ const transfer = new DataTransfer();+ transfer.setData("text/plain", text);+ paste(box, transfer, text);+ return settled(box);+ }++ /**+ * Put one post in one box, and answer for what is in there afterwards.+ *+ * Neither end of an attempt can be taken on trust, so the box is read at both+ * and what it holds is **counted**. `insertText` reports refused whenever the+ * editor handled the keystroke itself, with the text already in, so the+ * command's verdict is worth nothing; and an editor that rebuilds its own DOM+ * around what the browser wrote comes back holding the post several times+ * over, so "not empty" is not the same question as "filled".+ *+ * Three attempts, each starting on a box the editor has confirmed empty and+ * alternating the two roads in — the site's own road first, because the wrong+ * one is not only slower: the analyst is watching the composer, and an attempt+ * that has to be cleared is a post typed and wiped in front of them.+ *+ * **If none of them leaves the box holding the post, the box is emptied and+ * said so**: a post the analyst pastes in beats a post that says everything+ * six times, and the thread was on the clipboard before any of this was tried.+ */+ async function type(site, box, text) {+ const want = squeeze(text);+ const roads = site.roads ?? ["type", "paste"];+ let trouble = "stayed empty";+ for (let attempt = 0; attempt < 3; attempt += 1) {+ if (!(await clear(box))) return "would not empty";+ const road = roads[attempt % roads.length];+ const holds = road === "paste" ? await pasted(box, text) : await written(box, text);+ if (!holds) trouble = "stayed empty";+ else if (occurrences(holds, want) > 1) trouble = "went in more than once";+ // Not the same string is not wrong: an editor is free to normalise what it+ // keeps, and the script that argues with that is the one that types the+ // post in a second time. Once, or as near as can be told, is the answer.+ else return null;+ }+ await clear(box);+ return trouble;+ }++ /**+ * Hand a file to the composer's own file input, the way the picker does.+ *+ * Every one of these sites attaches through an `input[type=file]` it keeps+ * hidden behind the picture button. Assigning its `files` and firing `change`+ * is the site's own path — its validation, its thumbnail, its counter — and it+ * does not depend on the page trusting an event we made up.+ *+ * Whether it stuck is asked **before** the site is told, and never afterwards.+ * A composer empties the input as soon as it has read it, so that picking the+ * same picture twice still fires a change — so reading it back a moment later+ * finds nothing and calls the one path that worked a refusal.+ */+ function attach(site, box, transfer, input) {+ if (input) {+ input.files = transfer.files;+ if (input.files?.length) {+ input.dispatchEvent(new Event("change", { bubbles: true }));+ return true;+ }+ }+ // A paste that cannot carry a file is not a fallback; dropping is the one+ // road left, and it is the road this browser gave Bluesky all along.+ return site.dropOnBody || !CARRIES_FILES ? drop(transfer) : paste(box, transfer);+ }++ /**+ * Drop the files on the page, the way dragging them onto the window does.+ *+ * Bluesky's route, and the reason it has one: it keeps no file input to hand+ * anything to, but it listens for `drop` on the body and passes what it carries+ * to the same reader its paste uses. It reads `image/*` and `video/*` straight+ * off the items, and it puts them on the post it currently calls active — the+ * one just pressed.+ */+ function drop(transfer) {+ for (const kind of ["dragenter", "dragover", "drop"]) {+ document.body.dispatchEvent(+ new DragEvent(kind, { bubbles: true, cancelable: true, dataTransfer: transfer })+ );+ }+ return true;+ }++ /**+ * Rebuild a handed-over file on this side.+ *+ * It crosses as base64 rather than as a `data:` URL for one reason: this runs+ * in the page's world, so a read over the network answers to the page's own+ * CSP — and X allows no connection to `data:`. Every attachment came back+ * "Failed to fetch" and took the rest of the thread down with it. `atob` asks+ * the network for nothing, so there is nothing left to refuse.+ */+ function toFile(file) {+ const binary = atob(file.data ?? "");+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);+ return new File([bytes], file.name, { type: file.type });+ }++ /**+ * Fill one post. Returns null, or what to tell the analyst about this one.+ *+ * **A box that already holds something is left alone.** The first post arrives+ * with its text in the URL, and the composer's copy of it is never character+ * for character what was sent — bidi marks, trimming, its own normalisation —+ * so comparing the two said "different" and typed the whole post in again,+ * halfway through the text already there. What the analyst got was a thread+ * saying everything twice. Emptiness is the question that can be answered.+ */+ async function fill(site, box, post, index) {+ // Focused even when there is nothing to type into it: a composer hands a+ // picture to the post it calls active, and a post carrying an image and no+ // text is never typed into.+ focusBox(box);+ // Typing is the step that can fail without saying so: the editor keeps its+ // own state and a box that stayed empty means it ignored us.+ if (post.text && !holdsText(box)) {+ const trouble = await type(site, box, post.text);+ if (trouble) return `Post ${index + 1} ${trouble}.`;+ }+ if (!post.files?.length) return null;+ // One input per post where a site has them, so the pictures land under the+ // post they belong to rather than all under the first.+ const inputs = found(site.files);+ const transfer = new DataTransfer();+ for (const file of post.files) transfer.items.add(toFile(file));+ attach(site, box, transfer, inputs[index] ?? inputs[0]);+ // The site reads the files and draws thumbnails; moving on mid-read drops it.+ await sleep(900);+ // And nothing is claimed about how that went. Whether a picture is attached+ // is the site's own state, drawn its own way, and every reading of it from+ // here was wrong: the input is empty because it was read, not because it was+ // refused. The composer is in front of the analyst; it can answer for itself.+ return null;+ }++ /**+ * The box the next post belongs in: the first empty one under the post just+ * filled.+ *+ * Counting from the top is what an index does, and the count is not ours to+ * keep — the composer owns it. X draws a box under the timeline behind the+ * dialog, a site is free to open the new post next to the active one rather+ * than at the end, and either way the Nth box stopped being the Nth post.+ *+ * The button pressed is the one at the end, so the box it opens is the one at+ * the end: that is the answer whenever it is empty and is not the post just+ * written. Otherwise the first empty box below that one, which is the same+ * answer in a composer that numbers its boxes the way we would.+ */+ function nextBox(site, previous) {+ const all = boxes(site);+ const last = all.at(-1);+ if (last && last !== previous && !holdsText(last)) return last;+ const after = all.slice(all.indexOf(previous) + 1);+ return after.find((one) => !holdsText(one)) ?? null;+ }++ async function run() {+ const site = SITES.find((one) => one.match.test(location.hostname));+ if (!site) return { filled: 0, error: "Azimut does not know this composer." };++ const posts = window.__AZIMUT_HANDOFF__?.posts;+ delete window.__AZIMUT_HANDOFF__; // the page keeps nothing of the case+ if (!posts?.length) return { filled: 0 };++ const opened = await waitFor(() => {+ const nodes = boxes(site);+ return nodes.length ? nodes : null;+ });+ if (!opened) return { filled: 0, error: "The composer did not open in time." };++ let filled = 0;+ // What went wrong on one post does not stop the next: a thread missing its+ // third line still beats a composer holding nothing.+ const notes = [];+ // Stopping is not a reason to drop what went wrong on the way here: a post+ // left empty is why a composer refuses to open the next one, and the stop+ // on its own reads like the markup moved.+ const stop = (reason) => ({ filled, error: [...notes, reason].join(" ") });+ let box = boxes(site)[0];+ for (let i = 0; i < posts.length; i += 1) {+ if (i > 0) {+ // The **last** one. A composer that draws a footer under every post+ // draws an add button under every post too, and only the one at the end+ // appends — the others insert a post in the middle of the thread.+ //+ // Waited for, not looked for once: this is the composer's own state, and+ // it is the last thing here that was read the moment it was wanted. The+ // patience goes where the reason for it is — a post that handed over a+ // file is one the composer is still busy with; a post that handed over+ // nothing owes no wait.+ //+ // No button, no thread: stop where we are and say so. Half a thread+ // filled beats none, and the rest is one paste away.+ const patience = posts[i - 1].files?.length ? 20000 : 3000;+ const add = await waitFor(() => found(site.add, pressable).at(-1), patience);+ if (!add) return stop("Could not add the next post to the thread.");+ press(add);+ const grown = await waitFor(() => nextBox(site, box), 5000);+ if (!grown) return stop("The next post did not open.");+ await sleep(250); // it is drawn; let it become the one the composer listens to+ box = nextBox(site, box) ?? grown;+ }+ if (!box) return stop("Lost the composer while filling it.");+ const trouble = await fill(site, box, posts[i], i);+ if (trouble) notes.push(trouble);+ else filled += 1;+ }+ return notes.length ? { filled, error: notes.join(" ") } : { filled };+ }++ // The value the injection hands back to the worker, which is what says whether+ // the analyst needs telling anything.+ return run().catch((e) => ({+ filled: 0,+ error: e?.message || "The composer refused the thread.",+ }));+})();diff --git a/extension/manifest.json b/extension/manifest.jsonindex 18dad25..cf530cb 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -1,10 +1,16 @@{"manifest_version": 3,"name": "Azimut Capture",- "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.",+ "version": "0.3.0",+ "description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), save any other page as a bookmark, or fill a social composer with a thread the app prepared.","permissions": ["activeTab", "scripting", "storage", "notifications"],- "host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],+ "host_permissions": [+ "http://127.0.0.1/*",+ "http://localhost/*",+ "https://x.com/*",+ "https://twitter.com/*",+ "https://bsky.app/*"+ ],"background": {"service_worker": "background.js","scripts": ["background.js"]diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 78dcc3a..8ac1b1d 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -1,4 +1,4 @@-import { expect } from '@playwright/test';+import { expect, test } from '@playwright/test';export const CASE_ID = 'browser-test';export const PANEL_PATH = 'media/panel.svg';@@ -10,11 +10,16 @@ const PANEL_SVG = `<circle cx="520" cy="76" r="34" fill="#f4c95d"/></svg>`;-const TILE_SVG = `- <svg xmlns="http://www.w3.org/2000/svg" width="256" height="256">- <rect width="256" height="256" fill="#243747"/>- <path d="M0 190L70 120L140 175L210 80L256 140V256H0Z" fill="#4f7047"/>- </svg>`;+// A real raster tile, not an SVG: the map engine decodes tiles into bitmaps,+// and `createImageBitmap` refuses SVG. 16px of dark ground and a green ridge,+// scaled up over the tile — enough to tell imagery from an empty map in a+// failure screenshot.+const TILE_PNG = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAQElEQVR42mNUMXdnIAUwMZAI' ++ 'hrAGbUtSNEBUQ0jKnAS3F5egtiWSBri9aCqw24AmgdUqCGAhxiUoNuAxbKgkDQDARwagm0jS' ++ 'UwAAAABJRU5ErkJggg==',+ 'base64'+);const media = [{path: PANEL_PATH,@@ -516,6 +521,65 @@ const providers = [{capturable: true,}];+/**+ * The Maps JS basemap, offered only when a spec asks for it (`widget: true`).+ *+ * It is the one basemap that is not our tiles: Google's own map renders under+ * ours. A spec that wants it also wants `fakeGoogleMaps`, so that no key, no+ * network and no billed map load is involved.+ */+const WIDGET_PROVIDER = {+ id: 'google-js',+ label: 'Google Satellite (Maps JS)',+ url: 'https://maps.googleapis.com/maps/api/js?key=fixture',+ attribution: 'Map data © Google',+ max_zoom: 21,+ tile_size: 256,+ oversample: 1,+ imagery: true,+ capturable: false,+ widget: 'google-maps-js',+ meter: 'google_js',+ eco_max_zoom: 0,+};++/**+ * Stand in for the Maps JS API before the app loads.+ *+ * `loadGoogleMaps` resolves at once when `window.google.maps` is already there,+ * so this replaces the script, the key and the billing in one go. The map it+ * builds paints itself magenta, which is how a spec can tell whether it really+ * shows through our own canvas.+ */+export async function fakeGoogleMaps(page) {+ await page.addInitScript(() => {+ window.__googleMaps = [];+ window.google = {+ maps: {+ event: {+ addListenerOnce: (map, name, handler) => map.__once.push([name, handler]),+ trigger: (map, name) => map.__triggered.push(name),+ },+ Map: class {+ constructor(node, options) {+ this.node = node;+ this.options = options;+ this.cameras = [];+ this.__once = [];+ this.__triggered = [];+ node.style.background = 'rgb(255, 0, 255)';+ window.__googleMaps.push(this);+ }+ moveCamera(camera) {+ this.cameras.push(camera);+ }+ addListener() {}+ },+ },+ };+ });+}+function json(route, body, status = 200) {return route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });}@@ -597,18 +661,21 @@ function fixtureTemporalReading(raw) {}/**- * Run the real Svelte, Konva and Leaflet code while replacing only Azimut's+ * Run the real Svelte, Konva and map code while replacing only Azimut's* local API and files with deterministic fixtures. Any unexpected request is* recorded so a passing interaction test cannot silently depend on the network.*/export async function installAppFixture(page, options = {}) {const unexpected = [];+ const labelTiles = [];const captures = [];const proofSaves = [];const fixtureSavedIndex = options.savedIndex ?? savedIndex;const fixtureProofIndex = options.proofIndex ?? [];const fixtureMedia = (options.media ?? media).map((item) => ({ ...item }));const fixtureCases = options.cases ?? [caseOverview];+ const fixtureProviders = options.widget ? [...providers, WIDGET_PROVIDER] : providers;+ const widgetLoads = [];const fixtureSavedIndexes = options.savedIndexes ?? { [CASE_ID]: fixtureSavedIndex };const fixtureProofIndexes = options.proofIndexes ?? { [CASE_ID]: fixtureProofIndex };const savedIndexDelays = options.savedIndexDelays ?? {};@@ -632,6 +699,11 @@ export async function installAppFixture(page, options = {}) {const trashGroups = [...(options.trashGroups ?? [])];const trashWrites = [];const bundleCalls = [];+ // The case's saved search grids, held across requests: a sweep auto-saves, so+ // what was marked is readable from what was written.+ const fixtureGrids = new Map();+ const gridWrites = [];+ const skyQueries = [];// Where the graph's nodes have been dragged to, held across requests so a spec// can reload the view and find the arrangement still there.const graphPins = new Map(Object.entries(options.graphPins ?? {}));@@ -851,6 +923,15 @@ export async function installAppFixture(page, options = {}) {const url = new URL(request.url());const path = url.pathname;+ // The labels overlay is the one layer served straight from its provider —+ // the proxy cannot expand a `{s}` template. Answered here, with the same+ // bytes as a proxied tile, so a spec can prove the overlay was asked for+ // without the run touching the network.+ if (url.hostname.endsWith('.basemaps.cartocdn.com')) {+ labelTiles.push(request.url());+ return route.fulfill({ contentType: 'image/png', body: TILE_PNG });+ }+if (url.hostname !== '127.0.0.1') {unexpected.push(`${request.method()} ${request.url()}`);return route.abort('blockedbyclient');@@ -868,7 +949,7 @@ export async function installAppFixture(page, options = {}) {return route.fulfill({ contentType: 'image/svg+xml', body: PANEL_SVG });}if (path.startsWith('/api/tiles/')) {- return route.fulfill({ contentType: 'image/svg+xml', body: TILE_SVG });+ return route.fulfill({ contentType: 'image/png', body: TILE_PNG });}if (path === '/api/events') {return route.fulfill({ contentType: 'text/event-stream', body: '' });@@ -1492,7 +1573,33 @@ export async function installAppFixture(page, options = {}) {bundleCalls.push({ kind: 'job' });return json(route, bundleJob);}- if (caseId && path === `/api/cases/${caseId}/search-grids`) return json(route, []);+ if (caseId && path === `/api/cases/${caseId}/search-grids`) {+ return json(route, [...fixtureGrids.values()].map(({ name, spec, title }) => ({+ name,+ title,+ cells: Object.keys(spec.statuses ?? {}).length,+ cleared: Object.values(spec.statuses ?? {}).filter((s) => s === 'cleared').length,+ flagged: Object.values(spec.statuses ?? {}).filter((s) => s === 'flagged').length,+ })));+ }+ // The sweep auto-saves on every mark, so a spec can read the marks back out+ // of what was written rather than out of the canvas they are painted on.+ const gridMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/search-grids/(.+)$`));+ if (gridMatch) {+ const name = gridMatch[1];+ if (request.method() === 'PUT') {+ const body = request.postDataJSON();+ fixtureGrids.set(name, { name, spec: body.spec, title: body.title });+ gridWrites.push({ name, spec: body.spec });+ return json(route, { status: 'saved' });+ }+ if (request.method() === 'DELETE') {+ fixtureGrids.delete(name);+ return json(route, { status: 'deleted' });+ }+ const held = fixtureGrids.get(name);+ return held ? json(route, held.spec) : json(route, { detail: 'not found' }, 404);+ }const placementMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/(.+)/placement$`));@@ -1656,7 +1763,13 @@ export async function installAppFixture(page, options = {}) {if (path === `/api/cases/${CASE_ID}/entities/lookup`) {return json(route, { entity: fixtureLookupEntities[url.searchParams.get('value')] ?? null });}- if (path === '/api/satellite/providers') return json(route, providers);+ if (path === '/api/satellite/providers') return json(route, fixtureProviders);+ // one billed map load, counted where it happens: the tile proxy cannot see+ // the Maps JS widget, so the tool reports it itself+ if (path.startsWith('/api/satellite/usage/') && request.method() === 'POST') {+ widgetLoads.push(path.split('/').at(-1));+ return json(route, { ok: true });+ }if (path === '/api/satellite/imagery-date') {return json(route, { supported: false, date: null, source: null });}@@ -1740,6 +1853,31 @@ export async function installAppFixture(page, options = {}) {attribution: cities.length ? '© GeoNames (CC BY 4.0)' : null,});}+ // One day of sun and moon over a point: enough samples for the arc, the hour+ // ticks and the slider, with the sun up and the moon down at the chosen hour.+ if (path === '/api/geo/sky') {+ skyQueries.push({+ lat: Number(url.searchParams.get('lat')),+ lon: Number(url.searchParams.get('lon')),+ date: url.searchParams.get('date') ?? '',+ });+ const minutes = Array.from({ length: 25 }, (_, i) => i * 60);+ return json(route, {+ date: url.searchParams.get('date') || '2026-06-21',+ moment: { local: '2026-06-21T12:00:00', utc: '2026-06-21T10:00:00Z' },+ curve: {+ minutes,+ clock: minutes.map((m) => `${String(m / 60).padStart(2, '0')}:00`),+ sun_azimuth: minutes.map((m) => (m / 1440) * 360),+ sun_altitude: minutes.map((m) => Math.round(Math.sin((m / 1440) * Math.PI) * 60 - 5)),+ moon_azimuth: minutes.map((m) => ((m / 1440) * 360 + 180) % 360),+ moon_altitude: minutes.map((m) => Math.round(Math.sin((m / 1440) * Math.PI + 2) * 40)),+ moon_illuminated: minutes.map(() => 0.62),+ },+ sun: { rise: '05:45', set: '21:55', noon: '13:50' },+ moon: { phase: 'waxing gibbous', waxing: true, illuminated: 0.62 },+ });+ }if (path === '/api/geo/places') {const q = url.searchParams.get('q') ?? '';geoQueries.places.push(q);@@ -1760,6 +1898,10 @@ export async function installAppFixture(page, options = {}) {return {captures,+ labelTiles,+ widgetLoads,+ gridWrites,+ skyQueries,proofSaves,linkWrites,entityWrites,@@ -1792,6 +1934,50 @@ export async function installAppFixture(page, options = {}) {};}+/**+ * Wait for the map to be up.+ *+ * The signal is `lib/map`'s own ready flag, not a class the engine happens to+ * put on its container: a suite that recognises the engine is a suite pinned to+ * it, and swapping the engine (SPEC v3) would then rewrite every map spec.+ */+export async function awaitMapReady(page) {+ // The runner's Firefox has no WebGL and cannot be given any: it asks for a+ // native driver, a box with no GPU has none, and the software path a patched+ // build would take is not there — `tryNativeGL()`, then `EXHAUSTED_DRIVERS`,+ // read off its own console with the blocklist off, `webgl.allow-software` set+ // and both halves of mesa installed. So the map is answered by Chromium there.+ //+ // Only there. A developer's Firefox draws the map like any other browser, and+ // the specs run on both engines locally, which is where an engine-specific+ // break would show first. The skip is named in the report rather than hidden,+ // and it sits here because every spec that needs a map comes through this+ // line — a new one is covered the day it is written.+ test.skip(+ !!process.env.CI && test.info().project.name === 'firefox',+ 'the runner\'s Firefox has no WebGL; Chromium answers for the map there'+ );+ await expect(page.locator('.map[data-map-ready="true"]')).toBeVisible();+}++/**+ * What the map is painting, as bytes.+ *+ * A drawn shape has no element of its own — the engine paints every layer of+ * them into one canvas — so what a spec can hold onto is the picture. Two of+ * these differ when something was drawn, cleared or restyled, and comparing+ * them is how a spec says "that appeared" without naming the engine.+ */+export async function mapPicture(page) {+ await expect(page.locator('.map[data-map-ready="true"]')).toBeVisible();+ return page.locator('.map').screenshot();+}++/** Did the map's picture change? */+export function repainted(before, after) {+ return !before.equals(after);+}+export async function openProofWithPanel(page) {await page.goto('/#proof');await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.jsindex b475a10..2acb650 100644--- a/frontend/e2e/proof-canvas.spec.js+++ b/frontend/e2e/proof-canvas.spec.js@@ -83,7 +83,11 @@ test('a picked colour becomes the default for the next drawn shape', async ({ paawait page.mouse.up();await expect(page.locator('.shape-row')).toHaveCount(1);- // Pick a new colour while that first box is still selected.+ // Take the Box back up before picking. A shape puts the pen down when it+ // lands, so a colour chosen straight afterwards repaints it — that is the+ // point of putting it down. The pick this test is about is the other one:+ // made with a drawing tool in hand, where it sets the next shape.+ await page.getByTitle('Box (r)').click();await page.getByTitle('Annotation colour').click();await page.getByLabel('color #40c4ff').click();@@ -121,7 +125,9 @@ test('a picked stroke width becomes the default for the next drawn shape', asyncawait page.mouse.up();await expect(page.locator('.shape-row')).toHaveCount(1);- // Change the stroke width while the first box is still selected.+ // Box back in hand, so the width sets the next shape rather than the one just+ // drawn (see the colour test above).+ await page.getByTitle('Box (r)').click();await page.getByTitle('Stroke width', { exact: true }).click();await page.locator('.stroke-slider').fill('11');@@ -443,6 +449,9 @@ test('a fill is opt-in, rides the shape colour and survives the save', async ({await page.mouse.up();await expect(page.locator('.shape-row')).toHaveCount(1);+ // Box back in hand, so the fill answers to the next shape and leaves the+ // hollow one alone (see the colour test above).+ await page.getByTitle('Box (r)').click();await page.getByTitle('Fill', { exact: true }).click();await page.getByLabel('fill opacity').fill('40');@@ -471,7 +480,10 @@ test('the fill control is out for the kinds that cannot hold one', async ({ pagefixture.expectNoUnexpectedRequests();});-/** Two boxes side by side on the panel, drawn with the Box tool. */+/** Two boxes side by side on the panel, drawn with the Box tool. Armed once per+ * box, because each one puts the pen down as it lands — three boxes in a row is+ * the shortcut pressed three times. The second lands picked with Select already+ * back in hand, so no closing click is needed. */async function drawTwoBoxes(page) {const canvas = page.locator('.konva canvas').first();const box = await canvas.boundingBox();@@ -483,12 +495,14 @@ async function drawTwoBoxes(page) {await page.mouse.down();await page.mouse.move(cx - 20, cy + 10, { steps: 6 });await page.mouse.up();+ await expect(page.locator('.shape-row')).toHaveCount(1);+ await page.getByTitle('Box (r)').click();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();+ await expect(page.getByTitle('Select / move (v)')).toHaveClass(/active/);return { cx, cy };}@@ -888,9 +902,13 @@ test('a row picked in the side column takes the hand back to Select', async ({ pawait 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.+ // The box lands picked with the pen down, so its row is lit already.await expect(page.locator('.shape-row')).toHaveCount(1);+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);++ // Take the Box back up and it goes out: with a drawing tool in hand no row+ // lights up, because nothing on the canvas would answer to it.+ await page.getByTitle('Box (r)').click();await expect(page.locator('.shape-row.selected')).toHaveCount(0);await page.locator('.shape-row').click();@@ -1032,7 +1050,7 @@ test('a freehand stroke resizes from its handles, and its samples take the changfixture.expectNoUnexpectedRequests();});-test('a finished curve leaves the tool in hand', async ({ page }) => {+test('a finished curve puts the pen down, like every shape but the stamp', async ({ page }) => {const fixture = await installAppFixture(page);await openProofWithPanel(page);@@ -1054,10 +1072,17 @@ test('a finished curve leaves the tool in hand', async ({ page }) => {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/);+ // Closing the curve picks it and hands Select back, so the colour, the width+ // and the note go onto what was just drawn — which is nearly always what+ // follows a stroke.+ await expect(curve).not.toHaveClass(/active/);+ await expect(page.getByTitle('Select / move (v)')).toHaveClass(/active/);+ await expect(page.locator('.shape-row.selected')).toHaveCount(1);- // Three curves in a row is three drags, not three presses on `c` as well.+ // A second curve is `c` again: three in a row is the shortcut pressed three+ // times, not a tool nobody asked to keep.await page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 450)));+ await curve.click();await vertex(cx - 40, cy + 25);await vertex(cx, cy + 10);await page.mouse.dblclick(cx + 40, cy + 25);diff --git a/frontend/e2e/satellite-canvas.spec.js b/frontend/e2e/satellite-canvas.spec.jsindex c23533b..b2d70ba 100644--- a/frontend/e2e/satellite-canvas.spec.js+++ b/frontend/e2e/satellite-canvas.spec.js@@ -1,10 +1,10 @@import { test, expect } from '@playwright/test';-import { installAppFixture } from './app.fixture.js';+import { awaitMapReady, installAppFixture } from './app.fixture.js';test('opens Map with the case sidebar collapsed and lets the user reopen it', async ({ page }) => {const fixture = await installAppFixture(page);await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await expect(page.locator('.sidebar')).toHaveCount(0);await page.getByTitle('Toggle case sidebar').click();@@ -28,17 +28,17 @@ test('opens Map with the case sidebar collapsed and lets the user reopen it', asawait page.getByTitle('Toggle case sidebar').click();await expect(page.locator('.sidebar')).toBeVisible();await page.reload();- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await expect(page.locator('.sidebar')).toHaveCount(0);fixture.expectNoUnexpectedRequests();});-test('rotates the real Leaflet map with a middle-button gesture', async ({ page }) => {+test('rotates the real map with a middle-button gesture', async ({ page }) => {const fixture = await installAppFixture(page);await page.goto('/#satellite');+ await awaitMapReady(page);const map = page.locator('.map');- await expect(map).toHaveClass(/leaflet-container/);const box = await map.boundingBox();expect(box).not.toBeNull();@@ -53,11 +53,11 @@ test('rotates the real Leaflet map with a middle-button gesture', async ({ pagefixture.expectNoUnexpectedRequests();});-test('captures a marquee drawn on the real Leaflet surface', async ({ page }) => {+test('captures a marquee drawn on the real map surface', async ({ page }) => {const fixture = await installAppFixture(page);await page.goto('/#satellite');+ await awaitMapReady(page);const map = page.locator('.map');- await expect(map).toHaveClass(/leaflet-container/);await page.getByRole('button', { name: 'Capture options' }).click();await page.getByRole('button', { name: 'Select area', exact: true }).click();@@ -75,3 +75,42 @@ test('captures a marquee drawn on the real Leaflet surface', async ({ page }) =>expect(fixture.captures[0].height).toBeGreaterThan(100);fixture.expectNoUnexpectedRequests();});++test('says the map needs WebGL rather than drawing an empty panel without it', async ({ page }) => {+ // A browser can refuse WebGL: an old driver, a machine with no GPU, a profile+ // hardened to turn it off. The engine throws on the way up, and the tool used+ // to swallow it and leave the panel blank for good.+ await page.addInitScript(() => {+ const real = HTMLCanvasElement.prototype.getContext;+ HTMLCanvasElement.prototype.getContext = function (kind, ...rest) {+ return String(kind).startsWith('webgl') ? null : real.call(this, kind, ...rest);+ };+ });+ await installAppFixture(page);+ await page.goto('/#satellite');++ await expect(page.getByText('The map needs WebGL, which this browser does not have.')).toBeVisible();+ await expect(page.locator('.map[data-map-ready="true"]')).toHaveCount(0);+});++test('says it on a browser that has no WebGL of its own, not a stubbed one', async ({ page }) => {+ // The case above builds the refusal by taking `getContext` away. This one does+ // not build anything: the CI runner's Firefox is a real browser with no GL+ // driver under it, which is an environment we cannot fake and no longer have+ // to. Where WebGL exists — every developer's machine, and Chromium anywhere —+ // there is nothing here to see and the stubbed case above stands for it.+ await installAppFixture(page);+ await page.goto('/#satellite');++ const usable = await page.evaluate(() => {+ try {+ return !!document.createElement('canvas').getContext('webgl2');+ } catch {+ return false;+ }+ });+ test.skip(usable, 'this browser has WebGL; the stubbed case covers the message');++ await expect(page.getByText('The map needs WebGL, which this browser does not have.')).toBeVisible();+ await expect(page.locator('canvas')).toHaveCount(0);+});diff --git a/frontend/e2e/satellite-map.spec.js b/frontend/e2e/satellite-map.spec.jsnew file mode 100644index 0000000..6bb96d1--- /dev/null+++ b/frontend/e2e/satellite-map.spec.js@@ -0,0 +1,105 @@+import { test, expect } from '@playwright/test';+import { awaitMapReady, installAppFixture } from './app.fixture.js';++/**+ * What the map itself does, driven in a real browser.+ *+ * Two things here are not features but *conventions*, and both are written into+ * files on the analyst's disk: a whole zoom level is what every route takes and+ * every capture records, and a bearing turns the map clockwise — which is what+ * `engine/tiles.py` rotates a crop by, so a saved place or capture restores+ * mirrored if it ever flips. Nothing in this file names the engine; it asks+ * only what an analyst can see and what the backend was told.+ */++const hud = (page) => page.locator('.hud-coords').first();++async function openMap(page) {+ const fixture = await installAppFixture(page);+ const asked = [];+ page.on('request', (request) => {+ const at = /\/api\/tiles\/[^/]+\/(\d+)\//.exec(request.url());+ if (at) asked.push(Number(at[1]));+ });+ await page.goto('/#satellite');+ await awaitMapReady(page);+ return { fixture, asked };+}++/** Read one screen point's coordinates back, through a grid polygon vertex. */+async function vertexAt(page, fixture, dx, dy) {+ const box = await page.locator('.map').boundingBox();+ const cx = box.x + box.width / 2;+ const cy = box.y + box.height / 2;+ await page.getByRole('button', { name: 'Polygon' }).click();+ await page.mouse.click(cx + dx, cy + dy);+ await page.mouse.click(cx + dx + 60, cy + dy + 60);+ await page.mouse.click(cx + dx - 60, cy + dy + 60);+ await page.getByRole('button', { name: 'Confirm' }).click();+ await expect.poll(() => fixture.gridWrites.length).toBeGreaterThan(0);+ return fixture.gridWrites.at(-1).spec.aoi.vertices[0];+}++test('one notch of the wheel is one whole zoom level', async ({ page }) => {+ // The camera is continuous and the app is not. Left to itself the engine+ // moves about a fifth of a level per notch, which rounds back to the level+ // it started on: the map twitches and the wheel does nothing at all.+ const { asked } = await openMap(page);+ await expect(hud(page)).toContainText('z16');+ const box = await page.locator('.map').boundingBox();+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);++ await page.mouse.wheel(0, -120);+ await expect(hud(page)).toContainText('z17');+ await page.mouse.wheel(0, -120);+ await expect(hud(page)).toContainText('z18');+ await page.mouse.wheel(0, 120);+ await expect(hud(page)).toContainText('z17');++ // and the level the analyst is reading is the level the proxy was asked for+ await expect.poll(() => asked.includes(18)).toBe(true);+ expect(asked.every((zoom) => Number.isInteger(zoom))).toBe(true);+});++test('the zoom buttons walk the same levels', async ({ page }) => {+ await openMap(page);+ await page.getByRole('button', { name: 'Zoom in' }).click();+ await expect(hud(page)).toContainText('z17');+ await page.getByRole('button', { name: 'Zoom out' }).click();+ await expect(hud(page)).toContainText('z16');+});++test('a bearing turns the map clockwise, and the compass points at north', async ({ page }) => {+ const { fixture } = await openMap(page);+ // the readout is the map centre, and a turn is about the centre+ const [lat, lon] = (await hud(page).innerText()).split('\n')[0].split(',').map(Number);++ await page.getByRole('button', { name: /^0°$/ }).click();+ await page.getByLabel('Set bearing in degrees').fill('90');+ await page.getByLabel('Set bearing in degrees').press('Enter');+ await expect(page.getByRole('button', { name: /90°/ })).toBeVisible();++ await page.getByRole('button', { name: 'Grid Search' }).click();+ await expect(page.getByRole('button', { name: 'Polygon' })).toBeVisible();+ // north has swung to the right, so what is up the screen is now due west+ const up = await vertexAt(page, fixture, 0, -160);+ expect(up[1]).toBeLessThan(lon);+ expect(Math.abs(up[0] - lat)).toBeLessThan(0.001);++ // …and the needle followed north there, rather than to the opposite side+ const needle = await page.evaluate(+ () => getComputedStyle(document.querySelector('.compass svg')).transform+ );+ // a clockwise quarter turn: matrix(cos, sin, -sin, cos) at +90°+ expect(needle).toBe('matrix(0, 1, -1, 0, 0, 0)');+});++test('north is up again when the rose is pressed', async ({ page }) => {+ await openMap(page);+ await page.getByRole('button', { name: /^0°$/ }).click();+ await page.getByLabel('Set bearing in degrees').fill('215');+ await page.getByLabel('Set bearing in degrees').press('Enter');+ await expect(page.getByRole('button', { name: /215°/ })).toBeVisible();+ await page.getByRole('button', { name: 'Reset to north' }).click();+ await expect(page.getByRole('button', { name: /^0°$/ })).toBeVisible();+});diff --git a/frontend/e2e/satellite-overlays.spec.js b/frontend/e2e/satellite-overlays.spec.jsnew file mode 100644index 0000000..67e2e5a--- /dev/null+++ b/frontend/e2e/satellite-overlays.spec.js@@ -0,0 +1,279 @@+import { test, expect } from '@playwright/test';+import { awaitMapReady, installAppFixture, mapPicture, repainted } from './app.fixture.js';++/**+ * What the tool draws on the map, driven in a real browser.+ *+ * These paths had no browser coverage: the grid, the sky arc and the movable pin+ * were only ever asserted as strings in the source. They are also the paths that+ * a change of map engine rewrites, so this is the net that has to hold across+ * one — nothing here names the engine, only what an analyst can see and press.+ */++const tools = (page) => page.getByRole('button', { name: 'Grid Search' });++async function openGrid(page) {+ const fixture = await installAppFixture(page);+ await page.goto('/#satellite');+ await awaitMapReady(page);+ await tools(page).click();+ await expect(page.getByRole('button', { name: 'Box' })).toBeVisible();+ // the view opens at z16, where a dragged box is under one default 500 m cell+ await page.getByTitle('Cell size in metres for the next grid').fill('50');+ return fixture;+}++/**+ * Drag a box over the middle of the map, and wait for the lattice to appear.+ *+ * The cells are declared in one tick and painted a frame later — the engine+ * builds a layer's features off the main thread — so a click fired in the same+ * tick can land before there is anything under it to hit. An analyst never+ * moves that fast; a spec does.+ */+async function dragBox(page, from = [140, 130], to = [420, 330]) {+ const bare = await mapPicture(page);+ const box = await page.locator('.map').boundingBox();+ await page.mouse.move(box.x + from[0], box.y + from[1]);+ await page.mouse.down();+ await page.mouse.move(box.x + to[0], box.y + to[1], { steps: 8 });+ await page.mouse.up();+ await expect.poll(async () => repainted(bare, await mapPicture(page))).toBe(true);+}++const coverage = (page) => page.locator('.grid-cov-text');++test('draws a grid over a dragged area and counts its cells', async ({ page }) => {+ await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await expect(page.getByText('Drag a box on the map. Esc to cancel.')).toBeVisible();++ await dragBox(page);++ // the lattice is painted on a canvas, so what says it exists is its own count+ await expect(coverage(page)).toBeVisible();+ const total = Number((await coverage(page).innerText()).split('/')[1].split(' ')[0]);+ expect(total).toBeGreaterThan(1);+ await expect(coverage(page)).toContainText('0/');+ await expect(coverage(page)).toContainText('· 0%');+});++test('marks a cell where it was clicked, and files that mark', async ({ page }) => {+ const fixture = await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await dragBox(page);+ await expect(coverage(page)).toContainText('0/');++ const box = await page.locator('.map').boundingBox();+ await page.mouse.click(box.x + 200, box.y + 200);++ // one cell cleared: the click reached the shape on the canvas, and only it+ await expect(coverage(page)).toContainText('1/');+ await expect.poll(() => {+ const last = fixture.gridWrites.at(-1);+ return Object.values(last?.spec?.statuses ?? {});+ }).toEqual(['cleared']);+});++test('flags a cell on a right-click without cycling it', async ({ page }) => {+ const fixture = await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await dragBox(page);++ const box = await page.locator('.map').boundingBox();+ await page.mouse.click(box.x + 200, box.y + 200, { button: 'right' });++ await expect(coverage(page)).toContainText('flagged');+ await expect.poll(() => {+ const last = fixture.gridWrites.at(-1);+ return Object.values(last?.spec?.statuses ?? {});+ }).toEqual(['flagged']);+});++test('sweeps with the keyboard, cell after cell', async ({ page }) => {+ await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await dragBox(page);+ await page.getByRole('button', { name: 'Review' }).click();+ await expect(page.getByText('clear · F flag · S skip')).toBeVisible();++ await page.keyboard.press('c');+ await expect(coverage(page)).toContainText('1/');+ await page.keyboard.press('f');+ await expect(coverage(page)).toContainText('2/');+ await expect(coverage(page)).toContainText('1 flagged');+ await page.keyboard.press('Escape');+ await expect(page.getByText('clear · F flag · S skip')).toHaveCount(0);+});++test('hides the grid without closing it, then brings it back', async ({ page }) => {+ await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await dragBox(page); // which does not return until the lattice is on screen+ const drawn = await mapPicture(page);++ await page.getByRole('button', { name: 'Hide grid' }).click();+ // the lattice is gone from the imagery, and the grid is still open behind it+ const hidden = await mapPicture(page);+ expect(repainted(drawn, hidden)).toBe(true);+ await expect(coverage(page)).toBeVisible();++ await page.getByRole('button', { name: 'Show grid' }).click();+ expect(repainted(hidden, await mapPicture(page))).toBe(true);+});++test('reshapes the area from its corner handles', async ({ page }) => {+ await openGrid(page);+ await page.getByRole('button', { name: 'Box' }).click();+ await dragBox(page);+ const before = Number((await coverage(page).innerText()).split('/')[1].split(' ')[0]);++ await page.getByRole('button', { name: 'Edit area' }).click();+ await expect(page.getByText('Drag the corners to reshape.')).toBeVisible();+ const handles = page.locator('.grid-handle');+ await expect(handles).toHaveCount(4);++ const handle = await handles.first().boundingBox();+ await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);+ await page.mouse.down();+ await page.mouse.move(handle.x + 140, handle.y - 120, { steps: 8 });+ await page.mouse.up();++ // the area really changed size, so the lattice was rebuilt over it+ await expect+ .poll(async () => Number((await coverage(page).innerText()).split('/')[1].split(' ')[0]))+ .not.toBe(before);+ await expect(handles).toHaveCount(4); // and the handles snapped to the new box+});++test('places a polygon area point by point', async ({ page }) => {+ await openGrid(page);+ await page.getByRole('button', { name: 'Polygon' }).click();+ const box = await page.locator('.map').boundingBox();+ // clear of the grid panel, which covers the top-left of the map+ for (const [x, y] of [[420, 200], [620, 240], [520, 420]]) {+ await page.mouse.click(box.x + x, box.y + y);+ }+ await expect(page.getByText('Click to add points· 3')).toBeVisible();+ await expect(page.locator('.grid-handle')).toHaveCount(3);++ await page.getByRole('button', { name: 'Confirm' }).click();+ await expect(coverage(page)).toBeVisible();+ await expect(page.locator('.grid-handle')).toHaveCount(0);+});++test('draws the sun and moon arcs for an anchored point, and scrubs the hour', async ({ page }) => {+ const fixture = await installAppFixture(page);+ await page.goto('/#satellite');+ await awaitMapReady(page);+ const bare = await mapPicture(page);+ await page.getByRole('button', { name: 'Sun and moon' }).click();++ // the day is asked for, then asked again once it comes back named+ await expect.poll(() => fixture.skyQueries.length).toBe(2);+ const marks = page.locator('.sky-body');+ await expect(marks).toHaveCount(1); // the sun is up at midday, the moon is not+ // the arcs, the hour ticks and the two rays are painted on the map itself+ expect(repainted(bare, await mapPicture(page))).toBe(true);++ const before = await marks.first().getAttribute('style');+ const slider = page.getByRole('slider', { name: 'Time of day' });+ await slider.focus();+ for (let i = 0; i < 6; i += 1) await page.keyboard.press('ArrowRight');++ // the mark rode along its ray without asking the backend again+ await expect.poll(async () => (await marks.first().getAttribute('style')) !== before).toBe(true);+ expect(fixture.skyQueries).toHaveLength(2);+});++test('drops the sky layer when the mode closes', async ({ page }) => {+ await installAppFixture(page);+ await page.goto('/#satellite');+ await awaitMapReady(page);+ await page.getByRole('button', { name: 'Sun and moon' }).click();+ await expect(page.locator('.sky-body')).toHaveCount(1);+ const drawn = await mapPicture(page);++ await page.getByRole('button', { name: 'Sun and moon' }).click();+ await expect(page.locator('.sky-body')).toHaveCount(0);+ // and the arcs went with the mark, off the map's own picture+ expect(repainted(drawn, await mapPicture(page))).toBe(true);+});++test('carries the coordinates on a dragged pin, and drops it on exit', async ({ page }) => {+ await installAppFixture(page);+ await page.goto('/#satellite');+ await awaitMapReady(page);++ await page.getByTitle('Marker style').selectOption('pin');+ await page.getByTitle('Move the marker (coordinates follow it)').click();+ const pin = page.locator('.sat-marker');+ await expect(pin).toHaveCount(1);++ const readout = page.locator('.hud-coords');+ const before = await readout.innerText();+ const at = await pin.boundingBox();+ await page.mouse.move(at.x + at.width / 2, at.y + at.height / 2);+ await page.mouse.down();+ await page.mouse.move(at.x + 120, at.y + 90, { steps: 8 });+ await page.mouse.up();++ // the readout is what a capture files, so it follows the pin, not the centre+ await expect.poll(async () => (await readout.innerText()) !== before).toBe(true);++ await page.getByTitle('Move the marker (coordinates follow it)').click();+ await expect(pin).toHaveCount(0);+});++test('lays the OSM labels over the imagery, and lifts them off again', async ({ page }) => {+ // The toggle sat on the tool while the layer never heard about it: the effect+ // that carries it down read the map first, and while the map was still being+ // built the switch it was watching was never read at all.+ const fixture = await installAppFixture(page);+ const imagery = [];+ page.on('request', (request) => {+ if (request.url().includes('/api/tiles/')) imagery.push(request.url());+ });+ await page.goto('/#satellite');+ await awaitMapReady(page);+ const labels = page.getByLabel('Toggle OSM labels overlay');++ expect(fixture.labelTiles).toEqual([]);+ await labels.click();+ await expect.poll(() => fixture.labelTiles.length).toBeGreaterThan(0);++ // off again, and a pan proves it: the imagery is still being fetched and the+ // labels are not+ await labels.click();+ const laid = fixture.labelTiles.length;+ const painted = imagery.length;+ const box = await page.locator('.map').boundingBox();+ await page.mouse.move(box.x + 400, box.y + 300);+ await page.mouse.down();+ await page.mouse.move(box.x + 120, box.y + 120, { steps: 8 });+ await page.mouse.up();+ await expect.poll(() => imagery.length).toBeGreaterThan(painted);+ expect(fixture.labelTiles.length).toBe(laid);+});++test('measures a path clicked on the map, and clears it', async ({ page }) => {+ await installAppFixture(page);+ await page.goto('/#satellite');+ await awaitMapReady(page);+ await page.getByRole('button', { name: 'Measure tools' }).click();+ await page.getByRole('button', { name: 'Distance' }).click();++ const bare = await mapPicture(page);+ const box = await page.locator('.map').boundingBox();+ await page.mouse.click(box.x + 160, box.y + 160);+ await page.mouse.click(box.x + 360, box.y + 260);++ // two dots and the line between them, and the reading they add up to+ await expect(page.locator('.measure-value')).toHaveText(/\d+(\.\d+)?\s?(m|km)/);+ const drawn = await mapPicture(page);+ expect(repainted(bare, drawn)).toBe(true);++ await page.getByRole('button', { name: 'Clear points' }).click();+ await expect(page.locator('.measure-value')).toHaveCount(0);+ expect(repainted(drawn, await mapPicture(page))).toBe(true);+});diff --git a/frontend/e2e/satellite-search.spec.js b/frontend/e2e/satellite-search.spec.jsindex b14a828..c5e5229 100644--- a/frontend/e2e/satellite-search.spec.js+++ b/frontend/e2e/satellite-search.spec.js@@ -1,5 +1,5 @@import { test, expect } from '@playwright/test';-import { installAppFixture } from './app.fixture.js';+import { awaitMapReady, installAppFixture } from './app.fixture.js';const SAVED = [{@@ -22,7 +22,7 @@ const bar = (page) => page.getByRole('combobox', { name: 'Search a place or coortest('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 awaitMapReady(page);await bar(page).fill('kr');await expect(page.getByRole('option', { name: /Kramatorsk/ })).toBeVisible();@@ -38,7 +38,7 @@ test('proposes cities from the first letters, without asking the geocoder', asyntest('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 awaitMapReady(page);await bar(page).fill('kramatorsk');// the city is there straight away; the street arrives after the pause@@ -53,7 +53,7 @@ test('asks the geocoder once typing stops, and puts its matches last', async ({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 awaitMapReady(page);await bar(page).fill('kram');await expect(page.locator('#sat-suggestions .head').first()).toHaveText('Saved in this case');@@ -65,7 +65,7 @@ test('offers saved work in this case above anything looked up', async ({ page })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 awaitMapReady(page);await expect(page.locator('.hud-coords')).toContainText('48.85'); // the home view, Parisawait bar(page).fill('kramatorsk');@@ -81,7 +81,7 @@ test('flies the map to the row the arrows land on', async ({ page }) => {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 awaitMapReady(page);await bar(page).fill('50.4501, 30.5234');await expect(page.locator('#sat-suggestions .head').first()).toHaveText('Coordinates');@@ -96,7 +96,7 @@ test('recognises coordinates as they are typed', async ({ page }) => {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 awaitMapReady(page);await bar(page).fill('kramatorsk');await page.getByRole('option', { name: /Kramatorsk Donetsk/ }).first().click();@@ -111,7 +111,7 @@ test('remembers where it was sent, and offers it back on an empty bar', async ({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 awaitMapReady(page);await bar(page).fill('kram');await expect(page.locator('#sat-suggestions')).toBeVisible();diff --git a/frontend/e2e/satellite-widget.spec.js b/frontend/e2e/satellite-widget.spec.jsnew file mode 100644index 0000000..16c8763--- /dev/null+++ b/frontend/e2e/satellite-widget.spec.js@@ -0,0 +1,113 @@+import { test, expect } from '@playwright/test';+import { awaitMapReady, fakeGoogleMaps, installAppFixture, mapPicture } from './app.fixture.js';++/**+ * The one basemap that is not our tiles.+ *+ * Google's terms forbid taking those pixels out of its own map, so its map is+ * put *under* ours and the two cameras are kept in step (`lib/map/gmaps.js`).+ * The whole path is driven here against a stand-in Maps API — no key, no+ * network, no billed map load — because the parts that can go wrong are ours:+ * whether it shows through at all, whether it follows, whether it is credited,+ * and whether it is ever built twice.+ */++async function openWidget(page) {+ await fakeGoogleMaps(page);+ const fixture = await installAppFixture(page, { widget: true });+ await page.goto('/#satellite');+ await awaitMapReady(page);+ await page.getByTitle('Imagery provider').selectOption('google-js');+ await expect(page.locator('.map-glass')).toBeAttached();+ return fixture;+}++const maps = (page) => page.evaluate(() => window.__googleMaps.length);+const camera = (page) => page.evaluate(() => window.__googleMaps[0].cameras.at(-1));++test('shows through our own canvas rather than under it', async ({ page }) => {+ // The engine's canvas is transparent where nothing is drawn. If our map's own+ // background ever paints over the layer instead, the basemap is simply blank+ // and nothing else in the tool says so.+ await openWidget(page);+ const shot = await mapPicture(page);+ const magenta = await page.evaluate(async (bytes) => {+ const bitmap = await createImageBitmap(new Blob([new Uint8Array(bytes)]));+ const canvas = document.createElement('canvas');+ canvas.width = bitmap.width;+ canvas.height = bitmap.height;+ canvas.getContext('2d').drawImage(bitmap, 0, 0);+ const { data } = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);+ let lit = 0;+ for (let at = 0; at < data.length; at += 4) {+ if (data[at] > 200 && data[at + 1] < 60 && data[at + 2] > 200) lit += 1;+ }+ return lit;+ }, [...shot]);+ expect(magenta).toBeGreaterThan(10_000);+});++test('follows our camera, and covers the view at every bearing', async ({ page }) => {+ await openWidget(page);+ const opened = await camera(page);+ expect(opened.zoom).toBe(16); // the app's zoom, not the engine's++ await page.getByRole('button', { name: 'Zoom in' }).click();+ await expect.poll(async () => (await camera(page)).zoom).toBeGreaterThan(16.9);++ // a rotated rectangle fits inside the circle of its own diagonal, so the+ // element is a square of that diagonal — otherwise a turn eats the corners+ const turn = page.locator('.map-glass-turn');+ const side = await page.evaluate(() => {+ const el = document.querySelector('.map');+ return Math.ceil(Math.hypot(el.clientWidth, el.clientHeight));+ });+ await expect(turn).toHaveCSS('width', `${side}px`);+ await expect(turn).toHaveCSS('height', `${side}px`);++ await page.getByRole('button', { name: /^0°$/ }).click();+ await page.getByLabel('Set bearing in degrees').fill('90');+ await page.getByLabel('Set bearing in degrees').press('Enter');+ await expect(page.getByRole('button', { name: /90°/ })).toBeVisible();+ // turned the same way the map turned: clockwise+ await expect(turn).toHaveCSS('transform', 'matrix(0, 1, -1, 0, 0, 0)');+});++test('never takes the pointer, so every gesture is still ours', async ({ page }) => {+ await openWidget(page);+ await expect(page.locator('.map-glass')).toHaveCSS('pointer-events', 'none');+ // …except the credit, whose terms link has to stay reachable+ await expect(page.locator('.map-glass-credit')).toHaveCSS('pointer-events', 'auto');+ await expect(page.locator('.map-glass-credit')).toContainText('Map data © Google');+ await expect(page.locator('.map-glass-credit a')).toHaveAttribute('href', /terms_maps/);+});++test('is built once and counted once, however often it is shown', async ({ page }) => {+ // every google.maps.Map instantiation is a billed dynamic map load+ const fixture = await openWidget(page);+ expect(await maps(page)).toBe(1);+ await expect.poll(() => fixture.widgetLoads).toEqual(['google_js']);++ await page.getByTitle('Imagery provider').selectOption('esri-world-imagery');+ await expect(page.locator('.map-glass')).toHaveAttribute('hidden', '');+ await page.getByTitle('Imagery provider').selectOption('google-js');+ await expect(page.locator('.map-glass')).not.toHaveAttribute('hidden', '');++ expect(await maps(page)).toBe(1);+ expect(fixture.widgetLoads).toEqual(['google_js']);+});++test('leaves nothing of our own tiles between the analyst and the imagery', async ({ page }) => {+ await openWidget(page);+ const asked = [];+ page.on('request', (request) => {+ if (request.url().includes('/api/tiles/')) asked.push(request.url());+ });+ const box = await page.locator('.map').boundingBox();+ await page.mouse.move(box.x + 200, box.y + 200);+ await page.mouse.down();+ await page.mouse.move(box.x + 320, box.y + 300, { steps: 8 });+ await page.mouse.up();+ await page.waitForTimeout(800);+ expect(asked).toEqual([]);+});diff --git a/frontend/e2e/saved-linked-posts.spec.js b/frontend/e2e/saved-linked-posts.spec.jsindex e11338f..c37f667 100644--- a/frontend/e2e/saved-linked-posts.spec.js+++ b/frontend/e2e/saved-linked-posts.spec.js@@ -1,6 +1,8 @@import { test, expect } from '@playwright/test';-import { CASE_ID, installAppFixture } from './app.fixture.js';+import { CASE_ID, awaitMapReady, installAppFixture } from './app.fixture.js';+// The third one names a target this build dropped, which is what a draft saved+// before that looks like: it is listed, and it opens (on X, by normalizePostTarget).const linkedPosts = [{ id: 'post-1', name: 'panorama-publication', title: 'Panorama publication', target: 'x' },{ id: 'post-2', name: 'source-follow-up', title: 'Follow-up with sources', target: 'bluesky' },@@ -49,7 +51,7 @@ test('shows every linked post from a proof popup and opens the selected draft',});await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await page.getByRole('button', { name: 'Proofs', exact: true }).click();await expect(page.getByText('Panorama autostitch test')).toBeVisible();@@ -86,6 +88,7 @@ test('clears capture rows before a different case index arrives', async ({ page});await page.goto('/#satellite');+ await awaitMapReady(page); // the rows are read beside a map, and one mark is on itconst savedPanel = page.locator('.captures');await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();await page.getByRole('button', { name: 'Show saved work on the map' }).click();@@ -114,6 +117,7 @@ test('clears proof rows before a different case proof index arrives', async ({ p});await page.goto('/#satellite');+ await awaitMapReady(page); // the panel is the map tool's, and it opens with itawait page.getByRole('button', { name: 'Proofs', exact: true }).click();await expect(page.getByText('Proof A')).toBeVisible();await page.getByTitle('Switch case').click();diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.jsindex 4602d20..8132934 100644--- a/frontend/e2e/saved-relations.spec.js+++ b/frontend/e2e/saved-relations.spec.js@@ -1,13 +1,13 @@import { test, expect } from '@playwright/test';-import { CASE_ID, installAppFixture } from './app.fixture.js';+import { CASE_ID, awaitMapReady, installAppFixture } from './app.fixture.js';/**- * Relations on the map, in a real Leaflet popup.+ * Relations on the map, in a real card opened on a mark.*- * The popup is the one surface where a click has somewhere else to go: Leaflet- * closes a popup when a click reaches the map, and the card's own controls edit- * only the card. Rendering it server-side cannot tell us whether that holds, so- * these run in the browser.+ * The card is the one surface where a click has somewhere else to go: a click+ * that reaches the map closes it, and the card's own controls edit only the+ * card. Rendering it server-side cannot tell us whether that holds, so these+ * run in the browser.*/const point = {@@ -72,7 +72,7 @@ test('opens a stacked row’s relations without closing the card', async ({ page});await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await page.getByRole('button', { name: 'Show saved work on the map' }).click();await page.locator('.saved-mark').click();@@ -97,7 +97,7 @@ test('corrects the reading of a relation in place, and takes one back', async ({});await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await page.getByRole('button', { name: 'Show saved work on the map' }).click();await page.locator('.saved-mark').click();@@ -124,7 +124,7 @@ test('settles a suggested relation from the card, which survives the click', asy});await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await page.getByRole('button', { name: 'Show saved work on the map' }).click();await page.locator('.saved-mark').click();@@ -168,7 +168,7 @@ test('shows the findings on the card and leaves the pointers out', async ({ page});await page.goto('/#satellite');- await expect(page.locator('.map')).toHaveClass(/leaflet-container/);+ await awaitMapReady(page);await page.getByRole('button', { name: 'Show saved work on the map' }).click();await page.locator('.saved-mark').click();diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.jsindex 5ccd583..cba9d63 100644--- a/frontend/e2e/timeline.spec.js+++ b/frontend/e2e/timeline.spec.js@@ -1,5 +1,5 @@import { test, expect } from '@playwright/test';-import { CASE_ID, installAppFixture } from './app.fixture.js';+import { awaitMapReady, CASE_ID, installAppFixture } from './app.fixture.js';const person = {id: 'person-1',@@ -778,6 +778,7 @@ async function openTimelineOverJune(page, options = {}) {test('hands one window from the Timeline to the Map, the Board and back', async ({ page }) => {const fixture = await openTimelineOverJune(page);await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();+ await awaitMapReady(page); // the marks are drawn on it, so it has to be upconst layer = page.getByLabel('Timeline map layer');await expect(layer).toContainText('1 Jun – 21 Jun 2026');@@ -806,6 +807,7 @@ test('hands one window from the Timeline to the Map, the Board and back', asynctest('opens a statement in the Timeline from its mark on the map', async ({ page }) => {const fixture = await openTimelineOverJune(page);await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();+ await awaitMapReady(page); // the marks are drawn on it, so it has to be upawait page.locator('.temporal-mark').click();const popup = page.locator('.temporal-popup');@@ -830,6 +832,7 @@ test('draws the window and nothing else, framed on what it holds', async ({ page},});await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();+ await awaitMapReady(page); // the marks are drawn on it, so it has to be upawait expect(page.locator('.temporal-mark')).toHaveCount(1);await expect(page.locator('.saved-mark-place')).toHaveCount(0);@@ -859,6 +862,7 @@ test('says a window holds nothing placed instead of pulling the map out to say i});await setWindow(page, '2026-06-18T00:00', '2026-06-19T00:00');await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();+ await awaitMapReady(page); // the marks are drawn on it, so it has to be upconst layer = page.getByLabel('Timeline map layer');await expect(layer).toContainText('None of the 10 dated here carries a place.');diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex e4fbd94..80116de 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -11,14 +11,12 @@"@fontsource/oxanium": "^5.2.8","dompurify": "^3.4.13","konva": "^9.3.0",- "leaflet": "^1.9.4",- "leaflet-rotate": "^0.2.8",- "leaflet.gridlayer.googlemutant": "^0.16.0",+ "maplibre-gl": "^6.8.0","marked": "^17.0.6","mermaid": "^11.16.1"},"devDependencies": {- "@playwright/test": "^1.61.1",+ "@playwright/test": "^1.63.0","@sveltejs/vite-plugin-svelte": "^7.2.0","happy-dom": "^20.10.6","svelte": "^5.0.0",@@ -163,6 +161,92 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@mapbox/jsonlint-lines-primitives": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/@mapbox/jsonlint-lines-primitives/-/jsonlint-lines-primitives-2.0.3.tgz",+ "integrity": "sha512-0SElaV0uMxEnxzBhhX9WTuPyUeMsAN/SS0i16tjuba4/mio63MG9khjC1a0JAiPGXAwvwm4UfHJURCN7nyudQg==",+ "license": "MIT",+ "engines": {+ "node": ">= 22"+ }+ },+ "node_modules/@mapbox/point-geometry": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@mapbox/point-geometry/-/point-geometry-1.1.0.tgz",+ "integrity": "sha512-YGcBz1cg4ATXDCM/71L9xveh4dynfGmcLDqufR+nQQy3fKwsAZsWd/x4621/6uJaeB9mwOHE6hPeDgXz9uViUQ==",+ "license": "ISC"+ },+ "node_modules/@mapbox/tiny-sdf": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/@mapbox/tiny-sdf/-/tiny-sdf-2.2.0.tgz",+ "integrity": "sha512-LVL4wgI9YAum5V+LNVQO6QgFBPw7/MIIY4XJPNsPDMrjEwcE+JfKk1LuIl8GnF197ejVdC9QdPaxrx5gfgdGXg==",+ "license": "BSD-2-Clause"+ },+ "node_modules/@mapbox/unitbezier": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@mapbox/unitbezier/-/unitbezier-1.0.0.tgz",+ "integrity": "sha512-fqd515fjBmANKGGsQ286E2Wvj/XvDFpGzwJxq4CI6jMQue6Oy04uCKp+JWKF00xRTmk6cEu1jPJ9p3xqH8YWqQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/@mapbox/vector-tile": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@mapbox/vector-tile/-/vector-tile-3.0.0.tgz",+ "integrity": "sha512-Qf10S1uIHMk20ri/IVBnpS+esUEkVaR5Hftmz88jTInrpmWgPGJfPe3LVjjlE77trLx8tH6qjTG7uWH9hIq/0Q==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@mapbox/point-geometry": "~1.1.0",+ "@types/geojson": "^7946.0.16",+ "pbf": "^5.0.0"+ }+ },+ "node_modules/@maplibre/geojson-vt": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.1.1.tgz",+ "integrity": "sha512-FVMOcmSP/yqol45t7StApEyTL5/vmqBCuFhH9n+fFuINenhaX+YgHHIt1yJ86S8kln3uJLcMvmEU2cfn6E2eCQ==",+ "license": "ISC",+ "dependencies": {+ "kdbush": "^4.1.0"+ }+ },+ "node_modules/@maplibre/maplibre-gl-style-spec": {+ "version": "26.4.1",+ "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.4.1.tgz",+ "integrity": "sha512-I/qcIKVFHFSg1Meu/eqHrkSTjIez0gCsSaK56TNPutM3TkE61aSq6F1cZ4Kg4KiNs3cpViLtubDjfyRcQCdEJQ==",+ "license": "ISC",+ "dependencies": {+ "@mapbox/jsonlint-lines-primitives": "^2.0.3",+ "@mapbox/unitbezier": "^1.0.0",+ "json-stringify-pretty-compact": "^4.0.0",+ "minimist": "^1.2.8",+ "quickselect": "^3.0.0",+ "tinyqueue": "^3.0.0"+ },+ "bin": {+ "gl-style-format": "dist/gl-style-format.mjs",+ "gl-style-migrate": "dist/gl-style-migrate.mjs",+ "gl-style-validate": "dist/gl-style-validate.mjs"+ }+ },+ "node_modules/@maplibre/mlt": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.2.1.tgz",+ "integrity": "sha512-5n5dgolE2EYxwCKgx8vlwURCB8A+kyfJJyThlYimjlGgOcOe2Bhw9VxxnnHC91OC9PgHg+nVdgVPTYPkIo62vg==",+ "license": "(MIT OR Apache-2.0)",+ "dependencies": {+ "@mapbox/point-geometry": "^1.1.0"+ }+ },+ "node_modules/@maplibre/vt-pbf": {+ "version": "4.3.2",+ "resolved": "https://registry.npmjs.org/@maplibre/vt-pbf/-/vt-pbf-4.3.2.tgz",+ "integrity": "sha512-j6p0AdjvAR19Z3XaCysle7A4ZSo08tYOzxD0Y9NQylwPAkwJJeYub5b2eVucdeDh7erhv69DahoLOevDRERRUw==",+ "license": "MIT",+ "dependencies": {+ "@mapbox/point-geometry": "^1.1.0",+ "@types/geojson": "^7946.0.16",+ "pbf": "^5.1.0"+ }+ },"node_modules/@mermaid-js/parser": {"version": "1.2.0","resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.2.0.tgz",@@ -202,19 +286,19 @@}},"node_modules/@playwright/test": {- "version": "1.61.1",- "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.1.tgz",- "integrity": "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==",+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz",+ "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==","dev": true,"license": "Apache-2.0","dependencies": {- "playwright": "1.61.1"+ "playwright": "1.63.0"},"bin": {"playwright": "cli.js"},"engines": {- "node": ">=18"+ "node": ">=20"}},"node_modules/@rolldown/binding-android-arm64": {@@ -1647,6 +1731,12 @@"@types/trusted-types": "^2.0.7"}},+ "node_modules/earcut": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/earcut/-/earcut-3.2.3.tgz",+ "integrity": "sha512-vnS4AVwp1KHAF13i1vp1/2D5evWy3k5u/iW/B81QVsUZtV8cv2tU0b2VNFlqvh4kYwrFMDdjPCfAmfyJW9y14Q==",+ "license": "ISC"+ },"node_modules/entities": {"version": "7.0.1","resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",@@ -1756,6 +1846,12 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/gl-matrix": {+ "version": "3.4.4",+ "resolved": "https://registry.npmjs.org/gl-matrix/-/gl-matrix-3.4.4.tgz",+ "integrity": "sha512-latSnyDNt/8zYUB6VIJ6PCh2jBjJX6gnDsoCZ7LyW7GkqrD51EWwa9qCoGixj8YqBtETQK/xY7OmpTF8xz1DdQ==",+ "license": "MIT"+ },"node_modules/hachure-fill": {"version": "0.5.2","resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",@@ -1822,6 +1918,12 @@"@types/estree": "^1.0.6"}},+ "node_modules/json-stringify-pretty-compact": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/json-stringify-pretty-compact/-/json-stringify-pretty-compact-4.0.0.tgz",+ "integrity": "sha512-3CNZ2DnrpByG9Nqj6Xo8vqbjT4F6N+tb4Gb28ESAZjYZ5yqvmc56J+/kuIwkaAMOyblTQhUW7PxMkUb8Q36N3Q==",+ "license": "MIT"+ },"node_modules/katex": {"version": "0.16.47","resolved": "https://registry.npmjs.org/katex/-/katex-0.16.47.tgz",@@ -1847,6 +1949,12 @@"node": ">= 12"}},+ "node_modules/kdbush": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/kdbush/-/kdbush-4.1.0.tgz",+ "integrity": "sha512-e9vurzrXJQrFX6ckpHP3bvj5l+9CnYzkxDNnNQ1h2QTqdWsUAJgXiKdGNcOa1EY85dU8KbQ+z/FdQdB7P+9yfQ==",+ "license": "ISC"+ },"node_modules/khroma": {"version": "2.1.0","resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz",@@ -1878,27 +1986,6 @@"integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==","license": "MIT"},- "node_modules/leaflet": {- "version": "1.9.4",- "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz",- "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==",- "license": "BSD-2-Clause"- },- "node_modules/leaflet-rotate": {- "version": "0.2.8",- "resolved": "https://registry.npmjs.org/leaflet-rotate/-/leaflet-rotate-0.2.8.tgz",- "integrity": "sha512-BHtkn35DuJ377yBNn/7XVuV0oIfwJtmqv/wFQ0Lvh7QuVCAD2wfCK0/m9oA3k/LVOnJG8VEGyf3Duf/wTVzeKQ==",- "license": "GPL-3.0",- "peerDependencies": {- "leaflet": "^1.9.3"- }- },- "node_modules/leaflet.gridlayer.googlemutant": {- "version": "0.16.0",- "resolved": "https://registry.npmjs.org/leaflet.gridlayer.googlemutant/-/leaflet.gridlayer.googlemutant-0.16.0.tgz",- "integrity": "sha512-wN8DxR5zplhZA6a5998AOluCL97H5lkr1yCLOT7siaQyc+hT6E8kcGqjAuSsEUSoaf/U3H25x8Avkp9OpgJpng==",- "license": "Beerware"- },"node_modules/lightningcss": {"version": "1.32.0","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",@@ -2183,6 +2270,38 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/maplibre-gl": {+ "version": "6.8.0",+ "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.8.0.tgz",+ "integrity": "sha512-+ZkjKTodsVLY0ewQThvXRxXQsclcsSgOm5LlnrBM3G8AloMJKt6Haw8mY4xrOl8T0WMqH6DTYjktZ9zGQXZd4w==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "@mapbox/point-geometry": "^1.1.0",+ "@mapbox/tiny-sdf": "^2.2.0",+ "@mapbox/unitbezier": "^1.0.0",+ "@mapbox/vector-tile": "^3.0.0",+ "@maplibre/geojson-vt": "^6.1.1",+ "@maplibre/maplibre-gl-style-spec": "^26.4.1",+ "@maplibre/mlt": "^1.2.1",+ "@maplibre/vt-pbf": "^4.3.2",+ "@types/geojson": "^7946.0.16",+ "earcut": "^3.2.3",+ "gl-matrix": "^3.4.4",+ "kdbush": "^4.1.0",+ "murmurhash-js": "^1.0.0",+ "pbf": "^5.1.2",+ "potpack": "^2.1.0",+ "quickselect": "^3.0.0",+ "tinyqueue": "^3.0.0"+ },+ "engines": {+ "node": ">=16.14.0",+ "npm": ">=8.1.0"+ },+ "funding": {+ "url": "https://github.com/maplibre/maplibre-gl-js?sponsor=1"+ }+ },"node_modules/marked": {"version": "17.0.6","resolved": "https://registry.npmjs.org/marked/-/marked-17.0.6.tgz",@@ -2236,6 +2355,15 @@"node": ">= 20"}},+ "node_modules/minimist": {+ "version": "1.2.8",+ "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",+ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/mri": {"version": "1.2.0","resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",@@ -2246,6 +2374,12 @@"node": ">=4"}},+ "node_modules/murmurhash-js": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/murmurhash-js/-/murmurhash-js-1.0.0.tgz",+ "integrity": "sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==",+ "license": "MIT"+ },"node_modules/nanoid": {"version": "3.3.18","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",@@ -2298,6 +2432,18 @@"dev": true,"license": "MIT"},+ "node_modules/pbf": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",+ "integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "resolve-protobuf-schema": "^2.1.0"+ },+ "bin": {+ "pbf": "bin/pbf"+ }+ },"node_modules/picocolors": {"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",@@ -2319,50 +2465,32 @@}},"node_modules/playwright": {- "version": "1.61.1",- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",- "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==","dev": true,"license": "Apache-2.0","dependencies": {- "playwright-core": "1.61.1"+ "playwright-core": "1.63.0"},"bin": {"playwright": "cli.js"},"engines": {- "node": ">=18"- },- "optionalDependencies": {- "fsevents": "2.3.2"+ "node": ">=20"}},"node_modules/playwright-core": {- "version": "1.61.1",- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",- "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",+ "version": "1.63.0",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==","dev": true,"license": "Apache-2.0","bin": {"playwright-core": "cli.js"},"engines": {- "node": ">=18"- }- },- "node_modules/playwright/node_modules/fsevents": {- "version": "2.3.2",- "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",- "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",- "dev": true,- "hasInstallScript": true,- "license": "MIT",- "optional": true,- "os": [- "darwin"- ],- "engines": {- "node": "^8.16.0 || ^10.6.0 || >=11.0.0"+ "node": ">=20"}},"node_modules/points-on-curve": {@@ -2410,6 +2538,24 @@"node": "^10 || ^12 || >=14"}},+ "node_modules/potpack": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/potpack/-/potpack-2.1.0.tgz",+ "integrity": "sha512-pcaShQc1Shq0y+E7GqJqvZj8DTthWV1KeHGdi0Z6IAin2Oi3JnLCOfwnCo84qc+HAp52wT9nK9H7FAJp5a44GQ==",+ "license": "ISC"+ },+ "node_modules/protocol-buffers-schema": {+ "version": "3.6.1",+ "resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.1.tgz",+ "integrity": "sha512-VG2K63Igkiv9p76tk1lilczEK1cT+kCjKtkdhw1dQZV3k3IXJbd3o6Ho8b9zJZaHSnT2hKe4I+ObmX9w6m5SmQ==",+ "license": "MIT"+ },+ "node_modules/quickselect": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/quickselect/-/quickselect-3.0.0.tgz",+ "integrity": "sha512-XdjUArbK4Bm5fLLvlm5KpTFOiOThgfWWI4axAZDWg4E/0mKdZyI9tNEfds27qCi1ze/vwTR16kvmmGhRra3c2g==",+ "license": "ISC"+ },"node_modules/readdirp": {"version": "4.1.2","resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",@@ -2424,6 +2570,15 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/resolve-protobuf-schema": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",+ "integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",+ "license": "MIT",+ "dependencies": {+ "protocol-buffers-schema": "^3.3.1"+ }+ },"node_modules/robust-predicates": {"version": "3.0.3","resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",@@ -2624,6 +2779,12 @@"url": "https://github.com/sponsors/SuperchupuDev"}},+ "node_modules/tinyqueue": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/tinyqueue/-/tinyqueue-3.0.0.tgz",+ "integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",+ "license": "ISC"+ },"node_modules/tinyrainbow": {"version": "3.1.0","resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 437b713..c0e99d3 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -13,7 +13,7 @@"check": "svelte-check --output human --threshold warning"},"devDependencies": {- "@playwright/test": "^1.61.1",+ "@playwright/test": "^1.63.0","@sveltejs/vite-plugin-svelte": "^7.2.0","happy-dom": "^20.10.6","svelte": "^5.0.0",@@ -26,9 +26,7 @@"@fontsource/oxanium": "^5.2.8","dompurify": "^3.4.13","konva": "^9.3.0",- "leaflet": "^1.9.4",- "leaflet-rotate": "^0.2.8",- "leaflet.gridlayer.googlemutant": "^0.16.0",+ "maplibre-gl": "^6.8.0","marked": "^17.0.6","mermaid": "^11.16.1"}diff --git a/frontend/playwright.config.js b/frontend/playwright.config.jsindex 56b0c4b..eefc6d2 100644--- a/frontend/playwright.config.js+++ b/frontend/playwright.config.js@@ -7,7 +7,7 @@ export default defineConfig({retries: process.env.CI ? 1 : 0,// Canvas-heavy browser specs compete for CPU under Playwright's default of// one worker per core. Four keeps local runs parallel without turning normal- // Leaflet/Konva startup into a timeout; CI stays fully deterministic.+ // MapLibre/Konva startup into a timeout; CI stays fully deterministic.workers: process.env.CI ? 1 : 4,reporter: process.env.CI ? 'github' : 'list',use: {@@ -23,6 +23,14 @@ export default defineConfig({},projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },+ // Plain, after four attempts at giving this browser WebGL on a CI runner:+ // the blocklist turned off, the software fallback allowed, and both halves+ // of mesa installed each left the console saying the same thing —+ // `tryNativeGL()`, then `EXHAUSTED_DRIVERS`. Chromium carries its own+ // software renderer and needs none of that; a patched headless Firefox has+ // nowhere to fall back to. The map specs skip themselves there and say so+ // (`awaitMapReady` in `app.fixture.js`); every other spec runs, and locally+ // Firefox draws the map like anything else.{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },],});diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 58b89a2..2602e7b 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -300,8 +300,8 @@.topbar {height: var(--topbar-h);flex-shrink: 0;- /* own stacking context above the tool canvas: Leaflet's panes (z-index up- to 1000) otherwise swallow the case switcher's dropdown */+ /* own stacking context above the tool canvas: a map's own layers and+ controls otherwise swallow the case switcher's dropdown */position: relative;z-index: 1200;display: flex;diff --git a/frontend/src/app.css b/frontend/src/app.cssindex f352037..dac2126 100644--- a/frontend/src/app.css+++ b/frontend/src/app.css@@ -155,7 +155,7 @@color-scheme: light;}-/* Surfaces that sit *over imagery* — the Satellite map with its Leaflet+/* Surfaces that sit *over imagery* — the Satellite map with its owncontrols (zoom, scale, attribution) and floating tool clusters — were tunedfor the dark palette and must stay dark in every theme, or they clash withthe tiles beneath them. Opt in with class="dark-surface": it re-pins thediff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelteindex b6afa62..79e5dc0 100644--- a/frontend/src/components/Icon.svelte+++ b/frontend/src/components/Icon.svelte@@ -1,7 +1,7 @@<script module>/** Inline icon set (24×24, stroke-based, lucide-style). No external assets.- * Exported so code that has to build SVG outside a component (the Leaflet- * marker icons) draws from this one set instead of copying paths. */+ * Exported so code that has to build SVG outside a component (the map's+ * marker glyphs) draws from this one set instead of copying paths. */export const paths = {// navigation / toolsmedia: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm0 11 4.5-4.5a1 1 0 0 1 1.4 0L14 15.5m-1.5-1.5 2.6-2.6a1 1 0 0 1 1.4 0L21 15M9 9.5h.01',diff --git a/frontend/src/components/RelationList.svelte b/frontend/src/components/RelationList.svelteindex 399a94f..5a8076a 100644--- a/frontend/src/components/RelationList.svelte+++ b/frontend/src/components/RelationList.svelte@@ -63,11 +63,11 @@/*** A row control acts on its own relation, and nothing above it should treat the- * click as its own. That matters most in a map popup: Leaflet decides a click- * was "on the map" by walking up from the event target to find the popup- * container, and these controls replace themselves, so their button can already- * be detached by the time the event bubbles — the card would close under the- * analyst. Stopping inside the handler rather than on a wrapper, because Svelte+ * click as its own. That matters most in a map card: a click that reaches the+ * map closes it, and these controls replace themselves, so their button can+ * already be gone from the document by the time the event bubbles — the card+ * would close under the analyst, and no guard that has to find the button+ * again would help. Stopping inside the handler rather than on a wrapper, because Svelte* delegates these clicks to the app root: an ancestor that stopped them would* silence the buttons instead of protecting them.*/diff --git a/frontend/src/components/RelationList.test.js b/frontend/src/components/RelationList.test.jsindex 38aca35..1e9e18d 100644--- a/frontend/src/components/RelationList.test.js+++ b/frontend/src/components/RelationList.test.js@@ -69,7 +69,7 @@ describe('RelationList', () => {const hosts = {'EntityDetails.svelte': 'subjectType={entity.type}','../tools/satellite/SavedPopup.svelte': "subjectType={row.kind === 'place' ? 'place' : 'capture'}",- '../tools/Satellite.svelte': 'subjectType="place"',+ '../tools/satellite/PlaceDialog.svelte': 'subjectType="place"',};for (const [host, expected] of Object.entries(hosts)) {const body = readFileSync(new URL(host, import.meta.url), 'utf8');@@ -78,10 +78,10 @@ describe('RelationList', () => {});it('keeps its clicks to itself, inside each handler', () => {- // In a Leaflet popup, a click that looks like it reached the map closes the- // card. These controls replace themselves, so their button can be detached by- // the time the event bubbles and Leaflet's walk up to the popup container- // finds nothing. It has to be stopped *in* the handler: Svelte delegates these+ // In a map card, a click that looks like it reached the map closes the+ // card. These controls replace themselves, so their button can be gone from+ // the document by the time the event bubbles. It has to be stopped *in* the+ // handler: Svelte delegates these// clicks to the app root, so an ancestor that stopped them would silence the// buttons instead of shielding them.expect(source).toContain('function own(handler)');diff --git a/frontend/src/lib/coords.js b/frontend/src/lib/coords.jsindex b6a9796..114f298 100644--- a/frontend/src/lib/coords.js+++ b/frontend/src/lib/coords.js@@ -3,7 +3,7 @@// *shown*, per the user's Settings → General choice. Nothing here ever// changes what lands on disk, so a case reads the same for every reader.//-// Kept pure and Leaflet-free so it can be unit-tested.+// Kept pure and free of the map so it can be unit-tested.export const COORD_FORMATS = ['dd', 'dms', 'mgrs'];@@ -19,7 +19,7 @@ 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+ * A map keeps counting past the antimeridian as the analyst pans, so its* 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.*/diff --git a/frontend/src/lib/coords.test.js b/frontend/src/lib/coords.test.jsindex a5f267a..4a0a4ef 100644--- a/frontend/src/lib/coords.test.js+++ b/frontend/src/lib/coords.test.js@@ -189,7 +189,7 @@ describe('utmZone', () => {});describe('wrapLon', () => {- it('folds a longitude Leaflet kept counting past the date line', () => {+ it('folds a longitude the map 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);diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.jsindex 556a59b..3b3d46f 100644--- a/frontend/src/lib/extBridge.js+++ b/frontend/src/lib/extBridge.js@@ -75,6 +75,50 @@ export function captureTab({ timeoutMs = 4000, win = window } = {}) {});}+/**+ * Hand a prepared thread to the extension, which opens the composer and fills it.+ *+ * Resolves when the extension **takes** it, not when it has finished: filling is+ * tens of seconds — a tab, a composer mounting, a file at a time — and the answer+ * needed here is only whether the app should stand down. What the fill managed is+ * reported by the extension's own notifications.+ *+ * A rejection is not a failure to report: it means the app still owns the+ * hand-off and opens the intent page itself, exactly as it does with no extension+ * installed. Absent, switched off, not permitted on that site, silent: one+ * answer, one fallback.+ *+ * Hence the short timeout. It is a question with three cheap checks behind it,+ * and the caller is holding a click — a browser only lets a page open a tab for a+ * few seconds after one, so a slow no would spend the click and open nothing. An+ * old extension that has never heard of this message answers by staying silent,+ * which is exactly the case the timeout is short for.+ *+ * Nothing but paths crosses this channel. The extension fetches the bytes from+ * the local app with its own pairing token, so no case file is ever posted into+ * the page, and the token never reaches the app's DOM.+ */+export function handOffPost(payload, { timeoutMs = 2000, win = window } = {}) {+ return new Promise((resolve, reject) => {+ const id = `post-${++seq}`;+ const timer = setTimeout(() => {+ win.removeEventListener('message', onMessage);+ reject(new Error('the capture extension did not answer'));+ }, timeoutMs);+ function onMessage(event) {+ if (event.origin !== win.location.origin) return;+ const msg = event.data;+ if (!msg || msg.channel !== CHANNEL || msg.type !== 'post-handoff-result' || msg.id !== id) return;+ clearTimeout(timer);+ win.removeEventListener('message', onMessage);+ if (msg.ok) resolve(true);+ else reject(new Error(msg.error || 'the capture extension refused'));+ }+ win.addEventListener('message', onMessage);+ win.postMessage({ channel: CHANNEL, type: 'post-handoff', id, payload }, win.location.origin);+ });+}+/*** Subscribe to the extension's "activated" signal: the user just clicked the* extension on this tab (granting activeTab), so a previously refused capturediff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.jsindex b6de892..02c4e99 100644--- a/frontend/src/lib/extBridge.test.js+++ b/frontend/src/lib/extBridge.test.js@@ -1,6 +1,6 @@// @vitest-environment happy-domimport { describe, it, expect, afterEach } from 'vitest';-import { extensionVersion, extensionOutdated, captureTab, onActivated } from './extBridge.js';+import { extensionVersion, extensionOutdated, captureTab, handOffPost, onActivated } from './extBridge.js';// The bridge protocol is the app's only path to widget pixels, so what these// tests pin is the contract: detection reads the content script's marker, and@@ -100,3 +100,44 @@ describe('onActivated', () => {expect(calls).toBe(1); // unsubscribed — no further calls});});++// The same fake, answering hand-offs. The app's fallback hangs on this reply,+// so what is pinned is that only a correlated `ok` counts as taken.+function fakePostBridge(answer) {+ const onMessage = (event) => {+ const msg = event.data;+ if (!msg || msg.channel !== 'azimut-capture-ext' || msg.type !== 'post-handoff') return;+ window.postMessage(+ { channel: 'azimut-capture-ext', type: 'post-handoff-result', id: msg.id, ...answer(msg) },+ window.location.origin+ );+ };+ window.addEventListener('message', onMessage);+ return () => window.removeEventListener('message', onMessage);+}++describe('handOffPost', () => {+ it('resolves as soon as the extension takes it, not when it has finished', async () => {+ // filling is tens of seconds; the answer needed here is only whether the app+ // should stand down, and it is needed while the click can still open a tab+ const off = fakePostBridge(() => ({ ok: true, accepted: true }));+ await expect(handOffPost({ posts: [] })).resolves.toBe(true);+ off();+ });++ it('rejects when the extension declines, so the app opens the page itself', async () => {+ const off = fakePostBridge(() => ({ ok: false, error: 'not enabled for this site' }));+ await expect(handOffPost({ posts: [] })).rejects.toThrow('not enabled for this site');+ off();+ });++ it('rejects on silence, which is what no extension installed looks like', async () => {+ await expect(handOffPost({ posts: [] }, { timeoutMs: 120 })).rejects.toThrow('did not answer');+ });++ it('ignores a reply meant for another request', async () => {+ const off = fakePostBridge((msg) => ({ ok: true, accepted: true, id: `${msg.id}-not` }));+ await expect(handOffPost({ posts: [] }, { timeoutMs: 120 })).rejects.toThrow('did not answer');+ off();+ });+});diff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.jsindex 5c2bc4e..5677cd2 100644--- a/frontend/src/lib/extension.test.js+++ b/frontend/src/lib/extension.test.js@@ -25,7 +25,15 @@ function makeChrome(overrides = {}) {},session: { get: vi.fn(async () => ({})), set: vi.fn(), remove: vi.fn() },},- tabs: { captureVisibleTab: vi.fn(async () => 'data:image/png;base64,xyz') },+ tabs: {+ captureVisibleTab: vi.fn(async () => 'data:image/png;base64,xyz'),+ create: vi.fn(async () => ({ id: 7 })),+ // the worker waits for "complete"; the stub says so on the next tick+ onUpdated: {+ addListener: vi.fn((cb) => setTimeout(() => cb(7, { status: 'complete' }), 0)),+ removeListener: vi.fn(),+ },+ },scripting: { executeScript: vi.fn() },notifications: { create: vi.fn() },runtime: {@@ -58,14 +66,16 @@ function load({ chrome = makeChrome(), fetchImpl, imageBitmap, canvasLog } = {})'fetch','createImageBitmap','OffscreenCanvas',- `${source}\n;return { cropDataUrl, ingest, handle, settings };`+ 'btoa',+ `${source}\n;return { cropDataUrl, ingest, handle, settings, handOff };`);return factory(chrome,undefined,fetchImpl ?? vi.fn(),async () => imageBitmap ?? { width: 2000, height: 1200 },- OffscreenCanvasStub+ OffscreenCanvasStub,+ btoa // the real one: what a handed-over file carries is the assertion);}@@ -172,3 +182,124 @@ describe('handle: capture-tab (the app relay)', () => {expect(res.ok).toBe(false);});});++/** The fill runs after the answer, so the assertions on it wait for the effect. */+async function settle(fn, tries = 50) {+ for (let i = 0; i < tries; i += 1) {+ try {+ return fn();+ } catch {+ await new Promise((r) => setTimeout(r, 5));+ }+ }+ return fn();+}++describe('handOff: filling a composer the app prepared', () => {+ const payload = {+ url: 'https://x.com/compose/post?text=Geolocated',+ caseId: 'case-1',+ posts: [{ text: 'Geolocated', files: ['proofs/strike.png'] }, { text: 'Context', files: [] }],+ };++ /** A paired chrome. */+ function fillingChrome() {+ const chrome = makeChrome();+ chrome.storage.local.get = vi.fn(async (d) => ({+ ...d, backendUrl: 'http://127.0.0.1:8477', token: 'tok-123',+ }));+ return chrome;+ }++ const attachment = () => ({+ ok: true,+ blob: async () => ({ type: 'image/png', arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer }),+ });++ it('reads each attachment with the pairing token, then fills the tab it opened', async () => {+ const chrome = fillingChrome();+ const fetchImpl = vi.fn(async () => attachment());+ const { handOff } = load({ chrome, fetchImpl });+ chrome.scripting.executeScript = vi.fn(async () => [{ result: { filled: 2 } }]);++ const res = await handOff(payload);++ // answered on three cheap checks, while the click is still fresh enough for+ // the app to open a tab if the answer had been no+ expect(res).toEqual({ ok: true, accepted: true });+ await settle(() => expect(chrome.scripting.executeScript).toHaveBeenCalled());+ // paths become one token-bearing read each, against the app, not the page+ expect(fetchImpl).toHaveBeenCalledWith(+ 'http://127.0.0.1:8477/api/ingest/file?case_id=case-1&path=proofs%2Fstrike.png',+ { headers: { 'X-Azimut-Token': 'tok-123' } }+ );+ expect(chrome.tabs.create).toHaveBeenCalledWith({ url: payload.url, active: true });+ // Both injections in the page's own world: an editor ignores what an+ // extension's world makes, and there is no extension API on that side — so+ // the thread goes in on a global and the report comes back as a return value.+ const [setter, filler] = chrome.scripting.executeScript.mock.calls.map(([one]) => one);+ expect(setter.world).toBe('MAIN');+ // The file crosses as plain base64, never as a `data:` URL: the page rebuilds+ // it with atob, because a fetch on that side answers to the site's own CSP —+ // and X allows no connection to `data:`, so every attachment came back+ // "Failed to fetch" and took the rest of the thread with it.+ const [{ posts }] = setter.args;+ expect(posts).toHaveLength(2);+ expect(posts[0].files).toEqual([+ { name: 'strike.png', type: 'image/png', data: btoa('\x01\x02\x03') },+ ]);+ expect(filler).toEqual({ target: { tabId: 7 }, world: 'MAIN', files: ['handoff.js'] });+ });++ it('refuses an unpaired extension, which cannot read the files anyway', async () => {+ const chrome = makeChrome();+ chrome.storage.local.get = vi.fn(async (d) => ({ ...d, token: '' }));+ const { handOff } = load({ chrome });+ await expect(handOff(payload)).rejects.toThrow(/not paired/);+ expect(chrome.tabs.create).not.toHaveBeenCalled();+ });++ it('keeps no switch of its own: the one in Azimut is the whole answer', () => {+ // Two boxes for one question is a pair that can disagree, and the one that+ // says no is the one nobody thinks to look at.+ expect(source).not.toContain('handoff: false');+ expect(source).not.toContain('permissions.contains');+ });++ it('skips a file the app will not hand over instead of losing the thread', async () => {+ const chrome = fillingChrome();+ const fetchImpl = vi.fn(async () => ({ ok: false, status: 413 }));+ const { handOff } = load({ chrome, fetchImpl });+ chrome.scripting.executeScript = vi.fn(async () => [{ result: { filled: 2 } }]);++ await expect(handOff(payload)).resolves.toEqual({ ok: true, accepted: true });+ // and it says so, because a picture missing from a published thread is not+ // something to discover after posting+ await settle(() => expect(chrome.notifications.create).toHaveBeenCalled());+ });++ it('says what the fill could not do, since the app was answered long before', async () => {+ const chrome = fillingChrome();+ const { handOff } = load({ chrome, fetchImpl: vi.fn(async () => attachment()) });+ chrome.scripting.executeScript = vi.fn(async () => [+ { result: { filled: 1, error: 'Post 2 stayed empty.' } },+ ]);++ await handOff(payload);++ await settle(() =>+ expect(chrome.notifications.create).toHaveBeenCalledWith(+ expect.objectContaining({ message: expect.stringContaining('Post 2 stayed empty.') })+ )+ );+ });++ it('refuses a hand-off asked for by anything but the local app', async () => {+ const { handle } = load({ chrome: fillingChrome() });+ const res = await handle(+ { type: 'post-handoff', payload },+ { tab: { url: 'https://evil.example/' } }+ );+ expect(res.ok).toBe(false);+ });+});diff --git a/frontend/src/lib/extensionHandoff.test.js b/frontend/src/lib/extensionHandoff.test.jsnew file mode 100644index 0000000..82ff092--- /dev/null+++ b/frontend/src/lib/extensionHandoff.test.js@@ -0,0 +1,675 @@+// @vitest-environment happy-dom+/**+ * Tests for the script that fills a composer (extension/handoff.js).+ *+ * It is the one file that knows another site's DOM, so what is pinned here is+ * not the markup — that will change — but the two roads in and the rule around+ * them: a post is typed (`insertText`, the browser's own editing command) or+ * pasted, whichever road that site answers to, and the box is **read back and+ * counted** either way — an editor takes a post without saying so, refuses one+ * without saying so, and X's puts it in six times. A file is handed to the+ * composer's **own file input**. Nothing is ever submitted, and every way the+ * page can disappoint ends in a report of how far it got rather than a throw.+ *+ * Like the worker's suite next door, the source is evaluated with stubs instead+ * of a second npm project inside extension/. It runs in the page's world, so+ * there is no extension API to stub: the thread goes in on a global and the+ * report is the script's own return value.+ */+import { describe, it, expect, vi } 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 source = readFileSync(join(here, '../../../extension/handoff.js'), 'utf8');++class FakeDataTransfer {+ constructor() {+ this.text = null;+ this.files = [];+ this.items = { add: (file) => this.files.push(file) };+ }+ setData(type, value) {+ if (type === 'text/plain') this.text = value;+ }+ getData(type) {+ return (type === 'text/plain' ? this.text : null) ?? '';+ }+}++class FakeClipboardEvent extends Event {+ constructor(type, init = {}) {+ super(type, init);+ this.clipboardData = init.clipboardData;+ }+}++/**+ * Gecko's, which reads a different member.+ *+ * Its `ClipboardEventInit` has no `clipboardData`: it builds a clipboard of its+ * own out of `data`, which is text and nothing else. Not assumed — run against+ * both engines before it was written down here.+ */+class GeckoClipboardEvent extends Event {+ constructor(type, init = {}) {+ super(type, init);+ this.clipboardData = new FakeDataTransfer();+ if (init.dataType === 'text/plain') this.clipboardData.setData('text/plain', init.data);+ }+}++class FakeDragEvent extends Event {+ constructor(type, init = {}) {+ super(type, init);+ this.dataTransfer = init.dataTransfer;+ }+}++class FakeFile {+ constructor(parts, name, opts) {+ this.parts = parts;+ this.name = name;+ this.type = opts?.type;+ }+}++const BOX = (i) => `<div data-testid="tweetTextarea_${i}" contenteditable="true" tabindex="0"></div>`;+// X draws an empty post's placeholder as a sibling carrying the same test id+// with `_label` on the end — a match for the selector that is not a box.+const PLACEHOLDER = (i) => `<div data-testid="tweetTextarea_${i}_label">What is happening?!</div>`;+const FILE_INPUT = (i) => `<input type="file" data-testid="fileInput" data-post="${i}" />`;+const PNG = { name: 'proof.png', type: 'image/png', data: btoa('\x89PNG') };++/**+ * Run handoff.js against a page, and resolve with what it reported plus what it+ * did: where each post **landed** whichever road took it there, the two roads+ * separately for the tests that are about which one a site takes, and the files+ * it handed over.+ *+ * The stubbed composer takes both a keystroke and a paste, because the real ones+ * do — `takesPaste: false` and `canType: false` are how a test closes a road.+ */+function run({+ hostname = 'x.com', posts, html,+ canType = true, takesPaste = true, gecko = false,+ onPaste, onAttach, onType, onReady,+}) {+ document.body.innerHTML = html;+ const landed = [];+ const typed = [];+ const pastes = [];+ const attached = [];+ const dropped = [];+ const idOf = (el) => el.dataset.testid ?? el.className;+ // The stub writes where the **selection** is, like the browser's own command,+ // which is the whole point of placing the caret: focus alone left every post's+ // text going into the first box. It answers `selectAll`/`delete` too, the pair+ // an editor implements itself and the only way this script empties a box.+ //+ // It writes and then reports **refused**, which is what a real editor handling+ // the keystroke itself does — it cancels the browser's default. Trusting that+ // verdict put the post in a second time.+ const selectedAll = new Set();+ document.execCommand = vi.fn((command, _ui, value) => {+ const anchor = window.getSelection()?.anchorNode;+ const node = anchor?.nodeType === 1 ? anchor : anchor?.parentElement;+ const box = node?.closest?.('[contenteditable="true"]');+ if (!box) return false;+ if (command === 'selectAll') return !!selectedAll.add(box);+ if (command === 'delete') {+ if (selectedAll.delete(box)) box.textContent = '';+ return true;+ }+ if (command !== 'insertText' || !canType) return false;+ typed.push({ box: idOf(box), text: value });+ landed.push({ box: idOf(box), text: value });+ box.textContent += value;+ onType?.(box, value);+ return false;+ });+ for (const box of document.querySelectorAll('[contenteditable="true"]')) {+ box.addEventListener('paste', (e) => {+ const text = e.clipboardData.text;+ pastes.push({ box: idOf(box), text, files: e.clipboardData.files });+ if (takesPaste && text) {+ landed.push({ box: idOf(box), text });+ box.textContent += text;+ }+ onPaste?.(box, e);+ });+ }+ for (const input of document.querySelectorAll('input[type="file"]')) {+ input.addEventListener('change', () => {+ attached.push({ input: input.dataset.testid, files: input.files });+ onAttach?.(input);+ });+ }+ document.body.addEventListener('drop', (e) => dropped.push(e.dataTransfer.files));+ onReady?.(document);+ window.__AZIMUT_HANDOFF__ = { posts };+ // No `fetch` in scope on purpose — see the CSP test at the bottom.+ return new Function(+ 'location',+ 'DataTransfer',+ 'ClipboardEvent',+ 'DragEvent',+ 'File',+ // assigned rather than returned: the file opens with a doc comment, and a+ // `return` with a line break after it returns nothing at all+ `const report = ${source}\n; return report;`+ )(+ { hostname },+ FakeDataTransfer,+ gecko ? GeckoClipboardEvent : FakeClipboardEvent,+ FakeDragEvent,+ FakeFile+ ).then((report) => ({+ ...report,+ landed,+ typed,+ pastes,+ attached,+ dropped,+ }));+}++describe('filling a thread', () => {+ it('puts each post into its own box and gives its files to that post\'s input', async () => {+ const report = await run({+ posts: [+ { text: 'Geolocated.', files: [PNG] },+ { text: 'Context.', files: [] },+ ],+ // the second box appears when the add button is pressed; the page here+ // already holds both, which is what the script sees after that click+ html: `${BOX(0)}${FILE_INPUT(0)}${BOX(1)}${FILE_INPUT(1)}<button data-testid="addButton"></button>`,+ });++ expect(report.filled).toBe(2);+ expect(report.error).toBeUndefined();+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'Geolocated.' },+ { box: 'tweetTextarea_1', text: 'Context.' },+ ]);+ // the picture goes to the first post's own input, not to whichever one the+ // page drew first — a thread whose images all land on post 1 is worse than none+ expect(report.attached).toEqual([+ { input: 'fileInput', files: [expect.objectContaining({ name: 'proof.png' })] },+ ]);+ });++ it('takes the road the site answers to, and does not try the other one', async () => {+ // X's editor rebuilds itself around what `insertText` wrote and hands back+ // the post several times over. The loop below catches that and clears it, so+ // the thread came out right — but the analyst is watching the composer, and+ // what they saw was a post written six times and wiped. It is pasted into.+ const report = await run({+ posts: [{ text: 'Geolocated.', files: [] }],+ html: BOX(0),+ });++ expect(report.filled).toBe(1);+ expect(report.pastes).toEqual([{ box: 'tweetTextarea_0', text: 'Geolocated.', files: [] }]);+ expect(report.typed).toEqual([]); // nothing to clear, nothing to watch+ });++ it('falls back to a paste where the browser will not type for it', async () => {+ const report = await run({+ hostname: 'bsky.app', // this one is typed into first; the paste is behind it+ canType: false,+ posts: [{ text: 'Geolocated.', files: [] }],+ html: '<div role="dialog"><div class="ProseMirror" contenteditable="true"></div></div>',+ });++ expect(report.filled).toBe(1);+ expect(report.pastes).toEqual([{ box: 'ProseMirror', text: 'Geolocated.', files: [] }]);+ });++ it('says which post the composer refused instead of leaving it blank in silence', async () => {+ const report = await run({+ canType: false, // and a composer that takes neither road: nothing lands+ takesPaste: false,+ posts: [{ text: 'One.', files: [] }],+ html: BOX(0),+ });++ expect(report).toMatchObject({ filled: 0, error: 'Post 1 stayed empty.' });+ });++ it('is pasted into on the engine that spells a clipboard the other way', async () => {+ // What took X's thread apart on Firefox. The event was built the one way+ // Chromium reads, so Gecko's composer took an empty clipboard, the post went+ // in by keystroke instead, and **X never registered it**: the text sat in the+ // box, the site went on calling the post empty, and the "+" it draws over a+ // written post was not there. The thread stopped at the post after it, on a+ // composer that looked filled. It is spelled both ways now; this is the+ // other engine reading its own.+ const report = await run({+ gecko: true,+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `<div role="dialog">${BOX(0)}${BOX(1)}<button data-testid="addButton"></button></div>`,+ });++ expect(report.filled).toBe(2);+ expect(report.error).toBeUndefined();+ expect(report.pastes).toEqual([+ { box: 'tweetTextarea_0', text: 'One.', files: [] },+ { box: 'tweetTextarea_1', text: 'Two.', files: [] },+ ]);+ expect(report.typed).toEqual([]); // the site's own road, on both engines+ });++ it('carries what went wrong into the stop, rather than reporting the stop alone', async () => {+ // The two belong together: an empty post is *why* the composer would not+ // open the next one, and the stop on its own reads like the markup moved.+ const report = await run({+ canType: false,+ takesPaste: false,+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: BOX(0),+ });++ expect(report).toMatchObject({+ filled: 0,+ error: 'Post 1 stayed empty. Could not add the next post to the thread.',+ });+ }, 15000); // three attempts at the post, then the wait the add button is owed++ it('falls back to a paste where the composer keeps no file input', async () => {+ const report = await run({+ posts: [{ text: '', files: [PNG] }],+ html: BOX(0),+ });++ expect(report.filled).toBe(1);+ expect(report.pastes).toEqual([+ { box: 'tweetTextarea_0', text: null, files: [expect.objectContaining({ name: 'proof.png' })] },+ ]);+ });++ it('drops that file on the page instead, where a paste cannot carry one', async () => {+ const report = await run({+ gecko: true,+ posts: [{ text: '', files: [PNG] }],+ html: BOX(0),+ });++ expect(report.filled).toBe(1);+ expect(report.pastes).toEqual([]);+ expect(report.dropped.flat()).toEqual([expect.objectContaining({ name: 'proof.png' })]);+ });++ it('leaves a box that already holds something, whatever it holds', async () => {+ // The first post arrives with its text in the URL and the composer's copy is+ // never character for character what was sent, so comparing the two typed the+ // whole post in again, halfway through the text already there.+ const page = document.createElement('div');+ page.innerHTML = BOX(0);+ page.firstChild.textContent = '\u2066Geolocated.\u2069'; // bidi-isolated, as X keeps it+ const report = await run({+ posts: [{ text: 'Geolocated.', files: [] }],+ html: page.innerHTML,+ });++ expect(report.filled).toBe(1);+ expect(report.landed).toEqual([]); // nothing written twice+ expect(report.pastes).toEqual([]);+ });++ it('stops at the post it could not open, and says so', async () => {+ // no add button: half a thread filled beats none, and the rest is one paste+ // away because the app copied it before opening anything+ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: BOX(0),+ });++ expect(report.filled).toBe(1);+ expect(report.error).toMatch(/add the next post/);+ });++ it('reports a site it does not know rather than guessing at its markup', async () => {+ const report = await run({ hostname: 'threads.net', posts: [{ text: 'x' }], html: BOX(0) });++ expect(report).toMatchObject({ filled: 0, error: expect.stringContaining('does not know') });+ });++ it('writes past the placeholder X hangs on an empty post', async () => {+ // The placeholder carries the same test id with `_label` on the end, so it+ // matched the editor selector and, holding the words *What is happening?!*,+ // read as a post already written. Post 2 was skipped in silence. A composer+ // box is contenteditable; a placeholder never is.+ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `${BOX(0)}${PLACEHOLDER(1)}${BOX(1)}<button data-testid="addButton"></button>`,+ });++ expect(report.filled).toBe(2);+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_1', text: 'Two.' },+ ]);+ });++ it('fills the composer on screen, not the one the timeline keeps behind it', async () => {+ // Opening the composer by URL draws it over the timeline, which has a box of+ // its own — and that one comes first in the document.+ const report = await run({+ posts: [{ text: 'One.', files: [] }],+ html: `<div id="timeline">${BOX(0)}</div><div role="dialog">${BOX(9)}</div>`,+ });++ expect(report.filled).toBe(1);+ expect(report.landed).toEqual([{ box: 'tweetTextarea_9', text: 'One.' }]);+ });++ it('does not call an emptied input a refusal, nor stop the thread over one', async () => {+ // A composer empties its file input as soon as it has read it, so that+ // picking the same picture twice still fires a change. Reading it back after+ // that found nothing and reported "Post 1 would not take its files" about+ // the attachment sitting in the composer — and, being fatal, cost post 2.+ const report = await run({+ posts: [{ text: 'One.', files: [PNG] }, { text: 'Two.', files: [] }],+ html: `${BOX(0)}${FILE_INPUT(0)}${BOX(1)}<button data-testid="addButton"></button>`,+ onAttach: (input) => { input.files = []; }, // the site reads and clears+ });++ expect(report.filled).toBe(2);+ expect(report.error).toBeUndefined();+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_1', text: 'Two.' },+ ]);+ });++ it('does not write a post twice when the editor cancels the command it obeyed', async () => {+ // `insertText` reports refused whenever the editor handled the keystroke+ // itself and cancelled the browser's default — with the text already in.+ // Falling back on that verdict put post 2 in a second time. The paste road is+ // closed here, which is what puts this run on the typing one.+ const report = await run({+ takesPaste: false,+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `${BOX(0)}${BOX(1)}<button data-testid="addButton"></button>`,+ });++ expect(report.typed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_1', text: 'Two.' },+ ]);+ expect(document.querySelector('[data-testid="tweetTextarea_1"]').textContent).toBe('Two.');+ });++ it('empties the box and tries again when the post goes in more than once', async () => {+ // An editor that rebuilds its own DOM around what the browser wrote comes+ // back holding the post several times over — post 2 on X came out six deep.+ // "Not empty" is not the same question as "filled", so what the box holds is+ // counted, and the next attempt starts from empty rather than adding to it.+ let echoed = 0;+ const echo = (box, text) => {+ if (box.dataset.testid === 'tweetTextarea_1' && echoed++ === 0) box.textContent += text;+ };+ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `${BOX(0)}${BOX(1)}<button data-testid="addButton"></button>`,+ onType: echo,+ onPaste: (box, e) => echo(box, e.clipboardData.text),+ });++ expect(report.filled).toBe(2);+ expect(report.error).toBeUndefined();+ expect(document.querySelector('[data-testid="tweetTextarea_1"]').textContent).toBe('Two.');+ });++ it('leaves the box empty rather than a post that says everything six times', async () => {+ // Nothing left in a composer beats a mangled thread: the analyst pastes it+ // in, which is what they did before any of this existed.+ const report = await run({+ posts: [{ text: 'One.', files: [] }],+ html: BOX(0),+ // an editor that echoes everything it is given, by either road+ onType: (box, text) => { box.textContent += text; },+ onPaste: (box, e) => { box.textContent += e.clipboardData.text; },+ });++ expect(report).toMatchObject({ filled: 0, error: 'Post 1 went in more than once.' });+ expect(document.querySelector('[data-testid="tweetTextarea_0"]').textContent).toBe('');+ });++ it('presses the composer\'s add button, not the one the timeline keeps', async () => {+ const pressed = [];+ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `<div id="timeline">${BOX(7)}<button data-testid="addButton" data-where="timeline"></button></div>`+ + `<div role="dialog">${BOX(0)}${BOX(1)}<button data-testid="addButton" data-where="dialog"></button></div>`,+ onReady: (doc) => {+ for (const add of doc.querySelectorAll('[data-testid="addButton"]')) {+ add.addEventListener('click', () => pressed.push(add.dataset.where));+ }+ },+ });++ expect(pressed).toEqual(['dialog']);+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_1', text: 'Two.' },+ ]);+ });++ it('waits out a "+" the composer holds back while it reads an attachment', async () => {+ // X takes the button away, or refuses it, until it has finished reading what+ // was just handed over — and a video is read for far longer than a picture.+ // Read the moment it was wanted, it was not there yet, and a thread carrying+ // a clip stopped at the post after it.+ let pressed = 0;+ const report = await run({+ posts: [{ text: 'One.', files: [PNG] }, { text: 'Two.', files: [] }],+ html: `<div role="dialog">${BOX(0)}${FILE_INPUT(0)}`+ + '<button data-testid="addButton" aria-disabled="true"></button></div>',+ onAttach: (input) => {+ const add = input.parentElement.querySelector('[data-testid="addButton"]');+ setTimeout(() => add.removeAttribute('aria-disabled'), 1500);+ },+ onReady: (doc) => {+ const add = doc.querySelector('[data-testid="addButton"]');+ add.addEventListener('click', () => {+ pressed += 1;+ if (add.getAttribute('aria-disabled') === 'true') return;+ const box = doc.createElement('div');+ box.dataset.testid = 'tweetTextarea_1';+ box.setAttribute('contenteditable', 'true');+ add.before(box);+ });+ },+ });++ expect(pressed).toBe(1); // the one it was refusing was never pressed+ expect(report.filled).toBe(2);+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_1', text: 'Two.' },+ ]);+ });++ it('presses a button that listens for the pointer rather than the click', async () => {+ // Bluesky's "+" is a React Native for Web pressable: it hangs its press on+ // the pointer sequence, and it is not a `button` element either. A lone+ // `click()` on a selector asking for the tag pressed nothing at all, so the+ // thread stopped at post 1 while the run reported it filled.+ let pressed = 0;+ const report = await run({+ hostname: 'bsky.app',+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: '<div role="dialog"><div class="ProseMirror" contenteditable="true"></div>'+ + '<div role="button" aria-label="Add another post to thread"></div></div>',+ onReady: (doc) => {+ const add = doc.querySelector('[role="button"]');+ add.addEventListener('pointerup', () => {+ pressed += 1;+ const box = doc.createElement('div');+ box.className = 'ProseMirror';+ box.setAttribute('contenteditable', 'true');+ add.after(box);+ }, { once: true });+ },+ });++ expect(pressed).toBe(1);+ expect(report.filled).toBe(2);+ expect([...document.querySelectorAll('.ProseMirror')].map((box) => box.textContent))+ .toEqual(['One.', 'Two.']);+ });++ it('opens a new box for the post after one that carries only a picture', async () => {+ // Two real things at once: a post with a picture and no text leaves its box+ // empty, and a composer that re-renders hands back a different element for+ // the same post — so the box just filled is not even in the document any+ // more. "The first empty box" then meant the picture's, and post 3's text+ // landed on post 2. The box the add button opened is the one at the end.+ let opened = 1;+ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: '', files: [PNG] }, { text: 'Three.', files: [] }],+ html: `<div role="dialog">${BOX(0)}${FILE_INPUT(0)}<button data-testid="addButton"></button></div>`,+ onReady: (doc) => {+ const add = doc.querySelector('[data-testid="addButton"]');+ add.addEventListener('click', () => {+ for (const box of doc.querySelectorAll('[contenteditable="true"]')) {+ box.replaceWith(box.cloneNode(true)); // the composer redraws what it holds+ }+ const box = doc.createElement('div');+ box.dataset.testid = `tweetTextarea_${opened++}`;+ box.setAttribute('contenteditable', 'true');+ add.before(box);+ });+ },+ });++ expect(report.filled).toBe(3);+ expect(report.landed).toEqual([+ { box: 'tweetTextarea_0', text: 'One.' },+ { box: 'tweetTextarea_2', text: 'Three.' },+ ]);+ expect([...document.querySelectorAll('[contenteditable="true"]')].map((box) => box.textContent))+ .toEqual(['One.', '', 'Three.']);+ });++ it('finds the "+" by its glyph, where the site translated the label', async () => {+ // Bluesky translates it: in French the label reads *Ajouter un autre post au+ // fil de discussion*, which holds none of the words the selector was asking+ // for — so the thread stopped at post 1 in every language but English.+ // Loosening the label is not the answer either: *Ajouter un média au post*+ // sits one seat along in the same footer, and it opens a file picker.+ const plus = '<svg viewBox="0 0 24 24"><path d="M12 3a1 1 0 0 1 1 1v7h7a1 1 0 1 1 0 2h-7v7a1 1 0'+ + ' 1 1-2 0v-7H4a1 1 0 1 1 0-2h7V4a1 1 0 0 1 1-1Z"></path></svg>';+ const pressed = [];+ const report = await run({+ hostname: 'bsky.app',+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: '<div role="dialog"><div class="ProseMirror" contenteditable="true"></div>'+ + '<div role="button" aria-label="Ajouter un média au post">'+ + '<svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z"></path></svg></div>'+ + `<div role="button" aria-label="Ajouter un autre post au fil de discussion">${plus}</div></div>`,+ onReady: (doc) => {+ for (const button of doc.querySelectorAll('[role="button"]')) {+ button.addEventListener('pointerup', () => {+ pressed.push(button.getAttribute('aria-label'));+ if (!button.querySelector('path[d^="M12 3"]')) return; // the picker opens nothing here+ const box = doc.createElement('div');+ box.className = 'ProseMirror';+ box.setAttribute('contenteditable', 'true');+ button.after(box);+ }, { once: true });+ }+ },+ });++ expect(pressed).toEqual(['Ajouter un autre post au fil de discussion']);+ expect(report.filled).toBe(2);+ expect([...document.querySelectorAll('.ProseMirror')].map((box) => box.textContent))+ .toEqual(['One.', 'Two.']);+ });++ it('adds under the last post, where a composer draws a button beneath each one', async () => {+ // Bluesky draws a footer under every post, so it draws an add button under+ // every post: only the one at the end appends, and the others open a post in+ // the middle of the thread that the run then never writes into.+ const pressed = [];+ const report = await run({+ hostname: 'bsky.app',+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: '<div role="dialog"><div class="ProseMirror" contenteditable="true">One.</div>'+ + '<div role="button" aria-label="Add another post to thread" data-under="1"></div>'+ + '<div role="button" aria-label="Add another post to thread" data-under="2"></div></div>',+ onReady: (doc) => {+ for (const add of doc.querySelectorAll('[role="button"]')) {+ add.addEventListener('pointerup', () => {+ pressed.push(add.dataset.under);+ const box = doc.createElement('div');+ box.className = 'ProseMirror';+ box.setAttribute('contenteditable', 'true');+ add.after(box);+ }, { once: true });+ }+ },+ });++ expect(pressed).toEqual(['2']);+ expect(report.filled).toBe(2);+ expect([...document.querySelectorAll('.ProseMirror')].map((box) => box.textContent))+ .toEqual(['One.', 'Two.']);+ });++ it('drops a picture on the body for a composer that keeps no file input', async () => {+ // Bluesky picks files through an input it makes, clicks and throws away, so+ // there is nothing to hand one to. What it does keep is a `drop` listener on+ // the body, feeding the same reader as its paste.+ const report = await run({+ hostname: 'bsky.app',+ posts: [{ text: 'Geolocated.', files: [PNG] }],+ html: '<div role="dialog"><div class="ProseMirror" contenteditable="true"></div></div>',+ });++ expect(report.filled).toBe(1);+ expect(report.typed).toEqual([{ box: 'ProseMirror', text: 'Geolocated.' }]);+ expect(report.dropped).toEqual([[expect.objectContaining({ name: 'proof.png' })]]);+ expect(report.pastes).toEqual([]);+ });++ it('builds each file from base64, because a fetch here answers to the site', async () => {+ // It runs in the page's world, so `fetch('data:…')` is a connection the site+ // decides on — and X allows none to `data:`. Every attachment came back+ // "Failed to fetch", which took the whole thread down with it.+ expect(source).not.toMatch(/\bfetch\s*\(/);++ const report = await run({+ posts: [{ text: '', files: [PNG] }],+ html: `${BOX(0)}${FILE_INPUT(0)}`,+ });++ expect(report.attached).toEqual([+ { input: 'fileInput', files: [expect.objectContaining({ name: 'proof.png' })] },+ ]);+ // decoded to bytes, not handed over as the string it travelled as+ expect([...report.attached[0].files[0].parts[0]]).toEqual([0x89, 0x50, 0x4e, 0x47]);+ });++ it('never submits: the only button it presses is the one that threads', async () => {+ // Listener on the body, before the page is drawn, so every button click+ // inside it is counted whatever the script reaches for. (It also clicks the+ // boxes, which is how a composer knows which post is being typed into.)+ const clicked = [];+ document.body.addEventListener('click', (e) => {+ if (e.target.tagName === 'BUTTON') clicked.push(e.target.dataset.testid);+ });++ const report = await run({+ posts: [{ text: 'One.', files: [] }, { text: 'Two.', files: [] }],+ html: `${BOX(0)}${BOX(1)}<button data-testid="addButton"></button><button data-testid="tweetButton"></button>`,+ });++ expect(report.filled).toBe(2);+ expect(clicked).toEqual(['addButton']); // and never tweetButton+ });+});diff --git a/frontend/src/lib/gmaps.js b/frontend/src/lib/gmaps.jsdeleted file mode 100644index 1e053ca..0000000--- a/frontend/src/lib/gmaps.js+++ /dev/null@@ -1,188 +0,0 @@-/**- * Google Maps JavaScript API — loader + GoogleMutant layer factory.- *- * The EEA-viable Google satellite route (docs/IMAGERY_PROVIDERS.md § Google in- * the EEA): a real google.maps.Map rendered by the official JS API, synced- * under Leaflet by the GoogleMutant plugin so every Leaflet overlay (measure- * tools, markers, reference windows, labels) keeps working on top.- *- * Local-first: nothing here runs until the user actually selects the widget- * basemap — the script load *is* the user action needing the network.- *- * Billing: one "dynamic map load" per google.maps.Map instantiation; pan/zoom- * afterwards is free. The mutant layer must therefore be created once and- * reused across basemap switches — see the layer cache in Satellite.svelte.- */-// Import the plugin's ESM source and use its exported class directly. Both of-// its other integration surfaces are broken under a bundler (verified 2026-07):-// the bare specifier resolves to the "browser" IIFE build, which reads `this.L`-// and crashes the whole app at load (`this` is undefined in strict ESM), and-// the .mjs's own `L.gridLayer.googleMutant` factory binds to a global `L` it-// never imports, so `new L.GridLayer.GoogleMutant` is "not a constructor".-import GoogleMutant from 'leaflet.gridlayer.googlemutant/src/Leaflet.GoogleMutant.mjs';--/**- * GoogleMutant, but able to survive a rotated map.- *- * The mutant works by running a hidden google.maps.Map and cloning its <img>- * tile nodes into a plain Leaflet GridLayer — so the visible tiles rotate with- * the tile pane like any other layer. What breaks is coverage: the hidden map- * is sized to the Leaflet container, so Google only ever renders the tiles of- * an unrotated viewport, while leaflet-rotate asks the grid for the rotated- * bounding box. The corner tiles are never cloned and the view has holes.- *- * Sizing the hidden map to a square of the container's diagonal, centred on it,- * covers every bearing at once — a rotated W×H rect always fits inside the- * circle of its own diagonal — so no rotation handler is needed here. It costs- * extra tile renders inside the hidden map, but not extra billing: the dynamic- * map load is charged per google.maps.Map, and panning/rendering after it is- * free.- */-class RotatableGoogleMutant extends GoogleMutant {- _initMutantContainer() {- super._initMutantContainer();- this._fitMutantToDiagonal();- this._map.on('resize', this._fitMutantToDiagonal, this);- }-- onRemove(map) {- map.off('resize', this._fitMutantToDiagonal, this);- return super.onRemove(map);- }-- _fitMutantToDiagonal() {- if (!this._map || !this._mutantContainer) return;- const size = this._map.getSize();- const side = Math.ceil(Math.sqrt(size.x * size.x + size.y * size.y));- const style = this._mutantContainer.style;- style.width = `${side}px`;- style.height = `${side}px`;- // the container is .leaflet-top.leaflet-left (pinned at 0,0) — pull it back- // by half the overflow so the hidden map stays concentric with Leaflet's,- // which is what makes the coverage symmetric on all four sides- style.marginLeft = `${Math.round((size.x - side) / 2)}px`;- style.marginTop = `${Math.round((size.y - side) / 2)}px`;- if (this._mutant) window.google?.maps?.event?.trigger(this._mutant, 'resize');- }-}--let loadPromise = null;-let loadedKey = null; // the key the script was loaded with — one per page life--/** The API key the Maps JS script is already bound to, if loaded. Google's- * script can't be re-loaded with another key without a full page reload, so- * a key change after load can only be tested by reloading the app. */-export function googleMapsLoadedKey() {- return loadedKey;-}--/**- * Load the Maps JS API from the provider's loader URL (key included — a JS- * API key is client-side by design, referrer-restricted rather than secret).- *- * `onAuthFailure` fires if Google rejects the key — that can happen minutes- * after a successful load (gm_authFailure is async), so the caller must- * handle it as a runtime event, not a load error.- */-export function loadGoogleMaps(loaderUrl, { onAuthFailure } = {}) {- // gm_authFailure is Google's only key-rejection signal; keep it wired even- // when the script is already loaded (a Settings re-test swaps the handler)- window.gm_authFailure = () => onAuthFailure?.();- if (window.google?.maps) return Promise.resolve();- if (loadPromise) return loadPromise;- loadedKey = keyFromLoaderUrl(loaderUrl);- loadPromise = new Promise((resolve, reject) => {- const cb = '__azimutGmapsReady';- window[cb] = () => {- delete window[cb];- resolve();- };- const script = document.createElement('script');- script.src = `${loaderUrl}&loading=async&callback=${cb}`;- script.async = true;- script.onerror = () => {- loadPromise = null; // a network failure may be transient — allow retry- delete window[cb];- reject(new Error('could not load the Google Maps script'));- };- document.head.appendChild(script);- });- return loadPromise;-}--/**- * Prove a Maps JS key in the only place it can be proven: a real map in this- * browser. Loads the script, spins up a hidden 1-tile satellite map and races- * `tilesloaded` (key works) against `gm_authFailure` (Google rejected it) and- * a timeout. Because Google's script binds to one key per page life, a- * *changed* key can only be re-probed after a reload — callers should check- * googleMapsLoadedKey() first.- *- * The verdict carries `billed`: the probe's own map is a real dynamic map load- * on the user's bill, and no backend proxy can see it, so the caller must- * report it to the usage counter or the counter drifts under Google's number.- */-export async function probeKey(loaderUrl, { timeoutMs = 12000 } = {}) {- let rejected = false;- try {- await loadGoogleMaps(loaderUrl, { onAuthFailure: () => (rejected = true) });- } catch (e) {- // the script never loaded, so no map was ever constructed — nothing billed- return { ok: false, detail: e.message, billed: false };- }- const holder = document.createElement('div');- // Must stay INSIDE the viewport: Chrome culls rendering for off-screen- // fixed elements, so an off-screen map never fires `tilesloaded` and the- // probe times out on a perfectly good key (verified headless, 2026-07).- // Near-zero opacity keeps it invisible without suppressing rendering.- holder.style.cssText =- 'position:fixed;left:0;bottom:0;width:128px;height:128px;opacity:0.01;pointer-events:none';- document.body.appendChild(holder);- try {- const verdict = await new Promise((resolve) => {- const timer = setTimeout(- () => resolve({ ok: false, detail: 'no response from Google (timeout)' }),- timeoutMs- );- window.gm_authFailure = () => {- rejected = true;- clearTimeout(timer);- resolve({ ok: false, detail: 'Google rejected the key (gm_authFailure)' });- };- const map = new window.google.maps.Map(holder, {- center: { lat: 0, lng: 0 },- zoom: 1,- mapTypeId: 'satellite',- disableDefaultUI: true,- });- map.addListener('tilesloaded', () => {- clearTimeout(timer);- resolve(- rejected- ? { ok: false, detail: 'Google rejected the key (gm_authFailure)' }- : { ok: true, detail: 'satellite map rendered' }- );- });- });- // A google.maps.Map was constructed above, and Google bills one dynamic map- // load for every one it accepts — this throwaway included. Only a key it- // rejected is free: there is no valid project to bill it to. A timeout still- // counts, since the map was built and we cannot prove it was not served.- return { ...verdict, billed: !rejected };- } finally {- holder.remove();- }-}--function keyFromLoaderUrl(url) {- try {- return new URL(url).searchParams.get('key');- } catch {- return null;- }-}--/** A GoogleMutant satellite layer — one billed map load per creation. */-export function createSatelliteMutant(maxZoom = 21, attribution = 'Map data © Google') {- return new RotatableGoogleMutant({ type: 'satellite', maxZoom, attribution });-}diff --git a/frontend/src/lib/gmaps.test.js b/frontend/src/lib/gmaps.test.jsdeleted file mode 100644index a491552..0000000--- a/frontend/src/lib/gmaps.test.js+++ /dev/null@@ -1,103 +0,0 @@-// @vitest-environment happy-dom-import { describe, it, expect, afterEach } from 'vitest';--/**- * Stand in for the Maps JS API: a google.maps.Map that either renders- * (`tilesloaded`) or gets rejected (`gm_authFailure`), on the next microtask so- * probeKey has installed its handlers first.- */-function stubGoogleMaps({ reject = false } = {}) {- window.google = {- maps: {- Map: class {- constructor() {- this._listeners = {};- queueMicrotask(() => {- if (reject) window.gm_authFailure?.();- else this._listeners.tilesloaded?.();- });- }- addListener(event, cb) {- this._listeners[event] = cb;- }- },- },- };-}--describe('gmaps module', () => {- it('imports cleanly and constructs a real GridLayer mutant', async () => {- // Regression guards for the plugin's two broken integration surfaces- // (each one shipped a real bug): the "browser" IIFE entry crashes the- // whole bundle at load (`this.L`, `this` undefined in strict ESM), and- // its `L.gridLayer.googleMutant` factory binds to a global L it never- // imports ("GoogleMutant is not a constructor" at layer creation). We- // construct the exported class directly — this test fails if the import- // path or the constructor ever regresses.- const { createSatelliteMutant, googleMapsLoadedKey } = await import('./gmaps.js');- const L = (await import('leaflet')).default;- const layer = createSatelliteMutant(21, 'Map data © Google');- expect(layer instanceof L.GridLayer).toBe(true);- expect(layer.options.maxZoom).toBe(21);- expect(layer.options.attribution).toBe('Map data © Google');- expect(googleMapsLoadedKey()).toBe(null); // nothing loaded in tests- });-- it('sizes the hidden mutant map to the container diagonal, centred', async () => {- // What makes the Google basemap rotatable. The mutant clones tiles out of a- // hidden google.maps.Map sized to the Leaflet container, so a rotated view- // (leaflet-rotate asks the grid for the rotated bounding box) wants corner- // tiles Google never rendered — blank corners. A square of the diagonal,- // centred, covers every bearing at once. If this regresses, rotation still- // "works" but silently eats the corners of the map.- const { createSatelliteMutant } = await import('./gmaps.js');- const layer = createSatelliteMutant();- const container = document.createElement('div');- layer._mutantContainer = container;- layer._map = { getSize: () => ({ x: 800, y: 600 }) };-- layer._fitMutantToDiagonal();-- const side = Math.ceil(Math.sqrt(800 ** 2 + 600 ** 2)); // 1000- expect(container.style.width).toBe(`${side}px`);- expect(container.style.height).toBe(`${side}px`);- // pulled back by half the overflow, so it stays concentric with the map- expect(container.style.marginLeft).toBe(`${(800 - side) / 2}px`);- expect(container.style.marginTop).toBe(`${(600 - side) / 2}px`);- // the square must cover the container's own diagonal, whatever the bearing- expect(side).toBeGreaterThanOrEqual(Math.hypot(800, 600));- });-- describe('probeKey billing', () => {- afterEach(() => {- delete window.google;- delete window.gm_authFailure;- });-- it('flags the map load it costs when Google accepts the key', async () => {- // The probe builds a real google.maps.Map, which Google bills as a dynamic- // map load. It happens in the browser, so the backend tile proxy cannot- // see it — only this flag makes Settings report it. If it regresses,- // testing a key silently drifts the counter under Google's real number.- const { probeKey } = await import('./gmaps.js');- stubGoogleMaps();-- const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=good');-- expect(verdict.ok).toBe(true);- expect(verdict.billed).toBe(true);- });-- it('bills nothing for a key Google rejects', async () => {- // A rejected key renders no map and has no valid project to bill, so- // counting it would push the counter above Google's real number.- const { probeKey } = await import('./gmaps.js');- stubGoogleMaps({ reject: true });-- const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=bad');-- expect(verdict.ok).toBe(false);- expect(verdict.billed).toBe(false);- });- });-});diff --git a/frontend/src/lib/gridSearch.js b/frontend/src/lib/gridSearch.jsindex 3efb0bc..ec8d515 100644--- a/frontend/src/lib/gridSearch.js+++ b/frontend/src/lib/gridSearch.js@@ -1,6 +1,6 @@// Pure geometry + coverage bookkeeping for the Satellite Grid Search mode. A// grid overlays an area of interest with metric cells you sweep one by one,-// marking each cleared or flagged. Kept free of Leaflet so it can be+// marking each cleared or flagged. Kept free of the map so it can be// unit-tested; the component only handles drawing, flying and persistence.//// The grid is a fixed metric lattice: cells are addressed by integer (i, j)diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.jsnew file mode 100644index 0000000..609019c--- /dev/null+++ b/frontend/src/lib/map/basemap.js@@ -0,0 +1,278 @@+/**+ * What the map is made of: the imagery layer, the labels over it, and the one+ * basemap that is a live Google widget rather than a grid of our tiles.+ *+ * Everything here is engine work, which is why it sits inside `lib/map` and why+ * the tool above it only ever says *which* provider to show. The rules are the+ * expensive part and they are not obvious from the code they produce: which+ * providers go through our proxy, where a provider's pixels stop short of its+ * useful view, when a bigger tile is worth asking for, and which layer must+ * never be rebuilt because rebuilding it is billed. `tileTemplate`, `tileUrls`,+ * `sourceMaxZoom` and `rasterSource` are pure so those rules are read off tests+ * rather than off a running map (`basemap.test.js`).+ *+ * Two things the old engine needed here are gone with it, and both are worth+ * naming so nobody looks for them: a DOM grid of tiles had faint white seams at+ * fractional display scaling, which one canvas cannot have, and it refetched+ * throwaway intermediate zoom levels mid-gesture, which a billed provider paid+ * for. MapLibre overzooms what it already holds instead.+ */+import { createGoogleGlass, loadGoogleMaps } from './gmaps.js';++// A labels-only layer laid over the imagery: roads and place names readable+// without hiding the satellite view. Over a street basemap it would only+// double its own labels, which is why the tool keeps it to imagery.+const LABELS_URL =+ 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png';+const LABELS_ATTRIBUTION = '© OpenStreetMap contributors © CARTO';+const LABELS_MAX_ZOOM = 20;++/** What a `{s}` template is served from when the provider names no hosts. */+const DEFAULT_SUBDOMAINS = ['a', 'b', 'c'];+const LABELS_SUBDOMAINS = ['a', 'b', 'c', 'd'];++const IMAGERY = 'basemap-imagery';+const LABELS = 'basemap-labels';+/** Ours, so the first layer that is not is where the basemap stops. */+const OWNED = new Set([IMAGERY, LABELS]);++/**+ * Where a provider's tiles are fetched from.+ *+ * Every provider goes through the backend tile proxy: keys and session tokens+ * stay server-side, every billed tile is counted exactly once (browser cache+ * hits never reach the proxy), cacheable providers share the disk tile cache,+ * and coverage gaps come back overzoomed instead of as "not yet available"+ * placards. Only `{s}` subdomain templates (custom providers) stay direct —+ * the proxy cannot expand those.+ */+export function tileTemplate(provider, providerId) {+ return provider.url.includes('{s}') ? provider.url : `/api/tiles/${providerId}/{z}/{x}/{y}`;+}++/**+ * One template → the URLs the engine rotates between.+ *+ * MapLibre takes a list of hosts rather than a `{s}` pattern, so the pattern is+ * expanded here. The proxy's own template has no `{s}` and comes back as itself.+ */+export function tileUrls(template, subdomains) {+ if (!template.includes('{s}')) return [template];+ const hosts = subdomains?.length ? subdomains : DEFAULT_SUBDOMAINS;+ return hosts.map((host) => template.replace('{s}', host));+}++/**+ * The deepest tile this provider is ever asked for, counted the way the engine+ * counts tiles.+ *+ * Where a provider's pixels stop short of its useful view (Sentinel-2: native+ * z14, view z18), the engine keeps requesting the last level it has and scales+ * those tiles up. The extra zoom therefore costs nothing — asking Sentinel Hub+ * for z18 would buy its upsampling of the same pixels, 16× the tiles, every one+ * billed. A cell wider than 256 px shifts the whole grid down a level per+ * doubling, exactly as the URL zoom shifts.+ */+export function sourceMaxZoom(provider, cell) {+ const deepest = provider.max_native_zoom ?? provider.max_zoom;+ return deepest - Math.log2(cell / 256);+}++/**+ * The raster source one provider is served from, at a given cell size.+ *+ * @param {object} provider as `/api/satellite/providers` describes it+ * @param {string} providerId what the tiles are asked for — Sentinel-2 carries+ * its layer, window and cloud ceiling in it (lib/sentinel.js)+ * @param {number} cell grid cell in CSS px (lib/usage.js `layerCell`)+ */+export function rasterSource(provider, providerId, cell) {+ return {+ type: 'raster',+ tiles: tileUrls(tileTemplate(provider, providerId), provider.subdomains),+ // Bigger tiles shift the URL zoom down (512 → -1, 1024 → -2); an oversample+ // halves the cell so each tile is shown downscaled — deeper zoom on screen.+ // Google's mid-zoom mosaics are genuinely softer than its deep ones+ // (verified), so this is what makes the paid imagery actually look paid.+ tileSize: cell,+ minzoom: 0,+ maxzoom: sourceMaxZoom(provider, cell),+ attribution: provider.attribution,+ };+}++/**+ * Own the layers of one map.+ *+ * The callbacks are the app's business, not the map's: what a billed layer does+ * to the usage pill, what a rejected key does to Settings and to the selector.+ *+ * @param {object} engine the façade from `engine.js`+ * @param {object} [hooks]+ * @param {(provider: object) => void} [hooks.onMeteredTiles] a billed layer painted+ * @param {(provider: object) => void} [hooks.onWidgetLoad] a billed map load happened+ * @param {(provider: object) => void} [hooks.onWidgetAuthFailure] Google rejected the key+ * @param {(provider: object, error: Error) => void} [hooks.onWidgetFailed] the script never loaded+ */+export function createBasemaps(engine, hooks = {}) {+ const {+ onMeteredTiles = () => {},+ onWidgetLoad = () => {},+ onWidgetAuthFailure = () => {},+ onWidgetFailed = () => {},+ } = hooks;++ const map = engine.impl;+ let live = null; // `${providerId}@${cell}` currently on the map, tiles only+ // The Google widget is created ONCE and reused across basemap switches:+ // every google.maps.Map instantiation is a billed dynamic map load, while+ // hiding and showing the one we have costs nothing. Never destroyed until+ // the map goes, for the same reason.+ let glass = null;+ let labels = false;+ let wanted = null; // the provider id last asked for, so a slow load can tell+ let metered = null; // the billed provider whose tiles we are counting++ // Drawn shapes are appended by `surface.js`, so the first layer this module+ // does not own is where the basemap stops and the overlays begin.+ function ceiling() {+ return map.getLayersOrder().find((id) => !OWNED.has(id));+ }++ function onSourceData(event) {+ if (!metered || event.sourceId !== IMAGERY || !event.isSourceLoaded) return;+ // every visible tile is in, so what the proxy counted is now final+ onMeteredTiles(metered);+ }+ map.on('sourcedata', onSourceData);++ function dropTiles() {+ if (map.getLayer(IMAGERY)) map.removeLayer(IMAGERY);+ if (map.getSource(IMAGERY)) map.removeSource(IMAGERY);+ live = null;+ metered = null;+ }++ /**+ * Past its own ceiling the provider has no pixels, and the view has to stop+ * where capture sizing expects it to: `scaledCapture` reads the view zoom+ * against the provider maximum. The engine pulls the camera back itself when+ * the ceiling drops under it, which is what switching to a shallower provider+ * while zoomed deep needs.+ */+ function capZoom(provider) {+ map.setMaxZoom(provider.max_zoom - 1);+ }++ function showTiles(provider, providerId, cell) {+ dropTiles();+ capZoom(provider);+ map.addSource(IMAGERY, rasterSource(provider, providerId, cell));+ map.addLayer(+ { id: IMAGERY, type: 'raster', source: IMAGERY },+ map.getLayer(LABELS) ? LABELS : ceiling()+ );+ live = `${providerId}@${cell}`;+ if (provider.meter) {+ metered = provider;+ onMeteredTiles(provider);+ }+ }++ async function showWidget(provider) {+ try {+ await loadGoogleMaps(provider.url, {+ // Google's only key-rejection signal — it can fire minutes after a+ // clean load, so the caller handles it as a runtime event.+ onAuthFailure: () => onWidgetAuthFailure(provider),+ });+ } catch (error) {+ onWidgetFailed(provider, error);+ return;+ }+ if (wanted !== provider.id) return; // user moved on while loading+ dropTiles();+ capZoom(provider);+ if (!glass) {+ glass = createGoogleGlass(engine, {+ maxZoom: provider.max_zoom,+ attribution: provider.attribution,+ });+ onWidgetLoad(provider); // billed where it happens; the proxy cannot see it+ }+ glass.show();+ }++ function addLabels() {+ if (map.getLayer(LABELS)) return;+ map.addSource(LABELS, {+ type: 'raster',+ tiles: tileUrls(LABELS_URL, LABELS_SUBDOMAINS),+ tileSize: 256,+ minzoom: 0,+ maxzoom: LABELS_MAX_ZOOM,+ attribution: LABELS_ATTRIBUTION,+ });+ map.addLayer(+ {+ id: LABELS,+ type: 'raster',+ source: LABELS,+ // Past its own last level the overlay stops rather than being blown up:+ // a road name upscaled four times over a rooftop is a smear, and this+ // is what the map before it did. The two ceilings are the same number+ // and different questions — the source's is the deepest tile, the+ // layer's is the deepest view, which the engine counts one shallower.+ maxzoom: LABELS_MAX_ZOOM,+ },+ // above the imagery, below anything a tool draws+ ceiling()+ );+ }++ function dropLabels() {+ if (map.getLayer(LABELS)) map.removeLayer(LABELS);+ if (map.getSource(LABELS)) map.removeSource(LABELS);+ }++ return {+ /**+ * Show one provider. `providerId` carries Sentinel-2's layer, window and+ * cloud ceiling (lib/sentinel.js), so it is what the tiles are asked for+ * and never the bare provider id.+ */+ show(provider, providerId, cell) {+ wanted = provider?.id ?? null;+ if (!provider) return;+ if (provider.widget) {+ showWidget(provider);+ return;+ }+ glass?.hide();+ // Already the live layer — leave it alone. Returning to this tab refetches+ // the providers, and the fresh objects re-run the layer effect, so this is+ // the common path rather than an edge case; rebuilding it would drop and+ // refetch every visible tile, which reads on screen as a reloading map.+ // The cell is part of the answer: an oversampled provider changes it at+ // one zoom bracket, and that is a different grid of the same tiles.+ if (live === `${providerId}@${cell}`) {+ capZoom(provider);+ return;+ }+ showTiles(provider, providerId, cell);+ },++ setLabels(on) {+ if (on === labels) return;+ labels = on;+ if (on) addLabels();+ else dropLabels();+ },++ dispose() {+ map.off('sourcedata', onSourceData);+ glass?.destroy();+ glass = null;+ },+ };+}diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.jsnew file mode 100644index 0000000..f60eb0a--- /dev/null+++ b/frontend/src/lib/map/basemap.test.js@@ -0,0 +1,386 @@+// @vitest-environment happy-dom+import { describe, expect, it, vi } from 'vitest';+import { rasterSource, sourceMaxZoom, tileTemplate, tileUrls } from './basemap.js';++/**+ * The provider shapes are the ones `/api/satellite/providers` really answers+ * with (api/satellite.py) — trimmed to the fields the layer reads.+ */+const ESRI = {+ id: 'esri-world-imagery',+ url: 'https://services.arcgisonline.com/.../tile/{z}/{y}/{x}',+ attribution: 'Imagery © Esri',+ max_zoom: 19,+ max_native_zoom: null,+ tile_size: 256,+ meter: null,+};+const CUSTOM_XYZ = {+ id: 'custom-1',+ url: 'https://{s}.tiles.example.org/{z}/{x}/{y}.png',+ attribution: 'Someone',+ max_zoom: 18,+ max_native_zoom: null,+ tile_size: 256,+ meter: null,+};+const SENTINEL = {+ id: 'sentinel2',+ url: 'https://sh.dataspace.copernicus.eu/ogc/wmts/{key}?...',+ attribution: '© Copernicus Sentinel data',+ max_zoom: 18,+ max_native_zoom: 14,+ tile_size: 512,+ meter: 'sentinelhub',+};+const GOOGLE_TILES = {+ id: 'google-satellite',+ url: 'https://tile.googleapis.com/v1/2dtiles/{z}/{x}/{y}',+ attribution: 'Map data © Google',+ max_zoom: 22,+ max_native_zoom: null,+ tile_size: 1024,+ meter: 'google',+};+const WIDGET = {+ ...GOOGLE_TILES,+ id: 'google-js',+ widget: 'google-maps-js',+ max_zoom: 21,+ meter: 'google_js',+};++describe('where a provider’s tiles are fetched from', () => {+ it('sends every provider it can through the backend proxy', () => {+ // keys and session tokens stay server-side, and a billed tile is counted+ // exactly once — the proxy is the only place that can do either+ expect(tileTemplate(ESRI, 'esri-world-imagery')).toBe(+ '/api/tiles/esri-world-imagery/{z}/{x}/{y}'+ );+ });++ it('asks for the variant it is showing, not the bare provider', () => {+ // Sentinel-2's layer, window and ceiling ride on the id, so a tile cannot+ // be rendered from one window and filed as another+ expect(tileTemplate(SENTINEL, 'sentinel2~SWIR~2026-05-01~2026-05-01~CC20')).toBe(+ '/api/tiles/sentinel2~SWIR~2026-05-01~2026-05-01~CC20/{z}/{x}/{y}'+ );+ });++ it('leaves a subdomain template direct, because the proxy cannot expand it', () => {+ expect(tileTemplate(CUSTOM_XYZ, 'custom-1')).toBe(CUSTOM_XYZ.url);+ });++ it('expands a subdomain template itself, since the engine takes a list', () => {+ expect(tileUrls(CUSTOM_XYZ.url, undefined)).toEqual([+ 'https://a.tiles.example.org/{z}/{x}/{y}.png',+ 'https://b.tiles.example.org/{z}/{x}/{y}.png',+ 'https://c.tiles.example.org/{z}/{x}/{y}.png',+ ]);+ expect(tileUrls(CUSTOM_XYZ.url, ['x', 'y'])).toEqual([+ 'https://x.tiles.example.org/{z}/{x}/{y}.png',+ 'https://y.tiles.example.org/{z}/{x}/{y}.png',+ ]);+ });++ it('leaves the proxy’s own template as itself', () => {+ expect(tileUrls('/api/tiles/esri/{z}/{x}/{y}')).toEqual(['/api/tiles/esri/{z}/{x}/{y}']);+ });+});++describe('the deepest tile a provider is asked for', () => {+ it('is its own ceiling, on a plain 256 px grid', () => {+ expect(sourceMaxZoom(ESRI, 256)).toBe(19);+ });++ it('stops at the last level with real pixels, not at the last useful view', () => {+ // Sentinel-2 stops at z14 and stays useful to z18; requesting z18 would buy+ // server-side upsampling of the same pixels, 16× the tiles, every one billed+ expect(sourceMaxZoom(SENTINEL, 512)).toBe(13);+ });++ it('shifts down a level for every doubling of the cell', () => {+ // a 512 px cell covers the ground of four 256 px tiles one zoom deeper, so+ // the URL zoom it asks for is one shallower — the same shift the old+ // engine's zoomOffset made+ expect(sourceMaxZoom(GOOGLE_TILES, 512)).toBe(21);+ // and the z17 detail boost, a 256 px cell for a 1024 px tile+ expect(sourceMaxZoom(GOOGLE_TILES, 256)).toBe(22);+ });+});++describe('the source one provider is served from', () => {+ it('is a raster grid of the cell size asked for, credited to the provider', () => {+ expect(rasterSource(ESRI, ESRI.id, 256)).toEqual({+ type: 'raster',+ tiles: ['/api/tiles/esri-world-imagery/{z}/{x}/{y}'],+ tileSize: 256,+ minzoom: 0,+ maxzoom: 19,+ attribution: 'Imagery © Esri',+ });+ });++ it('never asks below zero, whatever the cell does to the numbering', () => {+ // a 512 px cell at world zoom would otherwise want a negative URL z+ expect(rasterSource(SENTINEL, 'sentinel2~a~~~CC100', 512).minzoom).toBe(0);+ });+});++describe('the layers on a map', () => {+ /** A MapLibre map, as far as basemap.js reaches into it. */+ function stubMap() {+ const sources = new Map();+ const layers = [];+ const calls = { setMaxZoom: [], on: [], off: [] };+ return {+ calls,+ sources,+ layers,+ addSource: (id, spec) => sources.set(id, spec),+ removeSource: (id) => sources.delete(id),+ getSource: (id) => sources.get(id),+ addLayer: (layer, beforeId) => {+ const at = beforeId ? layers.findIndex((l) => l.id === beforeId) : -1;+ if (at === -1) layers.push(layer);+ else layers.splice(at, 0, layer);+ },+ removeLayer: (id) => {+ const at = layers.findIndex((l) => l.id === id);+ if (at !== -1) layers.splice(at, 1);+ },+ getLayer: (id) => layers.find((l) => l.id === id),+ getLayersOrder: () => layers.map((l) => l.id),+ setMaxZoom: (...args) => calls.setMaxZoom.push(args),+ on: (...args) => calls.on.push(args),+ off: (...args) => calls.off.push(args),+ };+ }++ /** The façade, as far as basemap.js reaches into it. */+ function stubEngine(map = stubMap()) {+ return { impl: map, container: document.createElement('div') };+ }++ /**+ * The Google widget costs money to build, so `basemap.js` is exercised with+ * `gmaps.js` stubbed: what matters here is how many were ever made.+ */+ async function withStubbedGoogle(run, loader) {+ vi.resetModules();+ const glasses = [];+ vi.doMock('./gmaps.js', () => ({+ loadGoogleMaps: loader ?? vi.fn(async () => {}),+ createGoogleGlass: () => {+ const glass = { shown: 0, hidden: 0, destroyed: 0 };+ glass.show = () => (glass.shown += 1);+ glass.hide = () => (glass.hidden += 1);+ glass.destroy = () => (glass.destroyed += 1);+ glasses.push(glass);+ return glass;+ },+ }));+ const { createBasemaps } = await import('./basemap.js');+ try {+ await run({ createBasemaps, glasses });+ } finally {+ vi.doUnmock('./gmaps.js');+ vi.resetModules();+ }+ }++ it('takes the previous imagery off before putting the next one on', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.show(ESRI, ESRI.id, 256);+ basemaps.show(SENTINEL, 'sentinel2~TRUE_COLOR~~~CC100', 512);+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-imagery']);+ expect(map.sources.get('basemap-imagery').tiles[0]).toContain('sentinel2~TRUE_COLOR');+ });+ });++ it('caps the view at what the provider can serve', async () => {+ // capture sizing reads the view zoom against the provider maximum, and a+ // shallower provider asked past its ceiling answers with a placard+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ createBasemaps(stubEngine(map)).show({ ...ESRI, max_zoom: 17 }, 'opentopomap', 256);+ // the engine counts one level shallower than the app does+ expect(map.calls.setMaxZoom).toEqual([[16]]);+ });+ });++ it('leaves a layer alone when nothing about it changed', async () => {+ // returning to the tab refetches the providers, and the fresh objects re-run+ // the layer effect, so this is the common path rather than an edge case+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.show(ESRI, ESRI.id, 256);+ const first = map.sources.get('basemap-imagery');+ basemaps.show(ESRI, ESRI.id, 256);+ expect(map.sources.get('basemap-imagery')).toBe(first);+ });+ });++ it('rebuilds when the cell changes, because that is a different grid', async () => {+ // Google's oversample halves the cell at one zoom bracket+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.show(GOOGLE_TILES, GOOGLE_TILES.id, 512);+ basemaps.show(GOOGLE_TILES, GOOGLE_TILES.id, 256);+ expect(map.sources.get('basemap-imagery').tileSize).toBe(256);+ });+ });++ it('builds the Google widget once, however often it is shown', async () => {+ // every google.maps.Map instantiation is a billed dynamic map load+ await withStubbedGoogle(async ({ createBasemaps, glasses }) => {+ const onWidgetLoad = vi.fn();+ const basemaps = createBasemaps(stubEngine(), { onWidgetLoad });+ await basemaps.show(WIDGET, WIDGET.id, 256);+ basemaps.show(ESRI, ESRI.id, 256);+ await basemaps.show(WIDGET, WIDGET.id, 256);+ expect(glasses).toHaveLength(1);+ expect(onWidgetLoad).toHaveBeenCalledTimes(1);+ });+ });++ it('hides the widget rather than destroying it when the analyst moves on', async () => {+ await withStubbedGoogle(async ({ createBasemaps, glasses }) => {+ const basemaps = createBasemaps(stubEngine());+ await basemaps.show(WIDGET, WIDGET.id, 256);+ basemaps.show(ESRI, ESRI.id, 256);+ expect(glasses[0].hidden).toBe(1);+ expect(glasses[0].destroyed).toBe(0);+ });+ });++ it('takes the tiles off the map while the widget is showing', async () => {+ // the widget renders under a transparent canvas, so a tile layer left on+ // would sit between the analyst and Google's imagery+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.show(ESRI, ESRI.id, 256);+ await basemaps.show(WIDGET, WIDGET.id, 256);+ expect(map.getLayer('basemap-imagery')).toBeUndefined();+ expect(map.getSource('basemap-imagery')).toBeUndefined();+ });+ });++ it('reports a refused key instead of showing a dead basemap', async () => {+ const onWidgetFailed = vi.fn();+ await withStubbedGoogle(+ async ({ createBasemaps, glasses }) => {+ await createBasemaps(stubEngine(), { onWidgetFailed }).show(WIDGET, WIDGET.id, 256);+ expect(onWidgetFailed).toHaveBeenCalledWith(WIDGET, expect.any(Error));+ expect(glasses).toHaveLength(0); // nothing built, so nothing billed+ },+ vi.fn(async () => {+ throw new Error('could not load the Google Maps script');+ })+ );+ });++ it('drops a widget load the analyst has already moved on from', async () => {+ let release;+ await withStubbedGoogle(+ async ({ createBasemaps, glasses }) => {+ const basemaps = createBasemaps(stubEngine());+ const pending = basemaps.show(WIDGET, WIDGET.id, 256);+ basemaps.show(ESRI, ESRI.id, 256);+ release();+ await pending;+ expect(glasses).toHaveLength(0);+ },+ () => new Promise((resolve) => (release = resolve))+ );+ });++ it('keeps the pill honest for a billed layer, on arrival and once painted', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const onMeteredTiles = vi.fn();+ createBasemaps(stubEngine(map), { onMeteredTiles }).show(+ SENTINEL,+ 'sentinel2~a~~~CC100',+ 512+ );+ expect(onMeteredTiles).toHaveBeenCalledTimes(1);+ const painted = map.calls.on.find(([name]) => name === 'sourcedata')[1];+ painted({ sourceId: 'basemap-imagery', isSourceLoaded: true });+ expect(onMeteredTiles).toHaveBeenCalledTimes(2);+ // a tile still on its way says nothing yet+ painted({ sourceId: 'basemap-imagery', isSourceLoaded: false });+ expect(onMeteredTiles).toHaveBeenCalledTimes(2);+ });+ });++ it('says nothing about usage for a key-less layer', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const onMeteredTiles = vi.fn();+ createBasemaps(stubEngine(map), { onMeteredTiles }).show(ESRI, ESRI.id, 256);+ expect(onMeteredTiles).not.toHaveBeenCalled();+ const painted = map.calls.on.find(([name]) => name === 'sourcedata')[1];+ painted({ sourceId: 'basemap-imagery', isSourceLoaded: true });+ expect(onMeteredTiles).not.toHaveBeenCalled();+ });+ });++ it('stops the labels at their own last level rather than blowing them up', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ createBasemaps(stubEngine(map)).setLabels(true);+ // the deepest tile, and the deepest view, which the engine counts one+ // shallower — the same number, two questions+ expect(map.sources.get('basemap-labels').maxzoom).toBe(20);+ expect(map.getLayer('basemap-labels').maxzoom).toBe(20);+ expect(map.sources.get('basemap-labels').tiles).toHaveLength(4);+ });+ });++ it('adds the labels layer once and takes it off when asked', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.setLabels(true);+ basemaps.setLabels(true);+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-labels']);+ basemaps.setLabels(false);+ expect(map.layers).toEqual([]);+ });+ });++ it('keeps the labels over the imagery and both under what a tool draws', async () => {+ await withStubbedGoogle(async ({ createBasemaps }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ basemaps.show(ESRI, ESRI.id, 256);+ basemaps.setLabels(true);+ // a tool's own layer, appended above both+ map.addLayer({ id: 'sfc-1-fill' });+ // and now a different provider, which must not land on top of either+ basemaps.show(SENTINEL, 'sentinel2~a~~~CC100', 512);+ expect(map.layers.map((l) => l.id)).toEqual([+ 'basemap-imagery',+ 'basemap-labels',+ 'sfc-1-fill',+ ]);+ });+ });++ it('stops listening when the map goes, and lets the widget go with it', async () => {+ await withStubbedGoogle(async ({ createBasemaps, glasses }) => {+ const map = stubMap();+ const basemaps = createBasemaps(stubEngine(map));+ await basemaps.show(WIDGET, WIDGET.id, 256);+ basemaps.dispose();+ expect(map.calls.off).toEqual([['sourcedata', expect.any(Function)]]);+ expect(glasses[0].destroyed).toBe(1);+ });+ });+});diff --git a/frontend/src/lib/map/engine.css b/frontend/src/lib/map/engine.cssnew file mode 100644index 0000000..1456672--- /dev/null+++ b/frontend/src/lib/map/engine.css@@ -0,0 +1,191 @@+/*+ * The engine's own chrome, dressed as one of the app's surfaces.+ *+ * These selectors are the engine's DOM, not ours, which is why they live beside+ * the module that builds it rather than in whichever tool happens to hold a map:+ * a second map surface would otherwise inherit the widget's default white+ * speech-bubble look, and swapping the engine would have to hunt for these rules+ * in a tool's stylesheet.+ *+ * The popup is here for the same reason and one more: MapLibre draws the card's+ * pointer as a border triangle whose colour depends on which of eight sides the+ * card opened towards. That is eight rules of engine trivia, and no tool should+ * have to know it. A tool names its own card class and sets what is genuinely+ * its own — the width it needs — through `--popup-min-width`.+ *+ * Loaded by `engine.js`, so it arrives with the engine and leaves with it.+ */++.maplibregl-map {+ font-family: var(--font-sans);+ background: var(--bg-2);+ /* A stacking context of its own, so the widget basemap's negative layer+ (below) stays inside this element: paints over its background, under its+ canvas. Without it the layer drops behind that background and the basemap+ is simply a black rectangle. */+ isolation: isolate;+}++/* The engine puts its grab cursor on the canvas, which would win over a tool's+ own rule for an armed mode. Hold the cursor on the surface instead, where a+ tool can say `crosshair` and be obeyed. */+.map-surface {+ cursor: grab;+}+.map-surface:active {+ cursor: grabbing;+}+.map-surface .maplibregl-canvas-container.maplibregl-interactive,+.map-surface .maplibregl-canvas-container.maplibregl-interactive:active {+ cursor: inherit;+}++.maplibregl-ctrl.maplibregl-ctrl-attrib {+ background: rgba(24, 24, 24, 0.85);+ color: var(--text-3);+ font-size: 10px;+}+.maplibregl-ctrl-attrib a {+ color: var(--text-2);+}++/* zoom +/- (topleft) sits directly under the tool cluster instead of the+ engine's default corner margin, which used to land it on top of that cluster */+.maplibregl-ctrl-top-left .maplibregl-ctrl {+ margin: 58px 0 8px 12px;+}+.maplibregl-ctrl-group {+ background: var(--bg-2);+ box-shadow: 0 0 0 1px var(--border);+}+.maplibregl-ctrl-group button + button {+ border-top-color: var(--border);+}+.maplibregl-ctrl-group button:hover {+ background: var(--bg-3);+}+/* The engine's +/- glyphs are dark-on-light images, not text, so they are+ turned rather than recoloured — and turned back under the light theme, where+ dark on white is what the button already wants. */+.maplibregl-ctrl-group .maplibregl-ctrl-icon {+ filter: invert(1);+}+:root[data-theme='light'] .maplibregl-ctrl-group .maplibregl-ctrl-icon {+ filter: none;+}++/* Slim ruler-style scale: no boxed panel, just a light bracket + label floating+ directly on the map so it stays readable over any imagery. */+.maplibregl-ctrl-scale {+ border-color: rgba(255, 255, 255, 0.92);+ border-width: 0 1.5px 1.5px;+ background: transparent;+ padding: 0 4px 1px;+ margin: 0 10px 10px 0;+ color: #fff;+ font-size: 10px;+ font-weight: 600;+ line-height: 1.3;+ text-shadow:+ 0 1px 2px rgba(0, 0, 0, 0.85),+ 0 0 4px rgba(0, 0, 0, 0.5);+}++/* The card a mark opens, over imagery: one of the app's surfaces, not the+ engine's white bubble. A tool sets `--popup-min-width` for the width its own+ content needs. */+.maplibregl-popup-content {+ min-width: var(--popup-min-width, 0);+ padding: 12px 14px;+ border: 1px solid var(--border-strong);+ border-radius: var(--r-lg);+ background: var(--bg-1);+ box-shadow: var(--shadow-2);+ color: var(--text-1);+ line-height: 1.4;+}+.maplibregl-popup-close-button {+ padding: 4px 7px 0 0;+ color: var(--text-3);+ font-size: 15px;+}+.maplibregl-popup-close-button:hover {+ background: none;+ color: var(--text-1);+}+/* The pointer is the card's own surface, not its edge: the engine draws it as a+ border triangle, so a border colour is the only thing that reaches it — and+ the edge colour is translucent, which left the pointer all but invisible. */+.maplibregl-popup-anchor-top .maplibregl-popup-tip,+.maplibregl-popup-anchor-top-left .maplibregl-popup-tip,+.maplibregl-popup-anchor-top-right .maplibregl-popup-tip {+ border-bottom-color: var(--bg-1);+}+.maplibregl-popup-anchor-bottom .maplibregl-popup-tip,+.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip,+.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip {+ border-top-color: var(--bg-1);+}+.maplibregl-popup-anchor-left .maplibregl-popup-tip {+ border-right-color: var(--bg-1);+}+.maplibregl-popup-anchor-right .maplibregl-popup-tip {+ border-left-color: var(--bg-1);+}++/* The Google widget basemap (lib/map/gmaps.js) renders in its own map, under+ the engine's canvas. A negative z-index is what puts it there: inside the+ stacking context above, it paints over the container's background and under+ everything in flow, the canvas included. It never takes the pointer — our map+ owns every gesture — but the credit line does, so Google's terms link stays+ clickable. */+.map-glass {+ position: absolute;+ inset: 0;+ z-index: -1;+ overflow: hidden;+ pointer-events: none;+}+.map-glass-turn {+ position: absolute;+ transform-origin: 50% 50%;+}+.map-glass-map {+ width: 100%;+ height: 100%;+}+.map-glass-credit {+ position: absolute;+ right: 0;+ bottom: 0;+ display: flex;+ gap: 8px;+ padding: 1px 5px;+ background: rgba(24, 24, 24, 0.85);+ color: var(--text-3);+ font-size: 10px;+ pointer-events: auto;+}+.map-glass-credit a {+ color: var(--text-2);+}++/* What a shape says about itself under the cursor: the reading on a sky ray,+ the label on a sheet point. Never a card — it carries no controls and closes+ itself, so it takes no chrome and no pointer. */+.maplibregl-popup.map-tip {+ z-index: 700;+}+.map-tip .maplibregl-popup-content {+ min-width: 0;+ padding: 4px 8px;+ border-radius: var(--r-sm);+ background: color-mix(in srgb, var(--bg-0) 92%, transparent);+ box-shadow: var(--shadow-1);+ color: var(--text-1);+ font-size: var(--fs-xs);+ white-space: nowrap;+}+.map-tip .maplibregl-popup-tip {+ display: none;+}diff --git a/frontend/src/lib/map/engine.js b/frontend/src/lib/map/engine.jsnew file mode 100644index 0000000..48bd092--- /dev/null+++ b/frontend/src/lib/map/engine.js@@ -0,0 +1,132 @@+/**+ * Builds the map MapLibre renders, and hands back the neutral façade.+ *+ * The only file in the tools' reach that imports MapLibre — the pitch and+ * terrain of the 3D map (SPEC v3) are options on this map object, and the tools+ * above the façade never learn about either. What the map opens on, and the two+ * controls it always carries, are settled here rather than at the call site: a+ * second map surface must not be able to ship without a scale bar.+ *+ * Three of the engine's own defaults are turned off on purpose, and each one is+ * a gesture the tool already owns: right-drag flags a grid cell, shift-drag and+ * middle-drag turn the map, and the view is flat until the 3D map earns a pitch.+ */+// `MapLibreMap` rather than the `Map` alias: shadowing the global here is+// exactly the sort of thing that reads fine until someone needs a Map.+import { MapLibreMap, NavigationControl, ScaleControl, setWorkerUrl } from 'maplibre-gl';+import 'maplibre-gl/dist/maplibre-gl.css';+// The engine's worker, bundled and given a URL by our own build rather than by+// the engine's runtime guess — see the note in `vite.config.js`. Without this+// the worker never starts and the map draws imagery and nothing else: no+// shapes, no marks, no grid, and not one error in the console.+import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url';+import './engine.css';+import { mapFacade, engineZoom } from './facade.js';++setWorkerUrl(workerUrl);++/**+ * The style the map opens with: nothing.+ *+ * `basemap.js` adds the imagery and the labels, and `surface.js` the drawn+ * shapes. An empty style also leaves the canvas transparent, which is what lets+ * the Google widget basemap show through from underneath it.+ *+ * Written here rather than fetched, which is the whole of this engine's network+ * behaviour: no style URL, no glyphs, no sprite, no token and no telemetry. The+ * only thing it ever asks for is a tile the analyst's own basemap choice named.+ */+const EMPTY_STYLE = { version: 8, sources: {}, layers: [] };++/**+ * One notch of the wheel is one zoom level, as it was on the map this replaced.+ *+ * The engine's own rate asymptotes at a level per notch and only reaches about+ * 0.18 of one, which `settleOnLevel` then rounds straight back to where the+ * gesture started: the map twitched and stayed put, and the wheel did nothing+ * at all. At this rate a notch lands within a thousandth of a level, so the+ * settle has nothing left to correct that anyone could see — which matters,+ * because the settle zooms about the centre while the wheel zoomed about the+ * cursor, and a visible correction would slide the ground under it.+ *+ * A trackpad's small deltas are the engine's other rate and are left alone:+ * they accumulate through a gesture and settle once at the end, and a flick too+ * small to make a level snaps back to the one it started on — which is what the+ * old map did with them too.+ */+const WHEEL_ZOOM_RATE = 1 / 15;++/**+ * The camera comes to rest on a whole zoom level.+ *+ * A raster basemap holds one level of pixels per zoom, and every tile request,+ * capture and saved view records one whole number. The gesture itself stays+ * continuous — this only decides where it stops.+ */+function settleOnLevel(map) {+ let settling = false;+ map.on('moveend', () => {+ // the settling ease ends in a moveend of its own; that one is already level+ if (settling) {+ settling = false;+ return;+ }+ const zoom = map.getZoom();+ const level = Math.round(zoom);+ const off = Math.abs(zoom - level);+ if (off < 1e-6) return;+ settling = true;+ // A hair off — what a wheel notch leaves — is put right with no animation+ // at all: it is under a pixel, and the correction turns about the centre+ // while the gesture turned about the cursor, so anything visible would+ // slide the ground the analyst was aiming at. A genuine fractional rest+ // (a trackpad flick) eases, so the snap reads as something the map did.+ map.easeTo({ zoom: level, duration: off < 0.01 ? 0 : 160 });+ });+}++/**+ * @param {HTMLElement} container the element the map fills+ * @param {object} opts+ * @param {object} opts.view `{ lat, lon, zoom }` the map opens on+ * @param {boolean} [opts.imperial] scale bar in miles rather than metres+ */+export async function createMapEngine(container, { view, imperial = false } = {}) {+ const map = new MapLibreMap({+ container,+ style: EMPTY_STYLE,+ center: [view.lon, view.lat],+ zoom: engineZoom(view.zoom),+ // flat: an oblique view is the 3D map's, and it records a pitch of its own+ maxPitch: 0,+ pitchWithRotate: false,+ // the tool turns the map itself, from a middle- or shift-drag, around the+ // point that was grabbed rather than around the centre (lib/map/gestures.js)+ dragRotate: false,+ boxZoom: false,+ // the full credit line, as the tile providers' terms ask for it, rather+ // than the engine's ⓘ button on a narrow window+ attributionControl: { compact: false },+ });+ // stacked below the top-left tool cluster (fullscreen/labels/measure) via a+ // CSS offset, instead of the engine's default corner margin+ map.addControl(new NavigationControl({ showCompass: false }), 'top-left');+ // judging feature sizes (buildings, roads) needs a scale reference+ map.addControl(+ new ScaleControl({ unit: imperial ? 'imperial' : 'metric' }),+ 'bottom-right'+ );+ map.scrollZoom.setWheelZoomRate(WHEEL_ZOOM_RATE);+ // A source cannot be added before the style is up, and `basemap.js` adds one+ // as soon as this returns.+ await map.once('load');+ settleOnLevel(map);+ // A stable class for the tool's own cursor rules: a mode armed above the map+ // says so on the surface, whichever engine drew it.+ container.classList.add('map-surface');+ // The one thing outside code waits on. A browser test cannot ask the façade+ // whether the map is up, and asking it to recognise the engine's own class+ // names is how a suite ends up pinned to the engine it was written against.+ container.dataset.mapReady = 'true';+ return mapFacade(map, container);+}diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.jsnew file mode 100644index 0000000..cbef77a--- /dev/null+++ b/frontend/src/lib/map/facade.js@@ -0,0 +1,289 @@+/**+ * The map engine's boundary.+ *+ * Tools talk to the map through this façade and never to the engine, so+ * replacing the engine is a rewrite of `engine.js` rather than of the tools+ * above it. Two rules keep that promise:+ *+ * - **Nothing engine-shaped crosses the boundary.** A screen point is+ * `{ x, y }`, a position is `{ lat, lon }`, an extent is+ * `{ north, south, east, west }`. No LngLat, no Point, no layer.+ * - **Events are named for what happened to the view**, not for what the+ * engine calls it. `view-settled` is "the camera came to rest", whichever+ * engine event that turns out to be.+ *+ * Three translations are the whole reason this file exists, and each one is a+ * number that would otherwise be wrong in a request or on disk:+ *+ * - **Zoom.** MapLibre counts zoom on 512 px tiles and counts it continuously.+ * The app speaks the XYZ view zoom — one level deeper — in whole levels:+ * `zoom: int` on every route, one level of pixels per raster basemap, one+ * number recorded on a capture.+ * - **Bearing.** The app's bearing turns the map *clockwise*. MapLibre's is the+ * compass direction that is up, which is the same turn counted the other way.+ * - **Longitude.** An engine keeps counting past ±180° when the analyst pans+ * across the date line, every route bounds it to ±180, and an unwrapped+ * centre answered 422 over the Pacific.+ *+ * Nothing in this file imports the engine, so the translations are exercised+ * against a stub map instead of a browser (`facade.test.js`).+ */+import { wrapLon } from '../coords.js';+import { haversine } from '../measure.js';++/** What happened to the view → the engine events that say so. */+const EVENTS = {+ // MapLibre fires move events for any camera change, a zoom included, so one+ // name covers what used to take two.+ 'view-settled': ['moveend'],+ rotate: ['rotate'],+ click: ['click'],+};++/** The vocabulary `on()` accepts. */+export const MAP_EVENTS = Object.keys(EVENTS);++/**+ * How much deeper the app's zoom counts than the engine's.+ *+ * MapLibre's zoom is defined on 512 px tiles, XYZ zoom on 256 px ones, so the+ * same view is one number apart. Everything the app says about zoom — provider+ * ceilings, tile URLs, capture provenance, a saved place's view — is XYZ.+ */+const ZOOM_OFFSET = 1;++/**+ * The engine's zoom as the app says it: whole levels.+ *+ * The engine settles on a level (`engine.js`) so this rounds nothing the+ * analyst can see; what it protects against is a read taken mid-gesture+ * reaching a route as 16.37.+ */+export function viewZoom(engineZoom) {+ return Math.round(engineZoom + ZOOM_OFFSET);+}++/** …and back, for anything handed to the camera. */+export function engineZoom(zoom) {+ return zoom - ZOOM_OFFSET;+}++/**+ * The same reading unrounded, for whatever has to follow the camera itself+ * rather than say a number about it — the Google widget basemap under the map,+ * which would visibly jump a whole level otherwise.+ */+export function exactViewZoom(zoom) {+ return zoom + ZOOM_OFFSET;+}++/** 0–360, whatever the caller typed, dragged or read off a saved row. */+export function normalizeBearing(deg) {+ const value = Number(deg);+ if (!Number.isFinite(value)) return 0;+ return ((value % 360) + 360) % 360;+}++/**+ * The engine events one neutral name stands for.+ *+ * Throws on anything else: a typo that silently stopped delivering would read+ * as a map that quietly went dead.+ */+export function engineEvents(name) {+ const events = EVENTS[name];+ if (!events) throw new Error(`unknown map event: ${name}`);+ return events;+}++/** The smallest box holding every point, or null if there is nothing to hold. */+export function pointsExtent(points) {+ const usable = (points ?? []).filter(+ (point) => Number.isFinite(point?.lat) && Number.isFinite(point?.lon)+ );+ if (!usable.length) return null;+ const lats = usable.map((point) => point.lat);+ const lons = usable.map((point) => point.lon);+ return {+ north: Math.max(...lats),+ south: Math.min(...lats),+ east: Math.max(...lons),+ west: Math.min(...lons),+ };+}++/**+ * Frame padding as the engine wants it, from the `[x, y]` pair callers write.+ *+ * A number is the same on all four sides; a pair is horizontal then vertical,+ * which is how a caller thinks about leaving room beside a box.+ */+export function framePadding(padding) {+ if (padding == null) return 0;+ if (typeof padding === 'number') return padding;+ const [x, y] = padding;+ return { left: x, right: x, top: y, bottom: y };+}++/**+ * Wrap a built map in the façade.+ *+ * @param {object} map the engine's own map object+ * @param {HTMLElement} [container] the element the map was built in+ */+export function mapFacade(map, container) {+ /**+ * Layers that answer their own click.+ *+ * A click on a shape is not also a click on the map underneath: a cell of a+ * search grid cycles its own status, and the map's click handler — which+ * drops a polygon vertex or plants the sky anchor — must not fire behind it.+ * The engine delivers both, so the map's own relay asks first whether a+ * claiming layer was hit. Which layers claim is asked here rather than left+ * to listener order, so the answer does not depend on who registered first.+ */+ const claimed = new Set();++ function shapeUnder(point) {+ for (const claim of claimed) {+ const layers = claim.layers.filter((id) => map.getLayer(id));+ if (!layers.length) continue;+ if (map.queryRenderedFeatures(point, { layers, filter: claim.filter }).length) return true;+ }+ return false;+ }++ /** Where the camera is, in the terms the rest of the app uses. */+ function camera() {+ const centre = map.getCenter();+ return {+ lat: centre.lat,+ lon: wrapLon(centre.lng),+ zoom: viewZoom(map.getZoom()),+ bearing: normalizeBearing(-map.getBearing()),+ };+ }++ function fitBounds({ north, south, east, west }, options = {}) {+ const ceiling = options.maxZoom == null ? map.getMaxZoom() : engineZoom(options.maxZoom);+ const fitted = map.cameraForBounds(+ [+ [west, south],+ [east, north],+ ],+ { padding: framePadding(options.padding), maxZoom: ceiling }+ );+ if (!fitted) return;+ // The shallower whole level, not the nearest: the box has to still fit+ // inside the frame, and a raster basemap only has whole levels of pixels.+ // A box with no extent at all (one point) fits at any zoom, so clamp — the+ // engine's own ceiling is the answer there, never Infinity.+ const zoom = Math.min(ceiling, Math.floor(fitted.zoom));+ map.easeTo({+ center: fitted.center,+ zoom: Math.max(map.getMinZoom(), zoom),+ duration: options.animate ? 420 : 0,+ });+ }++ /** Frame every point handed over. False when none of them was usable. */+ function fitPoints(points, options) {+ const extent = pointsExtent(points);+ if (!extent) return false;+ fitBounds(extent, options);+ return true;+ }++ return {+ camera,+ getZoom: () => viewZoom(map.getZoom()),++ setView: ({ lat, lon }, zoom) => map.jumpTo({ center: [lon, lat], zoom: engineZoom(zoom) }),+ setZoom: (zoom) => map.setZoom(engineZoom(zoom)),+ setBearing: (deg) => map.setBearing(-normalizeBearing(deg)),+ /** Never animated: a rotation pans the map once per pointer move. */+ panBy: (dx, dy) => map.panBy([dx, dy], { duration: 0 }),+ fitBounds,+ fitPoints,++ containerPointToLatLng({ x, y }) {+ const position = map.unproject([x, y]);+ return { lat: position.lat, lon: wrapLon(position.lng) };+ },++ latLngToContainerPoint({ lat, lon }) {+ const point = map.project([lon, lat]);+ return { x: point.x, y: point.y };+ },++ /**+ * How far the view reaches on the ground, along each of its own sides.+ * What sizes anything drawn in metres — the sky arc is a circle around its+ * anchor, so a radius taken off the diagonal runs off a wide window.+ */+ viewSpanMeters() {+ const bounds = map.getBounds();+ const north = bounds.getNorth();+ const west = bounds.getWest();+ return {+ across: haversine({ lat: north, lon: west }, { lat: north, lon: bounds.getEast() }),+ down: haversine({ lat: north, lon: west }, { lat: bounds.getSouth(), lon: west }),+ };+ },++ /** The container changed size; re-read it. */+ resize: () => map.resize(),++ /**+ * Listen for something happening to the view. Returns the unsubscribe, so+ * a caller cannot hold one half of the pair.+ */+ on(name, handler) {+ const events = engineEvents(name);+ const relay =+ name === 'click'+ ? (event) => {+ if (shapeUnder(event.point)) return;+ handler({ lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) });+ }+ : () => handler(camera());+ for (const event of events) map.on(event, relay);+ return () => {+ for (const event of events) map.off(event, relay);+ };+ },++ /**+ * These layers answer their own clicks; keep the map's relay off them.+ * The filter narrows that to the features that really do — a shape drawn+ * under a mark to say how loosely it is placed answers nothing, and must+ * not swallow the click meant for the map. Returns the release, for a+ * surface that is torn down.+ */+ claimClicks(layers, filter) {+ const claim = { layers: [...layers], filter };+ claimed.add(claim);+ return () => claimed.delete(claim);+ },++ destroy() {+ if (container) delete container.dataset.mapReady;+ map.remove();+ },++ /**+ * The element the map fills. Every engine has one, and the gestures measure+ * and read it, so it crosses the boundary as itself.+ */+ container,++ /**+ * The engine's own map.+ *+ * The modules in `lib/map` are the engine, plainly: layers, sources and+ * markers are its vocabulary and there is no neutral way to say them.+ * Nothing above the façade may reach for this.+ */+ impl: map,+ };+}diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.jsnew file mode 100644index 0000000..0428d83--- /dev/null+++ b/frontend/src/lib/map/facade.test.js@@ -0,0 +1,355 @@+import { describe, expect, it, vi } from 'vitest';+import {+ MAP_EVENTS,+ engineEvents,+ engineZoom,+ exactViewZoom,+ framePadding,+ mapFacade,+ normalizeBearing,+ pointsExtent,+ viewZoom,+} from './facade.js';++/**+ * A map the façade can be driven against without a browser. The point of+ * keeping `facade.js` clear of the engine is that everything crossing the+ * boundary — the zoom convention, the bearing sign, wrapping, extents, point+ * shapes, the event vocabulary — is arithmetic and translation, so it is tested+ * here rather than in an e2e run.+ *+ * The numbers are the engine's own: zoom 15 on 512 px tiles is the app's z16,+ * and a MapLibre bearing of -37 is the app's 37.+ */+function stubMap(overrides = {}) {+ const calls = {+ jumpTo: [],+ setZoom: [],+ setBearing: [],+ panBy: [],+ easeTo: [],+ cameraForBounds: [],+ queryRenderedFeatures: [],+ on: [],+ off: [],+ resize: 0,+ removed: 0,+ };+ return {+ calls,+ getCenter: () => ({ lat: 48.8584, lng: 2.2945 }),+ getZoom: () => 15,+ getMinZoom: () => 0,+ getMaxZoom: () => 21,+ getBearing: () => -37,+ getBounds: () => ({+ getNorth: () => 0,+ getSouth: () => -1,+ getWest: () => 0,+ getEast: () => 1,+ }),+ getLayer: (id) => (id === 'gone' ? undefined : { id }),+ unproject: ([x, y]) => ({ lat: 40 + y, lng: 180 + x }),+ project: ([lon, lat]) => ({ x: lon * 10, y: lat * 10 }),+ jumpTo: (...args) => calls.jumpTo.push(args),+ setZoom: (...args) => calls.setZoom.push(args),+ setBearing: (...args) => calls.setBearing.push(args),+ panBy: (...args) => calls.panBy.push(args),+ easeTo: (...args) => calls.easeTo.push(args),+ cameraForBounds: (...args) => {+ calls.cameraForBounds.push(args);+ return { center: { lat: 2, lng: 5 }, zoom: 13.7, bearing: 0 };+ },+ queryRenderedFeatures: (...args) => {+ calls.queryRenderedFeatures.push(args);+ return [];+ },+ on: (...args) => calls.on.push(args),+ off: (...args) => calls.off.push(args),+ resize: () => (calls.resize += 1),+ remove: () => (calls.removed += 1),+ ...overrides,+ };+}++describe('the zoom convention', () => {+ it('counts one level deeper than the engine does', () => {+ // MapLibre's zoom is defined on 512 px tiles, XYZ zoom on 256 px ones+ expect(viewZoom(15)).toBe(16);+ expect(engineZoom(16)).toBe(15);+ expect(engineZoom(viewZoom(9))).toBe(9);+ });++ it('rounds, because every route takes a whole level', () => {+ // `zoom: int = Field(ge=1, le=22)` on the capture route; a read taken+ // mid-gesture must not reach it as 16.37+ expect(viewZoom(15.37)).toBe(16);+ expect(viewZoom(15.5)).toBe(17);+ expect(mapFacade(stubMap({ getZoom: () => 15.37 })).getZoom()).toBe(16);+ expect(mapFacade(stubMap({ getZoom: () => 15.37 })).camera().zoom).toBe(16);+ });++ it('keeps the unrounded reading for whatever follows the camera itself', () => {+ // the Google widget basemap under the map would jump a whole level+ expect(exactViewZoom(15.37)).toBeCloseTo(16.37, 10);+ });+});++describe('the bearing convention', () => {+ it('reads the engine’s turn as the app’s, which is the other way round', () => {+ // the app's bearing turns the map clockwise (engine/tiles.py rotates a+ // capture by it); MapLibre's names the compass direction that is up+ expect(mapFacade(stubMap()).camera().bearing).toBe(37);+ expect(mapFacade(stubMap({ getBearing: () => -270 })).camera().bearing).toBe(270);+ expect(mapFacade(stubMap({ getBearing: () => 90 })).camera().bearing).toBe(270);+ });++ it('negates on the way in too, so a saved bearing restores as it was saved', () => {+ const map = stubMap();+ mapFacade(map).setBearing(37);+ expect(map.calls.setBearing).toEqual([[-37]]);+ });++ it('normalises a bearing wherever it came from', () => {+ expect(normalizeBearing(-90)).toBe(270);+ expect(normalizeBearing(450)).toBe(90);+ expect(normalizeBearing(0)).toBe(0);+ // a saved row with no bearing, a half-typed angle+ expect(normalizeBearing(undefined)).toBe(0);+ expect(normalizeBearing('')).toBe(0);+ });++ it('normalises on the way in, so no call site has to', () => {+ const map = stubMap();+ mapFacade(map).setBearing(-45);+ expect(map.calls.setBearing).toEqual([[-315]]);+ });+});++describe('the map façade keeps the engine on its own side', () => {+ it('folds the map centre back inside the bounds every route enforces', () => {+ // an engine keeps counting past ±180 across the date line; the capture+ // route bounds lon to ±180, so an unwrapped centre answered 422+ const map = stubMap({ getCenter: () => ({ lat: 12, lng: 190.5 }) });+ expect(mapFacade(map).camera()).toEqual({ lat: 12, lon: -169.5, zoom: 16, bearing: 37 });+ });++ it('leaves a longitude that is already one alone, to the last decimal', () => {+ // this value is written into captures and proofs+ expect(mapFacade(stubMap()).camera().lon).toBe(2.2945);+ });++ it('hands out plain points and positions, never the engine’s own', () => {+ const facade = mapFacade(stubMap());+ expect(facade.containerPointToLatLng({ x: 4, y: 2 })).toEqual({ lat: 42, lon: -176 });+ expect(facade.latLngToContainerPoint({ lat: 3, lon: 5 })).toEqual({ x: 50, y: 30 });+ });++ it('moves the camera without animating it', () => {+ const map = stubMap();+ const facade = mapFacade(map);+ facade.setView({ lat: 1, lon: 2 }, 16);+ facade.setZoom(18);+ expect(map.calls.jumpTo).toEqual([[{ center: [2, 1], zoom: 15 }]]);+ expect(map.calls.setZoom).toEqual([[17]]);+ });++ it('never animates a pan: it re-pins a grabbed point mid-gesture', () => {+ const map = stubMap();+ mapFacade(map).panBy(3, -7);+ expect(map.calls.panBy).toEqual([[[3, -7], { duration: 0 }]]);+ });++ it('re-reads the container on request', () => {+ const map = stubMap();+ mapFacade(map).resize();+ expect(map.calls.resize).toBe(1);+ });+});++describe('framing an extent', () => {+ it('writes padding the way callers think about it', () => {+ expect(framePadding([10, 20])).toEqual({ left: 10, right: 10, top: 20, bottom: 20 });+ expect(framePadding(12)).toBe(12);+ expect(framePadding(undefined)).toBe(0);+ });++ it('speaks extents, and lets the engine order its own corners', () => {+ const map = stubMap();+ mapFacade(map).fitBounds({ north: 4, south: 1, east: 8, west: 2 }, { padding: [10, 10] });+ expect(map.calls.cameraForBounds[0][0]).toEqual([+ [2, 1],+ [8, 4],+ ]);+ });++ it('lands on the shallower whole level, so the box still fits', () => {+ // the fitted zoom is 13.7 in engine terms; rounding up would crop the box,+ // and a raster basemap only has whole levels of pixels+ const map = stubMap();+ mapFacade(map).fitBounds({ north: 4, south: 1, east: 8, west: 2 }, { maxZoom: 20 });+ expect(map.calls.cameraForBounds[0][1].maxZoom).toBe(19);+ expect(map.calls.easeTo).toEqual([+ [{ center: { lat: 2, lng: 5 }, zoom: 13, duration: 0 }],+ ]);+ });++ it('animates only when asked', () => {+ const map = stubMap();+ mapFacade(map).fitBounds({ north: 4, south: 1, east: 8, west: 2 }, { animate: true });+ expect(map.calls.easeTo[0][0].duration).toBeGreaterThan(0);+ });++ it('clamps a box with no extent at all to the engine’s own ceiling', () => {+ // one point fits at any zoom, and cameraForBounds says so+ const map = stubMap({+ cameraForBounds: () => ({ center: { lat: 1, lng: 1 }, zoom: Infinity, bearing: 0 }),+ });+ mapFacade(map).fitBounds({ north: 1, south: 1, east: 1, west: 1 });+ expect(map.calls.easeTo[0][0].zoom).toBe(21);+ });+});++describe('framing a set of points', () => {+ it('holds every point handed over', () => {+ expect(+ pointsExtent([+ { lat: 1, lon: 5 },+ { lat: -3, lon: 2 },+ { lat: 4, lon: 9 },+ ])+ ).toEqual({ north: 4, south: -3, east: 9, west: 2 });+ });++ it('ignores a row whose coordinates are not numbers', () => {+ // a sheet's coordinate column is text in a CSV until it is read+ expect(pointsExtent([{ lat: 1, lon: 2 }, { lat: null, lon: 3 }, {}])).toEqual({+ north: 1,+ south: 1,+ east: 2,+ west: 2,+ });+ });++ it('says there is nothing to frame rather than framing nothing', () => {+ expect(pointsExtent([])).toBeNull();+ expect(pointsExtent(undefined)).toBeNull();+ const map = stubMap();+ expect(mapFacade(map).fitPoints([{ lat: null, lon: null }])).toBe(false);+ // a layer that landed nowhere must leave the view where the analyst left it+ expect(map.calls.easeTo).toEqual([]);+ });++ it('frames what did arrive, and says so', () => {+ const map = stubMap();+ expect(+ mapFacade(map).fitPoints([{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }], { maxZoom: 17 })+ ).toBe(true);+ expect(map.calls.cameraForBounds[0][0]).toEqual([+ [2, 1],+ [4, 3],+ ]);+ });+});++describe('the event vocabulary', () => {+ it('names what happened to the view, not what the engine calls it', () => {+ expect(MAP_EVENTS).toEqual(['view-settled', 'rotate', 'click']);+ expect(engineEvents('view-settled')).toEqual(['moveend']);+ });++ it('refuses a name it does not know', () => {+ // a typo that quietly stopped delivering would read as a dead map+ expect(() => engineEvents('moveend')).toThrow(/unknown map event/);+ expect(() => mapFacade(stubMap()).on('zoomend', () => {})).toThrow(/unknown map event/);+ });++ it('hands a camera event the camera', () => {+ const map = stubMap();+ const seen = vi.fn();+ mapFacade(map).on('view-settled', seen);+ const [, relay] = map.calls.on[0];+ relay();+ expect(seen).toHaveBeenCalledWith({ lat: 48.8584, lon: 2.2945, zoom: 16, bearing: 37 });+ });++ it('hands a click the point clicked, wrapped like any other', () => {+ const map = stubMap();+ const seen = vi.fn();+ mapFacade(map).on('click', seen);+ map.calls.on[0][1]({ point: { x: 1, y: 1 }, lngLat: { lat: 7, lng: 200 } });+ expect(seen).toHaveBeenCalledWith({ lat: 7, lon: -160 });+ });++ it('returns the unsubscribe, so nobody can hold half the pair', () => {+ const map = stubMap();+ const off = mapFacade(map).on('rotate', () => {});+ off();+ expect(map.calls.off).toEqual([map.calls.on[0]]);+ });+});++describe('a click a shape has already answered', () => {+ it('does not also reach the map', () => {+ // a cell of a search grid cycles its own status; the map's handler, which+ // drops a polygon vertex, must not fire behind it+ const map = stubMap({ queryRenderedFeatures: () => [{ id: 1 }] });+ const facade = mapFacade(map);+ const seen = vi.fn();+ facade.claimClicks(['cells'], ['!=', ['get', 'interactive'], false]);+ facade.on('click', seen);+ map.calls.on[0][1]({ point: { x: 5, y: 6 }, lngLat: { lat: 1, lng: 2 } });+ expect(seen).not.toHaveBeenCalled();+ });++ it('asks only about the layers still on the map, and with the claim’s filter', () => {+ const map = stubMap();+ const facade = mapFacade(map);+ facade.claimClicks(['cells', 'gone'], ['has', 'sid']);+ facade.on('click', () => {});+ map.calls.on[0][1]({ point: { x: 5, y: 6 }, lngLat: { lat: 1, lng: 2 } });+ expect(map.calls.queryRenderedFeatures).toEqual([+ [{ x: 5, y: 6 }, { layers: ['cells'], filter: ['has', 'sid'] }],+ ]);+ });++ it('lets the map hear clicks again once the surface releases them', () => {+ const map = stubMap({ queryRenderedFeatures: () => [{ id: 1 }] });+ const facade = mapFacade(map);+ const seen = vi.fn();+ const release = facade.claimClicks(['cells']);+ facade.on('click', seen);+ release();+ map.calls.on[0][1]({ point: { x: 5, y: 6 }, lngLat: { lat: 1, lng: 2 } });+ expect(seen).toHaveBeenCalledWith({ lat: 1, lon: 2 });+ });++ it('leaves the map’s own click alone when nothing claimed it', () => {+ const map = stubMap({ queryRenderedFeatures: () => [{ id: 1 }] });+ const facade = mapFacade(map);+ const seen = vi.fn();+ facade.on('click', seen);+ map.calls.on[0][1]({ point: { x: 5, y: 6 }, lngLat: { lat: 1, lng: 2 } });+ expect(seen).toHaveBeenCalledOnce();+ expect(map.calls.queryRenderedFeatures).toEqual([]);+ });+});++describe('spans and teardown', () => {+ it('measures the view along its own sides, in metres', () => {+ // a degree at the equator is ~111.3 km both ways+ const { across, down } = mapFacade(stubMap()).viewSpanMeters();+ expect(across).toBeGreaterThan(110_000);+ expect(across).toBeLessThan(112_000);+ expect(down).toBeGreaterThan(110_000);+ expect(down).toBeLessThan(112_000);+ });++ it('drops the ready flag before the map goes, not after', () => {+ const container = { dataset: { mapReady: 'true' } };+ const map = stubMap();+ mapFacade(map, container).destroy();+ expect(container.dataset.mapReady).toBeUndefined();+ expect(map.calls.removed).toBe(1);+ });+});diff --git a/frontend/src/lib/map/gestures.js b/frontend/src/lib/map/gestures.jsnew file mode 100644index 0000000..ac56385--- /dev/null+++ b/frontend/src/lib/map/gestures.js@@ -0,0 +1,122 @@+/**+ * Drag gestures on the map surface: pull a rectangle, or grab a point and turn.+ *+ * Three tools use these — the capture marquee, the Grid Search area, and the+ * Google-Earth style rotation — and all three are the same two mechanics under+ * different modes. The modes stay with the tool, which decides *whether* a+ * gesture starts; the pointer bookkeeping and everything that touches the map+ * live here, so a gesture is written once and re-aimed at the next engine once.+ *+ * Both starters take the `mousedown` that began the gesture, own it (no engine+ * pan, no browser middle-click autoscroll), and track the rest on the window —+ * a drag that leaves the map still finishes, which is what makes a marquee+ * pulled past the edge behave.+ */+import { dragBearing, pivotPanOffset } from '../satRotate.js';++/** px to leave the pivot before the reference spoke is fixed. */+const ROTATE_DEADZONE = 8;++/** Where in the map container an event landed. */+function containerPoint(engine, event) {+ const rect = engine.container.getBoundingClientRect();+ return { x: event.clientX - rect.left, y: event.clientY - rect.top };+}++/**+ * Pull a rectangle out of a drag.+ *+ * `onChange` is handed the live box every move (`{ x0, y0, x1, y1 }` in+ * container px) and `onDone` the last one, or null if the drag never moved.+ *+ * @param {object} engine the façade from `engine.js`+ * @param {MouseEvent} event the mousedown that starts it+ * @param {object} opts+ * @param {number|null} [opts.ratio] width/height the box locks to; null is free+ * @param {(rect: object) => void} [opts.onChange]+ * @param {(rect: object) => void} [opts.onDone]+ */+export function startRectDrag(engine, event, { ratio = null, onChange, onDone } = {}) {+ event.stopPropagation();+ event.preventDefault();+ const start = containerPoint(engine, event);+ let rect = { x0: start.x, y0: start.y, x1: start.x, y1: start.y };+ onChange?.(rect);++ const move = (moved) => {+ const at = containerPoint(engine, moved);+ let { x, y } = at;+ if (ratio) {+ // lock the box to the chosen aspect ratio, sized from the larger delta+ const dx = x - start.x;+ const dy = y - start.y;+ let w = Math.abs(dx);+ let h = Math.abs(dy);+ if (w / h > ratio) h = w / ratio;+ else w = h * ratio;+ x = start.x + (dx < 0 ? -w : w);+ y = start.y + (dy < 0 ? -h : h);+ }+ rect = { x0: start.x, y0: start.y, x1: x, y1: y };+ onChange?.(rect);+ };++ const up = () => {+ window.removeEventListener('mousemove', move);+ window.removeEventListener('mouseup', up);+ onDone?.(rect);+ };++ window.addEventListener('mousemove', move);+ window.addEventListener('mouseup', up);+}++/**+ * Grab a point and turn the map around it.+ *+ * A map rotates about its centre, so after each bearing change the grabbed+ * geographic point is panned back under the cursor — which is what pins it+ * exactly where it was grabbed. `onPivot` is handed the grabbed point in+ * container px, for the target the tool draws there.+ *+ * @param {object} engine the façade from `engine.js`+ * @param {MouseEvent} event the middle-button mousedown that starts it+ * @param {object} opts+ * @param {(pivot: object) => void} [opts.onPivot]+ * @param {() => void} [opts.onEnd]+ */+export function startRotateDrag(engine, event, { onPivot, onEnd } = {}) {+ event.stopPropagation();+ event.preventDefault();+ const grab = containerPoint(engine, event);+ const pinned = engine.containerPointToLatLng(grab); // the location held still+ const startBearing = engine.camera().bearing;+ const startScreen = { x: event.clientX, y: event.clientY };+ onPivot?.(grab);+ let spoke = null; // reference direction, fixed once out of the deadzone++ const move = (moved) => {+ if (spoke === null) {+ if (Math.hypot(moved.clientX - startScreen.x, moved.clientY - startScreen.y) < ROTATE_DEADZONE) {+ return;+ }+ spoke = { x: moved.clientX, y: moved.clientY };+ return;+ }+ engine.setBearing(+ dragBearing(startBearing, startScreen, spoke, { x: moved.clientX, y: moved.clientY })+ );+ const now = engine.latLngToContainerPoint(pinned);+ const [dx, dy] = pivotPanOffset(grab, now);+ if (dx || dy) engine.panBy(dx, dy);+ };++ const up = () => {+ window.removeEventListener('mousemove', move);+ window.removeEventListener('mouseup', up);+ onEnd?.();+ };++ window.addEventListener('mousemove', move);+ window.addEventListener('mouseup', up);+}diff --git a/frontend/src/lib/map/gestures.test.js b/frontend/src/lib/map/gestures.test.jsnew file mode 100644index 0000000..28fac39--- /dev/null+++ b/frontend/src/lib/map/gestures.test.js@@ -0,0 +1,154 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { startRectDrag, startRotateDrag } from './gestures.js';++/** The façade, as far as the gestures reach into it. */+function stubEngine({ bearing = 0 } = {}) {+ const container = document.createElement('div');+ // happy-dom gives an unlaid-out element a zero rect; the offset is what the+ // gestures subtract, so state one.+ container.getBoundingClientRect = () => ({ left: 40, top: 20, width: 800, height: 600 });+ return {+ container,+ bearings: [],+ pans: [],+ camera: () => ({ lat: 0, lon: 0, zoom: 12, bearing }),+ containerPointToLatLng: ({ x, y }) => ({ lat: y / 10, lon: x / 10 }),+ latLngToContainerPoint: ({ lat, lon }) => ({ x: lon * 10 + 6, y: lat * 10 - 3 }),+ setBearing(deg) {+ this.bearings.push(deg);+ },+ panBy(dx, dy) {+ this.pans.push([dx, dy]);+ },+ };+}++function press(button = 0, clientX = 100, clientY = 100) {+ return {+ button,+ clientX,+ clientY,+ stopPropagation: vi.fn(),+ preventDefault: vi.fn(),+ };+}++function drag(clientX, clientY) {+ window.dispatchEvent(new window.MouseEvent('mousemove', { clientX, clientY }));+}++function release() {+ window.dispatchEvent(new window.MouseEvent('mouseup'));+}++afterEach(release);++describe('pulling a rectangle', () => {+ it('owns the gesture, so the map does not pan under the box', () => {+ const event = press();+ startRectDrag(stubEngine(), event);+ expect(event.stopPropagation).toHaveBeenCalled();+ expect(event.preventDefault).toHaveBeenCalled();+ });++ it('measures inside the container, not on the page', () => {+ const seen = [];+ startRectDrag(stubEngine(), press(0, 140, 120), { onChange: (r) => seen.push(r) });+ expect(seen[0]).toEqual({ x0: 100, y0: 100, x1: 100, y1: 100 });+ });++ it('follows the pointer, and hands the last box over on release', () => {+ const seen = [];+ const done = vi.fn();+ startRectDrag(stubEngine(), press(0, 140, 120), {+ onChange: (r) => seen.push(r),+ onDone: done,+ });+ drag(340, 320);+ expect(seen.at(-1)).toEqual({ x0: 100, y0: 100, x1: 300, y1: 300 });+ release();+ expect(done).toHaveBeenCalledWith({ x0: 100, y0: 100, x1: 300, y1: 300 });+ });++ it('locks a ratio off the larger delta, in the direction dragged', () => {+ const seen = [];+ startRectDrag(stubEngine(), press(0, 140, 120), {+ ratio: 16 / 9,+ onChange: (r) => seen.push(r),+ });+ drag(340, 150); // 200 across, 30 down — width leads+ const box = seen.at(-1);+ expect(box.x1 - box.x0).toBe(200);+ expect(box.y1 - box.y0).toBeCloseTo(112.5, 3);++ drag(120, 400); // dragged up and left: the box follows, ratio kept+ const back = seen.at(-1);+ expect(back.x1 - back.x0).toBeCloseTo(-497.78, 1);+ expect(back.y1 - back.y0).toBe(280);+ });++ it('keeps following after the pointer leaves the map', () => {+ // a marquee pulled past the edge still finishes+ const done = vi.fn();+ startRectDrag(stubEngine(), press(0, 140, 120), { onDone: done });+ drag(2000, -500);+ release();+ expect(done).toHaveBeenCalledWith({ x0: 100, y0: 100, x1: 1960, y1: -520 });+ });++ it('stops listening once released', () => {+ const seen = [];+ startRectDrag(stubEngine(), press(), { onChange: (r) => seen.push(r) });+ release();+ const after = seen.length;+ drag(500, 500);+ expect(seen).toHaveLength(after);+ });+});++describe('grabbing a point and turning', () => {+ it('reports the grabbed point in container px, for the target drawn there', () => {+ const onPivot = vi.fn();+ startRotateDrag(stubEngine(), press(1, 240, 220), { onPivot });+ expect(onPivot).toHaveBeenCalledWith({ x: 200, y: 200 });+ });++ it('ignores a nudge, so a click does not spin the map', () => {+ const engine = stubEngine();+ startRotateDrag(engine, press(1, 240, 220));+ drag(244, 224); // ~5.7 px, inside the deadzone+ expect(engine.bearings).toEqual([]);+ });++ it('turns once out of the deadzone, taking that direction as the reference', () => {+ const engine = stubEngine({ bearing: 30 });+ startRotateDrag(engine, press(1, 240, 220));+ drag(340, 220); // leaves the deadzone: this direction is 0 of the sweep+ expect(engine.bearings).toEqual([]);+ drag(240, 320); // a quarter turn from the reference spoke+ expect(engine.bearings).toHaveLength(1);+ expect(engine.bearings[0] - 30).toBeCloseTo(90, 6);+ });++ it('pans the grabbed location back under the cursor after every turn', () => {+ // the map rotates about its centre, so without this the point drifts away+ const engine = stubEngine();+ startRotateDrag(engine, press(1, 240, 220));+ drag(340, 220);+ drag(240, 320);+ expect(engine.pans).toEqual([[6, -3]]); // what the stub projection displaced+ });++ it('says when the turn is over', () => {+ const onEnd = vi.fn();+ startRotateDrag(stubEngine(), press(1), { onEnd });+ release();+ expect(onEnd).toHaveBeenCalledTimes(1);+ const engine = stubEngine();+ startRotateDrag(engine, press(1, 240, 220), {});+ release();+ drag(600, 600);+ expect(engine.bearings).toEqual([]);+ });+});diff --git a/frontend/src/lib/map/gmaps.js b/frontend/src/lib/map/gmaps.jsnew file mode 100644index 0000000..f30a5fb--- /dev/null+++ b/frontend/src/lib/map/gmaps.js@@ -0,0 +1,283 @@+/**+ * Google Maps JavaScript API — loader, key probe, and the basemap under glass.+ *+ * The EEA-viable Google satellite route (docs/IMAGERY_PROVIDERS.md § Google in+ * the EEA): a real google.maps.Map rendered by the official JS API. Google's+ * own map is the only thing on the page that may draw those pixels — its terms+ * forbid taking them out of it — so instead of feeding tiles into our map, this+ * puts Google's map *underneath* it and keeps the two cameras in step. The+ * engine's canvas is transparent where nothing is drawn, so the imagery shows+ * through and every overlay above it (measure tools, marks, grids, labels)+ * keeps working, untouched and unaware.+ *+ * Local-first: nothing here runs until the user actually selects the widget+ * basemap — the script load *is* the user action needing the network.+ *+ * Billing: one "dynamic map load" per google.maps.Map instantiation; pan/zoom+ * afterwards is free. The glass must therefore be created once and hidden+ * rather than destroyed when the analyst switches basemap — see `basemap.js`.+ */+import { exactViewZoom } from './facade.js';++/** Where Google's terms live, for the credit we state when Google's own is absent. */+const TERMS_URL = 'https://www.google.com/intl/en/help/terms_maps/';++let loadPromise = null;+let loadedKey = null; // the key the script was loaded with — one per page life++/** The API key the Maps JS script is already bound to, if loaded. Google's+ * script can't be re-loaded with another key without a full page reload, so+ * a key change after load can only be tested by reloading the app. */+export function googleMapsLoadedKey() {+ return loadedKey;+}++/**+ * Load the Maps JS API from the provider's loader URL (key included — a JS+ * API key is client-side by design, referrer-restricted rather than secret).+ *+ * `onAuthFailure` fires if Google rejects the key — that can happen minutes+ * after a successful load (gm_authFailure is async), so the caller must+ * handle it as a runtime event, not a load error.+ */+export function loadGoogleMaps(loaderUrl, { onAuthFailure } = {}) {+ // gm_authFailure is Google's only key-rejection signal; keep it wired even+ // when the script is already loaded (a Settings re-test swaps the handler)+ window.gm_authFailure = () => onAuthFailure?.();+ if (window.google?.maps) return Promise.resolve();+ if (loadPromise) return loadPromise;+ loadedKey = keyFromLoaderUrl(loaderUrl);+ loadPromise = new Promise((resolve, reject) => {+ const cb = '__azimutGmapsReady';+ window[cb] = () => {+ delete window[cb];+ resolve();+ };+ const script = document.createElement('script');+ script.src = `${loaderUrl}&loading=async&callback=${cb}`;+ script.async = true;+ script.onerror = () => {+ loadPromise = null; // a network failure may be transient — allow retry+ delete window[cb];+ reject(new Error('could not load the Google Maps script'));+ };+ document.head.appendChild(script);+ });+ return loadPromise;+}++/**+ * Prove a Maps JS key in the only place it can be proven: a real map in this+ * browser. Loads the script, spins up a hidden 1-tile satellite map and races+ * `tilesloaded` (key works) against `gm_authFailure` (Google rejected it) and+ * a timeout. Because Google's script binds to one key per page life, a+ * *changed* key can only be re-probed after a reload — callers should check+ * googleMapsLoadedKey() first.+ *+ * The verdict carries `billed`: the probe's own map is a real dynamic map load+ * on the user's bill, and no backend proxy can see it, so the caller must+ * report it to the usage counter or the counter drifts under Google's number.+ */+export async function probeKey(loaderUrl, { timeoutMs = 12000 } = {}) {+ let rejected = false;+ try {+ await loadGoogleMaps(loaderUrl, { onAuthFailure: () => (rejected = true) });+ } catch (e) {+ // the script never loaded, so no map was ever constructed — nothing billed+ return { ok: false, detail: e.message, billed: false };+ }+ const holder = document.createElement('div');+ // Must stay INSIDE the viewport: Chrome culls rendering for off-screen+ // fixed elements, so an off-screen map never fires `tilesloaded` and the+ // probe times out on a perfectly good key (verified headless, 2026-07).+ // Near-zero opacity keeps it invisible without suppressing rendering.+ holder.style.cssText =+ 'position:fixed;left:0;bottom:0;width:128px;height:128px;opacity:0.01;pointer-events:none';+ document.body.appendChild(holder);+ try {+ const verdict = await new Promise((resolve) => {+ const timer = setTimeout(+ () => resolve({ ok: false, detail: 'no response from Google (timeout)' }),+ timeoutMs+ );+ window.gm_authFailure = () => {+ rejected = true;+ clearTimeout(timer);+ resolve({ ok: false, detail: 'Google rejected the key (gm_authFailure)' });+ };+ const map = new window.google.maps.Map(holder, {+ center: { lat: 0, lng: 0 },+ zoom: 1,+ mapTypeId: 'satellite',+ disableDefaultUI: true,+ });+ map.addListener('tilesloaded', () => {+ clearTimeout(timer);+ resolve(+ rejected+ ? { ok: false, detail: 'Google rejected the key (gm_authFailure)' }+ : { ok: true, detail: 'satellite map rendered' }+ );+ });+ });+ // A google.maps.Map was constructed above, and Google bills one dynamic map+ // load for every one it accepts — this throwaway included. Only a key it+ // rejected is free: there is no valid project to bill it to. A timeout still+ // counts, since the map was built and we cannot prove it was not served.+ return { ...verdict, billed: !rejected };+ } finally {+ holder.remove();+ }+}++function keyFromLoaderUrl(url) {+ try {+ return new URL(url).searchParams.get('key');+ } catch {+ return null;+ }+}++/**+ * Google's own credit, stated by us.+ *+ * Only reached if Google's markup stops offering the node this moves upright —+ * the imagery is never shown bare, and the terms link stays reachable.+ */+function statedCredit(attribution) {+ const holder = document.createDocumentFragment();+ const text = document.createElement('span');+ text.textContent = attribution;+ const terms = document.createElement('a');+ terms.href = TERMS_URL;+ terms.target = '_blank';+ terms.rel = 'noopener noreferrer';+ terms.textContent = 'Terms';+ holder.append(text, terms);+ return holder;+}++/**+ * Google's satellite map, under the engine's transparent canvas.+ *+ * One billed dynamic map load per call, so `basemap.js` calls it once and hides+ * the result rather than making another.+ *+ * Two things make this work at any bearing. The map div is a square of the+ * container's *diagonal*, centred on it, because a rotated W×H rectangle always+ * fits inside the circle of its own diagonal — so every bearing is covered+ * without asking Google to redraw. And it is turned by CSS rather than by+ * Google, which has no bearing of its own on a raster satellite map.+ *+ * @param {object} engine the façade from `engine.js`+ * @param {object} [opts]+ * @param {number} [opts.maxZoom] the provider's own view ceiling+ * @param {string} [opts.attribution] what to state if Google's own node is gone+ */+export function createGoogleGlass(engine, { maxZoom = 21, attribution = 'Map data © Google' } = {}) {+ const map = engine.impl;+ const glass = document.createElement('div');+ glass.className = 'map-glass';+ glass.hidden = true;+ const turn = document.createElement('div');+ turn.className = 'map-glass-turn';+ const surface = document.createElement('div');+ surface.className = 'map-glass-map';+ const credit = document.createElement('div');+ credit.className = 'map-glass-credit';+ credit.replaceChildren(statedCredit(attribution));+ turn.append(surface);+ glass.append(turn, credit);+ engine.container.append(glass);++ const centre = map.getCenter();+ const google = new window.google.maps.Map(surface, {+ center: { lat: centre.lat, lng: centre.lng },+ zoom: exactViewZoom(map.getZoom()),+ mapTypeId: 'satellite',+ maxZoom,+ // Our map owns every gesture and every control; this one only ever renders+ // what it is told to. `pointer-events: none` on the glass says the same+ // thing to the browser, and both are needed: one stops Google's own+ // handlers, the other stops the pointer ever reaching them.+ disableDefaultUI: true,+ gestureHandling: 'none',+ keyboardShortcuts: false,+ // the camera it follows is continuous, so it must be able to sit between+ // whole levels rather than snapping and drifting out of register+ isFractionalZoomEnabled: true,+ tilt: 0,+ });++ /**+ * Google's own credit line, kept upright and clickable.+ *+ * It renders inside the map div, which is oversized and turned, so at any+ * bearing it would be rotated and pushed off screen. Moving the node into an+ * upright holder is the same trick the plugin used before this did.+ */+ function homeCredit() {+ const own = surface.querySelectorAll('.gm-style-cc');+ if (!own.length) return;+ credit.replaceChildren(...own);+ }+ window.google.maps.event.addListenerOnce(google, 'tilesloaded', homeCredit);++ /** Cover the container at every bearing, centred on it. */+ function fit() {+ const width = engine.container.clientWidth;+ const height = engine.container.clientHeight;+ const side = Math.ceil(Math.hypot(width, height));+ turn.style.width = `${side}px`;+ turn.style.height = `${side}px`;+ turn.style.left = `${Math.round((width - side) / 2)}px`;+ turn.style.top = `${Math.round((height - side) / 2)}px`;+ window.google?.maps?.event?.trigger(google, 'resize');+ }++ /** Put Google's camera where ours is. */+ function follow() {+ const at = map.getCenter();+ google.moveCamera({+ center: { lat: at.lat, lng: at.lng },+ zoom: exactViewZoom(map.getZoom()),+ });+ // The app's bearing turns the map clockwise and so does CSS `rotate()`, so+ // this is the app's own number — the engine counts the same turn the other+ // way (see `facade.js`).+ turn.style.transform = `rotate(${-map.getBearing()}deg)`;+ }++ const onResize = () => {+ fit();+ follow();+ };++ let shown = false;++ function hide() {+ if (!shown) return;+ shown = false;+ glass.hidden = true;+ map.off('move', follow);+ map.off('resize', onResize);+ }++ return {+ show() {+ if (shown) return;+ shown = true;+ glass.hidden = false;+ map.on('move', follow);+ map.on('resize', onResize);+ onResize();+ },++ hide,++ destroy() {+ hide();+ glass.remove();+ },+ };+}diff --git a/frontend/src/lib/map/gmaps.test.js b/frontend/src/lib/map/gmaps.test.jsnew file mode 100644index 0000000..11403e1--- /dev/null+++ b/frontend/src/lib/map/gmaps.test.js@@ -0,0 +1,237 @@+// @vitest-environment happy-dom+import { describe, it, expect, afterEach } from 'vitest';++/**+ * Stand in for the Maps JS API: a google.maps.Map that either renders+ * (`tilesloaded`) or gets rejected (`gm_authFailure`), on the next microtask so+ * probeKey has installed its handlers first.+ */+function stubGoogleMaps({ reject = false } = {}) {+ const built = [];+ const once = [];+ window.google = {+ maps: {+ event: {+ addListenerOnce: (map, name, handler) => once.push([map, name, handler]),+ trigger: (map, name) => (map.triggered = name),+ },+ Map: class {+ constructor(node, options) {+ this.node = node;+ this.options = options;+ this.cameras = [];+ this._listeners = {};+ built.push(this);+ queueMicrotask(() => {+ if (reject) window.gm_authFailure?.();+ else this._listeners.tilesloaded?.();+ });+ }+ moveCamera(camera) {+ this.cameras.push(camera);+ }+ addListener(event, cb) {+ this._listeners[event] = cb;+ }+ },+ },+ };+ return { built, once };+}++/** The façade and its map, as far as the glass reaches into them. */+function stubEngine({ zoom = 15, bearing = 0 } = {}) {+ const container = document.createElement('div');+ Object.defineProperty(container, 'clientWidth', { value: 800 });+ Object.defineProperty(container, 'clientHeight', { value: 600 });+ const handlers = {};+ return {+ container,+ handlers,+ impl: {+ getCenter: () => ({ lat: 48.8584, lng: 2.2945 }),+ getZoom: () => zoom,+ getBearing: () => bearing,+ on: (name, handler) => (handlers[name] = handler),+ off: (name) => delete handlers[name],+ },+ };+}++describe('gmaps module', () => {+ afterEach(() => {+ delete window.google;+ delete window.gm_authFailure;+ });++ it('renders Google’s own map under ours, and never takes the pointer', async () => {+ // Google's terms forbid taking those pixels out of its map, so its map is+ // put underneath ours instead of feeding tiles into it+ const { createGoogleGlass } = await import('./gmaps.js');+ const { built } = stubGoogleMaps();+ const engine = stubEngine();+ createGoogleGlass(engine, { maxZoom: 21 });++ const glass = engine.container.querySelector('.map-glass');+ expect(glass).not.toBeNull();+ expect(built).toHaveLength(1); // one billed dynamic map load, and only one+ expect(built[0].node.className).toBe('map-glass-map');+ expect(built[0].options).toMatchObject({+ mapTypeId: 'satellite',+ maxZoom: 21,+ disableDefaultUI: true,+ gestureHandling: 'none',+ isFractionalZoomEnabled: true,+ tilt: 0,+ });+ });++ it('states Google’s credit before any imagery is up, and lets Google’s own take over', async () => {+ const { createGoogleGlass } = await import('./gmaps.js');+ const { built, once } = stubGoogleMaps();+ const engine = stubEngine();+ createGoogleGlass(engine, { attribution: 'Map data © Google' });++ const credit = engine.container.querySelector('.map-glass-credit');+ expect(credit.textContent).toContain('Map data © Google');+ expect(credit.querySelector('a').href).toContain('terms_maps');++ // Google renders its own line inside the map div, which is turned and+ // oversized — so it is moved into this upright holder+ const own = document.createElement('div');+ own.className = 'gm-style-cc';+ own.textContent = 'Map data ©2026 Google';+ built[0].node.append(own);+ const [, name, homeCredit] = once[0];+ expect(name).toBe('tilesloaded');+ homeCredit();+ expect([...credit.children]).toEqual([own]);+ });++ it('keeps the stated credit when Google offers no line to move', async () => {+ // never Google's imagery with no credit at all+ const { createGoogleGlass } = await import('./gmaps.js');+ const { once } = stubGoogleMaps();+ const engine = stubEngine();+ createGoogleGlass(engine, { attribution: 'Map data © Google' });+ once[0][2]();+ expect(engine.container.querySelector('.map-glass-credit').textContent).toContain(+ 'Map data © Google'+ );+ });++ it('covers the container at every bearing, centred on it', async () => {+ // a rotated W×H rectangle always fits inside the circle of its own+ // diagonal, so a square of that diagonal needs no redraw per bearing. If+ // this regresses, rotation still "works" and silently eats the corners.+ const { createGoogleGlass } = await import('./gmaps.js');+ stubGoogleMaps();+ const engine = stubEngine();+ createGoogleGlass(engine).show();++ const turn = engine.container.querySelector('.map-glass-turn');+ const side = Math.ceil(Math.hypot(800, 600)); // 1000+ expect(turn.style.width).toBe(`${side}px`);+ expect(turn.style.height).toBe(`${side}px`);+ expect(turn.style.left).toBe(`${(800 - side) / 2}px`);+ expect(turn.style.top).toBe(`${(600 - side) / 2}px`);+ expect(side).toBeGreaterThanOrEqual(Math.hypot(800, 600));+ });++ it('puts Google’s camera where ours is, between whole levels', async () => {+ // the camera it follows is continuous, and snapping would drift the two+ // maps out of register mid-gesture+ const { createGoogleGlass } = await import('./gmaps.js');+ const { built } = stubGoogleMaps();+ createGoogleGlass(stubEngine({ zoom: 15.4 })).show();+ expect(built[0].cameras.at(-1)).toEqual({+ center: { lat: 48.8584, lng: 2.2945 },+ zoom: 16.4, // the app counts one level deeper than the engine+ });+ });++ it('turns Google’s map the way the app turns ours', async () => {+ // the app's bearing turns the map clockwise and so does CSS rotate(); the+ // engine counts the same turn the other way+ const { createGoogleGlass } = await import('./gmaps.js');+ stubGoogleMaps();+ const engine = stubEngine({ bearing: -90 }); // the app's 90+ createGoogleGlass(engine).show();+ expect(engine.container.querySelector('.map-glass-turn').style.transform).toBe('rotate(90deg)');+ });++ it('follows the camera only while it is showing', async () => {+ const { createGoogleGlass } = await import('./gmaps.js');+ const { built } = stubGoogleMaps();+ const engine = stubEngine();+ const glass = createGoogleGlass(engine);+ expect(engine.container.querySelector('.map-glass').hidden).toBe(true);+ expect(Object.keys(engine.handlers)).toEqual([]);++ glass.show();+ expect(Object.keys(engine.handlers).sort()).toEqual(['move', 'resize']);+ engine.handlers.move();+ const followed = built[0].cameras.length;++ glass.hide();+ expect(engine.container.querySelector('.map-glass').hidden).toBe(true);+ expect(Object.keys(engine.handlers)).toEqual([]);+ expect(built[0].cameras).toHaveLength(followed);+ });++ it('is hidden rather than rebuilt, because rebuilding it is billed', async () => {+ const { createGoogleGlass } = await import('./gmaps.js');+ const { built } = stubGoogleMaps();+ const glass = createGoogleGlass(stubEngine());+ glass.show();+ glass.hide();+ glass.show();+ glass.show();+ expect(built).toHaveLength(1);+ });++ it('takes its own DOM with it when the map goes', async () => {+ const { createGoogleGlass, googleMapsLoadedKey } = await import('./gmaps.js');+ stubGoogleMaps();+ const engine = stubEngine();+ const glass = createGoogleGlass(engine);+ glass.show();+ glass.destroy();+ expect(engine.container.querySelector('.map-glass')).toBeNull();+ expect(Object.keys(engine.handlers)).toEqual([]);+ expect(googleMapsLoadedKey()).toBe(null); // nothing loaded in tests+ });++ describe('probeKey billing', () => {+ afterEach(() => {+ delete window.google;+ delete window.gm_authFailure;+ });++ it('flags the map load it costs when Google accepts the key', async () => {+ // The probe builds a real google.maps.Map, which Google bills as a dynamic+ // map load. It happens in the browser, so the backend tile proxy cannot+ // see it — only this flag makes Settings report it. If it regresses,+ // testing a key silently drifts the counter under Google's real number.+ const { probeKey } = await import('./gmaps.js');+ stubGoogleMaps();++ const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=good');++ expect(verdict.ok).toBe(true);+ expect(verdict.billed).toBe(true);+ });++ it('bills nothing for a key Google rejects', async () => {+ // A rejected key renders no map and has no valid project to bill, so+ // counting it would push the counter above Google's real number.+ const { probeKey } = await import('./gmaps.js');+ stubGoogleMaps({ reject: true });++ const verdict = await probeKey('https://maps.googleapis.com/maps/api/js?key=bad');++ expect(verdict.ok).toBe(false);+ expect(verdict.billed).toBe(false);+ });+ });+});diff --git a/frontend/src/lib/map/surface.js b/frontend/src/lib/map/surface.jsnew file mode 100644index 0000000..c91278c--- /dev/null+++ b/frontend/src/lib/map/surface.js@@ -0,0 +1,698 @@+/**+ * A layer to draw on, declared rather than built.+ *+ * A caller says *what is on the map* — lines, rectangles, dots, marks — as+ * plain data, and the surface renders it. That is the whole point: the engine+ * this app started on had polyline and rectangle objects, MapLibre has GeoJSON+ * sources with style layers and DOM markers, and an API shaped like either+ * one's primitives would have to be written twice. This one is shaped like the+ * question instead.+ *+ * What that costs, and why it is still worth it:+ *+ * - **Shapes carry an id**, because a sweep restyles one cell of a thousand on+ * every keypress and rebuilding the lattice each time is not an option.+ * - **Styles use their own words** (`stroke`, `fill`, `dash`), translated here.+ * The values are the expensive part — a lattice that reads over dark imagery,+ * a flag colour that works for a colour-blind analyst — and they must not be+ * re-picked when the engine changes.+ * - **A mark is HTML at a position**, which both engines can do and neither+ * does the same way.+ *+ * How it is put together, because MapLibre's shape is not the API's:+ *+ * - **One source per surface, three layers over it.** MapLibre paints a whole+ * layer in one pass, so a thousand grid cells cost one draw rather than a+ * thousand nodes — the reason the old engine needed a canvas renderer here is+ * gone with it.+ * - **Style lives in feature properties**, read by data-driven paint+ * expressions. That is what lets one layer paint shapes that do not look+ * alike, and what lets `patch` change one of them without touching the rest.+ * - **A dash is the exception**: MapLibre scales a dash pattern by the line+ * width, so a pattern cannot be read off a feature. Each distinct pattern+ * gets its own thin layer instead, made the first time it appears.+ * - **A circle in metres is a traced ring**, not a scaled dot: it is a claim+ * about the ground, and a pixel radius interpolated over zoom stops being+ * true away from the equator.+ *+ * One surface is one set of layers: `visible(false)` keeps the shapes and hides+ * them, which is what an eye toggle means.+ */+import { Marker, Popup } from 'maplibre-gl';+import { destination } from '../measure.js';++/** Points around a traced ring. Enough that a circle reads as one at any zoom. */+const RING_STEPS = 64;++/** What the old engine painted an unstyled shape with, kept so nothing moved. */+const DEFAULTS = { stroke: '#3388ff', strokeWidth: 3, strokeOpacity: 1, radius: 10 };++let surfaces = 0; // one id prefix per surface, so two of them never collide++/**+ * Neutral style → the properties the paint expressions read.+ *+ * Every value the layers ask for is resolved here rather than defaulted in an+ * expression: `['get', 'strokeOpacity']` on a shape that never mentioned it+ * reads as 0, which paints nothing at all.+ */+export function styleProperties(style = {}) {+ const properties = {+ stroke: style.stroke ?? DEFAULTS.stroke,+ strokeWidth: style.strokeWidth ?? DEFAULTS.strokeWidth,+ strokeOpacity: style.strokeOpacity ?? DEFAULTS.strokeOpacity,+ radius: style.radius ?? DEFAULTS.radius,+ interactive: style.interactive ?? true,+ };+ // An unfilled shape is one the fill layer must not claim, so the key is+ // absent rather than transparent — the layer filters on having it at all.+ if (style.fill != null) {+ properties.fill = style.fill;+ properties.fillOpacity = style.fillOpacity ?? 0.2;+ }+ if (style.dash) properties.dashKey = dashKey(style.dash, properties.strokeWidth);+ return properties;+}++/**+ * The layer a dash belongs to.+ *+ * MapLibre counts a dash in line widths, not pixels, so the same pattern on two+ * different strokes is two different patterns. Callers write pixels, as the old+ * engine took them, and the width is folded in here.+ */+export function dashKey(dash, strokeWidth) {+ return `${String(dash).trim().split(/[\s,]+/).join('-')}@${strokeWidth}`;+}++/** …and the pattern that key stands for, in the units MapLibre wants. */+export function dashArray(key) {+ const [pattern, width] = key.split('@');+ return pattern.split('-').map((length) => Number(length) / Number(width));+}++/** A ring on the ground, `metres` from `at` all the way round. */+export function metreRing(at, metres) {+ const ring = [];+ for (let step = 0; step <= RING_STEPS; step += 1) {+ const point = destination(at, (360 * step) / RING_STEPS, metres);+ ring.push([point.lon, point.lat]);+ }+ return { type: 'Polygon', coordinates: [ring] };+}++function line(points) {+ return { type: 'LineString', coordinates: points.map((point) => [point.lon, point.lat]) };+}++function ring(points) {+ const coordinates = points.map((point) => [point.lon, point.lat]);+ const [first] = coordinates;+ const last = coordinates.at(-1);+ if (first && last && (first[0] !== last[0] || first[1] !== last[1])) coordinates.push(first);+ return { type: 'Polygon', coordinates: [coordinates] };+}++function box({ north, south, east, west }) {+ return {+ type: 'Polygon',+ coordinates: [+ [+ [west, south],+ [east, south],+ [east, north],+ [west, north],+ [west, south],+ ],+ ],+ };+}++/** The geometry one declared shape draws as, or null if it draws no geometry. */+export function shapeGeometry(shape) {+ switch (shape.kind) {+ case 'line':+ return line(shape.points);+ case 'polygon':+ return ring(shape.points);+ case 'rect':+ return box(shape.bounds);+ case 'dot':+ return { type: 'Point', coordinates: [shape.at.lon, shape.at.lat] };+ case 'circle':+ return metreRing(shape.at, shape.radiusM);+ case 'geojson':+ return shape.geometry;+ default:+ throw new Error(`unknown shape: ${shape.kind}`);+ }+}++/**+ * @param {object} engine the façade from `engine.js`+ * @param {object} [opts]+ * @param {(id: any) => void} [opts.onPopupOpen] a card was opened on a mark+ * @param {(id: any) => void} [opts.onPopupClose] …and closed again+ */+export function createSurface(engine, { onPopupOpen, onPopupClose } = {}) {+ const map = engine.impl;+ const prefix = `sfc-${++surfaces}`;+ const SOURCE = `${prefix}-shapes`;+ const FILL = `${prefix}-fill`;+ const LINE = `${prefix}-line`;+ const DOT = `${prefix}-dot`;++ let features = []; // the collection currently in the source+ let byShape = new Map(); // shape id → feature id+ let shapes = new Map(); // shape id → the shape as declared, for its handlers+ let marks = new Map(); // shape id → { marker, shape }+ let dashLayers = new Map(); // dash key → layer id+ let nextFeature = 1;+ let shown = true;+ let built = false;+ let openOn = null; // the mark whose card is up, so it can be closed by name+ let card = null; // the open card itself+ let tip = null; // the shared hover reading+ let tipAnchor; // the side it hangs on, which is the one thing it is rebuilt for+ let pointing = false; // this surface is the one holding the pointer cursor+ let releaseClicks = null;+ let answering = false; // something on this surface answers a click+ const listeners = []; // [type, layerId, handler] to unbind on destroy++ function paintLayers() {+ return [FILL, ...dashLayers.values(), LINE, DOT];+ }++ /**+ * Drawn shapes sit above the basemap and its labels, which is simply where+ * they land: `basemap.js` inserts below the first layer it does not own, and+ * these are appended.+ */+ function build() {+ if (built) return;+ built = true;+ map.addSource(SOURCE, {+ type: 'geojson',+ data: { type: 'FeatureCollection', features: [] },+ });+ map.addLayer({+ id: FILL,+ type: 'fill',+ source: SOURCE,+ filter: ['has', 'fill'],+ paint: {+ 'fill-color': ['to-color', ['get', 'fill']],+ 'fill-opacity': ['to-number', ['get', 'fillOpacity']],+ },+ });+ map.addLayer({+ id: LINE,+ type: 'line',+ source: SOURCE,+ // a dashed stroke is painted by its own layer, below+ filter: ['all', ['has', 'stroke'], ['!', ['has', 'dashKey']]],+ layout: { 'line-cap': 'round', 'line-join': 'round' },+ paint: lineStroke(),+ });+ map.addLayer({+ id: DOT,+ type: 'circle',+ source: SOURCE,+ // Only a dot, and a dot is the one thing drawn as a bare point. Without+ // the guard this layer would put a circle on *every vertex* of every line+ // and polygon in the surface, which is what a circle layer does.+ filter: ['==', ['geometry-type'], 'Point'],+ paint: {+ 'circle-radius': ['to-number', ['get', 'radius']],+ // a dot with no fill of its own is filled with its own stroke colour,+ // as the engine we came from filled it — and `fillOpacity` is then 0,+ // so it stays an outline+ 'circle-color': ['to-color', ['coalesce', ['get', 'fill'], ['get', 'stroke']]],+ 'circle-opacity': ['to-number', ['get', 'fillOpacity']],+ 'circle-stroke-color': ['to-color', ['get', 'stroke']],+ 'circle-stroke-width': ['to-number', ['get', 'strokeWidth']],+ 'circle-stroke-opacity': ['to-number', ['get', 'strokeOpacity']],+ },+ });+ if (!shown) applyVisibility();+ }++ function lineStroke() {+ return {+ 'line-color': ['to-color', ['get', 'stroke']],+ 'line-width': ['to-number', ['get', 'strokeWidth']],+ 'line-opacity': ['to-number', ['get', 'strokeOpacity']],+ };+ }++ function dashLayer(key) {+ const existing = dashLayers.get(key);+ if (existing) return existing;+ const id = `${prefix}-dash-${dashLayers.size}`;+ dashLayers.set(key, id);+ map.addLayer(+ {+ id,+ type: 'line',+ source: SOURCE,+ filter: ['==', ['get', 'dashKey'], key],+ layout: { 'line-cap': 'butt', 'line-join': 'round' },+ paint: { ...lineStroke(), 'line-dasharray': dashArray(key) },+ },+ // under the solid strokes, as the old engine drew them: a dashed hint+ // never covers a line that means something+ map.getLayer(LINE) ? LINE : undefined+ );+ if (!shown) map.setLayoutProperty(id, 'visibility', 'none');+ return id;+ }++ function source() {+ return map.getSource(SOURCE);+ }++ function push() {+ source()?.setData({ type: 'FeatureCollection', features });+ }++ // --- marks -----------------------------------------------------------------++ /**+ * Where the element's centre goes, so that the point the caller named sits on+ * the coordinate. Callers give a size and the pixel inside it that is "the+ * spot" (a pin's tip, a glyph's middle), which is how the old engine took it.+ */+ function markOffset(shape) {+ const [width, height] = shape.size ?? [0, 0];+ const [x, y] = shape.anchor ?? [width / 2, height / 2];+ return [width / 2 - x, height / 2 - y];+ }++ /**+ * The caller's glyph on a mark's element, swappable.+ *+ * Only the classes the caller named are exchanged: the engine puts its own on+ * this element — the ones that position it at all — and replacing the whole+ * `className` on a restyle would drop the mark to the corner of the map.+ */+ function dressMark(element, shape) {+ const previous = element.dataset.markClass;+ if (previous) element.classList.remove(...previous.split(' '));+ const named = (shape.className ?? '').trim();+ if (named) element.classList.add(...named.split(/\s+/));+ element.dataset.markClass = named;+ element.innerHTML = shape.html ?? '';+ element.style.width = shape.size ? `${shape.size[0]}px` : '';+ element.style.height = shape.size ? `${shape.size[1]}px` : '';+ return element;+ }++ function buildMark(shape) {+ const element = dressMark(document.createElement('div'), shape);+ if (shape.title) element.title = shape.title;+ if (shape.zIndex) element.style.zIndex = String(shape.zIndex);+ // The engine leaves a custom element's focusability to us. A mark that+ // opens a card is a control and takes the keyboard; a drag handle or a+ // hundred pins in a stack are not, and would only lengthen the tab order.+ if (shape.keyboard !== false && (shape.popup || shape.onClick)) {+ element.tabIndex = 0;+ element.setAttribute('role', 'button');+ }+ const marker = new Marker({+ element,+ anchor: 'center',+ offset: markOffset(shape),+ draggable: !!shape.draggable,+ })+ .setLngLat([shape.at.lon, shape.at.lat])+ .addTo(map);++ if (shape.popup || shape.onClick) {+ // The mark answers its own click; the map's handler — which drops a+ // polygon vertex or plants the sky anchor — must not fire behind it.+ element.addEventListener('click', (event) => {+ event.stopPropagation();+ shape.onClick?.(shape.id);+ // the same mark pressed again puts its card away, which is what a card+ // on a mark does everywhere — and the stopped click cannot do it+ if (!shape.popup) return;+ if (openOn === shape.id) closeCard();+ else openCard(shape, marker);+ });+ element.addEventListener('keydown', (event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ element.click();+ });+ }+ if (shape.onContextMenu) {+ element.addEventListener('contextmenu', (event) => {+ event.preventDefault();+ event.stopPropagation();+ shape.onContextMenu(shape.id);+ });+ }+ if (shape.onOver) element.addEventListener('mouseenter', () => shape.onOver(shape.id));+ if (shape.onOut) element.addEventListener('mouseleave', () => shape.onOut(shape.id));+ if (shape.tip) {+ element.addEventListener('mouseenter', () => showTip(shape.tip, shape.at));+ element.addEventListener('mouseleave', hideTip);+ }+ if (shape.onDragStart) marker.on('dragstart', () => shape.onDragStart(shape.id));+ if (shape.onDrag) {+ marker.on('drag', () => {+ const at = marker.getLngLat();+ shape.onDrag({ lat: at.lat, lon: at.lng }, shape.id);+ });+ }+ if (shape.onDragEnd) marker.on('dragend', () => shape.onDragEnd(shape.id));+ if (!shown) element.style.display = 'none';+ return marker;+ }++ // --- the card a mark opens -------------------------------------------------++ /**+ * The content is built when the card opens, not when the mark is drawn: a+ * layer of two hundred marks must not mount two hundred cards nobody asked+ * for. The engine's own marker-popup binding would build it up front, so the+ * card is opened here instead.+ */+ function openCard(shape, marker) {+ closeCard();+ const popup = new Popup({+ className: shape.popup.className,+ maxWidth: shape.popup.maxWidth == null ? 'none' : `${shape.popup.maxWidth}px`,+ closeOnClick: true,+ focusAfterOpen: false,+ });+ popup.setLngLat(marker.getLngLat());+ popup.setDOMContent(shape.popup.content());+ popup.on('close', () => {+ if (card !== popup) return;+ card = null;+ openOn = null;+ onPopupClose?.(shape.id);+ });+ popup.addTo(map);+ if (shape.popup.minWidth != null) {+ popup.getElement()?.style.setProperty('--popup-min-width', `${shape.popup.minWidth}px`);+ }+ card = popup;+ openOn = shape.id;+ onPopupOpen?.(shape.id);+ }++ function closeCard() {+ card?.remove();+ card = null;+ openOn = null;+ }++ // --- the reading a shape gives under the cursor ----------------------------++ /**+ * One reading is up at a time, and it is rebuilt only when the side it hangs+ * on changes: a path's reading follows the cursor, so this runs on every+ * mousemove over it.+ */+ function showTip(declared, at, lngLat) {+ const { text, sticky = false, direction, offset } = typeof declared === 'string'+ ? { text: declared }+ : declared;+ // 'top' is where the reading goes; a card's anchor names the side of it+ // nearest the point, so the two are opposites+ const anchor = direction === 'top' ? 'bottom' : undefined;+ if (!tip || tipAnchor !== anchor) {+ tip?.remove();+ tipAnchor = anchor;+ tip = new Popup({+ anchor,+ className: 'map-tip',+ closeButton: false,+ closeOnClick: false,+ focusAfterOpen: false,+ maxWidth: 'none',+ });+ }+ tip.setText(text);+ tip.setOffset(offset ?? 0);+ if (sticky) tip.trackPointer();+ else tip.setLngLat(lngLat ?? [at.lon, at.lat]);+ if (!tip.isOpen()) tip.addTo(map);+ }++ function hideTip() {+ tip?.remove();+ }++ // --- what a painted shape answers -----------------------------------------++ function shapeOf(feature) {+ return shapes.get(feature?.properties?.sid);+ }++ function usable(feature) {+ return feature?.properties?.interactive !== false;+ }++ /**+ * One handler across all of this surface's layers, not one per layer.+ *+ * A shape is in as many layers as it has paint — an outlined, filled cell is+ * in two — and a listener per layer would answer the same click twice, which+ * on a search grid means cycling a cell straight past the mark that was+ * meant. Rebound after every `set`, because a new dash pattern is a new layer+ * and a reading on a dashed ray still has to be heard.+ */+ function rebindHandlers() {+ for (const [type, layers, handler] of listeners) map.off(type, layers, handler);+ listeners.length = 0;+ const layers = paintLayers().filter((id) => map.getLayer(id));+ if (!layers.length) return;+ const bind = (type, handler) => {+ map.on(type, layers, handler);+ listeners.push([type, layers, handler]);+ };+ const hit = (event) => shapeOf(event.features?.find(usable));+ bind('click', (event) => {+ const shape = hit(event);+ if (shape?.onClick) shape.onClick(shape.id);+ });+ bind('contextmenu', (event) => {+ const shape = hit(event);+ if (shape?.onContextMenu) shape.onContextMenu(shape.id);+ });+ bind('mousemove', (event) => {+ const shape = hit(event);+ if (shape?.tip) showTip(shape.tip, null, event.lngLat);+ // a shape that answers a click says so, as the old engine's paths did+ if (shape?.onClick && !pointing) {+ pointing = true;+ map.getCanvas().style.cursor = 'pointer';+ }+ });+ bind('mouseleave', () => {+ hideTip();+ // only what this surface set, so leaving one shape does not clear the+ // cursor another surface is holding+ if (pointing) {+ pointing = false;+ map.getCanvas().style.cursor = '';+ }+ });+ }++ function applyVisibility() {+ for (const layer of paintLayers()) {+ if (map.getLayer(layer)) {+ map.setLayoutProperty(layer, 'visibility', shown ? 'visible' : 'none');+ }+ }+ for (const { marker } of marks.values()) {+ marker.getElement().style.display = shown ? '' : 'none';+ }+ }++ function dropMarks() {+ for (const { marker } of marks.values()) marker.remove();+ marks = new Map();+ }++ /**+ * Only a surface whose shapes answer clicks holds the map's own handler back,+ * and only over the shapes that actually answer. Re-made whenever the layer+ * list changes, since the claim is a list of names.+ */+ function refreshClaim() {+ releaseClicks?.();+ releaseClicks = answering+ ? engine.claimClicks(paintLayers(), ['!=', ['get', 'interactive'], false])+ : null;+ }++ return {+ /** Replace everything on this layer. */+ set(declared) {+ build();+ dropMarks();+ closeCard();+ hideTip();+ features = [];+ byShape = new Map();+ shapes = new Map();+ answering = false;+ let anonymous = 0;+ for (const shape of declared ?? []) {+ if (!shape) continue;+ // a shape with no id of its own still needs one: the source is keyed by+ // feature id, and `patch` is the only thing that ever asks for a name+ const id = shape.id ?? `anon-${anonymous++}`;+ shapes.set(id, shape);+ answering ||= !!(shape.onClick || shape.onContextMenu);+ if (shape.kind === 'marker') {+ marks.set(id, { marker: buildMark({ ...shape, id }), shape });+ continue;+ }+ const feature = nextFeature++;+ const properties = styleProperties(shape.style);+ // a pattern needs the layer that paints it before the feature asking+ // for it lands, or the shape is in no line layer at all and vanishes+ if (properties.dashKey) dashLayer(properties.dashKey);+ byShape.set(id, feature);+ features.push({+ type: 'Feature',+ id: feature,+ geometry: shapeGeometry(shape),+ properties: { ...properties, sid: id },+ });+ }+ push();+ rebindHandlers();+ refreshClaim();+ },++ /**+ * Change one shape without touching the others: a new style, a new outline+ * while a handle is dragged, a mark's own glyph. `icon` takes the same+ * `html`/`className`/`size`/`anchor` a mark was declared with.+ */+ patch(id, patch) {+ const mark = marks.get(id);+ if (mark) {+ if (patch.icon) {+ dressMark(mark.marker.getElement(), patch.icon);+ mark.marker.setOffset(markOffset(patch.icon));+ }+ if (patch.at) mark.marker.setLngLat([patch.at.lon, patch.at.lat]);+ return true;+ }+ const feature = byShape.get(id);+ if (feature == null) return false;+ const shape = shapes.get(id);+ const diff = { id: feature };+ if (patch.style) {+ const properties = styleProperties(patch.style);+ // a fill or a dash that was set and is now gone has to leave the+ // feature, or its layer keeps painting the shape+ diff.removeProperties = ['fill', 'fillOpacity', 'dashKey'].filter(+ (key) => !(key in properties)+ );+ diff.addOrUpdateProperties = Object.entries(properties).map(([key, value]) => ({+ key,+ value,+ }));+ if (properties.dashKey) {+ const before = dashLayers.size;+ dashLayer(properties.dashKey);+ // a pattern seen for the first time is a new layer, and both the+ // handlers and the click claim are lists of layer names+ if (dashLayers.size !== before) {+ rebindHandlers();+ refreshClaim();+ }+ }+ }+ const moved = patch.points+ ? { ...shape, points: patch.points }+ : patch.bounds+ ? { ...shape, bounds: patch.bounds }+ : patch.at+ ? { ...shape, at: patch.at }+ : null;+ if (moved) diff.newGeometry = shapeGeometry(moved);+ source()?.updateData({ update: [diff] });+ // keep the declared shape current, so a later move starts from this one+ if (moved) shapes.set(id, moved);+ return true;+ },++ /** Is this shape on the layer? */+ has(id) {+ return byShape.has(id) || marks.has(id);+ },++ /**+ * A mark's own element, for a class the CSS paints — the hover that ties a+ * row in the panel to its pin on the map. Undefined for a painted shape,+ * which has no element of its own to light up.+ */+ element(id) {+ return marks.get(id)?.marker.getElement();+ },++ /** Close the open card, wherever it is. */+ closePopup() {+ if (openOn != null) closeCard();+ },++ clear() {+ dropMarks();+ closeCard();+ hideTip();+ features = [];+ byShape = new Map();+ shapes = new Map();+ answering = false;+ push();+ refreshClaim();+ },++ /** Keep the shapes, take them off the map (or put them back). */+ visible(on) {+ shown = on;+ if (!built) return;+ applyVisibility();+ if (!on) {+ closeCard();+ hideTip();+ }+ },++ destroy() {+ dropMarks();+ closeCard();+ tip?.remove();+ tip = null;+ answering = false;+ refreshClaim();+ for (const [type, layers, handler] of listeners) map.off(type, layers, handler);+ listeners.length = 0;+ // Each of these is asked for before it is taken away, because the map+ // itself may already be gone: a tool tearing down destroys its own+ // surfaces before its map, but an overlay component's cleanup runs when+ // Svelte unmounts it, which is not ordered against either.+ if (built) {+ for (const layer of paintLayers()) {+ if (map.getLayer(layer)) map.removeLayer(layer);+ }+ if (map.getSource(SOURCE)) map.removeSource(SOURCE);+ }+ dashLayers = new Map();+ byShape = new Map();+ shapes = new Map();+ features = [];+ built = false;+ },+ };+}diff --git a/frontend/src/lib/map/surface.test.js b/frontend/src/lib/map/surface.test.jsnew file mode 100644index 0000000..fd1d293--- /dev/null+++ b/frontend/src/lib/map/surface.test.js@@ -0,0 +1,788 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { dashArray, dashKey, metreRing, shapeGeometry, styleProperties } from './surface.js';++/**+ * The surface is exercised against a stubbed map, because what it must get+ * right is the *translation*: which style words become which properties, which+ * shape kind becomes which geometry, and — the reason the module exists — that+ * changing one shape of a thousand does not rebuild the other 999.+ *+ * The geometry and the style translation are pure, so those are read straight+ * off the functions; the rest is read off the calls a stubbed map recorded.+ */++describe('styles keep their own words', () => {+ it('translates them into the properties the paint expressions read', () => {+ expect(+ styleProperties({ stroke: '#fff', strokeWidth: 2.5, strokeOpacity: 0.9 })+ ).toMatchObject({ stroke: '#fff', strokeWidth: 2.5, strokeOpacity: 0.9 });+ });++ it('resolves every value the layers ask for', () => {+ // `['get', 'strokeOpacity']` on a shape that never mentioned it reads as 0,+ // which paints nothing at all — so nothing is left to an expression default+ const properties = styleProperties({ stroke: '#fff' });+ expect(properties.strokeWidth).toBe(3);+ expect(properties.strokeOpacity).toBe(1);+ expect(properties.radius).toBe(10);+ expect(properties.interactive).toBe(true);+ });++ it('reads a fill colour as "there is a fill", and its absence as none', () => {+ expect(styleProperties({ fill: '#2b3040', fillOpacity: 0.62 })).toMatchObject({+ fill: '#2b3040',+ fillOpacity: 0.62,+ });+ // the fill layer filters on having the key at all, so an unfilled shape+ // must not carry a transparent one+ expect(styleProperties({ stroke: '#fff' })).not.toHaveProperty('fill');+ expect(styleProperties({ stroke: '#fff' })).not.toHaveProperty('fillOpacity');+ });++ it('keeps a transparent fill, which is not the same as no fill', () => {+ // an unchecked grid cell is a bright outline over nothing: a fill at zero+ // opacity, so the imagery reads through and the cell still answers a click+ expect(styleProperties({ fill: '#fff', fillOpacity: 0 })).toMatchObject({+ fill: '#fff',+ fillOpacity: 0,+ });+ });++ it('lets a shape refuse the pointer', () => {+ expect(styleProperties({ interactive: false }).interactive).toBe(false);+ });++ it('leaves a shape with no dash out of every dashed layer', () => {+ expect(styleProperties({ stroke: '#fff' })).not.toHaveProperty('dashKey');+ expect(styleProperties({ stroke: '#fff', dash: null })).not.toHaveProperty('dashKey');+ });+});++describe('a dash pattern', () => {+ it('carries the stroke width, because the engine scales it by that', () => {+ // callers write pixels, as the old engine took them+ expect(dashKey('6 6', 3.5)).toBe('[email protected]');+ expect(dashKey('5,4', 1.5)).toBe('[email protected]');+ });++ it('comes back in the units the engine wants', () => {+ // 6 px of dash on a 3.5 px stroke is 1.714 stroke widths+ expect(dashArray('[email protected]')).toEqual([6 / 3.5, 6 / 3.5]);+ expect(dashArray('[email protected]')).toEqual([5 / 1.5, 4 / 1.5]);+ });+});++describe('shapes become geometry', () => {+ it('writes a line as its points, longitude first', () => {+ expect(+ shapeGeometry({ kind: 'line', points: [{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }] })+ ).toEqual({ type: 'LineString', coordinates: [[2, 1], [4, 3]] });+ });++ it('closes a polygon the caller left open', () => {+ const ring = shapeGeometry({+ kind: 'polygon',+ points: [{ lat: 0, lon: 0 }, { lat: 1, lon: 0 }, { lat: 1, lon: 1 }],+ });+ expect(ring.coordinates[0]).toEqual([[0, 0], [0, 1], [1, 1], [0, 0]]);+ });++ it('writes an extent as its four corners', () => {+ expect(shapeGeometry({ kind: 'rect', bounds: { north: 4, south: 1, east: 8, west: 2 } })).toEqual(+ {+ type: 'Polygon',+ coordinates: [[[2, 1], [8, 1], [8, 4], [2, 4], [2, 1]]],+ }+ );+ });++ it('tells a pixel dot from a radius on the ground', () => {+ expect(shapeGeometry({ kind: 'dot', at: { lat: 1, lon: 2 } })).toEqual({+ type: 'Point',+ coordinates: [2, 1],+ });+ // a circle in metres is a claim about the ground, so it is traced on it+ const circle = shapeGeometry({ kind: 'circle', at: { lat: 48.85, lon: 2.29 }, radiusM: 500 });+ expect(circle.type).toBe('Polygon');+ expect(circle.coordinates[0]).toHaveLength(65);+ expect(circle.coordinates[0][0]).toEqual(circle.coordinates[0].at(-1));+ });++ it('traces a ring that really is that far away', () => {+ const [, north] = metreRing({ lat: 0, lon: 0 }, 1000).coordinates[0][0];+ // 1 km north of the equator is about 0.009°+ expect(north).toBeCloseTo(0.009, 3);+ });++ it('passes a footprint through as the geometry it already is', () => {+ const geometry = { type: 'MultiPolygon', coordinates: [[[[0, 0], [1, 0], [1, 1], [0, 0]]]] };+ expect(shapeGeometry({ kind: 'geojson', geometry })).toBe(geometry);+ });++ it('refuses a shape it does not know, rather than drawing nothing', () => {+ expect(() => shapeGeometry({ kind: 'blob' })).toThrow(/unknown shape/);+ });+});++// --- the stateful half -------------------------------------------------------++let createSurface;+let marks;+let cards;++/** A Marker/Popup pair that records what was asked of it. */+function stubClasses() {+ marks = [];+ cards = [];+ class Marker {+ constructor(options) {+ this.options = options;+ this.element = options.element;+ this.handlers = {};+ this.lngLat = null;+ this.offset = options.offset;+ this.removed = 0;+ marks.push(this);+ }+ setLngLat(at) {+ this.lngLat = at;+ return this;+ }+ getLngLat() {+ return { lat: this.lngLat[1], lng: this.lngLat[0] };+ }+ getElement() {+ return this.element;+ }+ setOffset(offset) {+ this.offset = offset;+ return this;+ }+ addTo() {+ this.added = true;+ return this;+ }+ on(name, handler) {+ this.handlers[name] = handler;+ return this;+ }+ remove() {+ this.removed += 1;+ return this;+ }+ }+ class Popup {+ constructor(options) {+ this.options = options;+ this.handlers = {};+ this.open = false;+ this.node = null;+ this.element = document.createElement('div');+ cards.push(this);+ }+ setLngLat(at) {+ this.lngLat = at;+ this.tracking = false;+ return this;+ }+ setDOMContent(node) {+ this.node = node;+ return this;+ }+ setText(text) {+ this.text = text;+ return this;+ }+ setOffset(offset) {+ this.offset = offset;+ return this;+ }+ trackPointer() {+ this.tracking = true;+ return this;+ }+ getElement() {+ return this.element;+ }+ isOpen() {+ return this.open;+ }+ on(name, handler) {+ this.handlers[name] = handler;+ return this;+ }+ addTo() {+ this.open = true;+ return this;+ }+ remove() {+ if (this.open) this.handlers.close?.();+ this.open = false;+ return this;+ }+ }+ return { Marker, Popup };+}++beforeEach(async () => {+ vi.resetModules();+ vi.doMock('maplibre-gl', () => stubClasses());+ ({ createSurface } = await import('./surface.js'));+});++afterEach(() => {+ vi.doUnmock('maplibre-gl');+ vi.resetModules();+});++/** A MapLibre map, as far as surface.js reaches into it. */+function stubMap() {+ const layers = [];+ const sources = new Map();+ const calls = { setData: [], updateData: [], on: [], off: [], visibility: [] };+ return {+ calls,+ layers,+ addSource: (id) =>+ sources.set(id, {+ setData: (data) => calls.setData.push([id, data]),+ updateData: (diff) => calls.updateData.push([id, diff]),+ }),+ getSource: (id) => sources.get(id),+ removeSource: (id) => sources.delete(id),+ addLayer: (layer, beforeId) => {+ const at = beforeId ? layers.findIndex((l) => l.id === beforeId) : -1;+ if (at === -1) layers.push(layer);+ else layers.splice(at, 0, layer);+ },+ getLayer: (id) => layers.find((l) => l.id === id),+ removeLayer: (id) => {+ const at = layers.findIndex((l) => l.id === id);+ if (at !== -1) layers.splice(at, 1);+ },+ getStyle: () => ({ layers }),+ setLayoutProperty: (id, key, value) => calls.visibility.push([id, key, value]),+ getCanvas: () => ({ style: {} }),+ on: (...args) => calls.on.push(args),+ off: (...args) => calls.off.push(args),+ };+}++function stubEngine(map = stubMap()) {+ const claims = [];+ return {+ impl: map,+ claims,+ claimClicks: (layers, filter) => {+ const claim = { layers, filter };+ claims.push(claim);+ return () => claims.splice(claims.indexOf(claim), 1);+ },+ };+}++/** The features the surface last pushed. */+const pushed = (map) => map.calls.setData.at(-1)[1].features;++const CELL = (id, north) => ({+ id,+ kind: 'rect',+ bounds: { north, south: north - 1, east: 1, west: 0 },+ style: { stroke: '#fff', fill: '#fff', fillOpacity: 0 },+});++describe('what the surface puts on the map', () => {+ it('builds one source and one layer per kind of paint', () => {+ const map = stubMap();+ createSurface(stubEngine(map)).set([CELL('a', 1)]);+ expect(map.layers.map((l) => l.type)).toEqual(['fill', 'line', 'circle']);+ expect(map.layers.every((l) => l.source.endsWith('-shapes'))).toBe(true);+ });++ it('paints a filled outline from both the fill and the line layer', () => {+ const map = stubMap();+ createSurface(stubEngine(map)).set([CELL('a', 1)]);+ const [fill, line] = map.layers;+ expect(fill.filter).toEqual(['has', 'fill']);+ expect(line.filter).toEqual(['all', ['has', 'stroke'], ['!', ['has', 'dashKey']]]);+ });++ it('keeps the circle layer to real points', () => {+ // a circle layer paints one on *every vertex* of every line and polygon+ const map = stubMap();+ createSurface(stubEngine(map)).set([CELL('a', 1)]);+ expect(map.layers.at(-1).filter).toEqual(['==', ['geometry-type'], 'Point']);+ });++ it('makes a layer for each dash pattern it is handed, once', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set([+ { id: 'ray', kind: 'line', points: [{ lat: 1, lon: 2 }], style: { strokeWidth: 3.5, dash: '6 6' } },+ { id: 'ring', kind: 'line', points: [{ lat: 1, lon: 2 }], style: { strokeWidth: 3.5, dash: '6 6' } },+ ]);+ const dashed = map.layers.filter((l) => l.paint?.['line-dasharray']);+ expect(dashed).toHaveLength(1);+ expect(dashed[0].paint['line-dasharray']).toEqual([6 / 3.5, 6 / 3.5]);+ // and the dashed stroke goes under the solid ones, as it was drawn before+ expect(map.layers.map((l) => l.type)).toEqual(['fill', 'line', 'line', 'circle']);+ });++ it('skips a hole in the shape list', () => {+ // a path that is not drawn yet is a null in the array, not a branch at+ // every call site+ const map = stubMap();+ createSurface(stubEngine(map)).set([null, CELL('a', 1)]);+ expect(pushed(map)).toHaveLength(1);+ });++ it('names every feature, so one can be changed without the rest', () => {+ const map = stubMap();+ createSurface(stubEngine(map)).set([CELL('a', 1), { kind: 'dot', at: { lat: 1, lon: 2 } }]);+ const features = pushed(map);+ expect(features.map((f) => f.properties.sid)).toEqual(['a', 'anon-0']);+ expect(features.every((f) => Number.isInteger(f.id))).toBe(true);+ });+});++describe('a mark is HTML at a position', () => {+ const MARK = {+ id: 'sky',+ kind: 'marker',+ at: { lat: 1, lon: 2 },+ html: '<i class="glyph"></i>',+ className: 'sky-body',+ size: [20, 20],+ anchor: [10, 10],+ keyboard: false,+ };++ it('puts the caller’s glyph on it, at the coordinate they named', () => {+ createSurface(stubEngine()).set([MARK]);+ const mark = marks[0];+ expect(mark.lngLat).toEqual([2, 1]);+ expect(mark.element.className).toContain('sky-body');+ expect(mark.element.innerHTML).toBe('<i class="glyph"></i>');+ expect(mark.element.style.width).toBe('20px');+ });++ it('sits the anchor the caller named on the coordinate', () => {+ const surface = createSurface(stubEngine());+ // a pin's tip is the bottom middle of its box+ surface.set([{ ...MARK, size: [24, 32], anchor: [12, 32] }]);+ expect(marks[0].offset).toEqual([0, -16]);+ surface.set([MARK]);+ expect(marks.at(-1).offset).toEqual([0, 0]);+ });++ it('takes the keyboard only when it is a control', () => {+ const surface = createSurface(stubEngine());+ surface.set([{ ...MARK, keyboard: false, onClick: () => {} }]);+ expect(marks.at(-1).element.tabIndex).toBe(-1);+ surface.set([{ ...MARK, keyboard: true, onClick: () => {} }]);+ expect(marks.at(-1).element.tabIndex).toBe(0);+ expect(marks.at(-1).element.getAttribute('role')).toBe('button');+ // a mark that answers nothing is not a control, whatever it says+ surface.set([{ ...MARK, keyboard: true }]);+ expect(marks.at(-1).element.tabIndex).toBe(-1);+ });++ it('keeps a mark’s click off the map underneath', () => {+ // a mark opens its card; the map's click handler drops a polygon vertex or+ // plants the sky anchor, and must not fire behind it+ const onClick = vi.fn();+ createSurface(stubEngine()).set([{ ...MARK, onClick }]);+ const event = new window.MouseEvent('click', { bubbles: true });+ const stopped = vi.spyOn(event, 'stopPropagation');+ marks[0].element.dispatchEvent(event);+ expect(stopped).toHaveBeenCalled();+ expect(onClick).toHaveBeenCalledWith('sky');+ });++ it('hands a drag the position in the app’s own terms', () => {+ const onDrag = vi.fn();+ const onDragStart = vi.fn();+ const onDragEnd = vi.fn();+ createSurface(stubEngine()).set([+ { id: 'sw', kind: 'marker', at: { lat: 1, lon: 2 }, draggable: true, onDrag, onDragStart, onDragEnd },+ ]);+ const mark = marks[0];+ expect(mark.options.draggable).toBe(true);+ mark.lngLat = [8, 9];+ mark.handlers.dragstart();+ mark.handlers.drag();+ mark.handlers.dragend();+ expect(onDragStart).toHaveBeenCalledWith('sw');+ expect(onDrag).toHaveBeenCalledWith({ lat: 9, lon: 8 }, 'sw');+ expect(onDragEnd).toHaveBeenCalledWith('sw');+ });++ it('says when the pointer arrives and leaves', () => {+ const onOver = vi.fn();+ const onOut = vi.fn();+ createSurface(stubEngine()).set([{ ...MARK, onOver, onOut }]);+ marks[0].element.dispatchEvent(new window.MouseEvent('mouseenter'));+ marks[0].element.dispatchEvent(new window.MouseEvent('mouseleave'));+ expect(onOver).toHaveBeenCalledWith('sky');+ expect(onOut).toHaveBeenCalledWith('sky');+ });++ it('hands out a mark’s own element, for the hover the panel shares', () => {+ const surface = createSurface(stubEngine());+ surface.set([MARK]);+ expect(surface.element('sky')).toBe(marks[0].element);+ expect(surface.element('nope')).toBeUndefined();+ });+});++describe('changing one shape', () => {+ const cells = [CELL('a', 1), CELL('b', 2)];++ it('restyles it without rebuilding the others', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set(cells);+ const pushes = map.calls.setData.length;+ expect(surface.patch('b', { style: { stroke: '#33c9ff', strokeWidth: 2.5 } })).toBe(true);+ expect(map.calls.setData).toHaveLength(pushes); // nothing was redrawn+ const [source, { update }] = map.calls.updateData.at(-1);+ expect(source).toBe(map.layers[0].source);+ expect(update).toHaveLength(1);+ expect(update[0].id).toBe(pushed(map)[1].id);+ expect(update[0].addOrUpdateProperties).toEqual(+ expect.arrayContaining([+ { key: 'stroke', value: '#33c9ff' },+ { key: 'strokeWidth', value: 2.5 },+ ])+ );+ });++ it('takes a fill off the feature when the new style has none', () => {+ // the fill layer filters on the key, so a leftover one keeps painting+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set(cells);+ surface.patch('a', { style: { stroke: '#fff' } });+ expect(map.calls.updateData.at(-1)[1].update[0].removeProperties).toEqual([+ 'fill',+ 'fillOpacity',+ 'dashKey',+ ]);+ });++ it('makes the layer a newly dashed shape needs', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set(cells);+ surface.patch('a', { style: { stroke: '#fff', strokeWidth: 2, dash: '4 4' } });+ expect(map.layers.filter((l) => l.paint?.['line-dasharray'])).toHaveLength(1);+ });++ it('moves an outline while a handle is dragged', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ const moved = () => map.calls.updateData.at(-1)[1].update[0].newGeometry;+ surface.set([+ { id: 'ring', kind: 'polygon', points: [{ lat: 1, lon: 2 }] },+ { id: 'box', kind: 'rect', bounds: { north: 1, south: 0, east: 1, west: 0 } },+ { id: 'here', kind: 'dot', at: { lat: 1, lon: 2 } },+ ]);+ // the field a kind moves by is the kind's own: vertices, an extent, a point+ surface.patch('ring', { points: [{ lat: 3, lon: 4 }, { lat: 5, lon: 6 }] });+ expect(moved().coordinates[0]).toEqual([+ [4, 3],+ [6, 5],+ [4, 3],+ ]);+ surface.patch('box', { bounds: { north: 4, south: 1, east: 8, west: 2 } });+ expect(moved().coordinates[0][0]).toEqual([2, 1]);+ surface.patch('here', { at: { lat: 7, lon: 8 } });+ expect(moved()).toEqual({ type: 'Point', coordinates: [8, 7] });+ });++ it('keeps a moved shape where it was moved to, for the next move', () => {+ // a polygon handle is dragged again from where it landed, not from the+ // vertices the shape was declared with+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set([{ id: 'ring', kind: 'polygon', points: [{ lat: 1, lon: 2 }] }]);+ surface.patch('ring', { points: [{ lat: 3, lon: 4 }, { lat: 5, lon: 6 }] });+ surface.patch('ring', { style: { stroke: '#000' } });+ // the restyle carries no geometry, and the one it had is untouched+ expect(map.calls.updateData.at(-1)[1].update[0]).not.toHaveProperty('newGeometry');+ });++ it('swaps a mark’s glyph for its new style, keeping the engine’s own classes', () => {+ const surface = createSurface(stubEngine());+ surface.set([{ id: 'pin', kind: 'marker', at: { lat: 1, lon: 2 }, className: 'old', html: '<a></a>' }]);+ // the engine puts its own positioning class on the element after we dress it+ marks[0].element.classList.add('maplibregl-marker');+ surface.patch('pin', {+ icon: { className: 'sat-marker', html: '<b></b>', size: [24, 32], anchor: [12, 32] },+ });+ expect(marks[0].element.innerHTML).toBe('<b></b>');+ expect([...marks[0].element.classList]).toEqual(['maplibregl-marker', 'sat-marker']);+ expect(marks[0].offset).toEqual([0, -16]);+ });++ it('says when there is no such shape, instead of throwing at a caller', () => {+ const surface = createSurface(stubEngine());+ surface.set(cells);+ expect(surface.patch('nope', { style: {} })).toBe(false);+ expect(surface.has('a')).toBe(true);+ expect(surface.has('nope')).toBe(false);+ });++ it('forgets the ids it no longer holds', () => {+ const surface = createSurface(stubEngine());+ surface.set(cells);+ surface.set([cells[0]]);+ expect(surface.has('b')).toBe(false);+ surface.clear();+ expect(surface.has('a')).toBe(false);+ });+});++describe('a shape that answers the pointer', () => {+ it('holds the map’s own click back, over the shapes that really answer', () => {+ const engine = stubEngine();+ createSurface(engine).set([{ ...CELL('a', 1), onClick: () => {} }]);+ expect(engine.claims).toHaveLength(1);+ expect(engine.claims[0].filter).toEqual(['!=', ['get', 'interactive'], false]);+ });++ it('claims nothing when nothing on it answers', () => {+ const engine = stubEngine();+ createSurface(engine).set([CELL('a', 1)]);+ expect(engine.claims).toHaveLength(0);+ });++ it('releases the claim when it is cleared', () => {+ const engine = stubEngine();+ const surface = createSurface(engine);+ surface.set([{ ...CELL('a', 1), onClick: () => {} }]);+ surface.clear();+ expect(engine.claims).toHaveLength(0);+ });++ it('answers a click once, not once per layer it is painted in', () => {+ // a filled, outlined cell is in two layers; twice would cycle it past the+ // status the analyst meant+ const map = stubMap();+ const onClick = vi.fn();+ const onContextMenu = vi.fn();+ createSurface(stubEngine(map)).set([{ ...CELL('a', 1), onClick, onContextMenu }]);+ const bound = map.calls.on.filter(([type]) => type === 'click');+ expect(bound).toHaveLength(1);+ expect(bound[0][1]).toEqual(expect.arrayContaining(map.layers.map((l) => l.id)));+ bound[0][2]({ features: [{ properties: { sid: 'a', interactive: true } }] });+ expect(onClick).toHaveBeenCalledTimes(1);+ map.calls.on.find(([type]) => type === 'contextmenu')[2]({+ features: [{ properties: { sid: 'a', interactive: true } }],+ });+ expect(onContextMenu).toHaveBeenCalledWith('a');+ });++ it('ignores a shape drawn only to say how loosely a mark is placed', () => {+ const map = stubMap();+ const onClick = vi.fn();+ createSurface(stubEngine(map)).set([{ ...CELL('a', 1), onClick }]);+ map.calls.on.find(([type]) => type === 'click')[2]({+ features: [{ properties: { sid: 'a', interactive: false } }],+ });+ expect(onClick).not.toHaveBeenCalled();+ });+});++describe('the reading a shape gives under the cursor', () => {+ it('follows the cursor when the caller asked it to', () => {+ const map = stubMap();+ createSurface(stubEngine(map)).set([+ { id: 'ray', kind: 'line', points: [{ lat: 1, lon: 2 }], tip: { text: 'az 210°', sticky: true } },+ ]);+ map.calls.on.find(([type]) => type === 'mousemove')[2]({+ features: [{ properties: { sid: 'ray', interactive: true } }],+ lngLat: { lat: 1, lng: 2 },+ });+ const tip = cards.at(-1);+ expect(tip.text).toBe('az 210°');+ expect(tip.tracking).toBe(true);+ expect(tip.options.className).toBe('map-tip');+ expect(tip.options.closeButton).toBe(false);+ });++ it('hangs on the side the caller named, and goes with the pointer', () => {+ const surface = createSurface(stubEngine());+ surface.set([+ {+ id: 'point',+ kind: 'marker',+ at: { lat: 1, lon: 2 },+ tip: { text: 'Quai sud', direction: 'top', offset: [0, -12] },+ },+ ]);+ marks[0].element.dispatchEvent(new window.MouseEvent('mouseenter'));+ // 'top' is where the reading goes, so the card's own anchor is its bottom+ expect(cards.at(-1).options.anchor).toBe('bottom');+ expect(cards.at(-1).offset).toEqual([0, -12]);+ expect(cards.at(-1).isOpen()).toBe(true);+ marks[0].element.dispatchEvent(new window.MouseEvent('mouseleave'));+ expect(cards.at(-1).isOpen()).toBe(false);+ });++ it('takes a bare string as the reading itself', () => {+ const map = stubMap();+ createSurface(stubEngine(map)).set([+ { id: 'tick', kind: 'line', points: [{ lat: 1, lon: 2 }], tip: 'Sun 14:20' },+ ]);+ map.calls.on.find(([type]) => type === 'mousemove')[2]({+ features: [{ properties: { sid: 'tick', interactive: true } }],+ lngLat: { lat: 1, lng: 2 },+ });+ expect(cards.at(-1).text).toBe('Sun 14:20');+ expect(cards.at(-1).tracking).toBe(false);+ });+});++describe('cards on a mark', () => {+ function withCard(hooks) {+ const content = vi.fn(() => document.createElement('p'));+ const surface = createSurface(stubEngine(), hooks);+ surface.set([+ {+ id: 'mark-1',+ kind: 'marker',+ at: { lat: 1, lon: 2 },+ popup: { content, className: 'saved-popup', minWidth: 296, maxWidth: 330 },+ },+ ]);+ return { surface, content, mark: marks[0] };+ }++ const openCard = (mark) => mark.element.dispatchEvent(new window.MouseEvent('click'));++ it('builds the card when it opens, not when the mark is drawn', () => {+ // a layer of two hundred marks must not mount two hundred cards+ const { content, mark } = withCard();+ expect(content).not.toHaveBeenCalled();+ openCard(mark);+ expect(content).toHaveBeenCalledTimes(1);+ const card = cards.at(-1);+ expect(card.options).toMatchObject({ className: 'saved-popup', maxWidth: '330px' });+ expect(card.node.tagName).toBe('P');+ expect(card.element.style.getPropertyValue('--popup-min-width')).toBe('296px');+ });++ it('says when a card opened and when it closed', () => {+ // the layer defers rebuilding while a card is open: it is a surface the+ // analyst works in, not a tooltip+ const onPopupOpen = vi.fn();+ const onPopupClose = vi.fn();+ const { mark } = withCard({ onPopupOpen, onPopupClose });+ openCard(mark);+ expect(onPopupOpen).toHaveBeenCalledWith('mark-1');+ cards.at(-1).remove();+ expect(onPopupClose).toHaveBeenCalledWith('mark-1');+ });++ it('closes the open card, wherever it is', () => {+ const { surface, mark } = withCard();+ surface.closePopup(); // nothing open: not an error+ openCard(mark);+ const card = cards.at(-1);+ surface.closePopup();+ expect(card.isOpen()).toBe(false);+ surface.closePopup(); // and closing again reaches nothing+ });++ it('puts the card away when the same mark is pressed again', () => {+ // the mark stops its own click, so the map's close-on-click cannot do it+ const { mark } = withCard();+ openCard(mark);+ const card = cards.at(-1);+ openCard(mark);+ expect(card.isOpen()).toBe(false);+ expect(cards.filter((c) => c.isOpen())).toHaveLength(0);+ openCard(mark);+ expect(cards.at(-1).isOpen()).toBe(true);+ });++ it('opens one card at a time', () => {+ const surface = createSurface(stubEngine());+ const popup = (id) => ({+ id,+ kind: 'marker',+ at: { lat: 1, lon: 2 },+ popup: { content: () => document.createElement('p'), maxWidth: 320 },+ });+ surface.set([popup('one'), popup('two')]);+ openCard(marks[0]);+ openCard(marks[1]);+ expect(cards.filter((c) => c.isOpen())).toHaveLength(1);+ });++ it('takes the card down when the shapes are replaced', () => {+ const { surface, mark } = withCard();+ openCard(mark);+ surface.set([]);+ expect(cards.at(-1).isOpen()).toBe(false);+ });+});++describe('the eye toggle', () => {+ it('keeps the shapes and hides them', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set([CELL('a', 1)]);+ surface.visible(false);+ expect(map.calls.visibility.map(([, , value]) => value)).toEqual(['none', 'none', 'none']);+ expect(surface.has('a')).toBe(true); // the grid is still open, just unseen+ map.calls.visibility.length = 0;+ surface.visible(true);+ expect(map.calls.visibility.every(([, , value]) => value === 'visible')).toBe(true);+ });++ it('hides a mark with the shapes, since it is not a layer', () => {+ const surface = createSurface(stubEngine());+ surface.set([{ id: 'm', kind: 'marker', at: { lat: 1, lon: 2 } }]);+ surface.visible(false);+ expect(marks[0].element.style.display).toBe('none');+ surface.visible(true);+ expect(marks[0].element.style.display).toBe('');+ });++ it('stays hidden however much is drawn on it', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.visible(false);+ surface.set([CELL('a', 1), { id: 'm', kind: 'marker', at: { lat: 1, lon: 2 } }]);+ expect(map.calls.visibility.every(([, , value]) => value === 'none')).toBe(true);+ expect(marks[0].element.style.display).toBe('none');+ });+});++describe('teardown', () => {+ it('takes its layers, its source and its listeners with it', () => {+ const map = stubMap();+ const engine = stubEngine(map);+ const surface = createSurface(engine);+ surface.set([{ ...CELL('a', 1), onClick: () => {} }, { id: 'm', kind: 'marker', at: { lat: 1, lon: 2 } }]);+ surface.destroy();+ expect(map.layers).toEqual([]);+ expect(map.getSource(`${map.calls.setData[0][0]}`)).toBeUndefined();+ expect(map.calls.off).toHaveLength(map.calls.on.length);+ expect(marks[0].removed).toBe(1);+ expect(engine.claims).toHaveLength(0);+ });++ it('can be drawn on again after it was torn down', () => {+ const map = stubMap();+ const surface = createSurface(stubEngine(map));+ surface.set([CELL('a', 1)]);+ surface.destroy();+ surface.set([CELL('b', 2)]);+ expect(map.layers.map((l) => l.type)).toEqual(['fill', 'line', 'circle']);+ expect(surface.has('b')).toBe(true);+ });+});diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.jsindex 17bf7e1..b1fbbc9 100644--- a/frontend/src/lib/measure.js+++ b/frontend/src/lib/measure.js@@ -1,5 +1,5 @@// Pure geodesic geometry for the Satellite measure tools (distance / area /-// angle). Points are { lat, lon } in degrees. Kept free of Leaflet so it can be+// angle). Points are { lat, lon } in degrees. Kept free of the map so it can be// unit-tested; the component only handles drawing and interaction.const R = 6378137; // Earth radius (m), WGS84 equatorial — matches Web Mercatordiff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.jsindex 61f877b..a41f29a 100644--- a/frontend/src/lib/mediaFilter.js+++ b/frontend/src/lib/mediaFilter.js@@ -47,13 +47,16 @@ export function isBroughtIn(item) {return BROUGHT_IN.has(item?.source?.type);}-/** The tools that make a file out of material the case already holds. Mirrors- * `links.MADE_HERE`; the server filters on the same set, and this is the- * in-memory pass a case small enough for one page takes instead. */-const MADE_HERE = new Set(['inspect']);+/** The tools whose output the app produced rather than the analyst gathered. Mirrors+ * `links.PRODUCED_HERE` — a wider set than the graph's `MADE_HERE`, and that file is+ * where the two and the reason they differ by a capture are written down. The server+ * filters on the same set, and this is the in-memory pass a case small enough for one+ * page takes instead. */+const MADE_HERE = new Set(['inspect', 'satellite', 'screenshot']);-/** Whether the case made this file rather than collected it: an extracted frame,- * an adjustment, a collage.+/** Whether the app produced this file rather than the analyst gathering it: an+ * extracted frame, an adjustment, a collage, a capture drawn out of tiles, a map+ * the extension grabbed off the screen.** Reads **how the file entered the case**, not everything true about it. Bytes* imported first and later found identical to a frame keep `upload`, because thatdiff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.jsindex 4309078..d51eeb6 100644--- a/frontend/src/lib/mediaFilter.test.js+++ b/frontend/src/lib/mediaFilter.test.js@@ -228,12 +228,18 @@ describe('what the case made, apart from what it collected', () => {const collage = item({ filename: 'collage.png', source: { type: 'inspect', op: 'collage' } });const upload = item({ filename: 'handed-over.jpg', source: { type: 'upload' } });const capture = item({ filename: 'map.png', source: { type: 'satellite' } });+ const grabbed = item({+ filename: 'maps.png',+ source: { type: 'screenshot', imagery_mode: 'satellite' },+ });- it('counts only the tools that compose case material', () => {+ it('counts only what the app produced, not what the analyst gathered', () => {expect(isMadeHere(frame)).toBe(true);expect(isMadeHere(collage)).toBe(true);- // Original imagery brought into the case, not made out of what it holds.- expect(isMadeHere(capture)).toBe(false);+ // Pixels the app drew out of tiles it fetched, and the same act through the+ // extension's window: a map view grabbed on purpose.+ expect(isMadeHere(capture)).toBe(true);+ expect(isMadeHere(grabbed)).toBe(true);expect(isMadeHere(upload)).toBe(false);expect(isMadeHere(item())).toBe(false);expect(isMadeHere(null)).toBe(false);@@ -243,11 +249,11 @@ describe('what the case made, apart from what it collected', () => {// The in-memory pass a case small enough for one page takes; a large case is// filtered in SQL, and both read the same set.expect(- visibleMedia([frame, upload, capture], { collectedOnly: true, sort: 'name' }).map(+ visibleMedia([frame, upload, capture, grabbed], { collectedOnly: true, sort: 'name' }).map((i) => i.filename)- ).toEqual(['handed-over.jpg', 'map.png']);- expect(visibleMedia([frame, upload, capture], { collectedOnly: false }).length).toBe(3);+ ).toEqual(['handed-over.jpg']);+ expect(visibleMedia([frame, upload, capture, grabbed], { collectedOnly: false }).length).toBe(4);expect(visibleMedia([frame, upload], { collectedOnly: true, query: 'frame' })).toEqual([]);});});diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.jsindex 1778267..3a77eeb 100644--- a/frontend/src/lib/post.js+++ b/frontend/src/lib/post.js@@ -26,16 +26,17 @@ export const MAX_POST_MEDIA = 4;/*** Publishing targets share the same prepared thread, but apply their own- * character rules and handoff URL. Mastodon uses its documented default here;- * an individual server may advertise a different limit.+ * character rules and composer address.+ *+ * Mastodon was here and was dropped: there is no one address to open. Its share+ * link is a redirector that asks which server first, so the app could not say+ * where the thread was going, and the extension could not fill a page nobody+ * knew the name of — one target of three behaving differently, invisibly, until+ * Publish was pressed. A draft saved with it opens on X (normalizePostTarget).*/export const POST_TARGETS = Object.freeze({x: { id: 'x', label: 'X', limit: 280, limitLabel: '280' },bluesky: { id: 'bluesky', label: 'Bluesky', limit: 300, limitLabel: '300' },- mastodon: {- id: 'mastodon', label: 'Mastodon', limit: 500, limitLabel: '500 default',- limitHelp: 'Your server may use another limit.',- },});const URL_RE = /https?:\/\/\S+/g;@@ -50,7 +51,7 @@ export function postTarget(target) {return POST_TARGETS[normalizePostTarget(target)];}-/** X and Mastodon reserve a fixed length for every HTTP(S) URL. */+/** X reserves a fixed length for every HTTP(S) URL, whatever the URL is. */export function weightedUrlLength(text) {const value = String(text ?? '');const stripped = value.replace(URL_RE, '');@@ -77,14 +78,51 @@ export function postCharacterCount(target, text) {/** Build a compose handoff for the first post. Replies stay on the clipboard. */export function postComposeUrl(target, text) {const encoded = encodeURIComponent(String(text ?? ''));- switch (normalizePostTarget(target)) {- case 'bluesky':- return `https://bsky.app/intent/compose?text=${encoded}`;- case 'mastodon':- return `https://share.joinmastodon.org/#text=${encoded}`;- default:- return `https://x.com/intent/post?text=${encoded}`;+ return normalizePostTarget(target) === 'bluesky'+ ? `https://bsky.app/intent/compose?text=${encoded}`+ : `https://x.com/intent/post?text=${encoded}`;+}++/**+ * Where the capture extension opens the thread.+ *+ * The **full** composer rather than the intent page, because that is the one that+ * builds a thread: the intent posts a single message, and the whole point here is+ * the run of posts under the first.+ *+ * The text rides in the URL as well as being typed, so the first post is filled+ * even when the page changes under the script and nothing else lands.+ */+export function postHandoffUrl(target, text) {+ const encoded = encodeURIComponent(String(text ?? ''));+ return normalizePostTarget(target) === 'bluesky'+ ? `https://bsky.app/intent/compose?text=${encoded}`+ : `https://x.com/compose/post?text=${encoded}`;+}++/** What one post may carry: four images, or one video, is every site's rule. */+export const MAX_HANDOFF_FILES = 4;++/**+ * The thread as the extension hands it over: one entry per post, in order, each+ * with the text to type and the case files to attach.+ *+ * A post with no text and no file is not a post; one with a picture and no text+ * is. Anything past the per-post limit is **counted, not dropped in silence** —+ * the caller says how many stayed behind, since the alternative is a thread that+ * looks complete and is missing an image.+ */+export function handoffThread(posts) {+ const kept = [];+ let dropped = 0;+ for (const post of posts ?? []) {+ const text = String(post?.text ?? '');+ const files = (post?.files ?? []).filter(Boolean);+ if (!text.trim() && !files.length) continue;+ if (files.length > MAX_HANDOFF_FILES) dropped += files.length - MAX_HANDOFF_FILES;+ kept.push({ text, files: files.slice(0, MAX_HANDOFF_FILES) });}+ return { posts: kept, dropped };}/**diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.jsindex 1672dbf..d548a96 100644--- a/frontend/src/lib/post.test.js+++ b/frontend/src/lib/post.test.js@@ -3,7 +3,7 @@ import {TWEET_TOKENS, DEFAULT_TWEET_BODY, tweetFields, buildTweet1,extraPostTweetText, groupPostMedia, mediaTweetText, newPostMediaTweet,applyPostTemplateStructure, normalizePostMediaPickerTarget, normPostTemplate, postMediaForType,- postCharacterCount, postComposeUrl, postReportMarkdown, postTarget,+ handoffThread, postCharacterCount, postComposeUrl, postHandoffUrl, postReportMarkdown, postTarget,proofSourceMediaPaths, renumberMediaTweetText, retargetMediaTweetText,sourceSection, sourceUrls,templateFromPost, templateUsesPostField, togglePostMedia,@@ -368,9 +368,8 @@ describe('post targets', () => {expect(postTarget('unknown')).toMatchObject({ id: 'x' });});- it('counts links for X and Mastodon, but graphemes for Bluesky', () => {+ it('counts links for X, but graphemes for Bluesky', () => {expect(postCharacterCount('x', 'A https://example.test/very-long-url')).toBe(25);- expect(postCharacterCount('mastodon', 'A https://example.test/very-long-url')).toBe(25);expect(postCharacterCount('bluesky', 'A https://example.test/very-long-url')).toBe(36);expect(postCharacterCount('bluesky', '👍🏽')).toBe(1);});@@ -378,7 +377,61 @@ describe('post targets', () => {it('builds the official compose handoff for each social target', () => {expect(postComposeUrl('x', 'A post')).toBe('https://x.com/intent/post?text=A%20post');expect(postComposeUrl('bluesky', 'A post')).toBe('https://bsky.app/intent/compose?text=A%20post');- expect(postComposeUrl('mastodon', 'A post')).toBe('https://share.joinmastodon.org/#text=A%20post');+ });++ it('opens the full composer where the extension takes over, since that is the one that threads', () => {+ // The intent page posts one message. The run of posts under the first is the+ // whole point of handing over, so it needs the composer that builds a thread.+ expect(postHandoffUrl('x', 'A post')).toBe('https://x.com/compose/post?text=A%20post');+ expect(postHandoffUrl('bluesky', 'A post')).toBe('https://bsky.app/intent/compose?text=A%20post');+ });++ it('opens a dropped or hand-edited target on X, like every other reader of one', () => {+ // Mastodon was a target and is not: its share link is a redirector that asks+ // which server first, so nothing could say where the thread was going.+ expect(postHandoffUrl('mastodon', 'A post')).toBe('https://x.com/compose/post?text=A%20post');+ expect(postComposeUrl('mastodon', 'A post')).toBe('https://x.com/intent/post?text=A%20post');+ expect(postTarget('mastodon').id).toBe('x');+ });+});++describe('handoffThread — the thread as the extension receives it', () => {+ it('pairs each post with the case files it carries', () => {+ const { posts, dropped } = handoffThread([+ { text: 'Geolocated.', files: ['proofs/strike.png'] },+ { text: 'Video:', files: ['media/clip.mp4'] },+ ]);++ expect(posts).toEqual([+ { text: 'Geolocated.', files: ['proofs/strike.png'] },+ { text: 'Video:', files: ['media/clip.mp4'] },+ ]);+ expect(dropped).toBe(0);+ });++ it('keeps a post that is only a picture, and drops one that is nothing', () => {+ const { posts } = handoffThread([+ { text: ' ', files: ['media/a.jpg'] },+ { text: '', files: [] },+ { text: 'Context.' },+ ]);++ expect(posts).toEqual([+ { text: ' ', files: ['media/a.jpg'] },+ { text: 'Context.', files: [] },+ ]);+ });++ it('counts what a post cannot carry rather than losing it quietly', () => {+ const files = ['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg', 'e.jpg', 'f.jpg'];+ const { posts, dropped } = handoffThread([{ text: 'Five angles', files }]);++ expect(posts[0].files).toEqual(['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg']);+ expect(dropped).toBe(2);+ });++ it('survives an absent list', () => {+ expect(handoffThread()).toEqual({ posts: [], dropped: 0 });});});diff --git a/frontend/src/lib/satRotate.js b/frontend/src/lib/satRotate.jsindex 5b735f7..4e19324 100644--- a/frontend/src/lib/satRotate.js+++ b/frontend/src/lib/satRotate.js@@ -1,12 +1,12 @@/*** Middle-drag map rotation for the Satellite tab — the same Google-Earth- * "grab & turn" as the Frame viewer, but driving a Leaflet map bearing.+ * "grab & turn" as the Frame viewer, but driving a map bearing.*- * Leaflet's `setBearing` always rotates about the map centre, so to turn around- * an arbitrary grabbed point we set the bearing and then pan the map so the- * grabbed location slides back under the cursor. These two pure helpers hold the- * bits that are easy to get subtly wrong (the swept-angle bearing and, above- * all, the *sign* of the compensating pan); the Leaflet glue lives in the tool.+ * A map rotates about its centre, so to turn around an arbitrary grabbed point+ * we set the bearing and then pan the map so the grabbed location slides back+ * under the cursor. These two pure helpers hold the bits that are easy to get+ * subtly wrong (the swept-angle bearing and, above all, the *sign* of the+ * compensating pan); the map glue lives in the tool, over `lib/map`'s façade.*/import { pointerAngleDeg } from './frameRotate.js';@@ -24,10 +24,10 @@ export function dragBearing(startBearing, pivot, start, cur) {}/**- * The `[dx, dy]` to `map.panBy` so a pivot that a bearing change pushed from+ * The `[dx, dy]` to hand `panBy` so a pivot that a bearing change pushed from* `grab` to `now` (both container-pixel points) returns exactly under `grab`.- * Leaflet's `panBy(offset)` shifts every container point by `-offset`, so to- * move the pivot by `grab - now` we pan by `now - grab`.+ * A `panBy(offset)` shifts every container point by `-offset`, so to move the+ * pivot by `grab - now` we pan by `now - grab`.*/export function pivotPanOffset(grab, now) {return [now.x - grab.x, now.y - grab.y];diff --git a/frontend/src/lib/satRotate.test.js b/frontend/src/lib/satRotate.test.jsindex 8cc5e17..00ca76a 100644--- a/frontend/src/lib/satRotate.test.js+++ b/frontend/src/lib/satRotate.test.js@@ -26,13 +26,13 @@ describe('dragBearing', () => {describe('pivotPanOffset', () => {it('cancels the drift so panBy re-pins the pivot under the grab point', () => {- // Leaflet shifts container points by -offset; panning by (now-grab) moves+ // A pan shifts container points by -offset; panning by (now-grab) moves// the drifted pivot (now) back onto grab.const grab = { x: 120, y: 80 };const now = { x: 135, y: 60 };const [dx, dy] = pivotPanOffset(grab, now);expect([dx, dy]).toEqual([15, -20]);- // apply the -offset shift Leaflet performs → pivot lands back on grab+ // apply the -offset shift a pan performs → pivot lands back on grabexpect(now.x - dx).toBe(grab.x);expect(now.y - dy).toBe(grab.y);});diff --git a/frontend/src/lib/skyOverlay.js b/frontend/src/lib/skyOverlay.jsindex b78517f..54178f3 100644--- a/frontend/src/lib/skyOverlay.js+++ b/frontend/src/lib/skyOverlay.js@@ -3,7 +3,7 @@** The overlay answers one question — *where was the light coming from, and how* high was it* — by drawing each body's track as an arc around the anchor point.- * Leaflet owns the drawing; what is here is everything that decides *what* to+ * The map owns the drawing; what is here is everything that decides *what* to* draw, kept apart because it is arithmetic over a day's samples and nothing* else. That makes it checkable: an arc that closes through the hours a body* spends below the horizon, or an hour tick on a sample that is under it, is adiff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex d25eca0..266b3b5 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -24,6 +24,7 @@ export const prefs = $state({homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite openspostMention: '@GeoConfirmed', // handle a fresh post draft is addressed topostTarget: 'x', // social composer a fresh post draft starts with+ postPrefill: true, // let the capture extension fill that composer on PublishsignatureHandle: '', // account handle stamped onto proofs that opt into itupdateCheckOnStart: true, // ask GitHub for a newer release when the page loadsupdateDismissedVersion: '', // the release tag muted with "don't show again"@@ -85,6 +86,7 @@ export function applyPrefs(s) {if (s.home_view) prefs.homeView = s.home_view;if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = noneif (s.post_target !== undefined) prefs.postTarget = s.post_target;+ if (s.post_prefill !== undefined) prefs.postPrefill = s.post_prefill;if (s.signature_handle !== undefined) prefs.signatureHandle = s.signature_handle; // '' = noneif (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;if (s.update_dismissed_version !== undefined)diff --git a/frontend/src/tools/MediaLibrary.render.test.js b/frontend/src/tools/MediaLibrary.render.test.jsnew file mode 100644index 0000000..edd9c99--- /dev/null+++ b/frontend/src/tools/MediaLibrary.render.test.js@@ -0,0 +1,176 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++/**+ * The header's upkeep menu, driven the way an analyst drives it.+ *+ * `MediaLibrary.test.js` reads the source for what the tool is wired to. This+ * one presses the `⋮`, because the two failures that matter here — a row that+ * sends the other row's sweep, and a menu that closes before its row fires —+ * both read as correct wiring in the source.+ */++const ITEMS = [+ {+ path: 'media/quai.jpg',+ filename: 'quai.jpg',+ kind: 'image',+ size: 1024,+ folder: '',+ added_at: '2026-08-01T10:00:00Z',+ sha256: '1'.repeat(64),+ thumbnail: 'media/.thumbs/quai-g2.jpg',+ thumb_state: 'ready',+ enrich_state: 'ready',+ },+ {+ path: 'media/clip.mp4',+ filename: 'clip.mp4',+ kind: 'video',+ size: 2048,+ folder: '',+ added_at: '2026-08-02T10:00:00Z',+ sha256: '2'.repeat(64),+ thumbnail: null,+ thumb_state: 'failed',+ enrich_state: 'none',+ },+];++let page = { items: ITEMS, total: ITEMS.length, next_cursor: null, facets: {} };++const get = vi.fn(async (url) => {+ if (url.includes('/media/page')) return page;+ if (url.includes('/entity-types')) return [];+ return {};+});+const post = vi.fn(async () => ({ queued: 1 }));+vi.mock('../lib/api.js', () => ({+ api: { get, post, del: vi.fn(), patch: vi.fn(), put: vi.fn() },+ ApiError: Error,+}));++const toast = vi.fn();+const reloadCase = vi.fn(async () => {});+const ensureCase = vi.fn(async () => ({ id: 'case-a' }));+const uiState = { tool: 'media', focusMedia: null, composeQueue: [], inspectPath: null };+vi.mock('../lib/state.svelte.js', async () => {+ const { caseState } = await import('../components/views.fixture.svelte.js');+ return { caseState, uiState, ensureCase, reloadCase, toast, fmtCoords: (v) => String(v) };+});+vi.mock('../components/EntityDetails.svelte', async () => await import('../components/Modal.svelte'));++const { default: MediaLibrary } = await import('./MediaLibrary.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(MediaLibrary, { target });+ flushSync();+ await settle();+ return target;+}++const toggle = () => target.querySelector('.upkeep-toggle');+const menu = () => target.querySelector('.upkeep-menu');+const rows = () => [...target.querySelectorAll('.upkeep-option')];+const row = (label) => rows().find((r) => r.textContent.trim().includes(label));++async function press(element) {+ element.click();+ flushSync();+ await settle();+}++async function key(name) {+ window.dispatchEvent(new KeyboardEvent('keydown', { key: name, bubbles: true }));+ flushSync();+ await settle();+}++beforeEach(() => {+ page = { items: ITEMS, total: ITEMS.length, next_cursor: null, facets: {} };+ vi.clearAllMocks();+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+});++describe('the upkeep menu', () => {+ it('keeps both sweeps behind one door, and shows no bare buttons for them', async () => {+ await open();++ expect(toggle()).not.toBeNull();+ expect(menu()).toBeNull(); // closed until asked for+ const labels = [...target.querySelectorAll('.tool-header button')].map((b) =>+ b.textContent.trim()+ );+ expect(labels).not.toContain('Thumbnails');+ expect(labels).not.toContain('Enrich');+ });++ it('opens on the door and lists the two sweeps', async () => {+ await open();+ await press(toggle());++ expect(menu()).not.toBeNull();+ expect(toggle().getAttribute('aria-expanded')).toBe('true');+ expect(rows().map((r) => r.textContent.trim())).toEqual([+ 'Regenerate missing thumbnails',+ 'Read file metadata',+ ]);+ });++ it('sends the thumbnail sweep for the whole case, not for one file', async () => {+ await open();+ await press(toggle());+ await press(row('Regenerate missing thumbnails'));++ expect(post).toHaveBeenCalledWith('/api/cases/case-a/media/thumbnails/regenerate', {});+ expect(menu()).toBeNull(); // the menu never hangs over the request it sent+ });++ it('sends the metadata sweep', async () => {+ await open();+ await press(toggle());+ await press(row('Read file metadata'));++ expect(post).toHaveBeenCalledWith('/api/cases/case-a/media/enrich', {});+ expect(menu()).toBeNull();+ });++ it('closes on the backdrop and on Escape, sending nothing', async () => {+ await open();++ await press(toggle());+ await press(target.querySelector('.upkeep-backdrop'));+ expect(menu()).toBeNull();++ await press(toggle());+ await key('Escape');+ expect(menu()).toBeNull();++ expect(post).not.toHaveBeenCalled();+ });++ it('leaves the door in place on a case with no media, with both rows refused', async () => {+ page = { items: [], total: 0, next_cursor: null, facets: {} };+ await open();+ await press(toggle());++ expect(toggle().disabled).toBe(false);+ expect(rows().map((r) => r.disabled)).toEqual([true, true]);+ });+});diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex f4c5329..97e0aa1 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -119,9 +119,10 @@);// --- what the case made, out of the way (independent of type and folder) ---- // A geolocation case ends up with 150 extracted frames beside 50 collected- // files, and the question "what did we actually collect" has no answer in a- // chooser: the chips are single-select and say "show me only X". This is the+ // A geolocation case ends up with 150 extracted frames and 60 satellite+ // captures beside 50 collected files, and the question "what did we actually+ // collect" has no answer in a chooser: the chips are single-select and say+ // "show me only X". This is the// other axis, so it is a switch. On by default — the library opens on what the// case collected, and the switch is how the working files come back; it says// how many they are rather than leaving them unannounced.@@ -306,8 +307,16 @@lightboxItem = lightboxImages[next];}- function onLightboxKey(e) {- if (!lightboxItem || uiState.tool !== 'media') return;+ // One handler for the tool's two overlays: the lightbox owns the arrows, the+ // upkeep menu only needs the Escape, and it reads first because it is the one+ // that can be open while the lightbox is not.+ function onMediaKey(e) {+ if (uiState.tool !== 'media') return;+ if (e.key === 'Escape' && upkeepOpen) {+ upkeepOpen = false;+ return;+ }+ if (!lightboxItem) return;if (e.key === 'Escape') lightboxItem = null;else if (e.key === 'ArrowLeft') lightboxStep(-1);else if (e.key === 'ArrowRight') lightboxStep(1);@@ -413,6 +422,20 @@);});+ // --- upkeep ---+ // Both sweeps below are repairs pressed once in a while: regenerate what+ // failed, read the metadata a version that could not read it left behind. As+ // header buttons they sat next to Download and Import, which read as if they+ // were a step of importing, and they took that much room all day for a press+ // a month. So they live behind the `⋮`, and what each one found is still said+ // out loud after it runs, by the toast.+ let upkeepOpen = $state(false);++ function runUpkeep(sweep) {+ upkeepOpen = false; // never leave the menu hanging over the request it sent+ sweep();+ }+// Queue (re)generation: a single failed thumbnail (path given) or every// missing/failed one across the case. The worker drains the queue; the poll// above reflects each result as it lands.@@ -837,22 +860,48 @@<button class="btn" onclick={() => fileInput.click()}><Icon name="upload" size={15} /> Import</button>- <button- class="btn"- onclick={() => regenerateThumbs()}- title="Regenerate missing or failed thumbnails"- disabled={!items.length}- >- <Icon name="reset" size={15} /> Thumbnails- </button>- <button- class="btn"- onclick={enrichMedia}- title="Read image EXIF, hashes and video metadata locally"- disabled={!items.length}- >- <Icon name="search" size={15} /> Enrich- </button>+ <!-- The two upkeep sweeps, behind one door. The door stays put on an empty+ case with its rows disabled: a header that reorganises itself on the+ first import is a header nobody learns. -->+ <div class="upkeep">+ <button+ class="btn upkeep-toggle"+ onclick={() => (upkeepOpen = !upkeepOpen)}+ aria-label="Media upkeep"+ aria-haspopup="menu"+ aria-expanded={upkeepOpen}+ >+ <Icon name="more" size={15} stroke={2.6} />+ </button>+ {#if upkeepOpen}+ <button+ class="upkeep-backdrop"+ onclick={() => (upkeepOpen = false)}+ aria-label="Close the upkeep menu"+ ></button>+ <div class="upkeep-menu card" role="menu" aria-label="Media upkeep">+ <button+ class="upkeep-option"+ role="menuitem"+ onclick={() => runUpkeep(regenerateThumbs)}+ disabled={!items.length}+ >+ <Icon name="reset" size={14} />+ <span>Regenerate missing thumbnails</span>+ </button>+ <button+ class="upkeep-option"+ role="menuitem"+ onclick={() => runUpkeep(enrichMedia)}+ title="Read image EXIF, hashes and video metadata locally"+ disabled={!items.length}+ >+ <Icon name="search" size={14} />+ <span>Read file metadata</span>+ </button>+ </div>+ {/if}+ </div><inputtype="file"multiple@@ -927,7 +976,7 @@type="button"aria-pressed={!collectedOnly}title={collectedOnly- ? `Show the ${madeHereCount} file${madeHereCount > 1 ? 's' : ''} the case made from material it already holds`+ ? `Show the ${madeHereCount} file${madeHereCount > 1 ? 's' : ''} the case produced itself`: 'Show only what the case collected'}onclick={toggleCollectedOnly}>@@ -1436,7 +1485,7 @@{/if}<!-- lightbox -->-<svelte:window onkeydown={onLightboxKey} />+<svelte:window onkeydown={onMediaKey} />{#if lightboxItem}<divclass="lightbox"@@ -1541,6 +1590,48 @@width: min(480px, 40vw);}+ /* upkeep menu */+ .upkeep {+ position: relative;+ display: flex;+ }+ .upkeep-toggle {+ min-width: 30px;+ padding-inline: 6px;+ }+ .upkeep-backdrop {+ position: fixed;+ inset: 0;+ z-index: 90;+ cursor: default;+ }+ .upkeep-menu {+ position: absolute;+ top: calc(100% + 6px);+ right: 0;+ z-index: 100;+ min-width: 250px;+ padding: 5px;+ box-shadow: var(--shadow-2);+ }+ .upkeep-option {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 7px 9px;+ border-radius: var(--r-sm);+ color: var(--text-1);+ font-size: var(--fs-sm);+ text-align: left;+ }+ .upkeep-option:hover:not(:disabled) {+ background: var(--bg-2);+ }+ .upkeep-option:disabled {+ color: var(--text-3);+ }+/* folder filter bar */.folder-bar {position: sticky;diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex 006c8fa..f834224 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -76,7 +76,9 @@ describe('Media Library enrichment', () => {expect(source).toContain('async function enrichMedia()');expect(source).toContain('await api.post(`/api/cases/${id}/media/enrich`, {})');expect(source).toContain('title="Read image EXIF, hashes and video metadata locally"');- expect(source).toContain('<Icon name="search" size={15} /> Enrich');+ expect(source).toContain('runUpkeep(enrichMedia)');+ // no effect reaches for it: the sweep is a press, not a mount+ expect(source).not.toMatch(/\$effect\([^)]*enrichMedia/);});it('polls media and Suggestions while enrichment is running', () => {diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex 6f9e04f..58c207e 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -2,7 +2,7 @@import { api } from '../lib/api.js';import { fileUrl } from '../lib/fileUrl.js';import { fetchAllEntities, lookupEntity, fetchDerivation } from '../lib/catalog.js';- import { caseState, uiState, toast, reloadCase, prefs } from '../lib/state.svelte.js';+ import { caseState, uiState, toast, reloadCase, prefs, updatesState } from '../lib/state.svelte.js';import { templatesState } from '../lib/state.svelte.js';import { createNote } from '../lib/notes.js';import { openNotebook } from '../lib/navigate.js';@@ -19,7 +19,9 @@normalizePostMediaPickerTarget, postMediaForType, renumberMediaTweetText, retargetMediaTweetText,normalizePostTarget, POST_TARGETS, postCharacterCount, postComposeUrl, postReportMarkdown,postTarget, templateUsesPostField, togglePostMedia, pointLines,+ handoffThread, postHandoffUrl,} from '../lib/post.js';+ import { extensionOutdated, extensionVersion, handOffPost } from '../lib/extBridge.js';import { bidiSafe } from '../lib/bidi.js';import { matchesQuery } from '../lib/mediaFilter.js';import Icon from '../components/Icon.svelte';@@ -975,9 +977,80 @@// ---- publish handoff (Azimut never posts on the analyst's behalf) --------+ /**+ * The thread as the extension receives it: what to type, and which case files+ * to attach to each post. Paths only — the extension reads the bytes from the+ * app with its own pairing token, so no case file passes through the page.+ */+ function handoffPayload() {+ return handoffThread([+ { text: bidiSafe(tweet1), files: proofPng ? [proofPng] : [] },+ ...(mediaEnabled && mediaType !== 'none'+ ? [{ text: bidiSafe(tweet2Text()), files: mediaPaths }]+ : []),+ ...extraTweets.map((tweet, i) => ({+ text: bidiSafe(extraTweetText(tweet, i + 3)),+ files: tweet.mediaPaths,+ })),+ ]);+ }++ /**+ * Why the extension did not take the thread, in a sentence the analyst can act+ * on — or null when there is nothing they could do about it.+ *+ * The switch is on and an extension is installed, so **the difference between+ * "it filled the composer" and "it didn't" has to be visible**: a Publish that+ * quietly does the old thing looks like a broken button, and the two reasons it+ * is usually the old thing — an extension older than the app, or one never+ * paired — are both one click away from fixed. Silence is kept for the case+ * that is not: an extension that answered something else.+ */+ function handOffExcuse(error) {+ const installed = extensionVersion();+ if (/did not answer/.test(error.message)) {+ // A build that predates this feature has no route for the message and says+ // nothing at all, which is what the short timeout is really detecting.+ return extensionOutdated(installed, updatesState.extensionBundled)+ ? 'Your capture extension is older than Azimut. Reinstall it from Settings → Capture extension to fill the composer.'+ : null;+ }+ return /paired/.test(error.message) ? `Composer not filled: ${error.message}.` : null;+ }++ /**+ * Let the extension open the composer and fill the thread, if it can.+ *+ * True when it took the hand-off — the tab is open and the app has nothing left+ * to do. False for every other case: no extension, switched off, not permitted+ * on that site, a target it cannot fill. The caller opens the intent page+ * exactly as it always did, so the feature can only ever be a layer over the+ * working path, never a step in front of it.+ */+ async function tryHandOff() {+ if (!prefs.postPrefill || !extensionVersion()) return false;+ const url = postHandoffUrl(target, bidiSafe(tweet1));+ if (!url || !caseState.current) return false;+ const { posts, dropped } = handoffPayload();+ if (!posts.length) return false;+ try {+ await handOffPost({ url, caseId: caseState.current.id, posts });+ // What it manages is the extension's to report — it is still filling while+ // this runs. What is said here is what is already true.+ const left = dropped ? ` ${dropped} file${dropped > 1 ? 's' : ''} over the per-post limit stayed behind.` : '';+ toast(`${targetInfo.label} is opening with the thread.${left} Nothing was posted.`, 'info', 4200);+ return true;+ } catch (e) {+ const excuse = handOffExcuse(e);+ if (excuse) toast(excuse, 'warn', 6000);+ return false;+ }+ }+async function publish() {// Social intents prefill the first post only. The rest is copied as replies.await copyAll(false);+ if (await tryHandOff()) return;const url = postComposeUrl(target, bidiSafe(tweet1));window.open(url, '_blank', 'noopener,noreferrer');toast(`Opened ${targetInfo.label}. Posts copied for replies.`, 'info', 3200);@@ -1187,33 +1260,6 @@></textarea></div>- {#if caseState.current}- <div class="field">- <div class="proof-head">- <span class="label" style="margin:0">Attached proof</span>- {#if proofPng}- <button class="btn btn-ghost btn-sm" onclick={() => copyImage(proofHref)} title="Copy this image">- <Icon name="copy" size={13} /> Copy image- </button>- <button class="btn btn-ghost btn-sm" onclick={openProofPicker} title="Attach a different proof">- <Icon name="proof" size={13} /> Change- </button>- <button class="btn btn-ghost btn-sm danger-hover" onclick={clearProof} title="Detach proof">- <Icon name="x" size={13} />- </button>- {/if}- </div>- {#if proofPng}- <a href={proofHref} target="_blank" rel="noreferrer">- <img class="proof-preview card" src={proofHref} alt="proof" />- </a>- {:else}- <button class="btn btn-ghost btn-sm proof-attach" onclick={openProofPicker}>- <Icon name="proof" size={14} /> Attach a proof- </button>- {/if}- </div>- {/if}</div><!-- right column: the thread -->@@ -1241,6 +1287,38 @@oninput={() => (tweet1Edited = true)}rows="11"></textarea>+ <!-- The proof is this post's attachment, so it rides on this card the way+ every other post carries its media. Read across the column, the thread+ is what will be published, picture by picture. -->+ {#if caseState.current}+ <div class="media-attach">+ {#if proofPng}+ <span class="attach-chip">+ <a href={proofHref} target="_blank" rel="noreferrer" title={proofPng}>+ {proofPng.replace(/^proofs\//, '')}+ </a>+ <button class="chip-x" onclick={clearProof} title="Detach proof">+ <Icon name="x" size={11} />+ </button>+ </span>+ <button class="btn btn-ghost btn-sm" onclick={() => copyImage(proofHref)} title="Copy this image">+ <Icon name="copy" size={13} /> Copy image+ </button>+ <button class="btn btn-ghost btn-sm" onclick={openProofPicker} title="Attach a different proof">+ <Icon name="proof" size={13} /> Change+ </button>+ {:else}+ <button class="btn btn-ghost btn-sm" onclick={openProofPicker}>+ <Icon name="proof" size={13} /> Attach a proof+ </button>+ {/if}+ </div>+ {#if proofPng}+ <a href={proofHref} target="_blank" rel="noreferrer">+ <img class="proof-preview card" src={proofHref} alt="proof" />+ </a>+ {/if}+ {/if}</div><!-- Post 2: media (Video / Image) -->@@ -1612,17 +1690,6 @@object-fit: contain;padding: 6px;}- .proof-head {- display: flex;- align-items: center;- gap: 10px;- margin-bottom: 6px;- }- .proof-attach {- align-self: flex-start;- border: 1px dashed var(--border);- }-/* Thread / tweet blocks */.tweet-block {padding: 12px 14px;diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.jsindex f6b926e..2fed555 100644--- a/frontend/src/tools/PostComposer.test.js+++ b/frontend/src/tools/PostComposer.test.js@@ -107,3 +107,87 @@ describe('Post Composer — coordinates that no longer parse', () => {);});});++describe('the attached proof', () => {+ const card = source.slice(+ source.indexOf('<!-- Post 1: geolocation -->'),+ source.indexOf('<!-- Post 2: media (Video / Image) -->'),+ );++ it('rides on the geolocation post, which is the post that carries it', () => {+ // It used to sit in the field column, a screen away from the text it is+ // published with, and reading the thread said nothing about the picture.+ expect(card).toContain('onclick={openProofPicker}');+ expect(card).toContain('<img class="proof-preview card" src={proofHref} alt="proof" />');+ expect(source).not.toContain('class="proof-head"');+ expect(source).not.toContain('Attached proof');+ });++ it('carries it the way every other post carries its media', () => {+ expect(card).toContain('<div class="media-attach">');+ expect(card).toContain('<span class="attach-chip">');+ expect(card).toContain('onclick={clearProof}');+ });+});++describe('handing the thread to the extension', () => {+ const publish = source.slice(source.indexOf('function handoffPayload'), source.indexOf('<div class="tool">'));++ it('sends paths, never files: the extension reads the bytes from the app itself', () => {+ expect(publish).toContain('files: proofPng ? [proofPng] : []');+ expect(publish).toContain('files: mediaPaths');+ expect(publish).toContain('files: tweet.mediaPaths');+ expect(publish).toContain('caseId: caseState.current.id');+ expect(publish).not.toContain('base64');+ });++ it('falls back to the page it always opened, for every way the hand-off can fail', () => {+ // absent, off, not permitted, a target it cannot fill: one answer, one path+ expect(publish).toContain('|| !extensionVersion()) return false;');+ expect(publish).toContain('if (!url || !caseState.current) return false;');+ expect(publish).toMatch(/catch \(e\) \{[\s\S]*?return false;/);+ expect(publish).toContain('if (await tryHandOff()) return;');+ expect(publish).toContain('window.open(url, \'_blank\', \'noopener,noreferrer\')');+ });++ it('copies the thread before handing it over, so a short fill is never a loss', () => {+ const body = source.slice(source.indexOf('async function publish()'), source.indexOf('</script>'));+ expect(body.indexOf('await copyAll(false);')).toBeLessThan(body.indexOf('tryHandOff()'));+ });++ it('says nothing was posted, because nothing was', () => {+ expect(publish).toContain('Nothing was posted.');+ });+});++describe('the Settings switch for filling the composer', () => {+ it('is what Publish asks first, so turning it off is the end of it', () => {+ expect(source).toContain('if (!prefs.postPrefill || !extensionVersion()) return false;');+ });++ it('claims only what is true when it says it: the fill is still running', () => {+ expect(source).toContain('is opening with the thread.');+ expect(source).not.toContain('Filled ${filled}');+ });+});++describe('when the extension does not take the thread', () => {+ const excuse = source.slice(source.indexOf('function handOffExcuse'), source.indexOf('* Let the extension open'));++ it('names the one reason the analyst can act on: an extension older than the app', () => {+ // A build that predates the feature has no route for the message and says+ // nothing at all, so Publish quietly did the old thing and read as broken.+ expect(excuse).toContain('extensionOutdated(installed, updatesState.extensionBundled)');+ expect(excuse).toContain('Reinstall it from Settings → Capture extension');+ });++ it('passes on the extension\'s own answer when pairing is what is missing', () => {+ expect(excuse).toContain('/paired/.test(error.message)');+ expect(excuse).toContain('Composer not filled:');+ });++ it('stays quiet otherwise, since the fallback is the behaviour they know', () => {+ expect(excuse).toContain(': null;');+ expect(source).toContain('if (excuse) toast(excuse, \'warn\', 6000);');+ });+});diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 4ee0dee..e4b0362 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -5,7 +5,7 @@import { api } from '../lib/api.js';import { lookupEntity, fetchAllEntities } from '../lib/catalog.js';import { matchesTerms } from '../lib/folderBrowse.js';- import { isSatelliteMedia } from '../lib/mediaFilter.js';+ import { isSatelliteMedia, sortItems } from '../lib/mediaFilter.js';import { deletedToast, RESTORABLE } from '../lib/trash.js';import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';import { templatesState } from '../lib/state.svelte.js';@@ -802,24 +802,33 @@// exactly when the Media Library does (isSatelliteMedia), so a Street View// grab reads the same on both screens.const captured = new Set(sats.map((s) => s.path));- return dedupeBySrc([- ...sats.map((s) => ({- ...satPanelInput(s, prefs.coordFormat),- label: `${fmtCoords(s.lat, s.lon)} · z${s.zoom}`,- ...panelPreview(s),- kind: isSatelliteMedia(s) ? 'satellite' : 'media',- folder: s.folder ?? '',- })),- ...media- .filter((m) => m.kind === 'image' && !captured.has(m.path))- .map((m) => ({- ...mediaPanelInput(m, media),- label: m.title || m.filename,- ...panelPreview(m),- kind: 'media',- folder: m.folder ?? '',+ // Newest first, across both halves at once. Each list arrives in that order+ // already, so concatenating them filed every capture above every photo — the+ // picker is opened for the frame cut a minute ago, and a proof of a strike is+ // built out of whichever of the two came in last.+ return sortItems(+ dedupeBySrc([+ ...sats.map((s) => ({+ ...satPanelInput(s, prefs.coordFormat),+ label: `${fmtCoords(s.lat, s.lon)} · z${s.zoom}`,+ ...panelPreview(s),+ kind: isSatelliteMedia(s) ? 'satellite' : 'media',+ folder: s.folder ?? '',+ added_at: s.added_at ?? s.fetched_at ?? '',})),- ]);+ ...media+ .filter((m) => m.kind === 'image' && !captured.has(m.path))+ .map((m) => ({+ ...mediaPanelInput(m, media),+ label: m.title || m.filename,+ ...panelPreview(m),+ kind: 'media',+ folder: m.folder ?? '',+ added_at: m.added_at ?? '',+ })),+ ]),+ 'newest'+ );}async function openNewProofDialog() {@@ -1473,7 +1482,7 @@// 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 && pathDraft.panel.id !== panel.id) finishPath(true, { keepTool: true });if (!pathDraft) {const node = new Konva.Line({points: [hit.nx, hit.ny], tension: 0.5, stroke: color,@@ -1645,6 +1654,14 @@};proof.shapes.push(s);selectedIds = [s.id];+ // The pen goes down with the shape. What follows a stroke is almost always+ // a word about it — its colour, its width, the note it carries — and the+ // toolbar edits the picked annotation, so leaving the tool in hand meant+ // every one of those first drew a second box nobody wanted. Drawing three+ // in a row is `r`, `r`, `r`, which is what the shortcuts are for. The+ // stamp is the exception and keeps the tool: marking six vehicles is one+ // act, not six.+ tool = 'select';dirty = true;}}@@ -1690,7 +1707,9 @@if (drawing) commitDrawing();}- function finishPath(commit) {+ /** Close the curve in hand. `keepTool` for the one caller that is opening the+ * next curve in the same gesture, where putting the pen down would strand it. */+ function finishPath(commit, { keepTool = false } = {}) {if (!pathDraft) return;const { node, points, panel } = pathDraft;pathDraft = null;@@ -1704,9 +1723,9 @@};proof.shapes.push(s);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.+ // The pen goes down, like the box, the line and the arrow it belongs beside:+ // the curve is picked so the toolbar edits it (see commitDrawing).+ if (!keepTool) tool = 'select';dirty = true;} else {proof.shapes = [...proof.shapes]; // force rebuild to drop the preview@@ -3245,12 +3264,26 @@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+ /**+ * Write the first row's coordinates down, if the field is still showing the+ * imagery's answer rather than one somebody typed.+ *+ * An empty field means "whatever the imagery says", and a save states only what+ * the proof holds: `statePoints` drops a row with no coordinates, and the whole+ * row goes with it. So naming that point, or calling it the camera, used to be+ * dropped too — the label was typed, the POST carried no point at all, and+ * nothing was filed. Anything that turns the row into a claim materialises the+ * answer first, which is what adding a second row already did.+ */+ function statePoint0() {+ if (!proof.points[0].coords.trim()) proof.points[0].coords = displayedCoords;+ }++ /** Add a row. The first one is materialised first: 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;+ statePoint0();proof.points = [...proof.points, blankPoint()];dirty = true;}@@ -3274,10 +3307,19 @@/** A camera stood in one place, so lighting one point puts the others out. */function togglePov(i) {const on = !proof.points[i].pov;+ if (on) statePoint0(); // POV is a claim about the point: state it (see statePoint0)proof.points = proof.points.map((one, at) => ({ ...one, pov: on && at === i }));dirty = true;}+ /** Name a point. The first row's coordinates are written down with it, or the+ * name is typed onto a row the save drops (see statePoint0). */+ function namePoint(i, value) {+ proof.points[i].label = value;+ if (i === 0) statePoint0();+ dirty = true;+ }+// order — this also promotes any color that was only implicitly ordered// (first-use) into an explicit, saved position.function moveLegendColor(i, delta) {@@ -3663,7 +3705,7 @@class="input point-label"placeholder="label"value={point.label}- oninput={(e) => { proof.points[i].label = e.target.value; dirty = true; }}+ oninput={(e) => namePoint(i, e.target.value)}/><!-- What the point means. Nothing in the composition can answer it:a rooftop shot is recorded somewhere it never shows, and adiff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.jsindex 2a1b70f..71e9188 100644--- a/frontend/src/tools/ProofComposer.test.js+++ b/frontend/src/tools/ProofComposer.test.js@@ -13,6 +13,13 @@ import {const source = readFileSync(new URL('./ProofComposer.svelte', import.meta.url), 'utf8');+/** The body of a top-level function in the component, for the assertions that are+ * about one of them rather than about the file. */+const bodyOfFn = (name) => {+ const at = source.indexOf(`function ${name}(`);+ return source.slice(at, source.indexOf('\n }', at));+};+describe('Proof Composer empty state', () => {it('hides proof-specific chrome until a proof is started', () => {const { body } = render(ProofComposer);@@ -120,7 +127,7 @@ describe('Proof Composer pickers', () => {});it('calls a capture satellite exactly when the Media Library does', () => {- expect(source).toContain("import { isSatelliteMedia } from '../lib/mediaFilter.js'");+ expect(source).toContain("import { isSatelliteMedia, sortItems } from '../lib/mediaFilter.js'");expect(source).toContain("kind: isSatelliteMedia(s) ? 'satellite' : 'media'");// captures are dropped from the media half by path, so a Street View grab// is listed once, under Other images, instead of twice@@ -129,6 +136,16 @@ describe('Proof Composer pickers', () => {expect(source).not.toContain('isSatelliteCapture');});+ it('lists both halves newest first, rather than every capture above every photo', () => {+ // Each list arrives newest first and concatenating them threw that away. The+ // picker is opened for the frame cut a minute ago, whichever half it came from.+ const fetch = bodyOfFn('fetchPanelItems');+ expect(fetch).toContain("added_at: s.added_at ?? s.fetched_at ?? ''");+ expect(fetch).toContain("added_at: m.added_at ?? ''");+ expect(fetch).toContain("'newest'");+ expect(fetch).toContain('return sortItems(');+ });+it('searches panels by their title, not by the file name', () => {expect(source).toContain('label: m.title || m.filename');expect(source).toContain('placeholder="Search titles…"');@@ -541,6 +558,19 @@ describe('the points a proof states', () => {// an empty field means "whatever the imagery says", and that answer has to// become the conclusion in writing before the list can growexpect(source).toContain("if (!proof.points[0].coords.trim()) proof.points[0].coords = displayedCoords;");+ expect(bodyOfFn('addPoint')).toContain('statePoint0();');+ });++ it('writes the coordinates down with the name typed onto them', () => {+ // The save states only what the proof holds: a row with no coordinates is+ // dropped, and the name typed onto the imagery's answer went with it — no+ // point in the request, no place filed, and nothing said so.+ expect(source).toContain('oninput={(e) => namePoint(i, e.target.value)}');+ expect(bodyOfFn('namePoint')).toContain('if (i === 0) statePoint0();');+ });++ it('writes them down for POV too, which is the same claim about the same row', () => {+ expect(bodyOfFn('togglePov')).toContain('if (on) statePoint0();');});it('chooses the conclusion by order, never by POV', () => {@@ -916,19 +946,37 @@ describe('picking from the side column', () => {});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'),- );+ const finish = source.slice(+ source.indexOf('function finishPath'),+ source.indexOf('function commitPasteNode'),+ );+ it('puts the pen down like the box, the line and the arrow beside it', () => {expect(finish).toContain("kind: 'curve'");- expect(finish).not.toContain("tool = 'select'");+ expect(finish).toContain('selectedIds = [s.id];');+ expect(finish).toContain("if (!keepTool) 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);');+ // The tool has to survive that close, or the curve it opens is stranded.+ expect(down).toContain(+ 'if (pathDraft && pathDraft.panel.id !== panel.id) finishPath(true, { keepTool: true });'+ );+ });+});++describe('finishing a shape', () => {+ const commit = source.slice(+ source.indexOf('function commitDrawing'),+ source.indexOf('function onPointerUp'),+ );++ it('picks it and puts the pen down, so the toolbar edits what was just drawn', () => {+ // What follows a stroke is almost always a word about it — its colour, its+ // width, the note it carries — and each of those used to draw a second box.+ expect(commit).toContain('selectedIds = [s.id];');+ expect(commit).toContain("tool = 'select';");});});diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex ab79fb4..0cd72a0 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -1,17 +1,21 @@<script>import { onMount, tick } from 'svelte';import { fileUrl } from '../lib/fileUrl.js';- import L from 'leaflet';- import 'leaflet/dist/leaflet.css';+ // The map is lib/map's: the engine, its layers, what is drawn on them and the+ // drag gestures. Nothing in this file knows which engine that is.+ import { createMapEngine } from '../lib/map/engine.js';+ import { createBasemaps } from '../lib/map/basemap.js';+ import { createSurface } from '../lib/map/surface.js';+ import { createSentinelState } from './satellite/state/sentinel.svelte.js';+ import { createSavedState } from './satellite/state/saved.svelte.js';import { api } from '../lib/api.js';import { setAnalysisPeriod } from '../lib/analysisSearch.svelte.js';import { temporalMapQuery } from '../lib/temporalMap.js';import { windowWords } from '../lib/timeline.js';- import { filterSaved, isMode, pendingLocate } from '../lib/geoTree.js';+ import { isMode } from '../lib/geoTree.js';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';@@ -25,7 +29,7 @@upRuns,} from '../lib/skyOverlay.js';import * as gridSearch from '../lib/gridSearch.js';- import { dragBearing, pivotPanOffset } from '../lib/satRotate.js';+ import { startRectDrag, startRotateDrag } from '../lib/map/gestures.js';import { clampSize, scaledCapture } from '../lib/captureSize.js';import { panelWidth } from '../lib/panelWidth.js';import PlaceSearch from './satellite/PlaceSearch.svelte';@@ -65,21 +69,22 @@dateAfterCoverage,} from '../lib/sentinel.js';import { createViewer, nextZ, restack } from '../lib/refViewers.js';- import { loadGoogleMaps, createSatelliteMutant } from '../lib/gmaps.js';import { matchesQuery } from '../lib/mediaFilter.js';import Icon from '../components/Icon.svelte';import Modal from '../components/Modal.svelte';import SearchInput from '../components/SearchInput.svelte';import FolderBrowser from '../components/FolderBrowser.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';- import FolderSelect from '../components/FolderSelect.svelte';- import RelationList from '../components/RelationList.svelte';- import RelationPicker from '../components/RelationPicker.svelte';import RefViewer from './RefViewer.svelte';import MapToolCluster from './satellite/MapToolCluster.svelte';import SunPanel from './satellite/SunPanel.svelte';import GridSearchPanel from './satellite/GridSearchPanel.svelte';import SentinelPicker from './satellite/SentinelPicker.svelte';+ import ScreenshotDialog from './satellite/ScreenshotDialog.svelte';+ import ExtensionGate from './satellite/ExtensionGate.svelte';+ import RefPicker from './satellite/RefPicker.svelte';+ import CaptureDetails from './satellite/CaptureDetails.svelte';+ import PlaceDialog from './satellite/PlaceDialog.svelte';import CaptureOptions from './satellite/CaptureOptions.svelte';import SavedTree from './satellite/SavedTree.svelte';import SavedSearch from './satellite/SavedSearch.svelte';@@ -89,8 +94,10 @@let mapEl;let toolEl; // Browser fullscreen target.- let map = $state.raw(null);- let tileLayer;+ // The map, through lib/map's façade: no engine type reaches this file's+ // camera, projection or event code.+ let engine = $state.raw(null);+ let basemaps = null; // lib/map/basemap.js: the imagery layer and the labels over itlet providers = $state([]);let providerId = $state('esri-world-imagery');let coordsText = $state('');@@ -99,7 +106,7 @@let center = $state({ ...prefs.homeView });let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none'let moveMode = $state(false); // pin decoupled from center, draggable- let marker = null; // Leaflet marker instance while in move mode+ let markerSurface = null; // lib/map/surface.js — holds the pin while in move modelet markerLatLng = $state(null); // {lat, lon} of the moved pinlet bearing = $state(0);// Middle-drag rotates the map around the grabbed point.@@ -108,10 +115,9 @@let capturing = $state(false);let captureHover = $state(false); // previewing the crop frame (capture group hover)let hideOverlays = $state(false); // frame/marquee outlines must not land in a screen crop- // One compact Saved index for places, captures and filed screenshots.- let saved = $state([]);- let savedKind = $state('all');- let savedQuery = $state('');+ // The case's saved work — both indexes, the panel's filter and the Locate+ // pass — is its own store (state/saved.svelte.js).+ const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });let savedSearchOpen = $state(false);let savedOverlay = $state(false); // map layer: off by default, session onlylet temporalMap = $state(null); // Timeline handoff, session-only@@ -121,18 +127,7 @@/** 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());let hoveredSavedId = $state(null); // shared by the tree, the modal and the map- // Proofs use a separate mode because they can borrow capture coordinates.- // Fetch them only when that mode opens.- let savedProofs = $state([]);- let savedFor = null; // case id held by both Saved indexes- let proofsFor = null; // the case id savedProofs was loaded for- const savedRows = $derived(isMode(savedKind) ? savedProofs : saved);- // The map layer follows the Saved panel filter.- const savedShown = $derived(filterSaved(savedRows, { kind: savedKind, query: savedQuery }));let revealSavedId = $state(null);let capturesCollapsed = $state(false);// the Saved panel's left edge is a drag handle; the width sticks across reloads@@ -146,13 +141,11 @@let savedW = $state(savedPanel.loadWidth());let savedResizing = $state(false);let mapReady = $state(false);+ let mapRefused = $state(false);// OSM labels overlay: a transparent labels-only layer laid over the imagery so// roads / place names are readable without hiding the satellite view (item 1).let osmOverlay = $state(false);- let labelsLayer = null;- const LABELS_URL =- 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png';// The labels overlay only makes sense over satellite imagery — over a street// base map (OSM) it just doubles the road/place labels, so it's disabled then// and force-off if the provider changes to a non-imagery one (item 1).@@ -165,55 +158,21 @@const isWidgetBase = $derived(!!currentProvider?.widget);const captureBlocked = $derived(currentProvider?.capturable === false && !isWidgetBase);- // --- Sentinel-2: which layer, and over which window (lib/sentinel.js) ---- // Sentinel-2 is the one basemap with choices in it. Both live here and are- // packed onto the provider id, which is what the map, the capture and the- // cache all key on.- let s2Layer = $state(DEFAULT_LAYER);- // One date, not a range: a Sentinel-2 image *is* a pass on a day. (The WMTS- // window underneath is a range, so we send day/day — but a range is a mosaic- // of several passes, which is not a thing you can point at and date.)- let s2Date = $state(''); // '' = the layer's default, i.e. the most recent pass- // Cloud ceiling, in percent. 100 = render whatever passed overhead, which is- // the default because the *instance* has a filter of its own (20% in the- // standard template) and a scene above it renders as nothing at all: without- // saying MAXCC=100 we would be hiding cloudy days without ever saying so.- let s2Maxcc = $state(DEFAULT_MAXCC);- let s2MenuOpen = $state(false);- let s2MenuEl = $state(); // bound to the popover wrapper — outside-click detection- let s2Layers = $state([]); // [{id,label,hint}] — catalogue until the instance is asked- let s2LayersSource = $state('');- let s2LayersAsked = false; // the instance is asked once per session, on first open- // The month the calendar is showing, and the passes found in it:- // { 'YYYY-MM-DD': {cloud, granules} }. A day with no entry has no imagery and- // is not selectable — the same rule the Copernicus browser follows.- let s2Month = $state(monthOf(''));- let s2Passes = $state({});- let s2PassesFor = $state(''); // the month+place s2Passes describes- let s2PassesBusy = $state(false);- let s2PassesNote = $state('');- let s2VerifyingDate = $state('');- let s2CoverageRev = $state(0);- // The newest pass over this point — what "most recent" is actually showing.- // The layer's default window renders the latest acquisition, so naming it is- // the difference between a dated image and an undated one.- let s2Latest = $state('');- let s2LatestFor = $state(''); // the place s2Latest was resolved for+ // --- Sentinel-2: which layer, and over which window ---+ // The one basemap with choices in it. What has been asked, what came back and+ // what is still in flight all live in its own store; the choices ride on the+ // provider id, which is what the map, the capture and the cache key on.+ const s2 = createSentinelState({+ place: () => ({ lat: center.lat, lon: center.lon }),+ onBilled: refreshUsage,+ notify: toast,+ api,+ });const isSentinel = $derived(currentProvider?.id === SENTINEL_ID);- // A half-typed date is not a date: it stays "most recent" rather than- // becoming a request the backend would refuse.- const s2Window = $derived(- validDay(s2Date) ? { from: s2Date, to: s2Date } : { from: '', to: '' }- );// A pinned day *is* the acquisition date — the one provider that can answer// "when was this taken?" without being asked.- const s2PinnedDate = $derived(isSentinel && s2Window.from ? s2Window.from : null);- const s2LayerHint = $derived(s2Layers.find((l) => l.id === s2Layer)?.hint ?? '');- const s2LayerLabel = $derived(- s2Layers.find((l) => l.id === s2Layer)?.label ?? s2Layer.replace(/_/g, ' ').toLowerCase()- );- // the pill is small: "false colour (infrared)" doesn't fit, "FALSE COLOR" does- const s2LayerShort = $derived(s2Layer.replace(/_/g, ' '));+ const s2PinnedDate = $derived(isSentinel && s2.window.from ? s2.window.from : null);+ let s2MenuEl = $state(); // bound to the popover wrapper — outside-click detection// --- keyed-provider usage (IMAGERY_PROVIDERS.md) ---// Metered tiles are proxied through the backend, which counts each one it@@ -274,7 +233,7 @@// (lib/sentinel.js), so none of them can be rendered from one window and// filed as another.const displayedProviderId = $derived(- variantId(displayedBaseId, { layer: s2Layer, ...s2Window, maxcc: s2Maxcc })+ variantId(displayedBaseId, s2.variant));// memoized so the layer is only rebuilt when the cell actually changes// (i.e. crossing the z17 boost bracket), not on every zoom step@@ -297,7 +256,7 @@// Measure tools (item 5): distance / area / angle drawn on the map.let measureMode = $state(null); // null | 'distance' | 'area' | 'angle'let measurePoints = $state([]);- let measureLayer = null;+ let measureSurface = null; // lib/map/surface.jslet toolsOpen = $state(false);// External-maps quick links, in the SAVED panel (item 6).@@ -323,15 +282,11 @@let renameText = $state(''); // the title being typed while renaminglet reviewKey = $state(null); // 'i:j' of the cell under review, or nulllet gridSaveTimer; // debounce the persist call- let gridLayer = null; // Leaflet layerGroup of the cells- let gridAoiLayer = null; // Leaflet layerGroup of the area outline + handles- let gridDraftLayer = null; // Leaflet layerGroup of the in-progress polygon- let gridRenderer = null; // one shared canvas renderer for all the cells- let cellRects = new Map(); // 'i:j' -> Leaflet rectangle (for cheap restyles)- let aoiOutline = null; // Leaflet path: the area's dashed outline+ let gridCells = null; // lib/map/surface.js — the lattice, on a canvas+ let gridAoi = null; // …the area outline and its drag handles+ let gridDraft = null; // …the polygon being placedlet dragBounds = null; // live rect bounds while a corner handle is draggedlet liveVerts = null; // live polygon vertices while a vertex handle is dragged- let draftLine = null; // Leaflet polyline of the in-progress polygonconst gridCov = $derived(grid ? gridSearch.coverage(grid) : null);const savedOthers = $derived(gridList.filter((g) => g.name !== gridName));const GRID_MAX_CELLS = gridSearch.MAX_CELLS;@@ -339,11 +294,17 @@// clearly over dark imagery; cleared greys the cell out; flagged fills yellow// (chosen over red so it reads for colour-blind analysts too).const CELL_STYLE = {- unchecked: { color: '#ffffff', weight: 1, opacity: 0.7, fill: true, fillColor: '#fff', fillOpacity: 0 },- cleared: { color: '#ffffff', weight: 1, opacity: 0.55, fill: true, fillColor: '#2b3040', fillOpacity: 0.62 },- flagged: { color: '#ffcf33', weight: 1.5, opacity: 1, fill: true, fillColor: '#ffdb4d', fillOpacity: 0.6 },+ unchecked: { stroke: '#ffffff', strokeWidth: 1, strokeOpacity: 0.7, fill: '#fff', fillOpacity: 0 },+ cleared: { stroke: '#ffffff', strokeWidth: 1, strokeOpacity: 0.55, fill: '#2b3040', fillOpacity: 0.62 },+ flagged: { stroke: '#ffcf33', strokeWidth: 1.5, strokeOpacity: 1, fill: '#ffdb4d', fillOpacity: 0.6 },+ };+ const AOI_STYLE = {+ stroke: '#f5a623',+ strokeWidth: 1.5,+ strokeOpacity: 0.9,+ dash: '5 4',+ interactive: false,};- const AOI_STYLE = { color: '#f5a623', weight: 1.5, opacity: 0.9, fill: false, dashArray: '5 4', interactive: false };const CORNERS = ['sw', 'se', 'nw', 'ne']; // rect resize handles@@ -354,27 +315,10 @@let refPicker = $state(false); // the "pick an image" modallet refMedia = $state([]); // case images available to referencelet refLoading = $state(false);- let refQuery = $state('');- let refBrowserOpen = $state(false); // "…" swaps the grid for the folder browser- let refBrowsePath = $state('');- let refBrowseSelection = $state(null);let refSeq = 0; // id source for spawned windows- const REF_SEARCH_MIN = 6; // below that, the grid is easier to scan than to search-- // Same free-text match as the Media Library (filename, title, notes, folder,- // download source), so what works there works here.- const visibleRefMedia = $derived(- caseState.current ? refMedia.filter((m) => matchesQuery(m, refQuery)) : []- );- const refBrowserEntries = $derived(- refMedia.map((m) => ({ ...m, id: m.path, attrs: { folder: m.folder ?? '' } }))- );async function openRefPicker() {refPicker = true;- refQuery = '';- resetRefBrowser();- refBrowserOpen = false;refLoading = true;try {const id = caseState.current?.id;@@ -388,31 +332,6 @@}}- function resetRefBrowser() {- refBrowsePath = '';- refBrowseSelection = null;- }-- function toggleRefBrowser() {- if (refBrowserOpen) {- refBrowserOpen = false;- return;- }- refQuery = '';- resetRefBrowser();- refBrowserOpen = true;- }-- function openRefFolder(path) {- refBrowsePath = path;- refBrowseSelection = null;- }-- function confirmRefBrowser() {- const item = refBrowserEntries.find((entry) => entry.path === refBrowseSelection);- if (item) addRef(item);- }-function addRef(item) {const vs = uiState.refViewers;const n = vs.length;@@ -458,51 +377,49 @@providers = await api.get('/api/satellite/providers');await prefsReady; // the home view has to land before the map is builtcenter = { ...prefs.homeView };- // leaflet-rotate patches the global L, so expose it before importing.- window.L = L;- await import('leaflet-rotate');- map = L.map(mapEl, {- center: [center.lat, center.lon],- zoom: center.zoom,- zoomControl: false,- attributionControl: true,- rotate: true,- rotateControl: false,- touchRotate: true,- shiftKeyRotate: true,+ try {+ engine = await createMapEngine(mapEl, {+ view: center,+ imperial: prefs.units === 'imperial',+ });+ } catch (e) {+ // The engine draws through WebGL and a browser can refuse it: an old+ // driver, a machine with no GPU, a profile hardened to turn it off. It+ // throws on the way up, and nothing below this line means anything+ // without a map — so the tool says so instead of drawing an empty panel+ // and leaving the analyst to wonder which part broke.+ console.error(e);+ mapRefused = true;+ return null;+ }+ basemaps = createBasemaps(engine, {+ onMeteredTiles: refreshUsage,+ // one billed map load, counted where it happens (the proxy can't see it)+ onWidgetLoad: (provider) =>+ api.post(`/api/satellite/usage/${provider.meter}`).then(refreshUsage).catch(() => {}),+ onWidgetAuthFailure,+ onWidgetFailed: (provider, error) => {+ toast(`Google Maps failed to load: ${error.message}`, 'danger', 6000);+ providerId = 'esri-world-imagery';+ },});setLayer();- setOverlay();- // stacked below the top-left tool cluster (fullscreen/labels/measure) via- // CSS offset below, instead of Leaflet's default corner margin- L.control.zoom({ position: 'topleft' }).addTo(map);- // judging feature sizes (buildings, roads) needs a scale reference- L.control.scale({- metric: prefs.units !== 'imperial',- imperial: prefs.units === 'imperial',- position: 'bottomright',- }).addTo(map);- map.on('moveend zoomend', () => {- const c = map.getCenter();- // 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() };+ basemaps.setLabels(osmOverlay);+ // the façade wraps the centre back inside ±180 for us, which is what every+ // route the capture reaches enforces+ const offSettled = engine.on('view-settled', (view) => {+ center = { lat: view.lat, lon: view.lon, zoom: view.zoom };});- map.on('rotate', () => {- bearing = Math.round(map.getBearing());+ const offRotate = engine.on('rotate', (view) => {+ bearing = Math.round(view.bearing);});- map.on('click', onMapClick);- // keep tiles seam-free (see deSeamTiles): re-flatten after any reposition,- // and un-flatten right before a zoom so the reposition doesn't double-offset- map.on('moveend zoomend viewreset rotateend', scheduleDeSeam);- map.on('zoomstart', reSeamTiles);- // middle-mouse drag rotates the view (item 3). Capture-phase so we can stop- // the event before Leaflet's own container drag handler (which treats the- // middle button as a pan) ever sees it — otherwise a turn also pans.+ const offClick = engine.on('click', onMapClick);+ // middle-mouse or shift drag rotates the view (item 3). Capture-phase so we+ // can stop the event before the engine's own container drag handler ever+ // sees it — otherwise a turn also pans.mapEl.addEventListener('mousedown', onMiddleRotateStart, true);// left-drag draws the capture marquee when that mode is armed (capture-phase- // so Leaflet's pan handler never sees the gesture)+ // so the engine's pan handler never sees the gesture)mapEl.addEventListener('mousedown', onSelectStart, true);// left-drag draws a Grid Search area when the rectangle tool is armedmapEl.addEventListener('mousedown', onGridRectStart, true);@@ -517,7 +434,14 @@window.removeEventListener('keydown', onKeydown);document.removeEventListener('fullscreenchange', onFullscreenChange);offActivated();- map.remove();+ offSettled();+ offRotate();+ offClick();+ basemaps.dispose();+ for (const surface of [measureSurface, sunSurface, markerSurface, gridCells, gridAoi, gridDraft]) {+ surface?.destroy();+ }+ engine.destroy();};}@@ -554,286 +478,26 @@else if (fullscreen && !document.fullscreenElement) toggleFullscreen();}- // --- OSM labels overlay (item 1) ---- function setOverlay() {- if (!map) return;- if (osmOverlay && !labelsLayer) {- labelsLayer = L.tileLayer(LABELS_URL, {- subdomains: 'abcd',- maxZoom: 20,- pane: 'overlayPane', // above the imagery tiles, below markers/controls- attribution: '© OpenStreetMap contributors © CARTO',- }).addTo(map);- labelsLayer.on('load tileload', scheduleDeSeam); // keep overlay seam-free too- } else if (!osmOverlay && labelsLayer) {- labelsLayer.remove();- labelsLayer = null;- }- }-// force the labels overlay off whenever the base isn't imagery (item 1)$effect(() => {if (!baseIsImagery && osmOverlay) osmOverlay = false;});$effect(() => {- osmOverlay; // toggle the labels overlay- setOverlay();+ const on = osmOverlay; // read before the guard: `basemaps?.` short-circuits+ // away the dependency while the map is still being built, and the toggle+ // then never reaches the layers again (build() applies the opening state).+ if (basemaps) basemaps.setLabels(on);});- // --- Sentinel-2 layers & passes ---- // The catalogue costs nothing and reaches no network (the backend answers it- // from its own list); `check` asks the user's instance what it really serves,- // which is the only authority — a configuration can rename or drop any layer.- async function loadS2Layers(check = false, quiet = false) {- try {- const r = await api.get(`/api/satellite/sentinel/layers${check ? '?check=true' : ''}`);- s2Layers = r.layers ?? [];- s2LayersSource = r.source ?? '';- // a layer that vanished with the list can't stay selected- if (s2Layers.length && !s2Layers.some((l) => l.id === s2Layer)) s2Layer = s2Layers[0].id;- if (quiet) return;- if (check && r.detail) toast(r.detail, 'warn', 6000);- else if (check && r.source === 'instance') {- toast(`${r.layers.length} layers read from your instance`, 'ok');- }- } catch (e) {- toast(`Sentinel-2 layers: ${e.message}`, 'danger');- }- }-- function toggleS2Menu() {- s2MenuOpen = !s2MenuOpen;- if (!s2MenuOpen) return;- // Ask the instance what it actually serves, once per session. The built-in- // list is only a fallback: a configuration serves whatever it was built- // with, and offering a layer that isn't there just 400s when picked.- if (!s2LayersAsked) {- s2LayersAsked = true;- loadS2Layers(true, true);- } else if (!s2Layers.length) {- loadS2Layers(false);- }- loadS2Passes();- }-- // Passes are looked up per month *and* per place — Sentinel-2's swath means- // the answer genuinely differs a few km away. Cached so paging back to a- // month already seen is free; the key is the map centre rounded to ~100 m,- // because a nudge of the map is not a new question.- const s2PassCache = new Map();- const s2PassPending = new Map();- const s2CoverageCache = new Map();- const s2PlaceKey = () => sentinelPlaceKey(center.lat, center.lon);- // the ceiling is part of the question: the same day is available under 100%- // and a gap under 20%, so a cached answer must not outlive the number- const s2CoverageKey = (day, place = s2PlaceKey(), layer = s2Layer, maxcc = s2Maxcc) =>- `${layer}@${maxcc}@${day}@${place}`;- let s2PassRequestId = 0;- let s2PickRequestId = 0;-- /**- * One month's passes over one place: `{ 'YYYY-MM-DD': {cloud, granules} }`,- * or null when the lookup failed. Cached — paging back to a month already- * seen must not spend a second request.- */- async function fetchS2Month(- month, place, force = false, lat = center.lat, lon = center.lon- ) {- const key = `${month}@${place}`;- if (!force && s2PassCache.has(key)) return s2PassCache.get(key);- if (!force && s2PassPending.has(key)) return s2PassPending.get(key);- if (force) s2PassCache.delete(key);- const { from, to } = monthBounds(month);- const request = (async () => {- try {- const r = await api.get(- `/api/satellite/sentinel/dates?lat=${lat}&lon=${lon}` +- `&start=${from}&end=${to}`- );- const byDay = {};- for (const d of r.dates) byDay[d.date] = { cloud: d.cloud, granules: d.granules };- s2PassCache.set(key, byDay);- refreshUsage(); // the lookup is billed: keep the pill honest- return byDay;- } catch {- return null;- }- })();- s2PassPending.set(key, request);- try {- return await request;- } finally {- if (s2PassPending.get(key) === request) s2PassPending.delete(key);- }- }-- /**- * Which days Sentinel-2 actually passed over this point, and how cloudy each- * was. This is what makes the calendar honest: a day with no pass is not- * selectable, so you can't pick a date, pay for a tile and discover it was a- * coverage gap. One metadata request per month (~1/100th of a tile's- * processing units), only while the picker is open.- */- async function loadS2Passes(force = false) {- const requestId = ++s2PassRequestId;- const lat = center.lat;- const lon = center.lon;- const place = s2PlaceKey();- const key = `${s2Month}@${place}`;- s2PassesBusy = true;- s2PassesNote = '';- const days = await fetchS2Month(s2Month, place, force, lat, lon);- if (requestId !== s2PassRequestId) return;- if (days) {- s2Passes = days;- s2PassesFor = key;- if (!Object.keys(days).length) s2PassesNote = 'No Sentinel-2 pass here this month.';- } else {- // an empty month and a failed lookup are different facts. Never blur them:- // greying every day out because the network hiccuped would be a lie about- // what exists.- s2Passes = {};- s2PassesFor = '';- s2PassesNote = 'Could not read this month’s passes. The days below do not confirm coverage.';- }- s2PassesBusy = false;- }-- function stepS2Month(delta) {- s2Month = addMonths(s2Month, delta);- loadS2Passes();- }-- /**- * Which pass "most recent" is showing. Sentinel-2 revisits every ~5 days, so- * this month usually answers it; early in a month it may not, and one step- * back does. Two requests at worst, once per place — the alternative is a- * basemap that can't say what date it is showing, which for satellite- * imagery is most of the point.- */- async function resolveS2Latest() {- const place = s2PlaceKey();- const maxcc = s2Maxcc;- const key = `${place}@${maxcc}`;- if (s2LatestFor === key) return;- const today = isoDay(new Date());- for (const month of [monthOf(today), addMonths(monthOf(today), -1)]) {- const days = await fetchS2Month(month, place);- if (days === null) return; // lookup failed — say nothing rather than guess- // the ceiling drops cloudy passes from the tiles, so "most recent" is the- // newest pass it still allows, not the newest pass there is- const latest = latestAllowedPass(days, today, maxcc);- if (latest) {- s2Latest = latest;- s2LatestFor = key;- return;- }- }- // no pass in ~2 months: real (deep polar winter, persistent gaps) — the- // pill falls back to "most recent" rather than inventing a date- s2Latest = '';- s2LatestFor = key;- }-- function clearS2Date() {- s2PickRequestId += 1;- s2VerifyingDate = '';- s2Date = '';- }-- function s2DateStatus(day) {- s2CoverageRev;- return s2CoverageCache.get(s2CoverageKey(day));- }-- /** Is this day's pass above the ceiling, i.e. filtered out of the tiles? */- function s2Filtered(day) {- return overCloudCeiling(s2Passes[day]?.cloud, s2Maxcc);- }-- /**- * A new cloud ceiling. It reaches the tiles through the provider id, so the- * only thing left to settle is a pinned date the new ceiling excludes: that- * day renders nothing, so it goes back to most recent rather than to a blank- * map nobody asked for.- */- function setS2Maxcc(value) {- const ceiling = Math.round(Number(value));- if (!validMaxcc(ceiling) || ceiling === s2Maxcc) return;- s2Maxcc = ceiling;- if (s2Date && overCloudCeiling(s2Passes[s2Date]?.cloud, ceiling)) {- const cloud = cloudLabel(s2Passes[s2Date].cloud);- const day = s2Date;- clearS2Date();- toast(`${day} is ${cloud}, over the ${ceiling}% ceiling. Back to most recent.`, 'warn');- }- }-- async function pickS2Date(day) {- if (day === s2Date) {- clearS2Date();- return;- }- if (!s2Passes[day] || s2PassesStale || s2PassesBusy || s2VerifyingDate) return;- if (s2Filtered(day)) {- toast(`${day} is ${cloudLabel(s2Passes[day].cloud)}, over the ${s2Maxcc}% ceiling.`, 'warn');- return;- }-- const lat = center.lat;- const lon = center.lon;- const place = s2PlaceKey();- const layer = s2Layer;- const maxcc = s2Maxcc;- const key = s2CoverageKey(day, place, layer, maxcc);- const known = s2CoverageCache.get(key);- if (known === true) {- s2Date = day;- return;- }- if (known === false) {- toast(`No imagery at the crosshair on ${day}.`, 'warn');- return;- }-- const requestId = ++s2PickRequestId;- s2VerifyingDate = day;- try {- const result = await api.get(coverageRequestPath({ lat, lon, layer, date: day, maxcc }));- s2CoverageCache.set(key, result.available === true);- s2CoverageRev += 1;- refreshUsage();- if (requestId !== s2PickRequestId) return;- if (place !== s2PlaceKey() || layer !== s2Layer || maxcc !== s2Maxcc) {- toast('The view changed. Pick the date again.', 'warn');- return;- }- s2Date = dateAfterCoverage(s2Date, day, result.available);- if (!result.available) toast(`No imagery at the crosshair on ${day}.`, 'warn');- } catch (e) {- if (requestId === s2PickRequestId) {- toast(`Could not check imagery for ${day}: ${e.message}`, 'danger');- }- } finally {- if (requestId === s2PickRequestId) s2VerifyingDate = '';- }- }-- // The passes on screen describe the place they were fetched for; once the map- // has moved somewhere else they are stale and must not grey out real imagery.- const s2PassesStale = $derived(- !!s2PassesFor && s2PassesFor !== `${s2Month}@${s2PlaceKey()}`- );-// While the picker is open, a settled pan refreshes its dates. The stale// cells are disabled immediately; the debounce avoids a request per frame.$effect(() => {- if (!s2MenuOpen || !isSentinel) return;- s2Month;- s2PlaceKey();+ if (!s2.menuOpen || !isSentinel) return;+ s2.month;+ s2.placeKey;clearTimeout(s2PassTimer);- s2PassTimer = setTimeout(() => loadS2Passes(), 600);+ s2PassTimer = setTimeout(() => s2.loadPasses(), 600);return () => clearTimeout(s2PassTimer);});let s2PassTimer;@@ -846,10 +510,10 @@if (!mapReady || displayedBaseId !== SENTINEL_ID) return;center.lat;center.lon;- s2Maxcc; // a new ceiling can make a different pass the most recent one+ s2.maxcc; // a new ceiling can make a different pass the most recent oneclearTimeout(s2LatestTimer);// debounced: panning must not spend a request per frame- s2LatestTimer = setTimeout(() => resolveS2Latest().catch(() => {}), 900);+ s2LatestTimer = setTimeout(() => s2.resolveLatest().catch(() => {}), 900);});let s2LatestTimer;@@ -880,42 +544,23 @@// --- middle-drag rotate (item 3), Google-Earth style ---// Grab a point → the map turns around *that* point (not the centre) as the- // cursor sweeps, with a sober target marking the pivot. Leaflet only rotates+ // cursor sweeps, with a sober target marking the pivot. A map only rotates// about the centre, so after each bearing change we pan the grabbed geographic// point back under the cursor — keeping it pinned exactly where you grabbed.- const ROTATE_DEADZONE = 8; // px to leave the pivot before the spoke is fixedfunction onMiddleRotateStart(e) {- if (e.button !== 1 || !map) return;- // own the gesture: no Leaflet pan, no browser middle-click autoscroll- e.stopPropagation();- e.preventDefault();- const rect = mapEl.getBoundingClientRect();- const grab = L.point(e.clientX - rect.left, e.clientY - rect.top);- const pivotLatLng = map.containerPointToLatLng(grab); // the pinned location- const startBearing = map.getBearing();- const startScreen = { x: e.clientX, y: e.clientY };- rotatePivot = { x: grab.x, y: grab.y };- rotating = true;- let startAngle = null; // reference spoke, fixed once out of the deadzone- const move = (ev) => {- if (startAngle === null) {- if (Math.hypot(ev.clientX - startScreen.x, ev.clientY - startScreen.y) < ROTATE_DEADZONE) return;- startAngle = { x: ev.clientX, y: ev.clientY };- return;- }- setBearing(dragBearing(startBearing, startScreen, startAngle, { x: ev.clientX, y: ev.clientY }));- // re-pin: pan the grabbed location back under the grab point- const now = map.latLngToContainerPoint(pivotLatLng);- const [dx, dy] = pivotPanOffset(grab, now);- if (dx || dy) map.panBy([dx, dy], { animate: false });- };- const up = () => {- rotating = false;- window.removeEventListener('mousemove', move);- window.removeEventListener('mouseup', up);- };- window.addEventListener('mousemove', move);- window.addEventListener('mouseup', up);+ if (!engine) return;+ // Middle button, or shift and the left one — the second was the old map's+ // own gesture, kept rather than quietly dropped. Never shift over a mode+ // already waiting for a left drag, though: those own the button.+ const shiftDrag = e.button === 0 && e.shiftKey && !selectArmed && gridDraw !== 'rect';+ if (e.button !== 1 && !shiftDrag) return;+ startRotateDrag(engine, e, {+ onPivot: (pivot) => {+ rotatePivot = pivot;+ rotating = true;+ },+ onEnd: () => (rotating = false),+ });}function startEditBearing() {@@ -963,35 +608,35 @@}fullscreen = !fullscreen;await tick();- map?.invalidateSize();+ engine?.resize();}function onFullscreenChange() {if (document.fullscreenElement === toolEl) fullscreen = true;else if (!document.fullscreenElement) fullscreen = false;- tick().then(() => map?.invalidateSize());+ tick().then(() => engine?.resize());}// --- measure tools (item 5) ---- function onMapClick(e) {+ /** Where the analyst clicked, `{ lat, lon }` from the façade. */+ function onMapClick(at) {// Grid Search polygon: each click drops a vertexif (gridDraw === 'polygon') {- polyDraft = [...polyDraft, { lat: e.latlng.lat, lon: e.latlng.lng }];+ polyDraft = [...polyDraft, at];renderDraft();return;}// Sun & moon: one click plants the anchor the day's path is drawn fromif (sunPlacing) {- sunAnchor = { lat: e.latlng.lat, lon: e.latlng.lng };+ sunAnchor = at;sunSky = null;sunPlacing = false;return;}if (!measureMode) return;- const pt = { lat: e.latlng.lat, lon: e.latlng.lng };// an angle is exactly three points; a fourth click starts a fresh angleif (measureMode === 'angle' && measurePoints.length >= 3) measurePoints = [];- measurePoints = [...measurePoints, pt];+ measurePoints = [...measurePoints, at];redrawMeasure();}@@ -999,7 +644,7 @@measureMode = measureMode === m ? null : m;if (measureMode) selectArmed = false; // measuring and marquee can't both be armedmeasurePoints = [];- measureLayer?.clearLayers();+ measureSurface?.clear();}// toggling the panel shut also drops any active measure tool — otherwise the@@ -1011,31 +656,31 @@function clearMeasure() {measurePoints = [];- measureLayer?.clearLayers();+ measureSurface?.clear();}+ const MEASURE_STROKE = { stroke: '#f5a623', strokeWidth: 2.5, strokeOpacity: 0.95 };+ const MEASURE_DOT = {+ radius: 4,+ stroke: '#fff',+ strokeWidth: 2,+ fill: '#f5a623',+ fillOpacity: 1,+ };+function redrawMeasure() {- if (!map) return;- if (!measureLayer) measureLayer = L.layerGroup().addTo(map);- measureLayer.clearLayers();- const latlngs = measurePoints.map((p) => [p.lat, p.lon]);- const stroke = { color: '#f5a623', weight: 2.5, opacity: 0.95 };- if (measureMode === 'area' && latlngs.length >= 2) {- L.polygon(latlngs, { ...stroke, fillColor: '#f5a623', fillOpacity: 0.15 }).addTo(- measureLayer- );- } else if (latlngs.length >= 2) {- L.polyline(latlngs, stroke).addTo(measureLayer);- }- for (const p of measurePoints) {- L.circleMarker([p.lat, p.lon], {- radius: 4,- color: '#fff',- weight: 2,- fillColor: '#f5a623',- fillOpacity: 1,- }).addTo(measureLayer);- }+ if (!engine) return;+ measureSurface ??= createSurface(engine);+ const path =+ measurePoints.length < 2+ ? null+ : measureMode === 'area'+ ? { kind: 'polygon', points: measurePoints, style: { ...MEASURE_STROKE, fill: '#f5a623', fillOpacity: 0.15 } }+ : { kind: 'line', points: measurePoints, style: MEASURE_STROKE };+ measureSurface.set([+ path,+ ...measurePoints.map((point) => ({ kind: 'dot', at: point, style: MEASURE_DOT })),+ ]);}const measureReadout = $derived.by(() => {@@ -1069,151 +714,30 @@if (row.source_url && !fullscreen) window.open(row.source_url, '_blank', 'noopener,noreferrer');return;}- if (!map) return;- map.setView([row.lat, row.lon], Number(row.zoom) || map.getZoom());- setBearing(Number(row.bearing) || 0);- }-- // --- tile seam fix ---- // Leaflet positions each tile with a `translate3d(...)` transform, which- // promotes it to its own GPU layer. At fractional OS display scaling (e.g.- // 125/150%) an integer CSS position lands on a half physical pixel, so every- // tile edge is antialiased independently and bleeds the map background as a- // faint white grid — browser- and zoom-independent. Painting tiles with plain- // left/top (no transform, no backface-visibility promotion — see CSS) keeps- // them in the shared pane layer, where neighbouring edges meet on whole- // pixels. Rotation/zoom still use their own pane transforms, so both keep- // working. We convert after Leaflet positions the tiles, and revert to- // transform positioning just before a zoom so the reposition is glitch-free.- let deSeamRaf = 0;- function deSeamTiles() {- deSeamRaf = 0;- if (!mapEl) return;- for (const t of mapEl.querySelectorAll('.leaflet-tile')) {- const m = /translate3d\((-?[\d.]+)px,\s*(-?[\d.]+)px/.exec(t.style.transform);- if (!m) continue; // already flat, or a rotated matrix we shouldn't touch- t.style.left = m[1] + 'px';- t.style.top = m[2] + 'px';- t.style.transform = 'none';- }- }- function scheduleDeSeam() {- if (!deSeamRaf) deSeamRaf = requestAnimationFrame(deSeamTiles);- }- // put the translate transform back before Leaflet repositions tiles for a new- // zoom, so a tile is never briefly offset by both left/top and translate3d- function reSeamTiles() {- if (!mapEl) return;- for (const t of mapEl.querySelectorAll('.leaflet-tile')) {- if (t.style.transform === 'none' && t.style.left) {- t.style.transform = `translate3d(${t.style.left}, ${t.style.top}, 0)`;- t.style.left = '';- t.style.top = '';- }- }+ if (!engine) return;+ engine.setView(row, Number(row.zoom) || engine.getZoom());+ setBearing(row.bearing);}- // The Google widget layer is created ONCE and reused across basemap- // switches: every google.maps.Map instantiation is a billed dynamic map- // load, while re-adding the same layer costs nothing. Never destroyed- // until the tool unmounts, for the same reason.- let mutantLayer = null;+ // The layers are lib/map's (basemap.js); what reaches them from here is which+ // provider to show and what a billed one owes the usage pill and Settings.+ function setLayer() {+ if (!displayedProvider || !basemaps) return;+ basemaps.show(displayedProvider, displayedProviderId, displayedCell);+ }- async function setWidgetLayer(p) {+ // Google rejected the Maps JavaScript key. Persist the verdict (which benches+ // the basemap), tell the user, and let the provider refetch fall the map back+ // to Esri.+ async function onWidgetAuthFailure(provider) {try {- await loadGoogleMaps(p.url, {- onAuthFailure: async () => {- // Google's only key-rejection signal — can fire minutes after a- // clean load. Persist the verdict (benches the basemap), tell the- // user, and let the provider refetch fall the map back to Esri.- try {- await api.post(`/api/settings/keys/${p.meter}/status`, {- ok: false,- detail: 'Google rejected the Maps JavaScript key (gm_authFailure)',- });- } catch { /* the toast still tells the user */ }- toast('Google rejected the Maps JavaScript key. Basemap disabled; see Settings', 'danger', 8000);- providers = await api.get('/api/satellite/providers');- },+ await api.post(`/api/settings/keys/${provider.meter}/status`, {+ ok: false,+ detail: 'Google rejected the Maps JavaScript key (gm_authFailure)',});- } catch (e) {- toast(`Google Maps failed to load: ${e.message}`, 'danger', 6000);- providerId = 'esri-world-imagery';- return;- }- if (displayedProvider?.id !== p.id) return; // user moved on while loading- if (!mutantLayer) {- mutantLayer = createSatelliteMutant(p.max_zoom, p.attribution);- // one billed map load, counted where it happens (the proxy can't see it)- api.post(`/api/satellite/usage/${p.meter}`).then(refreshUsage).catch(() => {});- }- // Already the live layer — leave it alone. Returning to this tab refetches- // the providers, and the fresh objects re-run the layer effect, so this is- // the common path rather than an edge case. Re-adding costs no map load- // (the mutant reuses its google.maps.Map), but Leaflet drops and re-clones- // every tile in the grid, which reads on screen as a reloading map.- if (tileLayer === mutantLayer) return;- if (tileLayer) tileLayer.remove();- if (map.getZoom() > p.max_zoom) map.setZoom(p.max_zoom);- tileLayer = mutantLayer.addTo(map);- }-- function setLayer() {- const p = displayedProvider;- if (!p || !map) return;- if (p.widget) {- setWidgetLayer(p);- return;- }- // every provider goes through the backend tile proxy: keys and session- // tokens stay server-side, every billed tile is counted exactly once- // (browser cache hits never reach the proxy), cacheable providers share- // the disk tile cache, and coverage gaps come back overzoomed instead of- // as "not yet available" placards. Only {s} subdomain templates (custom- // providers) stay direct — the proxy can't expand those.- const url = p.url.includes('{s}') ? p.url : `/api/tiles/${displayedProviderId}/{z}/{x}/{y}`;- // maxZoom caps the map itself (no map-level maxZoom is set), which is what- // keeps a shallower provider (OpenTopoMap, z17) from ever being asked for- // tiles it would answer with a "max zoom layer" placard — and keeps the- // view zoom at or under the provider max, which capture sizing relies on.- const opts = { attribution: p.attribution, maxZoom: p.max_zoom };- // Where a provider's pixels stop short of its useful view (Sentinel-2:- // native z14, view z18), Leaflet keeps requesting the native level and- // scales those tiles up in CSS. The extra zoom therefore costs nothing —- // asking Sentinel Hub for z18 would buy its upsampling of the same pixels,- // 16× the tiles, every one billed.- if (p.max_native_zoom != null) opts.maxNativeZoom = p.max_native_zoom;- // grid cell in CSS px (lib/usage.js layerCell): bigger tiles offset the- // URL z down (512 → -1, 1024 → -2); an oversample halves the cell so each- // tile is shown downscaled — deeper zoom on screen. Google's mid-zoom- // mosaics are genuinely softer than its deep ones (verified), so this is- // what makes the paid imagery actually look paid.- if (displayedCell !== 256 || p.tile_size > 256) {- opts.tileSize = displayedCell;- opts.zoomOffset = -Math.log2(displayedCell / 256);- opts.minNativeZoom = 0; // never ask for negative URL z at world zooms- }- if (p.meter) {- // billed tiles: skip the throwaway fetches Leaflet makes mid-zoom-animation- // (intermediate zoom levels that get discarded). Deliberately NOT- // updateWhenIdle: it delays sharp tiles until the map fully settles,- // leaving the scaled-up previous zoom (visible blur) on screen — and it- // saves nothing, since each visible tile is only ever fetched once.- opts.updateWhenZooming = false;- opts.keepBuffer = 4;- }- if (tileLayer) tileLayer.remove();- // Past its maxZoom Leaflet drops a grid layer entirely rather than upscale- // it, so switching to a shallower provider (OpenTopoMap, z17) while zoomed- // deeper would leave a blank map. Pull the view back to what it can serve.- if (map.getZoom() > p.max_zoom) map.setZoom(p.max_zoom);- tileLayer = L.tileLayer(url, opts).addTo(map);- tileLayer.on('load tileload', scheduleDeSeam);- if (p.meter) {- refreshUsage();- // 'load' fires once all visible tiles are in — keep the pill current- tileLayer.on('load', refreshUsage);- }+ } catch { /* the toast still tells the user */ }+ toast('Google rejected the Maps JavaScript key. Basemap disabled; see Settings', 'danger', 8000);+ providers = await api.get('/api/satellite/providers');}$effect(() => {@@ -1237,23 +761,20 @@api.get('/api/satellite/providers').then((r) => (providers = r));});+ // A different case drops everything this one was holding: both indexes, the+ // dialogs open over them, and the two session layers.+ let openFor = null;$effect(() => {const id = caseState.current?.id;caseState.rev; // re-fetch when the case is reloaded elsewhere (e.g. sidebar delete)- if (savedFor !== id) {- savedFor = id;- saved = [];- savedProofs = [];- proofsFor = null;+ if (openFor !== id) {+ openFor = id;savedSearchOpen = false;hoveredSavedId = null;revealSavedId = null;deleteTarget = null;notesItem = null;placeModal = null;- locateStopped = true;- locateGeneration += 1;- locating = null;temporalMapSeq += 1;temporalMap = null;temporalMapLoading = false;@@ -1261,55 +782,34 @@// The points came out of another case's sheet, so they go with it.sheetPoints = null;}- if (!id) {- return;- }- let live = true;- api- .get(`/api/cases/${id}/satellite/index`)- .then((rows) => { if (live) saved = rows; })- .catch(() => { if (live) saved = []; });- return () => { live = false; };+ return savedWork.load(id);});- // The proofs index, read the first time the Proofs position is opened. Keyed- // on the case *and its revision*: filing or saving a proof reloads the case,- // and a stale list would still show the folder the proof just left.- $effect(() => {- const id = caseState.current?.id;- const stamp = `${id}:${caseState.rev}`;- if (!id || !isMode(savedKind) || proofsFor === stamp) return;- proofsFor = stamp;- let live = true;- api- .get(`/api/cases/${id}/proofs/index`)- .then((rows) => { if (live) savedProofs = rows; })- .catch(() => { if (live) { savedProofs = []; proofsFor = null; } });- return () => { live = false; };- });+ // The proofs index, read the first time the Proofs position is opened.+ $effect(() => savedWork.loadProofs(caseState.current?.id, caseState.rev));// another workspace asked to show one capture: clear whatever filter is on so// it can't be hidden, then let the tree open its branch and scroll to it$effect(() => {const path = uiState.focusCapture;if (!path) return;- const row = saved.find((item) => item.path === path);+ const row = savedWork.rows.find((item) => item.path === path);if (!row) return;uiState.focusCapture = null;capturesCollapsed = false;- savedKind = 'all';- savedQuery = '';+ savedWork.kind = 'all';+ savedWork.query = '';revealSavedId = row.id;});// the map container resizes when the sidebar toggles or is dragged wider, and// reappears from display:none when the tool tab is re-selected (tools stay- // mounted) — all need Leaflet to re-measure and redraw tiles for the exposed area+ // mounted) — all need the map to re-measure and redraw for the exposed area$effect(() => {uiState.sidebarOpen; // track the global sidebar toggleuiState.sidebarW; // …and its width, live through a resize dragif (!mapReady || uiState.tool !== 'satellite') return;- tick().then(() => map?.invalidateSize());+ tick().then(() => engine?.resize());});// fly to coordinates handed off from the sidebar (place entity click) —@@ -1322,9 +822,9 @@if (target.provider && providers.some((provider) => provider.id === target.provider)) {providerId = target.provider;}- const zoom = Number.isFinite(target.zoom) ? target.zoom : Math.max(map.getZoom(), 16);- map.setView([target.lat, target.lon], zoom);- setBearing(Number.isFinite(target.bearing) ? target.bearing : 0);+ const zoom = Number.isFinite(target.zoom) ? target.zoom : Math.max(engine.getZoom(), 16);+ engine.setView(target, zoom);+ setBearing(target.bearing);}});@@ -1341,9 +841,8 @@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 });+ engine?.fitPoints(handed.points, { padding: [48, 48], maxZoom: 17 });});});@@ -1378,13 +877,11 @@// it pulled the view out to whatever continents the case has saved work on,// which reads as the layer showing everything rather than showing nothing.// With nothing to frame, the map stays where the analyst left it.- const points = result.items.flatMap((item) =>- item.place_entities.map((place) => [place.lat, place.lon])- );+ const points = result.items.flatMap((item) => item.place_entities);if (!points.length) return;tick().then(() => {- if (run !== temporalMapSeq || !map) return;- map.fitBounds(L.latLngBounds(points), { padding: [54, 54], maxZoom: 14 });+ if (run !== temporalMapSeq) return;+ engine?.fitPoints(points, { padding: [54, 54], maxZoom: 14 });});}).catch((error) => {@@ -1443,7 +940,7 @@let sunSky = $state(null);let sunLoading = $state(false);let sunPlacing = $state(false);- let sunLayer = null;+ let sunSurface = null; // lib/map/surface.jslet sunTicket = 0;function toggleSunMode() {@@ -1455,7 +952,7 @@if (!sunAnchor) sunAnchor = markerLatLng ?? { lat: center.lat, lon: center.lon };} else {sunPlacing = false;- sunLayer?.clearLayers();+ sunSurface?.clear();}}@@ -1504,38 +1001,24 @@return value || fallback;}- // The body itself, as a mark on its own ray: it rides between the anchor, which- // stands for the zenith, and the arc, which stands for the horizon, so how far- // up it is reads as how close to you it is. The geometry and the glyph are in- // `lib/skyOverlay.js`; this only hands them to Leaflet.- function bodyIcon(kind, colour, illuminated, waxing) {- const size = 20;- return L.divIcon({- className: 'sky-body', // replaces Leaflet's boxed default- html: bodySvg(kind, colour, illuminated, waxing, size),- iconSize: [size, size],- iconAnchor: [size / 2, size / 2],- });- }+ const SKY_BODY_SIZE = 20;function drawSun() {- if (!map) return;- if (!sunLayer) sunLayer = L.layerGroup().addTo(map);- sunLayer.clearLayers();- if (!sunMode || !sunSky || !sunAnchor) return;+ if (!engine) return;+ sunSurface ??= createSurface(engine);+ if (!sunMode || !sunSky || !sunAnchor) {+ sunSurface.clear();+ return;+ }const origin = sunAnchor;- const bounds = map.getBounds();// Sized off the *shorter* side of the view, not its diagonal: the arc is a// circle around the anchor, so a radius set by the diagonal runs off the top// and bottom of a wide window.- const across = map.distance(bounds.getNorthWest(), bounds.getNorthEast());- const down = map.distance(bounds.getNorthWest(), bounds.getSouthWest());+ const { across, down } = engine.viewSpanMeters();const reach = Math.min(across, down) * 0.22;- const at = (azimuth, scale = 1) => {- const point = measure.destination(origin, azimuth, reach * scale);- return [point.lat, point.lon];- };+ const at = (azimuth, scale = 1) => measure.destination(origin, azimuth, reach * scale);const curve = sunSky.curve;+ const shapes = [];for (const body of [{@@ -1554,58 +1037,73 @@},]) {// Thin and translucent: the imagery underneath is what is being read.+ const thin = { stroke: body.colour, strokeWidth: 2.5, strokeOpacity: 0.9 };for (const run of upRuns(body.altitude)) {- L.polyline(- run.map((i) => at(body.azimuth[i])),- { color: body.colour, weight: 2.5, opacity: 0.9 }- ).addTo(sunLayer);+ shapes.push({ kind: 'line', points: run.map((i) => at(body.azimuth[i])), style: thin });}for (const { index: i, long } of hourTicks(curve.minutes, body.altitude)) {- L.polyline([at(body.azimuth[i], 0.94), at(body.azimuth[i], long ? 1.1 : 1.03)], {- color: body.colour,- weight: 2.5,- opacity: 0.9,- })- .bindTooltip(`${body.label} ${curve.clock[i]} · az ${Math.round(body.azimuth[i])}°`)- .addTo(sunLayer);+ shapes.push({+ kind: 'line',+ points: [at(body.azimuth[i], 0.94), at(body.azimuth[i], long ? 1.1 : 1.03)],+ style: thin,+ tip: `${body.label} ${curve.clock[i]} · az ${Math.round(body.azimuth[i])}°`,+ });}const altitude = body.altitude[sunIndex];const below = isBelow(altitude);const reading = bodyReading(body.label, curve.clock[sunIndex], body.azimuth[sunIndex], altitude);- L.polyline([[origin.lat, origin.lon], at(body.azimuth[sunIndex])], {- color: body.colour,- weight: 3.5,- opacity: below ? 0.6 : 1,- dashArray: below ? '6 6' : null,- })- .bindTooltip(reading, { sticky: true })- .addTo(sunLayer);+ shapes.push({+ kind: 'line',+ points: [origin, at(body.azimuth[sunIndex])],+ style: {+ stroke: body.colour,+ strokeWidth: 3.5,+ strokeOpacity: below ? 0.6 : 1,+ dash: below ? '6 6' : null,+ },+ tip: { text: reading, sticky: true },+ });// Nothing rides the ray while the body is under the horizon: the dashed// ray already says where it is, and a mark on it would claim it is visible.+ //+ // The body itself is a mark on its own ray: it rides between the anchor,+ // which stands for the zenith, and the arc, which stands for the horizon,+ // so how far up it is reads as how close to you it is. The geometry and+ // the glyph are in `lib/skyOverlay.js`.if (!below) {- L.marker(at(body.azimuth[sunIndex], markScale(altitude)), {- icon: bodyIcon(+ shapes.push({+ kind: 'marker',+ at: at(body.azimuth[sunIndex], markScale(altitude)),+ className: 'sky-body', // replaces the engine's boxed default+ html: bodySvg(body.key,body.colour,curve.moon_illuminated[sunIndex],- sunSky.moon.waxing+ sunSky.moon.waxing,+ SKY_BODY_SIZE),+ size: [SKY_BODY_SIZE, SKY_BODY_SIZE],+ anchor: [SKY_BODY_SIZE / 2, SKY_BODY_SIZE / 2],keyboard: false,- })- .bindTooltip(body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading)- .addTo(sunLayer);+ tip: body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading,+ });}}- L.circleMarker([origin.lat, origin.lon], {- radius: 4,- color: '#fff',- weight: 2,- fillColor: themeColour('--accent', '#e8a33d'),- fillOpacity: 1,- }).addTo(sunLayer);+ shapes.push({+ kind: 'dot',+ at: origin,+ style: {+ radius: 4,+ stroke: '#fff',+ strokeWidth: 2,+ fill: themeColour('--accent', '#e8a33d'),+ fillOpacity: 1,+ },+ });+ sunSurface.set(shapes);}// Redraw on any of: a new day, a new hour, a new anchor, the mode closing.@@ -1620,9 +1118,7 @@// The arc is drawn in metres, so a zoom or a pan has to restretch it.$effect(() => {if (!mapReady || !sunMode) return;- const redraw = () => drawSun();- map.on('zoomend moveend', redraw);- return () => map.off('zoomend moveend', redraw);+ return engine.on('view-settled', () => drawSun());});let searching = $state(false);@@ -1634,13 +1130,13 @@// coordinates first (decimal or DMS); anything else is a place nametry {const parsed = await api.post('/api/geo/parse', { text });- map.setView([parsed.lat, parsed.lon], Math.max(map.getZoom(), 16));+ engine.setView(parsed, Math.max(engine.getZoom(), 16));return;} catch {/* not coordinates — fall through to geocoding */}const place = await api.get(`/api/geo/geocode?q=${encodeURIComponent(text)}`);- map.setView([place.lat, place.lon], Math.max(map.getZoom(), 13));+ engine.setView(place, Math.max(engine.getZoom(), 13));if (place.display_name) toast(place.display_name, 'info', 5000);} catch {toast('No match. Try coordinates ("50.4501, 30.5234"), DMS, or a place name', 'danger');@@ -1657,13 +1153,12 @@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));+ if (!engine || !Number.isFinite(item.lat) || !Number.isFinite(item.lon)) return;+ engine.setView(item, item.zoom ?? Math.max(engine.getZoom(), 13));}function setBearing(deg) {- if (!map) return;- map.setBearing(((deg % 360) + 360) % 360);+ engine?.setBearing(deg); // the façade normalises whatever it is handed}function resetNorth() {@@ -1720,19 +1215,15 @@let selectArmed = $state(false); // marquee mode: drag a box on the map to capturelet selRect = $state(null); // live marquee { x0, y0, x1, y1 } in map-container px+ const PIN = 'pin'; // the one shape on the move-mode surface+function markerIcon(style) {const { size, anchor } = markerGeometry(style);- return L.divIcon({- className: 'sat-marker',- iconSize: size,- iconAnchor: anchor,- html: markerSvg(style),- });+ return { className: 'sat-marker', html: markerSvg(style), size, anchor };}function removeMarker() {- if (marker) marker.remove();- marker = null;+ markerSurface?.clear();markerLatLng = null;}@@ -1743,17 +1234,20 @@removeMarker();return;}- const c = map.getCenter();- marker = L.marker(c, {- draggable: true,- icon: markerIcon(markerStyle),- zIndexOffset: 1000,- }).addTo(map);- markerLatLng = { lat: c.lat, lon: c.lng };- marker.on('drag move', () => {- const p = marker.getLatLng();- markerLatLng = { lat: p.lat, lon: p.lng };- });+ const c = engine.camera();+ markerSurface ??= createSurface(engine);+ markerLatLng = { lat: c.lat, lon: c.lon };+ markerSurface.set([+ {+ id: PIN,+ kind: 'marker',+ at: markerLatLng,+ ...markerIcon(markerStyle),+ draggable: true,+ zIndex: 1000,+ onDrag: (at) => (markerLatLng = at),+ },+ ]);}// keep the live marker's look in sync with the chosen style; leaving move@@ -1762,42 +1256,42 @@if (markerStyle === 'none' && moveMode) {moveMode = false;removeMarker();- } else if (marker) {- marker.setIcon(markerIcon(markerStyle));+ } else if (markerSurface?.has(PIN)) {+ markerSurface.patch(PIN, { icon: markerIcon(markerStyle) });}});- // The single capture path. `centerLL` frames the crop (a Leaflet LatLng);- // `baseW`/`baseH` are the crop size at the current view zoom, then scaled to- // the chosen output resolution. `rectCss` is the same frame as a rectangle in- // map-container px — only the widget path needs it, since it crops screen- // pixels rather than stitching tiles. The recorded point is the moved pin (if- // any), else the crop centre.- async function doCapture(centerLL, baseW, baseH, rectCss) {+ // The single capture path. `framedOn` is the `{ lat, lon }` the crop is+ // framed on; `baseW`/`baseH` are the crop size at the current view zoom, then+ // scaled to the chosen output resolution. `rectCss` is the same frame as a+ // rectangle in map-container px — only the widget path needs it, since it+ // crops screen pixels rather than stitching tiles. The recorded point is the+ // moved pin (if any), else the crop centre.+ async function doCapture(framedOn, baseW, baseH, rectCss) {if (capturing) return;// widget basemaps have no tiles to stitch: same frame, screen pixels- if (isWidgetBase) return doWidgetCapture(centerLL, rectCss);+ if (isWidgetBase) return doWidgetCapture(framedOn, rectCss);capturing = true;const { zoom, width, height, mult } = scaledCapture(baseW, baseH, resolution, center.zoom, providerMaxZoom);- let marker_x = 0, marker_y = 0, marker_lat = centerLL.lat, marker_lon = centerLL.lng;- if (moveMode && marker) {- const ll = marker.getLatLng();- marker_lat = ll.lat;- marker_lon = ll.lng;+ let marker_x = 0, marker_y = 0, marker_lat = framedOn.lat, marker_lon = framedOn.lon;+ if (moveMode && markerLatLng) {+ const pin = markerLatLng; // the drag keeps it current, so it is the pin+ marker_lat = pin.lat;+ marker_lon = pin.lon;// pin offset from the crop centre in container px (already accounts for// rotation), scaled up to the output pixel size- const c0 = map.latLngToContainerPoint(centerLL);- const cp = map.latLngToContainerPoint(ll);+ const c0 = engine.latLngToContainerPoint(framedOn);+ const cp = engine.latLngToContainerPoint(pin);marker_x = Math.round((cp.x - c0.x) * mult);marker_y = Math.round((cp.y - c0.y) * mult);}try {const c = await ensureCase();const result = await api.post(`/api/cases/${c.id}/satellite/capture`, {- lat: centerLL.lat,- lon: centerLL.lng,+ lat: framedOn.lat,+ lon: framedOn.lon,zoom,width,height,@@ -1834,7 +1328,7 @@function captureCentered() {const [w, h] = presetSize;const r = mapEl.getBoundingClientRect();- doCapture(map.getCenter(), w, h, {+ doCapture(engine.camera(), w, h, {x: (r.width - w) / 2,y: (r.height - h) / 2,w,@@ -1912,7 +1406,7 @@}// The widget arm of doCapture: grab the tab via the extension, crop, file.- async function doWidgetCapture(centerLL, rect) {+ async function doWidgetCapture(framedOn, rect) {if (!extensionVersion()) {extGateOpen = true;return;@@ -1939,7 +1433,7 @@const img = await extFrame();const canvas = await shotCropCanvas(img, rect, Math.round(rect.w), Math.round(rect.h));const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));- await fileScreenshot(blob, centerLL, true);+ await fileScreenshot(blob, framedOn, true);} catch (e) {if (e.needsActivation) {// one-time per tab: the browser only lets the extension screenshot a@@ -1966,12 +1460,12 @@// coordinates are the centre of a registered crop (the frame paths) or just// the map view at filing time (a pasted screenshot) — the backend keeps that// distinction in provenance.- async function fileScreenshot(blob, centerLL, framed) {+ async function fileScreenshot(blob, framedOn, framed) {const c = await ensureCase();const form = new FormData();form.append('image', blob, 'screenshot.png');- form.append('lat', String(centerLL ? centerLL.lat : center.lat));- form.append('lon', String(centerLL ? centerLL.lng : center.lon));+ form.append('lat', String(framedOn ? framedOn.lat : center.lat));+ form.append('lon', String(framedOn ? framedOn.lon : center.lon));form.append('zoom', String(center.zoom));form.append('bearing', String(bearing));form.append('provider', currentProvider.id);@@ -1988,79 +1482,32 @@}// --- manual screenshot dialog (fallback: paste / drop) ---+ // The dialog owns its own preview and paste handling; these are the two acts+ // it needs from the tool — a frame of this tab, and filing what it holds.let shotOpen = $state(false);- let shotBlob = $state(null);- let shotPreview = $state(''); // object URL for the <img> preview- let shotBusy = $state(false);-- function shotReset() {- if (shotPreview) URL.revokeObjectURL(shotPreview);- shotBlob = null;- shotPreview = '';- }- function shotClose() {- shotReset();- shotOpen = false;- }- function shotTake(file) {- if (!file || !file.type?.startsWith('image/')) return;- shotReset();- shotBlob = file;- shotPreview = URL.createObjectURL(file);- }- function onShotPaste(e) {- const item = [...(e.clipboardData?.items ?? [])].find((i) => i.type.startsWith('image/'));- if (item) {- e.preventDefault();- shotTake(item.getAsFile());- }- }- function onShotDrop(e) {- e.preventDefault();- shotTake(e.dataTransfer?.files?.[0]);- }-- // One-click grab of the whole map view into the dialog's preview: the same- // extension frame as a framed capture, minus the crop, at native resolution.- // The preview is what lets the user judge it before filing. The dialog itself- // is only reachable with the extension present (no extension → the gate points- // at Settings instead), so this grab is always available here.- let shotGrabbing = $state(false);- async function shotGrab() {- if (shotGrabbing) return;- shotGrabbing = true;++ /** The whole map view as a PNG blob, through the extension. Null if refused. */+ async function grabView() {try {const img = await extFrame();- const r0 = mapEl.getBoundingClientRect();- const canvas = await shotCropCanvas(img, { x: 0, y: 0, w: r0.width, h: r0.height });- const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));- if (blob) shotTake(new File([blob], 'screenshot.png', { type: 'image/png' }));+ const rect = mapEl.getBoundingClientRect();+ const canvas = await shotCropCanvas(img, { x: 0, y: 0, w: rect.width, h: rect.height });+ return await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));} catch (e) {// extension missing or refused — the paste path still workstoast(`Screen capture unavailable (${e.message}). Paste a screenshot instead`, 'warn', 6000);- } finally {- shotGrabbing = false;+ return null;}}- // paste works anywhere while the dialog is open — no need to focus a zone- $effect(() => {- if (!shotOpen) return;- window.addEventListener('paste', onShotPaste);- return () => window.removeEventListener('paste', onShotPaste);- });- async function shotSave() {- if (!shotBlob || shotBusy) return;- shotBusy = true;+ /** File what the dialog holds, at the map view rather than a registered frame. */+ async function fileScreenshotBlob(blob) {try {- // a pasted image is not registered to any frame: its coordinates are the- // map view at filing time, and provenance says so (framed: false)- await fileScreenshot(shotBlob, null, false);- shotClose();+ await fileScreenshot(blob, null, false);+ return true;} catch (e) {toast(`Could not file the screenshot: ${e.message}`, 'danger', 6000);- } finally {- shotBusy = false;+ return false;}}@@ -2076,9 +1523,9 @@// …and the Sentinel-2 layer/date popover$effect(() => {- if (!s2MenuOpen) return;+ if (!s2.menuOpen) return;const onDocMousedown = (e) => {- if (s2MenuEl && !s2MenuEl.contains(e.target)) s2MenuOpen = false;+ if (s2MenuEl && !s2MenuEl.contains(e.target)) s2.menuOpen = false;};document.addEventListener('mousedown', onDocMousedown, true);return () => document.removeEventListener('mousedown', onDocMousedown, true);@@ -2096,50 +1543,26 @@}function onSelectStart(e) {- if (!selectArmed || e.button !== 0 || !map) return;- // own the gesture so Leaflet doesn't pan while we draw the box- e.stopPropagation();- e.preventDefault();- const rect = mapEl.getBoundingClientRect();- const start = { x: e.clientX - rect.left, y: e.clientY - rect.top };- selRect = { x0: start.x, y0: start.y, x1: start.x, y1: start.y };- const move = (ev) => {- let x1 = ev.clientX - rect.left;- let y1 = ev.clientY - rect.top;- if (ratioValue) {- // lock the box to the chosen aspect ratio, sized from the larger delta- const dx = x1 - start.x;- const dy = y1 - start.y;- let w = Math.abs(dx);- let h = Math.abs(dy);- if (w / h > ratioValue) h = w / ratioValue;- else w = h * ratioValue;- x1 = start.x + (dx < 0 ? -w : w);- y1 = start.y + (dy < 0 ? -h : h);- }- selRect = { x0: start.x, y0: start.y, x1, y1 };- };- const up = () => {- window.removeEventListener('mousemove', move);- window.removeEventListener('mouseup', up);- finishSelect();- };- window.addEventListener('mousemove', move);- window.addEventListener('mouseup', up);+ if (!selectArmed || e.button !== 0 || !engine) return;+ startRectDrag(engine, e, {+ ratio: ratioValue,+ onChange: (rect) => (selRect = rect),+ onDone: finishSelect,+ });}- function finishSelect() {- const r = selRect;+ function finishSelect(r) {selRect = null;if (!r) return;const w = Math.abs(r.x1 - r.x0);const h = Math.abs(r.y1 - r.y0);if (w < 12 || h < 12) return; // an accidental click / tiny drag: ignore- const centerLL = map.containerPointToLatLng(- L.point((r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2)- );+ const framedOn = engine.containerPointToLatLng({+ x: (r.x0 + r.x1) / 2,+ y: (r.y0 + r.y1) / 2,+ });selectArmed = false; // one box per arm — re-arm to draw another- doCapture(centerLL, Math.round(w), Math.round(h), {+ doCapture(framedOn, Math.round(w), Math.round(h), {x: Math.min(r.x0, r.x1),y: Math.min(r.y0, r.y1),w,@@ -2170,24 +1593,17 @@}function ensureGridLayers() {- if (!map) return;- if (!gridRenderer) gridRenderer = L.canvas({ padding: 0.5 });- if (!gridLayer) gridLayer = L.layerGroup();- if (!gridAoiLayer) gridAoiLayer = L.layerGroup();- if (!gridDraftLayer) gridDraftLayer = L.layerGroup();+ if (!engine) return;+ gridCells ??= createSurface(engine);+ gridAoi ??= createSurface(engine);+ gridDraft ??= createSurface(engine);syncGridVisibility();}// the eye toggle keeps the grid but drops its layers off the map so you can// read the bare imagery underneath, then puts them backfunction syncGridVisibility() {- if (!map) return;- for (const lyr of [gridLayer, gridAoiLayer, gridDraftLayer]) {- if (!lyr) continue;- const on = map.hasLayer(lyr);- if (gridHidden && on) map.removeLayer(lyr);- else if (!gridHidden && !on) map.addLayer(lyr);- }+ for (const surface of [gridCells, gridAoi, gridDraft]) surface?.visible(!gridHidden);}function toggleGridHidden() {@@ -2212,57 +1628,44 @@}function clearGridLayers() {- cellRects.clear();- aoiOutline = null;- draftLine = null;- gridLayer?.clearLayers();- gridAoiLayer?.clearLayers();- gridDraftLayer?.clearLayers();+ gridCells?.clear();+ gridAoi?.clear();+ gridDraft?.clear();}- function gridHandleIcon() {- return L.divIcon({ className: 'grid-handle', iconSize: [16, 16], iconAnchor: [8, 8] });- }-- function cellLatLngBounds(i, j) {- const b = gridSearch.cellBounds(grid, i, j);- return [[b.south, b.west], [b.north, b.east]];- }+ // a handle is an empty box the CSS draws; the shape only says where it is+ const GRID_HANDLE = { className: 'grid-handle', size: [16, 16], anchor: [8, 8] };function cellStyle(key) {const base = CELL_STYLE[grid?.statuses[key] || 'unchecked'];// the cell under review gets a bright cyan outline — distinct from the// yellow flag and the grey cleared fill for colour-blind readability- return key === reviewKey ? { ...base, color: '#33c9ff', weight: 2.5, opacity: 1 } : base;+ return key === reviewKey+ ? { ...base, stroke: '#33c9ff', strokeWidth: 2.5, strokeOpacity: 1 }+ : base;}function renderGrid() {ensureGridLayers();- gridLayer.clearLayers();- cellRects.clear();- if (!grid) return;- for (const [i, j] of gridSearch.cellsInAoi(grid)) {- const key = gridSearch.cellKey(i, j);- const rect = L.rectangle(cellLatLngBounds(i, j), {- renderer: gridRenderer,- bubblingMouseEvents: false,- ...cellStyle(key),- });- rect.on('click', (e) => {- L.DomEvent.stop(e);- cycleCell(i, j);- });- rect.on('contextmenu', (e) => {- L.DomEvent.stop(e);- flagCell(i, j);- });- rect.addTo(gridLayer);- cellRects.set(key, rect);+ if (!grid) {+ gridCells.clear();+ return;}+ gridCells.set(+ [...gridSearch.cellsInAoi(grid)].map(([i, j]) => ({+ id: gridSearch.cellKey(i, j),+ kind: 'rect',+ bounds: gridSearch.cellBounds(grid, i, j),+ style: cellStyle(gridSearch.cellKey(i, j)),+ onClick: () => cycleCell(i, j),+ onContextMenu: () => flagCell(i, j),+ }))+ );}+ // One cell of a thousand, on every keypress of a sweep: never a rebuild.function restyleCell(key) {- cellRects.get(key)?.setStyle(cellStyle(key));+ gridCells?.patch(key, { style: cellStyle(key) });}function setReview(key) {@@ -2298,40 +1701,76 @@// --- editing the area of interest (rect corners / polygon vertices) ---// The area box + handles show only while editing the area; once a grid is// drawn the box is hidden and just the cells remain.+ const AOI_OUTLINE = 'outline'; // the one shape the drag handles reshape live+function renderAoi() {ensureGridLayers();- gridAoiLayer.clearLayers();- aoiOutline = null;- if (!grid || !editArea) return;+ if (!grid || !editArea) {+ gridAoi.clear();+ return;+ }const b = gridSearch.aoiBounds(grid.aoi);+ const handle = (id, at, onDragStart, onDrag) => ({+ id,+ kind: 'marker',+ at,+ ...GRID_HANDLE,+ draggable: true,+ keyboard: false,+ zIndex: 1200,+ onDragStart,+ onDrag,+ onDragEnd: () => (grid.aoi.type === 'rect' ? commitResize() : commitVertEdit()),+ });if (grid.aoi.type === 'rect') {- aoiOutline = L.rectangle([[b.south, b.west], [b.north, b.east]], AOI_STYLE).addTo(gridAoiLayer);- for (const corner of CORNERS) {- const m = L.marker(gridSearch.cornerLatLng(b, corner), {- draggable: true,- keyboard: false,- icon: gridHandleIcon(),- zIndexOffset: 1200,- });- m.on('dragstart', () => (dragBounds = { ...gridSearch.aoiBounds(grid.aoi) }));- m.on('drag', (e) => onCornerDrag(corner, e.target.getLatLng()));- m.on('dragend', commitResize);- m.addTo(gridAoiLayer);- }- } else {- aoiOutline = L.polygon(grid.aoi.vertices, AOI_STYLE).addTo(gridAoiLayer);- addVertHandles();+ gridAoi.set([+ { id: AOI_OUTLINE, kind: 'rect', bounds: b, style: AOI_STYLE },+ ...CORNERS.map((corner) => {+ const [lat, lon] = gridSearch.cornerLatLng(b, corner);+ return handle(+ corner,+ { lat, lon },+ () => (dragBounds = { ...gridSearch.aoiBounds(grid.aoi) }),+ (at) => onCornerDrag(corner, at)+ );+ }),+ ]);+ return;}+ // reshape a confirmed polygon: a draggable handle on every vertex+ gridAoi.set([+ {+ id: AOI_OUTLINE,+ kind: 'polygon',+ points: grid.aoi.vertices.map(([lat, lon]) => ({ lat, lon })),+ style: AOI_STYLE,+ },+ ...grid.aoi.vertices.map(([lat, lon], k) =>+ handle(+ k,+ { lat, lon },+ () => (liveVerts = grid.aoi.vertices.map((vertex) => [...vertex])),+ (at) => onVertexDrag(k, at)+ )+ ),+ ]);}- function onCornerDrag(corner, latlng) {+ function onCornerDrag(corner, at) {if (!dragBounds) return;- if (corner[0] === 'n') dragBounds.north = latlng.lat;- else dragBounds.south = latlng.lat;- if (corner[1] === 'e') dragBounds.east = latlng.lng;- else dragBounds.west = latlng.lng;- const b = gridSearch.normalizeBounds(dragBounds);- aoiOutline?.setBounds([[b.south, b.west], [b.north, b.east]]);+ if (corner[0] === 'n') dragBounds.north = at.lat;+ else dragBounds.south = at.lat;+ if (corner[1] === 'e') dragBounds.east = at.lon;+ else dragBounds.west = at.lon;+ gridAoi.patch(AOI_OUTLINE, { bounds: gridSearch.normalizeBounds(dragBounds) });+ }++ function onVertexDrag(k, at) {+ if (!liveVerts) return;+ liveVerts[k] = [at.lat, at.lon];+ gridAoi.patch(AOI_OUTLINE, {+ points: liveVerts.map(([lat, lon]) => ({ lat, lon })),+ });}function commitResize() {@@ -2350,27 +1789,6 @@scheduleGridSave();}- // reshape a confirmed polygon: draggable handles on every vertex- function addVertHandles() {- grid.aoi.vertices.forEach((v, k) => {- const m = L.marker([v[0], v[1]], {- draggable: true,- keyboard: false,- icon: gridHandleIcon(),- zIndexOffset: 1200,- });- m.on('dragstart', () => (liveVerts = grid.aoi.vertices.map((x) => [...x])));- m.on('drag', (e) => {- if (!liveVerts) return;- const ll = e.target.getLatLng();- liveVerts[k] = [ll.lat, ll.lng];- aoiOutline?.setLatLngs(liveVerts);- });- m.on('dragend', commitVertEdit);- m.addTo(gridAoiLayer);- });- }-function commitVertEdit() {if (!liveVerts || !grid) return;const verts = liveVerts;@@ -2404,8 +1822,7 @@gridDraw = type;// hide the current cells while drawing so map clicks reach the canvas// (polygon vertices) instead of being swallowed by a cell underneath- gridLayer?.clearLayers();- cellRects.clear();+ gridCells?.clear();if (type === 'polygon') {polyDraft = [];renderDraft();@@ -2417,80 +1834,72 @@gridDraw = null;polyDraft = [];selRect = null;- draftLine = null;- gridDraftLayer?.clearLayers();+ gridDraft?.clear();if (wasDrawing && grid) renderGrid(); // restore the cells hidden while drawing}// rectangle area: drag a box (mirrors the capture marquee, reusing selRect for// the live outline). Armed while gridDraw === 'rect'.function onGridRectStart(e) {- if (gridDraw !== 'rect' || e.button !== 0 || !map) return;- e.stopPropagation();- e.preventDefault();- const rect = mapEl.getBoundingClientRect();- const start = { x: e.clientX - rect.left, y: e.clientY - rect.top };- selRect = { x0: start.x, y0: start.y, x1: start.x, y1: start.y };- const move = (ev) => {- selRect = { x0: start.x, y0: start.y, x1: ev.clientX - rect.left, y1: ev.clientY - rect.top };- };- const up = () => {- window.removeEventListener('mousemove', move);- window.removeEventListener('mouseup', up);- finishGridRect();- };- window.addEventListener('mousemove', move);- window.addEventListener('mouseup', up);+ if (gridDraw !== 'rect' || e.button !== 0 || !engine) return;+ startRectDrag(engine, e, {+ onChange: (rect) => (selRect = rect),+ onDone: finishGridRect,+ });}- function finishGridRect() {- const r = selRect;+ function finishGridRect(r) {selRect = null;gridDraw = null;if (!r || Math.abs(r.x1 - r.x0) < 12 || Math.abs(r.y1 - r.y0) < 12) {if (grid) renderGrid(); // stray click: restore the cells hidden to drawreturn;}- const p1 = map.containerPointToLatLng(L.point(r.x0, r.y0));- const p2 = map.containerPointToLatLng(L.point(r.x1, r.y1));+ const p1 = engine.containerPointToLatLng({ x: r.x0, y: r.y0 });+ const p2 = engine.containerPointToLatLng({ x: r.x1, y: r.y1 });doApplyArea({type: 'rect',- bounds: gridSearch.normalizeBounds({ south: p1.lat, north: p2.lat, west: p1.lng, east: p2.lng }),+ bounds: gridSearch.normalizeBounds({ south: p1.lat, north: p2.lat, west: p1.lon, east: p2.lon }),});}// polygon area: click to drop vertices (handled in onMapClick), drag the// handles to adjust, Confirm to build.- function draftLatLngs() {- return gridSearch.closeRing(polyDraft.map((p) => [p.lat, p.lon]));+ const DRAFT_RING = 'ring';++ function draftRing() {+ return gridSearch.closeRing(polyDraft.map((point) => [point.lat, point.lon]))+ .map(([lat, lon]) => ({ lat, lon }));}function renderDraft() {ensureGridLayers();- gridDraftLayer.clearLayers();- draftLine = null;- if (gridDraw !== 'polygon') return;- draftLine = L.polyline(draftLatLngs(), {- color: '#f5a623',- weight: 1.5,- opacity: 0.95,- dashArray: '5 4',- }).addTo(gridDraftLayer);- polyDraft.forEach((p, k) => {- const m = L.marker([p.lat, p.lon], {+ if (gridDraw !== 'polygon') {+ gridDraft.clear();+ return;+ }+ gridDraft.set([+ {+ id: DRAFT_RING,+ kind: 'line',+ points: draftRing(),+ style: { stroke: '#f5a623', strokeWidth: 1.5, strokeOpacity: 0.95, dash: '5 4' },+ },+ ...polyDraft.map((point, k) => ({+ id: k,+ kind: 'marker',+ at: point,+ ...GRID_HANDLE,draggable: true,keyboard: false,- icon: gridHandleIcon(),- zIndexOffset: 1200,- });- m.on('drag', (e) => {- const ll = e.target.getLatLng();- polyDraft[k] = { lat: ll.lat, lon: ll.lng };- draftLine?.setLatLngs(draftLatLngs());- });- m.on('dragend', renderDraft);- m.addTo(gridDraftLayer);- });+ zIndex: 1200,+ onDrag: (at) => {+ polyDraft[k] = at;+ gridDraft.patch(DRAFT_RING, { points: draftRing() });+ },+ onDragEnd: renderDraft,+ })),+ ]);}function confirmPolygon() {@@ -2498,7 +1907,7 @@const vertices = polyDraft.map((p) => [p.lat, p.lon]);gridDraw = null;polyDraft = [];- gridDraftLayer?.clearLayers();+ gridDraft?.clear();doApplyArea({ type: 'polygon', vertices });}@@ -2536,11 +1945,7 @@function flyToCell([i, j]) {setReview(gridSearch.cellKey(i, j));const b = gridSearch.cellBounds(grid, i, j);- map.fitBounds([[b.south, b.west], [b.north, b.east]], {- padding: [80, 80],- maxZoom: 20,- animate: true,- });+ engine.fitBounds(b, { padding: [80, 80], maxZoom: 20, animate: true });}function startReview() {@@ -2738,14 +2143,7 @@const row = deleteTarget;try {const caseId = caseState.current.id;- let result;- if (row.kind === 'place') {- result = await api.del(`/api/cases/${caseId}/entities/${row.id}`);- } else {- result = await api.del(- `/api/cases/${caseId}/satellite?path=${encodeURIComponent(row.path)}`- );- }+ const result = await savedWork.remove(caseId, row);deleteTarget = null;await reloadCase(); // re-reads the saved index and the case sidebardeletedToast(caseId, result, row.title || coordsLabel(row));@@ -2768,44 +2166,19 @@* relations is accepted with it — the API keeps that invariant, and a point* confirmed here while the edge tying it to its capture stayed proposed would* be the two surfaces disagreeing about one click. */- let acceptingId = $state(null);- async function acceptSaved(row) {- if (acceptingId) return;- acceptingId = row.id;- try {- await api.patch(`/api/cases/${caseState.current.id}/entities/${row.id}`, {- status: 'confirmed',- });- await reloadCase(); // re-reads the saved index and the case sidebar- toast('Point accepted', 'ok', 1600);- } catch (e) {- toast(`Could not accept this point: ${e.message}`, 'danger');- } finally {- acceptingId = null;- }- }+ const acceptSaved = (row) => savedWork.accept(caseState.current.id, row);// --- details modal (title + notes) ---+ // The dialog owns the fields; this owns the PATCH and what it means for the+ // rest of the case.let notesItem = $state(null);- let notesText = $state('');- let notesTitle = $state('');- let notesFolder = $state('');- let notesSaving = $state(false);-- function openNotes(row) {- notesItem = row;- notesText = row.notes ?? '';- notesTitle = row.title ?? coordsLabel(row);- notesFolder = row.folder ?? '';- }- async function saveNotes() {+ async function saveNotes({ title, folder, notes }) {if (!notesItem) return;- notesSaving = true;try {await api.patch(`/api/cases/${caseState.current.id}/satellite`,- { path: notesItem.path, notes: notesText, title: notesTitle, folder: notesFolder }+ { path: notesItem.path, notes, title, folder });notesItem = null;// the mirrored place entity was retitled too — refresh the sidebar@@ -2813,8 +2186,6 @@toast('Saved', 'ok', 1600);} catch (e) {toast(e.message, 'danger');- } finally {- notesSaving = false;}}@@ -2850,49 +2221,14 @@async function toggleCaptures() {capturesCollapsed = !capturesCollapsed;- // the map container just resized — let Leaflet redraw tiles for the new size+ // the map container just resized — let the map redraw for the new sizeawait tick();- map?.invalidateSize();+ engine?.resize();}- function loadSavedGroup() {- try {- return localStorage.getItem(GROUP_KEY) === 'folders' ? 'folders' : 'geo';- } catch {- return 'geo'; // localStorage unavailable (private mode) — non-fatal- }- }-- $effect(() => {- try {- localStorage.setItem(GROUP_KEY, savedGroup);- } catch {- /* ignore */- }- });-- // File a saved item into a My-work folder, dropped onto a folder in the- // panel. One PATCH through the shared filing route (a capture's sidecar is- // the authority, a place carries the folder itself), then the case reload- // every other edit here does: the index, the sidebar and the map overlay all- // read the new filing from it.- async function moveSaved(row, folder) {- // the row's kind *is* its entity type, bar the screenshot that rides the- // capture type. Filing a proof as a capture would route it to PATCH /media,- // the sidecar of an image it is not.- const entity = {- id: row.id,- type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture',- attrs: { path: row.path },- };- try {- await assignFolder(caseState.current.id, entity, folder);- await reloadCase();- toast(folder ? `Filed in ${folder}` : 'Removed from My work', 'ok', 1600);- } catch (e) {- toast(e.message, 'danger');- }- }+ // Dropped onto a folder in the panel: the index, the sidebar and the map+ // overlay all read the new filing from the case reload that follows.+ const moveSaved = (row, folder) => savedWork.move(caseState.current.id, row, folder);// --- resize: the Saved panel's left edge is a drag handle ---const SAVED_KEY_STEP = 16;@@ -2915,14 +2251,14 @@if (!frame) {frame = requestAnimationFrame(() => {frame = 0;- map?.invalidateSize({ animate: false });+ engine?.resize();});}};const up = () => {savedResizing = false;if (frame) cancelAnimationFrame(frame);- map?.invalidateSize({ animate: false });+ engine?.resize();savedPanel.saveWidth(savedW); // one write per drag, not one per framewindow.removeEventListener('pointermove', move);window.removeEventListener('pointerup', up);@@ -2938,14 +2274,14 @@setSavedWidth(savedW + step);savedPanel.saveWidth(savedW);await tick();- map?.invalidateSize({ animate: false });+ engine?.resize();}async function resetSavedWidth() {setSavedWidth(savedPanel.DEFAULT_W);savedPanel.saveWidth(savedW);await tick();- map?.invalidateSize({ animate: false });+ engine?.resize();}// A width dragged out on a wide screen would eat a narrower window whole, so@@ -2957,64 +2293,9 @@return () => window.removeEventListener('resize', onWindowResize);});- // --- Locate: fill in the country of everything that still has none ---------- // One batch per request (Nominatim is one lookup a second), looped until the- // backlog is empty. Progress is the stored geography itself, so cancelling- // keeps whatever was already resolved and a later pass picks up where this- // one stopped.- const LOCATE_BATCH = 10;- let locating = $state(null); // { done, total } while a pass runs- let locateStopped = false;- let locateGeneration = 0;-- async function runLocate() {- if (locating || !caseState.current) return;- const id = caseState.current.id;- const generation = ++locateGeneration;- locateStopped = false;- const total = pendingLocate(saved);- locating = { done: 0, total };- let located = 0;- let failed = 0;- let throttled = false;- try {- let remaining = total;- while (remaining > 0 && !locateStopped && generation === locateGeneration) {- const batch = await api.post(- `/api/cases/${id}/satellite/locate?limit=${LOCATE_BATCH}`- );- if (generation !== locateGeneration) return;- located += batch.located;- failed += batch.failed;- throttled = Boolean(batch.throttled);- // A batch that resolved nothing means the network is down, or that- // Nominatim put us in its penalty box — not that the next one will do- // better: stop instead of hammering it forever.- const stalled = batch.remaining >= remaining;- remaining = batch.remaining;- locating = { done: total - remaining, total };- if (stalled || throttled) break;- }- if (generation !== locateGeneration) return;- const rows = await api.get(`/api/cases/${id}/satellite/index`);- if (generation !== locateGeneration) return;- saved = rows;- toast(- throttled- ? `Located ${located} of ${total}. OpenStreetMap is rate-limiting this address; wait a minute and run Locate again`- : failed- ? `Located ${located} of ${total}. ${failed} lookup(s) failed; run Locate again to retry`- : `Located ${located} of ${total}`,- failed || throttled ? 'warn' : 'ok'- );- } catch (e) {- if (generation === locateGeneration) {- toast(`Locate stopped: ${e.message}`, 'danger', 6000);- }- } finally {- if (generation === locateGeneration) locating = null;- }- }+ // Locate fills in the country of everything that still has none, one bounded+ // batch at a time (state/saved.svelte.js).+ const runLocate = () => savedWork.runLocate(caseState.current?.id);// --- place edit modal (title + notes), used for both save & later edits ---// { id: string|null, title, notes, folder, lat, lon, zoom, bearing }; id null = new@@ -3116,7 +2397,7 @@<div class="spacer"></div><PlaceSearchbind:value={coordsText}- savedRows={saved}+ savedRows={savedWork.rows}centre={{ lat: center.lat, lon: center.lon }}units={prefs.units}{searching}@@ -3135,12 +2416,16 @@><div class="map" bind:this={mapEl}></div>+ {#if mapRefused}+ <p class="map-refused">The map needs WebGL, which this browser does not have.</p>+ {/if}+<!-- saved work on the map: navigation only, off by default, session-only.It draws the panel's current selection, not the whole index. -->{#if savedOverlay}<SavedOverlay- map={mapReady ? map : null}- items={savedShown}+ engine={mapReady ? engine : null}+ items={savedWork.shown}caseId={caseState.current?.id}coords={coordsLabel}{fullscreen}@@ -3149,13 +2434,13 @@onedit={editSaved}onproof={sendToComposer}onpost={openLinkedPost}- onshowproofs={() => (savedKind = 'proofs')}+ onshowproofs={() => (savedWork.kind = 'proofs')}onrefresh={reloadCase}/>{/if}{#if sheetPoints}- <SheetPointsOverlay map={mapReady ? map : null} points={sheetPoints.points} />+ <SheetPointsOverlay engine={mapReady ? engine : null} points={sheetPoints.points} /><!-- Both temporary layers can be on at once, so this one sits under the otherrather than on top of it. --><div class="temporal-layer-card" class:stacked={temporalMap} aria-label="Sheet map layer">@@ -3172,7 +2457,7 @@{#if temporalMap}<TemporalMapOverlay- map={mapReady ? map : null}+ engine={mapReady ? engine : null}items={temporalMap.items}caseId={caseState.current?.id}onopen={openTemporalTimeline}@@ -3215,7 +2500,7 @@{gridMode}{toggleGridMode}bind:savedOverlay- savedCount={saved.length}+ savedCount={savedWork.rows.length}referenceCount={uiState.refViewers.length}{openRefPicker}{setMeasureMode}@@ -3301,7 +2586,7 @@</div>{/if}- <!-- fixed center marker; a draggable Leaflet marker takes over in move mode -->+ <!-- fixed center marker; a draggable map marker takes over in move mode -->{#if markerStyle !== 'none' && !moveMode}<div class="marker-overlay marker-{markerStyle}" aria-hidden="true">{#if markerStyle === 'pin'}@@ -3359,22 +2644,22 @@class="date-pill mono"class:exact={!!s2PinnedDate}title={s2PinnedDate- ? `Sentinel-2 ${s2LayerLabel} from this exact date`- : s2Latest- ? `Sentinel-2 ${s2LayerLabel}: most recent pass over this point`- : `Sentinel-2 ${s2LayerLabel}: most recent pass (open the picker to date it)`}+ ? `Sentinel-2 ${s2.layerLabel} from this exact date`+ : s2.latest+ ? `Sentinel-2 ${s2.layerLabel}: most recent pass over this point`+ : `Sentinel-2 ${s2.layerLabel}: most recent pass (open the picker to date it)`}><Icon name="clock" size={11} />- {s2PinnedDate ?? s2Latest ?? ''}+ {s2PinnedDate ?? s2.latest ?? ''}{#if !s2PinnedDate}- <span class="tag">{s2Latest ? 'latest' : 'most recent'}</span>+ <span class="tag">{s2.latest ? 'latest' : 'most recent'}</span>{/if}- {#if s2Layer !== DEFAULT_LAYER}- <span class="tag layer">{s2LayerShort}</span>+ {#if s2.layer !== DEFAULT_LAYER}+ <span class="tag layer">{s2.layerShort}</span>{/if}- {#if s2Maxcc !== DEFAULT_MAXCC}+ {#if s2.maxcc !== DEFAULT_MAXCC}<span class="tag" title="Passes over this cloud cover are not rendered"- >≤{s2Maxcc}% cloud</span+ >≤{s2.maxcc}% cloud</span>{/if}</span>@@ -3399,7 +2684,7 @@title={bearing ? 'Reset to north' : 'North up · middle-drag the map to rotate'}aria-label="Reset to north">- <svg width="30" height="30" viewBox="0 0 34 34" style="transform: rotate({-bearing}deg)">+ <svg width="30" height="30" viewBox="0 0 34 34" style="transform: rotate({bearing}deg)"><polygon points="17,4 13,18 17,15 21,18" fill="#e5484d" /><polygon points="17,30 13,16 17,19 21,16" fill="#8a93a5" /></svg>@@ -3439,33 +2724,12 @@{#if isSentinel}<SentinelPickerbind:menuEl={s2MenuEl}- menuOpen={s2MenuOpen}- toggleMenu={toggleS2Menu}- bind:layer={s2Layer}- layers={s2Layers}- layerHint={s2LayerHint}- layersSource={s2LayersSource}- loadLayers={loadS2Layers}- bind:date={s2Date}- maxcc={s2Maxcc}- setMaxcc={setS2Maxcc}+ {s2}{maxccLabel}- filtered={s2Filtered}- month={s2Month}{monthLabel}- stepMonth={stepS2Month}{monthGrid}- passes={s2Passes}{cloudClass}{cloudLabel}- passesBusy={s2PassesBusy}- passesNote={s2PassesNote}- passesStale={s2PassesStale}- verifyingDate={s2VerifyingDate}- dateStatus={s2DateStatus}- pickDate={pickS2Date}- clearDate={clearS2Date}- loadPasses={loadS2Passes}/>{/if}{#if usagePill}@@ -3584,7 +2848,7 @@><Icon name={capturesCollapsed ? 'chevronLeft' : 'chevronRight'} size={15} /><span class="label" style="margin:0">Saved</span>- <span class="count">{saved.length}</span>+ <span class="count">{savedWork.rows.length}</span></button>{#if capturesCollapsed}<!-- collapsed: header acts as the toggle back to the list -->@@ -3633,18 +2897,18 @@{/if}<SavedTree- rows={savedRows}+ rows={savedWork.shownRows}folders={caseState.current?.folders ?? []}caseId={caseState.current?.id}coords={coordsLabel}{fullscreen}- bind:kind={savedKind}- bind:query={savedQuery}- bind:group={savedGroup}+ bind:kind={savedWork.kind}+ bind:query={savedWork.query}+ bind:group={savedWork.group}bind:hoveredId={hoveredSavedId}onmove={moveSaved}revealId={revealSavedId}- {locating}+ locating={savedWork.locating}onopen={openSaved}onedit={editSaved}ondelete={(row) => (deleteTarget = row)}@@ -3652,7 +2916,7 @@onaccept={acceptSaved}onbrowse={() => (savedSearchOpen = true)}onlocate={runLocate}- oncancelLocate={() => (locateStopped = true)}+ oncancelLocate={savedWork.stopLocate}/></div>{/if}@@ -3677,87 +2941,29 @@/>{/if}-<!-- satellite notes modal -->{#if notesItem}- <Modal title="Capture details" onclose={() => (notesItem = null)} width="420px">- <label for="capture-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>- <input- id="capture-title"- class="input"- placeholder={coordsLabel(notesItem)}- bind:value={notesTitle}- />- <label for="capture-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>- <FolderSelect- id="capture-folder"- bind:value={notesFolder}- folders={caseState.current?.folders ?? []}- emptyLabel="My work (root)"- />- <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />- <div class="sat-info-rows">- <div class="sat-info-row">- <span class="sat-info-label">Coordinates</span>- <span class="mono">{coordsLabel(notesItem)}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Provider</span>- <span>{notesItem.provider ?? notesItem.site ?? '—'}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Zoom</span>- <span>{notesItem.zoom ?? '—'}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Captured</span>- <span class="mono">{notesItem.fetched_at?.slice(0, 10)}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Imagery date</span>- <span class="mono">{notesItem.imagery_date ?? '—'}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Image</span>- <a- class="link-out"- class:disabled={fullscreen}- href={fullscreen ? undefined : fileUrl(caseState.current?.id, notesItem.path)}- target="_blank"- rel="noreferrer"- aria-disabled={fullscreen}- title={leavesFullscreen ?? 'Open the full image'}- >Open the full image <Icon name="external" size={12} /></a>- </div>- </div>- <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />- <label for="capture-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>- <textarea- id="capture-notes"- class="textarea"- rows="5"- placeholder="Add observations, links, context…"- bind:value={notesText}- ></textarea>- <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">- <button class="btn" onclick={() => (notesItem = null)}>Cancel</button>- <button class="btn btn-primary" onclick={saveNotes} disabled={notesSaving}>- {notesSaving ? 'Saving…' : 'Save'}- </button>- </div>- </Modal>+ <CaptureDetails+ row={notesItem}+ caseId={caseState.current?.id}+ folders={caseState.current?.folders ?? []}+ coords={coordsLabel}+ {leavesFullscreen}+ onsave={saveNotes}+ onclose={() => (notesItem = null)}+ />{/if}<!-- Search every saved item at full width: the same index the tree reads, withthumbnails and a sort. No fetch, no network. -->{#if savedSearchOpen}<SavedSearch- rows={savedRows}+ rows={savedWork.shownRows}caseId={caseState.current?.id}coords={coordsLabel}{fullscreen}centre={{ lat: center.lat, lon: center.lon }}- bind:kind={savedKind}- bind:query={savedQuery}+ bind:kind={savedWork.kind}+ bind:query={savedWork.query}bind:hoveredId={hoveredSavedId}onclose={() => (savedSearchOpen = false)}onopen={openSaved}@@ -3768,226 +2974,55 @@/>{/if}-<!-- The manual way in, for when the Capture button's extension grab can't be- used or the screenshot came from somewhere else entirely. -->-{#if shotOpen && !shotGrabbing}- <Modal title="File a screenshot" onclose={shotClose} width="520px">- <p class="shot-hint">- The <strong>Capture</strong> button already crops this basemap off the screen- through the usual frame. Use this when it can't:- grab the whole map view below, or paste- (<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.- Unlike a framed capture, this is filed at the current <em>view</em>- (<span class="mono">{fmtCoords(center.lat, center.lon)}</span>, z{center.zoom}).- the coordinates describe the map, not a registered crop. The Google attribution- is burned into a footer either way; keep Google's on-screen credits inside the- frame too.- </p>- <div style="display:flex;justify-content:center;margin-bottom:10px">- <button class="btn btn-primary" onclick={shotGrab} disabled={shotGrabbing}>- {#if shotGrabbing}<span class="spinner"></span> Grabbing…{:else}- <Icon name="satellite" size={14} /> Capture the view{/if}- </button>- </div>- <div- class="shot-zone"- class:has-image={!!shotPreview}- role="button"- tabindex="0"- ondrop={onShotDrop}- ondragover={(e) => e.preventDefault()}- >- {#if shotPreview}- <img src={shotPreview} alt="screenshot to file" />- {:else}- <span>Paste (Ctrl+V) or drop the screenshot here</span>- {/if}- </div>- <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">- {#if shotPreview}- <button class="btn" onclick={shotReset}>Clear</button>- {/if}- <button class="btn" onclick={shotClose}>Cancel</button>- <button class="btn btn-primary" onclick={shotSave} disabled={!shotBlob || shotBusy}>- {shotBusy ? 'Filing…' : 'File as capture'}- </button>- </div>- </Modal>+{#if shotOpen}+ <ScreenshotDialog+ view={center}+ {fmtCoords}+ grab={grabView}+ file={fileScreenshotBlob}+ onclose={() => (shotOpen = false)}+ />{/if}-<!-- Google JS capture gate: this basemap can only be captured through the- browser extension (screen pixels are the only thing Google's terms allow- out of the widget, and the extension is the promptless way to get them).- Explain briefly and point at Settings; never a half-working share flow. -->{#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- 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.- </p>- <p class="shot-hint">- Install it from <strong>Settings → Capture extension</strong>, then reload- this tab.- </p>- <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">- <button class="btn" onclick={() => (extGateOpen = false)}>Cancel</button>- <button- class="btn btn-primary"- onclick={() => {- extGateOpen = false;- uiState.settingsTab = 'extension';- uiState.tool = 'settings';- }}- >- Open Settings- </button>- </div>- </Modal>+ <ExtensionGate+ onclose={() => (extGateOpen = false)}+ onsettings={() => {+ extGateOpen = false;+ uiState.settingsTab = 'extension';+ uiState.tool = 'settings';+ }}+ />{/if}-<!-- place edit / save-with-details modal -->{#if placeModal}- <Modal- title={placeModal.id ? 'Edit place' : 'Save place'}+ <PlaceDialog+ draft={placeModal}+ caseId={caseState.current?.id}+ folders={caseState.current?.folders ?? []}+ saving={placeSaving}+ coords={placeCoordsLabel}+ onsave={savePlaceModal}onclose={() => (placeModal = null)}- width="420px"- >- <label for="place-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>- <input- id="place-title"- class="input"- placeholder={placeCoordsLabel(placeModal)}- bind:value={placeModal.title}- />- <label for="place-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>- <FolderSelect- id="place-folder"- bind:value={placeModal.folder}- folders={caseState.current?.folders ?? []}- emptyLabel="My work (root)"- />- <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />- <div class="sat-info-rows">- <div class="sat-info-row">- <span class="sat-info-label">Coordinates</span>- <span class="mono">{placeCoordsLabel(placeModal)}</span>- </div>- <div class="sat-info-row">- <span class="sat-info-label">Zoom</span>- <span>z{placeModal.zoom}{placeModal.bearing ? ` · ${Math.round(placeModal.bearing)}°` : ''}</span>- </div>- </div>- <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />- <!-- what this point already claims, and why it is being saved — said while- the analyst still knows: the photo it geolocates, the video whose- metadata pointed here -->- <span style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Relations</span>- {#if placeModal.relations?.length}- <RelationList- caseId={caseState.current.id}- relations={placeModal.relations}- subjectType="place"- actionFilter="relation"- onwalk={(entity) => { placeModal = null; openEntity(entity); }}- onchanged={async () => {- await loadPlaceRelations(placeModal?.id);- await reloadCase();- }}- />- {/if}- <RelationPicker subjectType="place" bind:value={placeModal.relation} />- <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />- <label for="place-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>- <textarea- id="place-notes"- class="textarea"- rows="5"- placeholder="Add observations, links, context…"- bind:value={placeModal.notes}- ></textarea>- <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">- <button class="btn" onclick={() => (placeModal = null)}>Cancel</button>- <button class="btn btn-primary" onclick={savePlaceModal} disabled={placeSaving}>- {placeSaving ? 'Saving…' : 'Save'}- </button>- </div>- </Modal>+ onwalk={(entity) => {+ placeModal = null;+ openEntity(entity);+ }}+ onchanged={async () => {+ await loadPlaceRelations(placeModal?.id);+ await reloadCase();+ }}+ />{/if}-<!-- reference-image picker: choose a case image to float over the map. Pure- scratch aid — the window is never captured or saved. -->{#if refPicker}- <Modal title="Add reference" onclose={() => (refPicker = false)} width="560px">- <p class="ref-hint">- Float a case image or video over the map to compare against the imagery.- Reference windows are never captured or saved.- </p>- {#if refLoading}- <div class="ref-empty">Loading…</div>- {:else if !refMedia.length}- <div class="ref-empty">- No images or videos in this case yet. Import one in the Media Library first.- </div>- {:else}- {#if refBrowserOpen || refMedia.length > REF_SEARCH_MIN}- <div class="ref-search">- <SearchInput- bind:value={refQuery}- placeholder="Search media…"- count={`${visibleRefMedia.length}/${refMedia.length}`}- width="100%"- />- <button- class="btn btn-ghost btn-sm browse-btn"- title={refBrowserOpen ? 'Show every image' : 'Browse folders'}- onclick={toggleRefBrowser}- >…</button>- </div>- {/if}- {#if refBrowserOpen}- <FolderBrowser- entries={refBrowserEntries}- path={refBrowsePath}- rootLabel="Case media"- selectedId={refBrowseSelection}- matches={(entry) => matchesQuery(entry, refQuery)}- emptyText="This folder has no matching media."- icon={(entry) => (entry.kind === 'video' ? 'video' : 'image')}- label={(entry) => entry.title ?? entry.filename}- onnavigate={openRefFolder}- onselect={(entry) => (refBrowseSelection = entry.path)}- onconfirm={(entry) => addRef(entry)}- />- <div class="ref-actions">- <button class="btn btn-primary btn-sm" disabled={!refBrowseSelection} onclick={confirmRefBrowser}>- Add selected- </button>- </div>- {:else if !visibleRefMedia.length}- <div class="ref-empty">No media matches this search.</div>- {:else}- <div class="ref-grid">- {#each visibleRefMedia as m (m.path)}- <button class="ref-pick" onclick={() => addRef(m)} title={m.title ?? m.filename}>- <div class="ref-thumb">- {#if m.thumbnail}- <img src={fileUrl(caseState.current.id, m.thumbnail)} alt={m.filename} loading="lazy" />- {:else}- <Icon name={m.kind === 'video' ? 'video' : 'image'} size={26} />- {/if}- {#if m.kind === 'video'}- <span class="ref-kind"><Icon name="video" size={11} /></span>- {/if}- </div>- <span class="ref-name">{m.title ?? m.filename}</span>- </button>- {/each}- </div>- {/if}- {/if}- </Modal>+ <RefPicker+ media={refMedia}+ loading={refLoading}+ caseId={caseState.current?.id}+ onpick={addRef}+ onclose={() => (refPicker = false)}+ />{/if}<style>@@ -4004,9 +3039,9 @@flex: 1;min-width: 0;overflow: hidden;- /* keep the map's z-index range (Leaflet panes/controls up to 1000, our own- clusters above them) to itself, so a dialog portalled into the fullscreen- tool still lands on top of it */+ /* keep the map's z-index range (the engine's own controls, our clusters above+ them, and the widget basemap on a negative layer below) to itself, so a+ dialog portalled into the fullscreen tool still lands on top of it */isolation: isolate;}.map {@@ -4014,6 +3049,16 @@inset: 0;background: var(--bg-2);}+ .map-refused {+ position: absolute;+ inset: 0;+ display: grid;+ place-content: center;+ margin: 0;+ padding: 0 24px;+ text-align: center;+ color: var(--text-2);+ }.temporal-layer-card.stacked { top: 150px; }.temporal-layer-card {position: absolute;@@ -4182,19 +3227,17 @@position: absolute;top: 12px;left: 12px;- /* above Leaflet's own control corners (z-index 1000) so the measure panel- is never hidden behind the zoom +/- buttons (item 7) */+ /* above the engine's own control corners so the measure panel is never+ hidden behind the zoom +/- buttons (item 7) */z-index: 1100;display: flex;flex-direction: column;gap: 8px;align-items: flex-start;}- .map-wrap.measuring :global(.leaflet-container),- .map-wrap.selecting :global(.leaflet-container) {- cursor: crosshair;- }- .map-wrap.grid-drawing :global(.leaflet-container) {+ .map-wrap.measuring :global(.map-surface),+ .map-wrap.selecting :global(.map-surface),+ .map-wrap.grid-drawing :global(.map-surface) {cursor: crosshair;}@@ -4592,196 +3635,5 @@color: var(--accent);}- .sat-info-rows {- display: flex;- flex-direction: column;- gap: 6px;- }- .sat-info-row {- display: flex;- gap: 10px;- font-size: var(--fs-sm);- align-items: baseline;- }- .sat-info-label {- color: var(--text-3);- font-size: var(--fs-xs);- min-width: 80px;- flex-shrink: 0;- }- /* Leaflet dark-theme adjustments */- :global(.leaflet-container) {- font-family: var(--font-sans);- background: var(--bg-2);- image-rendering: smooth;- }- /* NB: no backface-visibility / transform promotion on tiles — that forces- each tile onto its own GPU layer and reintroduces the white seams the- deSeamTiles() left/top positioning removes (see script). */- :global(.leaflet-control-attribution) {- background: rgba(24, 24, 24, 0.85) !important;- color: var(--text-3) !important;- font-size: 10px;- }- :global(.leaflet-control-attribution a) {- color: var(--text-2) !important;- }- :global(.leaflet-bar a) {- background: var(--bg-2) !important;- color: var(--text-1) !important;- border-color: var(--border) !important;- }- :global(.leaflet-bar a:hover) {- background: var(--bg-3) !important;- }- /* zoom +/- (topleft) sits directly under the fullscreen/labels/measure- cluster instead of Leaflet's default corner margin, which used to land- it right on top of that cluster */- :global(.leaflet-top.leaflet-left) {- top: 58px !important;- left: 12px !important;- }- :global(.leaflet-top.leaflet-left .leaflet-control) {- margin: 0 0 8px !important;- }- :global(.leaflet-pane) {- will-change: transform;- }- /* Slim ruler-style scale: no boxed panel, just a light bracket + label- floating directly on the map so it stays readable over any imagery. */- :global(.leaflet-control-scale) {- background: transparent !important;- border: none !important;- box-shadow: none !important;- padding: 0 !important;- margin: 0 10px 10px 0 !important;- }- :global(.leaflet-control-scale-line) {- background: transparent !important;- border: none !important;- border-left: 1.5px solid rgba(255, 255, 255, 0.92) !important;- border-right: 1.5px solid rgba(255, 255, 255, 0.92) !important;- border-bottom: 1.5px solid rgba(255, 255, 255, 0.92) !important;- color: #fff !important;- font-size: 10px !important;- font-weight: 600 !important;- line-height: 1.3 !important;- padding: 0 4px 1px !important;- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.85), 0 0 4px rgba(0, 0, 0, 0.5) !important;- }-- /* reference-image picker */- .ref-hint {- font-size: var(--fs-sm);- color: var(--text-2);- margin: 0 0 12px;- }- .ref-search {- display: flex;- align-items: center;- gap: 6px;- margin-bottom: 10px;- }- .ref-search :global(.search-box) {- flex: 1;- }- .browse-btn {- min-width: 30px;- font-size: var(--fs-lg);- line-height: 1;- }- .ref-actions {- display: flex;- justify-content: flex-end;- margin-top: 10px;- }- .shot-hint {- font-size: var(--fs-sm);- color: var(--text-2);- margin: 0 0 12px;- }- .shot-zone {- display: flex;- align-items: center;- justify-content: center;- min-height: 180px;- border: 1px dashed var(--border);- border-radius: 6px;- color: var(--text-3);- font-size: var(--fs-sm);- overflow: hidden;- }- .shot-zone.has-image {- border-style: solid;- }- .shot-zone img {- max-width: 100%;- max-height: 320px;- display: block;- }- .ref-empty {- padding: 24px 4px;- text-align: center;- font-size: var(--fs-sm);- color: var(--text-3);- }- .ref-grid {- display: grid;- grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));- gap: 10px;- max-height: 52vh;- overflow-y: auto;- }- .ref-pick {- display: flex;- flex-direction: column;- gap: 5px;- padding: 0;- background: none;- border: none;- color: var(--text-2);- cursor: pointer;- text-align: left;- }- .ref-thumb {- position: relative;- aspect-ratio: 4 / 3;- border-radius: var(--radius-1);- overflow: hidden;- background: var(--bg-2);- display: grid;- place-items: center;- color: var(--text-3);- border: 1px solid var(--border);- }- .ref-kind {- position: absolute;- bottom: 4px;- right: 4px;- display: grid;- place-items: center;- padding: 2px;- border-radius: var(--radius-1);- color: #fff;- background: rgba(16, 16, 16, 0.75);- backdrop-filter: blur(4px);- }- .ref-pick:hover .ref-thumb {- border-color: var(--accent);- }- .ref-thumb img {- width: 100%;- height: 100%;- object-fit: cover;- }- .ref-name {- font-size: var(--fs-xs);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .ref-pick:hover .ref-name {- color: var(--accent);- }</style>diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.jsindex cb211e0..3d6d27f 100644--- a/frontend/src/tools/Satellite.test.js+++ b/frontend/src/tools/Satellite.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { readFileSync } from 'node:fs';+import { readdirSync, readFileSync } from 'node:fs';const source = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');const cluster = readFileSync(@@ -7,90 +7,60 @@ const cluster = readFileSync('utf8');// The sky overlay's geometry moved to `lib/skyOverlay.js`, where it is exercised-// against real numbers (`skyOverlay.test.js`); the tool hands it to Leaflet.+// against real numbers (`skyOverlay.test.js`); the tool hands it to the map.const sky = readFileSync(new URL('../lib/skyOverlay.js', import.meta.url), 'utf8');-describe('Satellite saved work', () => {- it('opens the case on one compact index, not on every capture row', () => {- expect(source).toContain('/satellite/index');- // the flat Places and Captures lists, and everything that served only them- expect(source).not.toContain('fetchAllEntities');- expect(source).not.toContain('capturesSubCollapsed');- expect(source).not.toContain('placesCollapsed');- expect(source).not.toContain('cap-list');- expect(source).not.toContain('place-list');- });+/** The tool and everything it is made of, for the checks that must hold of all of it. */+function satelliteSources() {+ const files = { 'Satellite.svelte': source };+ const dir = new URL('./satellite/', import.meta.url);+ for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {+ if (!entry.isFile() || entry.name.endsWith('.test.js')) continue;+ const at = `${entry.parentPath}/${entry.name}`;+ files[at.slice(at.indexOf('/satellite/') + 1)] = readFileSync(at, 'utf8');+ }+ return files;+}- it('hands the index to the tree, the search and the map overlay', () => {+describe('Satellite saved work', () => {+ // The indexes, the filter, the Locate pass and the row actions are the store's+ // (`satellite/state/saved.svelte.test.js`, which exercises them for real).+ // What is this file's business is that the tool hands them over.+ it('hands one store to the tree, the search and the map overlay', () => {+ expect(source).toContain("import { createSavedState } from './satellite/state/saved.svelte.js'");expect(source).toContain('<SavedTree');expect(source).toContain('<SavedSearch');expect(source).toContain('<SavedOverlay');- expect(source).toContain('rows={savedRows}');- expect(source).toContain('items={savedShown}');- });-- it('draws the panel’s filtered selection on the map, not the whole index', () => {- expect(source).toContain(- 'const savedShown = $derived(filterSaved(savedRows, { kind: savedKind, query: savedQuery }))'- );- // the overlay must never be handed the unfiltered index again- expect(source).not.toContain('items={saved}');+ expect(source).toContain('rows={savedWork.shownRows}');+ // the overlay draws the panel's filtered selection, never the whole index+ expect(source).toContain('items={savedWork.shown}');+ expect(source).not.toContain('items={savedWork.rows}');});- it('reads the proofs index only once the Proofs position is opened', () => {- // opening a case must not pay for a view it may never show- expect(source).toContain('const savedRows = $derived(isMode(savedKind) ? savedProofs : saved)');- expect(source).toContain('if (!id || !isMode(savedKind) || proofsFor === stamp) return');- expect(source).toContain('`/api/cases/${id}/proofs/index`');+ it('loads and drops both indexes with the case, through the store', () => {+ expect(source).toContain('return savedWork.load(id);');+ expect(source).toContain('savedWork.loadProofs(caseState.current?.id, caseState.rev)');});- it('files a dragged row through its own entity type', () => {- // a proof filed as a capture would be routed to PATCH /media, which is the- // sidecar of an image the proof is not- expect(source).toContain("row.kind === 'proof' ? 'proof'");+ it('closes over this case for every row action', () => {+ // a pass or a PATCH must never land in the case the analyst just left+ expect(source).toContain('savedWork.accept(caseState.current.id, row)');+ expect(source).toContain('savedWork.move(caseState.current.id, row, folder)');+ expect(source).toContain('savedWork.runLocate(caseState.current?.id)');+ expect(source).toContain('await savedWork.remove(caseId, row)');});- it('re-reads the proofs index when the case is reloaded, not only when it changes', () => {- // filing a proof reloads the case; keying only on the id would leave the- // panel showing the folder the proof just left- expect(source).toContain('const stamp = `${id}:${caseState.rev}`');- });-- it('drops both saved indexes before loading a different case', () => {+ it('drops the dialogs and the session layers before another case', () => {const effect = source.slice(- source.indexOf('if (savedFor !== id)'),- source.indexOf('return () => { live = false; };', source.indexOf('if (savedFor !== id)'))+ source.indexOf('if (openFor !== id)'),+ source.indexOf('return savedWork.load(id);'));- expect(effect).toContain('saved = []');- expect(effect).toContain('savedProofs = []');- expect(effect).toContain('proofsFor = null');expect(effect).toContain('savedSearchOpen = false');expect(effect).toContain('deleteTarget = null');expect(effect).toContain('notesItem = null');expect(effect).toContain('placeModal = null');- expect(effect).toContain('locateGeneration += 1');- expect(effect.indexOf('saved = []')).toBeLessThan(effect.indexOf('/satellite/index'));- });-- it('ignores an earlier case response after the case changes', () => {- expect(source).toContain('.then((rows) => { if (live) saved = rows; })');- expect(source).toContain('return () => { live = false; };');- });-- it('opens a proof rather than queueing it as a panel of a new one', () => {- expect(source).toContain("if (item.kind === 'proof') {");- expect(source).toContain('uiState.openProof = item.name');- });-- it('opens a linked post in the existing Post Composer draft flow', () => {- expect(source).toContain('function openLinkedPost(post)');- expect(source).toContain('uiState.openDraft = post.name');- expect(source).toContain('onpost={openLinkedPost}');- });-- it('shares one hovered id between the panel and the map', () => {- expect(source).toContain('let hoveredSavedId = $state(null)');- expect((source.match(/bind:hoveredId=\{hoveredSavedId\}/g) ?? []).length).toBe(3);+ expect(effect).toContain('temporalMap = null');+ expect(effect).toContain('sheetPoints = null');});it('keeps the map overlay off by default and out of the case file', () => {@@ -102,39 +72,25 @@ describe('Satellite saved work', () => {expect(source).not.toContain('savedOverlay:');});- it('runs Locate in bounded batches that can be stopped', () => {- expect(source).toContain('/satellite/locate?limit=${LOCATE_BATCH}');- expect(source).toContain(- 'while (remaining > 0 && !locateStopped && generation === locateGeneration)'- );- expect(source).toContain('oncancelLocate={() => (locateStopped = true)}');- });-- it('stops the Locate loop when a batch resolves nothing', () => {- // offline, every batch comes back with the same backlog — looping on that- // would hammer Nominatim forever- expect(source).toContain('const stalled = batch.remaining >= remaining');- expect(source).toContain('if (stalled || throttled) break;');+ it('shares one hovered id between the panel and the map', () => {+ expect(source).toContain('let hoveredSavedId = $state(null)');+ expect((source.match(/bind:hoveredId=\{hoveredSavedId\}/g) ?? []).length).toBe(3);});- it('stops and says so when OpenStreetMap is rate-limiting the address', () => {- // a 429 is not a lookup failure: running the pass again is exactly the- // wrong advice, so the pass ends and the toast says to wait- expect(source).toContain('throttled = Boolean(batch.throttled)');- expect(source).toContain('OpenStreetMap is rate-limiting this address');+ it('opens a proof rather than queueing it as a panel of a new one', () => {+ expect(source).toContain("if (item.kind === 'proof') {");+ expect(source).toContain('uiState.openProof = item.name');});- it('does not let a Locate pass continue in another case', () => {- expect(source).toContain('const id = caseState.current.id');- expect(source).toContain('const generation = ++locateGeneration');- expect(source).toContain('generation === locateGeneration');- expect(source).toContain('`/api/cases/${id}/satellite/locate?limit=${LOCATE_BATCH}`');- expect(source).toContain('if (generation !== locateGeneration) return');+ it('opens a linked post in the existing Post Composer draft flow', () => {+ expect(source).toContain('function openLinkedPost(post)');+ expect(source).toContain('uiState.openDraft = post.name');+ expect(source).toContain('onpost={openLinkedPost}');});it('reveals a capture the case sidebar points at, whatever the filter was', () => {- expect(source).toContain("savedKind = 'all'");- expect(source).toContain("savedQuery = ''");+ expect(source).toContain("savedWork.kind = 'all'");+ expect(source).toContain("savedWork.query = ''");expect(source).toContain('revealSavedId = row.id');});});@@ -146,65 +102,59 @@ describe('Capture extension settings handoff', () => {});describe('filing saved work from its details dialog', () => {+ const captureDialog = readFileSync(+ new URL('./satellite/CaptureDetails.svelte', import.meta.url),+ 'utf8'+ );+it('offers the same folder picker the rest of the app uses, in both dialogs', () => {- expect(source).toContain("import FolderSelect from '../components/FolderSelect.svelte'");- expect(source).toContain('bind:value={notesFolder}');- expect(source).toContain('bind:value={placeModal.folder}');- expect((source.match(/emptyLabel="My work \(root\)"/g) ?? []).length).toBe(2);+ expect(captureDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");+ expect(captureDialog).toContain('bind:value={folder}');+ expect(captureDialog).toContain('emptyLabel="My work (root)"');+ const placeDialog = readFileSync(+ new URL('./satellite/PlaceDialog.svelte', import.meta.url),+ 'utf8'+ );+ expect(placeDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");+ expect(placeDialog).toContain('bind:value={draft.folder}');+ expect(placeDialog).toContain('emptyLabel="My work (root)"');});it('opens each dialog on the folder the item is already in', () => {- expect(source).toContain("notesFolder = row.folder ?? ''");+ expect(captureDialog).toContain("let folder = $state(row.folder ?? '')");expect(source).toContain("folder: row.folder ?? ''");});it('files a capture in the patch it already sends', () => {- expect(source).toContain('title: notesTitle, folder: notesFolder');+ expect(source).toContain('{ path: notesItem.path, notes, title, folder }');});it('files a place, whether it is being saved or edited', () => {expect(source).toContain("attrs: { notes: m.notes.trim(), folder: m.folder ?? '' }");- expect(source).toMatch(/notes: m\.notes,\s*\n\s*folder: m\.folder,/);+ expect(source).toContain('folder: m.folder,');});});-describe('reference picker search', () => {- it('searches the case media instead of only listing it', () => {- expect(source).toContain("import { matchesQuery } from '../lib/mediaFilter.js'");- expect(source).toContain('matchesQuery(m, refQuery)');- expect(source).toContain('{#each visibleRefMedia as m (m.path)}');- });-- it('only shows the box once the grid is long enough to need it', () => {- expect(source).toContain('const REF_SEARCH_MIN = 6');- });-- it('opens the picker on a cleared query', () => {- expect(source).toMatch(/refPicker = true;\s*\n\s*refQuery = '';/);- });-- it('tells the user when the search matched nothing', () => {- expect(source).toContain('No media matches this search.');- });-- it('swaps the grid for the folder browser behind the "…" button', () => {- expect(source).toContain('<FolderBrowser');- expect(source).toContain('onclick={toggleRefBrowser}');- expect(source).toContain('entries={refBrowserEntries}');- expect(source).toContain("rootLabel=\"Case media\"");- // the browser reads the folder off attrs, like every other picker- expect(source).toContain("attrs: { folder: m.folder ?? '' }");+describe('reference windows', () => {+ // the picker itself is `satellite/RefPicker.svelte`, which owns the search,+ // the folder browser and what an empty case says+ it('reads the case media once, when the picker opens', () => {+ expect(source).toContain('async function openRefPicker()');+ expect(source).toContain('`/api/cases/${id}/media`');+ expect(source).toContain("m.kind === 'image' || m.kind === 'video'");});- it('keeps the search box up while browsing and filters the rows with it', () => {- expect(source).toContain('{#if refBrowserOpen || refMedia.length > REF_SEARCH_MIN}');- expect(source).toContain('matches={(entry) => matchesQuery(entry, refQuery)}');+ it('spawns the window the picker handed back, and closes it', () => {+ expect(source).toContain('onpick={addRef}');+ expect(source).toContain('createViewer(`ref-${++refSeq}`, item');+ expect(source).toContain('refPicker = false;');});- it('adds the browsed pick on double-click or the confirm button', () => {- expect(source).toContain('onconfirm={(entry) => addRef(entry)}');- expect(source).toContain('disabled={!refBrowseSelection}');- expect(source).toContain('onclick={confirmRefBrowser}');+ it('keeps the windows out of the case: session state, never captured', () => {+ // they live in uiState for the tab's life, and the crop hides them+ expect(source).toContain('uiState.refViewers');+ expect(source).not.toContain('refViewers:');+ expect(source).toContain('.map-wrap.grabbing');});});@@ -233,8 +183,16 @@ describe('the saved panel is resizable', () => {expect(source).toContain('savedPanel.saveWidth(savedW); // one write per drag');});+ it('leaves the left button to whichever mode is armed for it', () => {+ // shift and the left button turn the map, but the capture marquee and the+ // grid box are both waiting on that same drag+ expect(source).toContain(+ "e.button === 0 && e.shiftKey && !selectArmed && gridDraw !== 'rect'"+ );+ });+it('redraws the map for the new size', () => {- expect(source).toContain('map?.invalidateSize({ animate: false })');+ expect(source).toContain('engine?.resize()');});it('hides the handle when the panel is collapsed to its rail', () => {@@ -244,29 +202,14 @@ describe('the saved panel is resizable', () => {describe('filing saved work by dragging it in the panel', () => {it('hands the tree both groupings, the case folders and a move handler', () => {- expect(source).toContain('bind:group={savedGroup}');- expect(source).toContain('folders={caseState.current?.folders ?? []}');+ expect(source).toContain('bind:group={savedWork.group}');expect(source).toContain('onmove={moveSaved}');- });-- it('remembers which grouping the panel was left on', () => {- expect(source).toContain("const GROUP_KEY = 'azimut:satelliteSavedGroup'");- expect(source).toContain('let savedGroup = $state(loadSavedGroup())');- expect(source).toContain('localStorage.setItem(GROUP_KEY, savedGroup)');- });-- it('moves through the shared filing route, then reloads the case', () => {- expect(source).toContain("import { assignFolder } from '../lib/filing.js'");- expect(source).toContain('await assignFolder(caseState.current.id, entity, folder)');- expect(source).toContain(- "type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture'"- );- expect(source).toContain('await reloadCase();\n toast(');+ expect(source).toContain('folders={caseState.current?.folders ?? []}');});it('leaves folder browsing out of the search modal', () => {- expect(source).not.toContain('savedBrowsing');- expect(source).not.toContain('bind:path=');+ const modal = source.slice(source.indexOf('<SavedSearch'));+ expect(modal).not.toContain('onmove');});});@@ -304,8 +247,9 @@ describe('sun and moon mode', () => {// the anchor stands for the zenith and the arc for the horizon, the same// radial convention as the compass rosetteexpect(sky).toContain('return (90 - altitude) / 90;');- expect(source).toContain('at(body.azimuth[sunIndex], markScale(altitude))');- expect(source).toContain('function bodyIcon(kind, colour, illuminated, waxing)');+ expect(source).toContain('at: at(body.azimuth[sunIndex], markScale(altitude))');+ // the glyph is skyOverlay's; the tool only says where the mark rides+ expect(source).toContain('html: bodySvg(');});it('leaves the ray bare while the body is under the horizon', () => {@@ -324,14 +268,14 @@ describe('sun and moon mode', () => {it('names the altitude on the mark and on the ray', () => {expect(sky).toContain('alt ${Math.round(altitude)}°');expect(source).toContain('bodyReading(');- expect(source).toContain("bindTooltip(body.key === 'moon'");+ expect(source).toContain("tip: body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading");});it('keeps a body below the horizon on the map, dashed', () => {expect(source).toContain('const altitude = body.altitude[sunIndex]');expect(sky).toContain('return altitude < 0;');expect(source).toContain('const below = isBelow(altitude)');- expect(source).toContain("dashArray: below ? '6 6' : null");+ expect(source).toContain("dash: below ? '6 6' : null");});it('scrubs the hour without asking the backend again', () => {@@ -347,15 +291,15 @@ describe('sun and moon mode', () => {});it('sizes the arc off the shorter side of the view, so it stays on screen', () => {- // a radius set by the diagonal runs off the top and bottom of a wide window+ // a radius set by the diagonal runs off the top and bottom of a wide window.+ // How far the view reaches each way is the façade's answer (facade.test.js);+ // which of the two the arc rides on is this tool's.+ expect(source).toContain('const { across, down } = engine.viewSpanMeters()');expect(source).toContain('Math.min(across, down) * 0.22');- expect(source).toContain('bounds.getNorthWest(), bounds.getNorthEast()');});it('restretches the arc when the view moves, since it is drawn in metres', () => {- expect(source).toContain("map.on('zoomend moveend', redraw)");- expect(source).toContain("map.off('zoomend moveend', redraw)");- expect(source).toContain('bounds.getNorthWest(), bounds.getSouthWest()');+ expect(source).toContain("return engine.on('view-settled', () => drawSun())");});it('takes the handoff from Coords & Sky into the same mode', () => {@@ -368,21 +312,9 @@ describe('sun and moon mode', () => {});describe('accepting a proposed point from the Saved panel', () => {- // import enrichment still proposes places from a file's GPS, and the panel- // reading them is where they are settled- it('sends the same PATCH the sidebar does, so one click means one thing', () => {- expect(source).toContain("status: 'confirmed',");- expect(source).toContain('onaccept={acceptSaved}');- });-- it('re-reads the case, or the row would keep claiming it is proposed', () => {- const fn = source.slice(source.indexOf('async function acceptSaved'));- expect(fn.slice(0, fn.indexOf('\n }'))).toContain('await reloadCase()');- });-- it('offers it in the search modal too, which lists the same index', () => {- const modal = source.slice(source.indexOf('<SavedSearch'));- expect(modal.slice(0, modal.indexOf('/>'))).toContain('onaccept={acceptSaved}');+ it('offers it wherever the panel lists a row', () => {+ // the tree and the search modal read the same index, so both offer it+ expect((source.match(/onaccept=\{acceptSaved\}/g) ?? []).length).toBe(2);});});@@ -396,11 +328,34 @@ describe('Satellite — lifecycle and the date line', () => {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() };');+ it('takes the centre as the façade hands it over, and never rewraps it', () => {+ // Folding a centre back inside ±180 across the antimeridian is stated once,+ // in lib/map (facade.test.js). A tool that reached for wrapLon again would+ // be the second place that guarantee could be got wrong.+ expect(source).toContain("engine.on('view-settled', (view) => {");+ expect(source).toContain('center = { lat: view.lat, lon: view.lon, zoom: view.zoom };');+ expect(source).not.toContain('wrapLon');+ });++ it('goes through the façade for the camera, not through the engine', () => {+ // What must never come back is a tool moving, projecting or measuring the+ // map itself: that is the whole point of `lib/map`, and it is what made+ // replacing the engine a rewrite of five modules instead of a tool.+ expect(source).toContain("import { createMapEngine } from '../lib/map/engine.js';");+ expect(source).not.toContain('map.setView');+ expect(source).not.toContain('map.getCenter');+ expect(source).not.toContain('map.containerPointToLatLng');+ expect(source).not.toContain('map.latLngToContainerPoint');+ });++ it('names no engine at all, not even in a class or a comment', () => {+ // The engine's chrome is dressed in lib/map/engine.css, and a mode armed+ // above the map says so on `.map-surface`, whichever engine drew it. This+ // held across one engine change; it is what will make the next one cheap.+ for (const [name, text] of Object.entries(satelliteSources())) {+ expect(text.toLowerCase(), name).not.toContain('leaflet');+ expect(text.toLowerCase(), name).not.toContain('maplibre');+ }});});@@ -408,7 +363,7 @@ 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('savedRows={savedWork.rows}');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@@ -428,6 +383,6 @@ describe('Satellite — the search bar', () => {});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));');+ expect(source).toContain('engine.setView(item, item.zoom ?? Math.max(engine.getZoom(), 13));');});});diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex 983ac96..2c38e27 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -10,7 +10,7 @@import { templateFromPost } from '../lib/post.js';import { formatCoords, parseHomeView } from '../lib/coords.js';import { USAGE_LINKS, ECO_MAX_ZOOM } from '../lib/usage.js';- import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';+ import { probeKey, googleMapsLoadedKey } from '../lib/map/gmaps.js';import { extensionVersion } from '../lib/extBridge.js';import { CASE_FOLDER_LABEL, saveDestination } from '../lib/exportDest.js';import Icon from '../components/Icon.svelte';@@ -191,6 +191,7 @@let home = $state({ lat: '', lon: '', zoom: '' });let mention = $state('');let postTarget = $state('x');+ let postPrefill = $state(true);let updateOnStart = $state(true); // pop a notice on load when a release is out// whether saving a proof files its point as a place, or asks firstlet proofPlaceAuto = $state(true);@@ -403,6 +404,7 @@home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };mention = s.post_mention ?? '';postTarget = s.post_target ?? 'x';+ postPrefill = s.post_prefill ?? true;updateOnStart = s.update_check_on_start ?? true;proofPlaceAuto = s.proof_place_auto ?? true;applyPrefs(s); // the rest of the app reads these live@@ -695,6 +697,7 @@{uploadSignature}bind:mentionbind:postTarget+ bind:postPrefillbind:signatureHandlebind:sigInput/>diff --git a/frontend/src/tools/satellite/CaptureDetails.svelte b/frontend/src/tools/satellite/CaptureDetails.sveltenew file mode 100644index 0000000..afbcc7d--- /dev/null+++ b/frontend/src/tools/satellite/CaptureDetails.svelte@@ -0,0 +1,128 @@+<script>+ /**+ * One capture's title, folder and notes, over what the case knows about it.+ *+ * The read-only rows are the provenance an analyst checks before writing+ * anything: which provider served the pixels, at what zoom, when it was+ * taken, and the imagery's own acquisition date when the provider could say+ * it. "—" is a real answer here — no provider is asked twice to fill a gap.+ */+ import Icon from '../../components/Icon.svelte';+ import Modal from '../../components/Modal.svelte';+ import FolderSelect from '../../components/FolderSelect.svelte';+ import { fileUrl } from '../../lib/fileUrl.js';++ let {+ /** The saved-index row being edited. */+ row,+ caseId,+ folders = [],+ /** Format a row's coordinates the way the analyst set it. */+ coords,+ /** Set while the map owns the whole screen, so a new tab would go unseen. */+ leavesFullscreen = null,+ onsave,+ onclose,+ } = $props();++ // The dialog opens on the row it was given and edits copies: it is mounted+ // per row and dropped on close, so the initial value is the whole intent.+ // svelte-ignore state_referenced_locally+ let title = $state(row.title ?? coords(row));+ // svelte-ignore state_referenced_locally+ let folder = $state(row.folder ?? '');+ // svelte-ignore state_referenced_locally+ let notes = $state(row.notes ?? '');+ let saving = $state(false);++ async function save() {+ saving = true;+ try {+ await onsave({ title, folder, notes });+ } finally {+ saving = false;+ }+ }+</script>++<Modal title="Capture details" {onclose} width="420px">+ <label for="capture-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>+ <input id="capture-title" class="input" placeholder={coords(row)} bind:value={title} />+ <label for="capture-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>+ <FolderSelect+ id="capture-folder"+ bind:value={folder}+ {folders}+ emptyLabel="My work (root)"+ />+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <div class="sat-info-rows">+ <div class="sat-info-row">+ <span class="sat-info-label">Coordinates</span>+ <span class="mono">{coords(row)}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Provider</span>+ <span>{row.provider ?? row.site ?? '—'}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Zoom</span>+ <span>{row.zoom ?? '—'}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Captured</span>+ <span class="mono">{row.fetched_at?.slice(0, 10)}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Imagery date</span>+ <span class="mono">{row.imagery_date ?? '—'}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Image</span>+ <a+ class="link-out"+ class:disabled={!!leavesFullscreen}+ href={leavesFullscreen ? undefined : fileUrl(caseId, row.path)}+ target="_blank"+ rel="noreferrer"+ aria-disabled={!!leavesFullscreen}+ title={leavesFullscreen ?? 'Open the full image'}+ >Open the full image <Icon name="external" size={12} /></a>+ </div>+ </div>+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <label for="capture-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>+ <textarea+ id="capture-notes"+ class="textarea"+ rows="5"+ placeholder="Add observations, links, context…"+ bind:value={notes}+ ></textarea>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ <button class="btn" onclick={onclose}>Cancel</button>+ <button class="btn btn-primary" onclick={save} disabled={saving}>+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+</Modal>++<style>+ .sat-info-rows {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .sat-info-row {+ display: flex;+ gap: 10px;+ font-size: var(--fs-sm);+ align-items: baseline;+ }+ .sat-info-label {+ color: var(--text-3);+ font-size: var(--fs-xs);+ min-width: 80px;+ flex-shrink: 0;+ }+</style>diff --git a/frontend/src/tools/satellite/ExtensionGate.svelte b/frontend/src/tools/satellite/ExtensionGate.sveltenew file mode 100644index 0000000..025c73f--- /dev/null+++ b/frontend/src/tools/satellite/ExtensionGate.svelte@@ -0,0 +1,38 @@+<script>+ /**+ * The Google widget basemap can only be captured through the browser+ * extension: screen pixels are the only thing Google's terms allow out of the+ * widget, and the extension is the promptless way to get them.+ *+ * So this explains it and points at Settings. Never a half-working share flow,+ * and never a quiet fallback to filing some other image instead.+ */+ import Modal from '../../components/Modal.svelte';++ let { onclose, onsettings } = $props();+</script>++<Modal title="Capture needs the browser extension" {onclose} width="460px">+ <p class="gate-hint">+ 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.+ </p>+ <p class="gate-hint">+ Install it from <strong>Settings → Capture extension</strong>, then reload+ this tab.+ </p>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ <button class="btn" onclick={onclose}>Cancel</button>+ <button class="btn btn-primary" onclick={onsettings}>Open Settings</button>+ </div>+</Modal>++<style>+ .gate-hint {+ font-size: var(--fs-sm);+ color: var(--text-2);+ margin: 0 0 12px;+ }+</style>diff --git a/frontend/src/tools/satellite/MapToolCluster.svelte b/frontend/src/tools/satellite/MapToolCluster.svelteindex 8dd7236..f8057f6 100644--- a/frontend/src/tools/satellite/MapToolCluster.svelte+++ b/frontend/src/tools/satellite/MapToolCluster.svelte@@ -125,7 +125,7 @@background: rgba(24, 24, 24, 0.88);backdrop-filter: blur(6px);}- /* stacked directly under Leaflet's zoom bar (top 58px + 64px tall + its 8px+ /* stacked directly under the engine's zoom bar (top 58px + 64px tall + its 8pxmargin), same width, so +/- and these read as one column of view controls */.view-cluster {position: absolute;diff --git a/frontend/src/tools/satellite/PlaceDialog.svelte b/frontend/src/tools/satellite/PlaceDialog.sveltenew file mode 100644index 0000000..6074765--- /dev/null+++ b/frontend/src/tools/satellite/PlaceDialog.svelte@@ -0,0 +1,108 @@+<script>+ /**+ * A place, being saved or edited: its title, folder, notes and what it+ * claims.+ *+ * The relations are here rather than only in the sidebar because this is the+ * moment the analyst still knows *why* the point is being saved — the photo it+ * geolocates, the video whose metadata pointed here. And a point that can gain+ * a relation here has to be able to lose one here too, which is why an+ * existing place shows what it already holds.+ *+ * The draft is the caller's object, edited in place: it carries the+ * coordinates, the zoom and the bearing the map was on, none of which this+ * dialog may change.+ */+ import Modal from '../../components/Modal.svelte';+ import FolderSelect from '../../components/FolderSelect.svelte';+ import RelationList from '../../components/RelationList.svelte';+ import RelationPicker from '../../components/RelationPicker.svelte';++ let {+ /** `{ id, title, notes, folder, lat, lon, zoom, bearing, relation, relations }`;+ * a null id means this point does not exist yet. */+ draft,+ caseId,+ folders = [],+ saving = false,+ /** Format the point the way the analyst set it. */+ coords,+ onsave,+ onclose,+ /** Follow a related entity into its own tool, which closes this. */+ onwalk,+ /** A relation was corrected or taken back: re-read them. */+ onchanged,+ } = $props();+</script>++<Modal title={draft.id ? 'Edit place' : 'Save place'} {onclose} width="420px">+ <label for="place-title" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Title</label>+ <input id="place-title" class="input" placeholder={coords(draft)} bind:value={draft.title} />+ <label for="place-folder" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin:10px 0 5px">Folder</label>+ <FolderSelect+ id="place-folder"+ bind:value={draft.folder}+ {folders}+ emptyLabel="My work (root)"+ />+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <div class="sat-info-rows">+ <div class="sat-info-row">+ <span class="sat-info-label">Coordinates</span>+ <span class="mono">{coords(draft)}</span>+ </div>+ <div class="sat-info-row">+ <span class="sat-info-label">Zoom</span>+ <span>z{draft.zoom}{draft.bearing ? ` · ${Math.round(draft.bearing)}°` : ''}</span>+ </div>+ </div>+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <span style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Relations</span>+ {#if draft.relations?.length}+ <RelationList+ {caseId}+ relations={draft.relations}+ subjectType="place"+ actionFilter="relation"+ {onwalk}+ {onchanged}+ />+ {/if}+ <RelationPicker subjectType="place" bind:value={draft.relation} />+ <hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />+ <label for="place-notes" style="display:block;font-size:var(--fs-xs);color:var(--text-3);margin-bottom:5px">Notes</label>+ <textarea+ id="place-notes"+ class="textarea"+ rows="5"+ placeholder="Add observations, links, context…"+ bind:value={draft.notes}+ ></textarea>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ <button class="btn" onclick={onclose}>Cancel</button>+ <button class="btn btn-primary" onclick={onsave} disabled={saving}>+ {saving ? 'Saving…' : 'Save'}+ </button>+ </div>+</Modal>++<style>+ .sat-info-rows {+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .sat-info-row {+ display: flex;+ gap: 10px;+ font-size: var(--fs-sm);+ align-items: baseline;+ }+ .sat-info-label {+ color: var(--text-3);+ font-size: var(--fs-xs);+ min-width: 80px;+ flex-shrink: 0;+ }+</style>diff --git a/frontend/src/tools/satellite/PlaceSearch.svelte b/frontend/src/tools/satellite/PlaceSearch.svelteindex 5c1aedc..e202cf2 100644--- a/frontend/src/tools/satellite/PlaceSearch.svelte+++ b/frontend/src/tools/satellite/PlaceSearch.svelte@@ -121,7 +121,21 @@schedule(value);}+ /**+ * The question has been answered, so stop asking it.+ *+ * A lookup still on the clock is a request for a place name nobody wants any+ * more — and for a typed coordinate, one the geocoder should never have been+ * troubled with at all. Picking a row is faster than the debounce, so without+ * this the request goes out after the analyst has already moved the map.+ */+ function settle() {+ clearTimeout(localTimer);+ clearTimeout(remoteTimer);+ }+function choose(item) {+ settle();open = false;at = -1;recents = pushRecent(item);@@ -144,6 +158,8 @@event.preventDefault();if (at >= 0 && rows[at]) choose(rows[at]);else {+ // the bar's own search takes it from here, and asks for itself+ settle();open = false;onsubmit(value);}diff --git a/frontend/src/tools/satellite/PlaceSearch.test.js b/frontend/src/tools/satellite/PlaceSearch.test.jsindex 9ac3f09..3e51bdb 100644--- a/frontend/src/tools/satellite/PlaceSearch.test.js+++ b/frontend/src/tools/satellite/PlaceSearch.test.js@@ -70,6 +70,17 @@ describe('choosing', () => {expect(source).toContain('onsubmit(value)');});+ it('stops the lookup once the question has been answered', () => {+ // Picking a row is far quicker than the geocoder debounce, so a request+ // left on the clock reaches Nominatim after the analyst has already moved+ // the map — and for a typed coordinate it should never have gone at all.+ expect(source).toContain('function settle() {');+ expect(source).toContain('clearTimeout(localTimer);\n clearTimeout(remoteTimer);');+ expect(source).toContain('function choose(item) {\n settle();');+ // …and the same when Enter hands the text to the bar's own search+ expect(source).toContain("// the bar's own search takes it from here, and asks for itself");+ });+it('remembers what was picked', () => {expect(source).toContain('recents = pushRecent(item)');});diff --git a/frontend/src/tools/satellite/RefPicker.svelte b/frontend/src/tools/satellite/RefPicker.sveltenew file mode 100644index 0000000..1b8d874--- /dev/null+++ b/frontend/src/tools/satellite/RefPicker.svelte@@ -0,0 +1,228 @@+<script>+ /**+ * Pick a case image or video to float over the map.+ *+ * A reference window is a pure scratch aid — never captured, never saved — so+ * this reads the case's media and hands one back. Two ways in, because a case+ * with two hundred images is a different problem from a case with four: the+ * grid, and the folder browser behind "…". The search box only appears once+ * the grid is long enough to need it.+ */+ import Icon from '../../components/Icon.svelte';+ import Modal from '../../components/Modal.svelte';+ import SearchInput from '../../components/SearchInput.svelte';+ import FolderBrowser from '../../components/FolderBrowser.svelte';+ import { fileUrl } from '../../lib/fileUrl.js';+ import { matchesQuery } from '../../lib/mediaFilter.js';++ let {+ /** The case's images and videos, already loaded. */+ media = [],+ loading = false,+ caseId,+ /** Take this one as a reference window. */+ onpick,+ onclose,+ } = $props();++ const SEARCH_MIN = 6; // below that, the grid is easier to scan than to search++ let query = $state('');+ let browsing = $state(false); // "…" swaps the grid for the folder browser+ let path = $state('');+ let selection = $state(null);++ // Same free-text match as the Media Library (filename, title, notes, folder,+ // download source), so what works there works here.+ const visible = $derived(media.filter((item) => matchesQuery(item, query)));+ const entries = $derived(+ media.map((item) => ({ ...item, id: item.path, attrs: { folder: item.folder ?? '' } }))+ );++ function resetBrowser() {+ path = '';+ selection = null;+ }++ function toggleBrowser() {+ if (browsing) {+ browsing = false;+ return;+ }+ query = '';+ resetBrowser();+ browsing = true;+ }+</script>++<Modal title="Add reference" {onclose} width="560px">+ <p class="ref-hint">+ Float a case image or video over the map to compare against the imagery.+ Reference windows are never captured or saved.+ </p>+ {#if loading}+ <div class="ref-empty">Loading…</div>+ {:else if !media.length}+ <div class="ref-empty">+ No images or videos in this case yet. Import one in the Media Library first.+ </div>+ {:else}+ {#if browsing || media.length > SEARCH_MIN}+ <div class="ref-search">+ <SearchInput+ bind:value={query}+ placeholder="Search media…"+ count={`${visible.length}/${media.length}`}+ width="100%"+ />+ <button+ class="btn btn-ghost btn-sm browse-btn"+ title={browsing ? 'Show every image' : 'Browse folders'}+ onclick={toggleBrowser}+ >…</button>+ </div>+ {/if}+ {#if browsing}+ <FolderBrowser+ {entries}+ {path}+ rootLabel="Case media"+ selectedId={selection}+ matches={(entry) => matchesQuery(entry, query)}+ emptyText="This folder has no matching media."+ icon={(entry) => (entry.kind === 'video' ? 'video' : 'image')}+ label={(entry) => entry.title ?? entry.filename}+ onnavigate={(to) => {+ path = to;+ selection = null;+ }}+ onselect={(entry) => (selection = entry.path)}+ onconfirm={(entry) => onpick(entry)}+ />+ <div class="ref-actions">+ <button+ class="btn btn-primary btn-sm"+ disabled={!selection}+ onclick={() => {+ const item = entries.find((entry) => entry.path === selection);+ if (item) onpick(item);+ }}+ >+ Add selected+ </button>+ </div>+ {:else if !visible.length}+ <div class="ref-empty">No media matches this search.</div>+ {:else}+ <div class="ref-grid">+ {#each visible as item (item.path)}+ <button class="ref-pick" onclick={() => onpick(item)} title={item.title ?? item.filename}>+ <div class="ref-thumb">+ {#if item.thumbnail}+ <img src={fileUrl(caseId, item.thumbnail)} alt={item.filename} loading="lazy" />+ {:else}+ <Icon name={item.kind === 'video' ? 'video' : 'image'} size={26} />+ {/if}+ {#if item.kind === 'video'}+ <span class="ref-kind"><Icon name="video" size={11} /></span>+ {/if}+ </div>+ <span class="ref-name">{item.title ?? item.filename}</span>+ </button>+ {/each}+ </div>+ {/if}+ {/if}+</Modal>++<style>+ .ref-hint {+ font-size: var(--fs-sm);+ color: var(--text-2);+ margin: 0 0 12px;+ }+ .ref-search {+ display: flex;+ align-items: center;+ gap: 6px;+ margin-bottom: 10px;+ }+ .ref-search :global(.search-box) {+ flex: 1;+ }+ .browse-btn {+ flex-shrink: 0;+ padding: 0 8px;+ font-size: var(--fs-md);+ line-height: 1;+ }+ .ref-actions {+ display: flex;+ justify-content: flex-end;+ margin-top: 10px;+ }+ .ref-empty {+ padding: 24px 0;+ text-align: center;+ color: var(--text-3);+ font-size: var(--fs-sm);+ }+ .ref-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ gap: 10px;+ max-height: 60vh;+ overflow: auto;+ }+ .ref-pick {+ display: flex;+ flex-direction: column;+ gap: 4px;+ padding: 0;+ background: none;+ border: none;+ color: var(--text-2);+ cursor: pointer;+ text-align: left;+ }+ .ref-thumb {+ position: relative;+ aspect-ratio: 4 / 3;+ border-radius: var(--radius-1);+ overflow: hidden;+ background: var(--bg-2);+ display: grid;+ place-items: center;+ color: var(--text-3);+ border: 1px solid var(--border);+ }+ .ref-kind {+ position: absolute;+ bottom: 4px;+ right: 4px;+ display: grid;+ place-items: center;+ padding: 2px;+ border-radius: var(--radius-1);+ color: #fff;+ background: rgba(16, 16, 16, 0.75);+ backdrop-filter: blur(4px);+ }+ .ref-pick:hover .ref-thumb {+ border-color: var(--accent);+ }+ .ref-thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .ref-name {+ font-size: var(--fs-xs);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .ref-pick:hover .ref-name {+ color: var(--accent);+ }+</style>diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelteindex 09c580c..e33935d 100644--- a/frontend/src/tools/satellite/SavedOverlay.svelte+++ b/frontend/src/tools/satellite/SavedOverlay.svelte@@ -1,17 +1,17 @@<script>/*** Session-only Saved navigation layer.- * Owns the Leaflet group and rebuilds it when items or zoom change.+ * Owns its drawing surface and rebuilds it when items or zoom change.*/import { mount, unmount } from 'svelte';- import L from 'leaflet';+ import { createSurface } from '../../lib/map/surface.js';import { paths } from '../../components/Icon.svelte';import { groupSavedMarkers, markerPrecision } from '../../lib/savedMarkers.js';import { openEntity } from '../../lib/navigate.js';import SavedPopup from './SavedPopup.svelte';let {- map = null,+ engine = null,items = [],caseId,coords,@@ -49,20 +49,24 @@const worked = mark.items.some((row) => row.proofs > 0)? '<i class="saved-mark-worked"></i>': '';- return L.divIcon({+ return {className: 'saved-mark-wrap',html: `<span class="saved-mark saved-mark-${kind}">${glyph(GLYPH[kind] ?? 'pin', 13)}${count}${worked}</span>`,- iconSize: [24, 24],- iconAnchor: [12, 12],- });+ size: [24, 24],+ anchor: [12, 12],+ };}- // Mount popup content as a component inside Leaflet's container.+ // Mount the card's content as a component, inside the popup's own element.let mounted = null;function popupContent(mark) {const host = document.createElement('div');if (mounted) unmount(mounted);+ const close = (then) => (arg) => {+ surface.closePopup();+ then?.(arg);+ };mounted = mount(SavedPopup, {target: host,props: {@@ -70,74 +74,45 @@caseId,coords,fullscreen,- onopen: (row) => {- map.closePopup();- onopen(row);- },- onedit: (row) => {- map.closePopup();- onedit(row);- },- onproof: (row) => {- map.closePopup();- onproof?.(row);- },- onpost: (post) => {- map.closePopup();- onpost?.(post);- },- onshowproofs: () => {- map.closePopup();- onshowproofs?.();- },+ onopen: close(onopen),+ onedit: close(onedit),+ onproof: close(onproof),+ onpost: close(onpost),+ onshowproofs: close(onshowproofs),// opening a related media leaves the map, so close the card first — the// same gesture as every other row here, rather than a popup that// vanishes without saying it would- onentity: (entity) => {- map.closePopup();- openEntity(entity);- },+ onentity: close(openEntity),onrefresh: () => onrefresh?.(),},});return host;}+ // How tightly the marks are grouped follows the zoom, and only the zoom: a pan+ // settles at the same zoom, reads the same number, and rebuilds nothing.$effect(() => {- if (!map) return;- const sync = () => (zoom = map.getZoom());- sync();- map.on('zoomend', sync);- return () => map.off('zoomend', sync);+ if (!engine) return;+ zoom = engine.getZoom();+ return engine.on('view-settled', (view) => (zoom = view.zoom));});// Is a card open? Rebuilding the layer destroys it, and the card is a surface// the analyst works in — settling relations, reading a stack. So a refreshed// index waits for the card to close rather than pulling it out from under them.let popupOpen = $state(false);- $effect(() => {- if (!map) return;- const opened = () => (popupOpen = true);- const closed = () => (popupOpen = false);- map.on('popupopen', opened);- map.on('popupclose', closed);- return () => {- map.off('popupopen', opened);- map.off('popupclose', closed);- };- });- // The group is replaced by `rebuild` and torn down when the overlay itself goes- // away — deliberately not through the data effect's cleanup, which Svelte runs- // before every re-run, including one that decides to defer.- let group = null;+ // The surface is redrawn by `rebuild` and torn down when the overlay itself+ // goes away — deliberately not through the data effect's cleanup, which Svelte+ // runs before every re-run, including one that decides to defer.+ let surface = null;let builtFor = null; // the case the current layer was built for$effect(() => {- if (!map) return;+ if (!engine) return;return () => {- group?.remove();- group = null;+ surface?.destroy();+ surface = null;elements = new Map();if (mounted) {unmount(mounted);@@ -151,7 +126,7 @@const cid = caseId;const precision = markerPrecision(zoom);const held = popupOpen; // tracked, so closing the card applies what waited- if (!map) return;+ if (!engine) return;// A different case is never deferred: leaving another case's marks on the map// would be worse than closing a card.if (held && builtFor === cid) return;@@ -169,53 +144,60 @@* A mark with neither returns nothing and draws exactly as it always has —* absence is a state, never something to flag.*/- function shapesFor(mark) {+ function shapesFor(mark, id) {const row = mark.items.find((r) => r.footprint || r.radius_m > 0);if (!row) return [];const style = {- color: '#f5a623',- weight: 1.5,- opacity: 0.9,- fillColor: '#f5a623',+ stroke: '#f5a623',+ strokeWidth: 1.5,+ strokeOpacity: 0.9,+ fill: '#f5a623',fillOpacity: 0.12,// never steals the click from the pin it sits underinteractive: false,};return row.footprint- ? [L.geoJSON(row.footprint, { style: () => style })]- : [L.circle([mark.lat, mark.lon], { ...style, radius: row.radius_m })];+ ? [{ id: `${id}:shape`, kind: 'geojson', geometry: row.footprint, style }]+ : [{ id: `${id}:shape`, kind: 'circle', at: mark, radiusM: row.radius_m, style }];}function rebuild(rows, precision) {const marks = groupSavedMarkers(rows, precision);- const next = new Map();- group?.remove();- group = L.layerGroup(- marks.flatMap((mark) => {- const marker = L.marker([mark.lat, mark.lon], {- icon: icon(mark),+ surface ??= createSurface(engine, {+ onPopupOpen: () => (popupOpen = true),+ onPopupClose: () => (popupOpen = false),+ });+ surface.set(+ marks.flatMap((mark, at) => [+ // the shape first, so the pin stays on top of its own uncertainty+ ...shapesFor(mark, at),+ {+ id: at,+ kind: 'marker',+ at: mark,+ ...icon(mark),title: mark.items.length > 1 ? `${mark.items.length} saved here` : mark.items[0].title,keyboard: false,- });- marker.on('add', () => {- // one proof can hold two points, so identity here is the row key,- // not the entity: hovering either place must light that place- for (const row of mark.items) next.set(row.key ?? row.id, marker.getElement());- });- marker.on('mouseover', () => (hoveredId = mark.items[0].key ?? mark.items[0].id));- marker.on('mouseout', () => (hoveredId = null));- // every mark opens its card, one item or five: clicking a pin should- // tell you what is there before it moves the map out from under you- marker.bindPopup(() => popupContent(mark), {- className: 'saved-popup',- minWidth: 296,- maxWidth: 330,- autoPanPadding: [24, 24],- });- // the shape first, so the pin stays on top of its own uncertainty- return [...shapesFor(mark), marker];- })- ).addTo(map);+ onOver: () => (hoveredId = mark.items[0].key ?? mark.items[0].id),+ onOut: () => (hoveredId = null),+ // every mark opens its card, one item or five: clicking a pin should+ // tell you what is there before it moves the map out from under you+ popup: {+ content: () => popupContent(mark),+ className: 'saved-popup',+ minWidth: 296,+ maxWidth: 330,+ },+ },+ ])+ );+ // one proof can hold two points, so identity here is the row key, not the+ // entity: hovering either place must light that place+ const next = new Map();+ marks.forEach((mark, at) => {+ const element = surface.element(at);+ for (const row of mark.items) next.set(row.key ?? row.id, element);+ });elements = next;}@@ -231,13 +213,9 @@</script><style>- /* Leaflet builds these elements itself, outside this component's markup, so+ /* The map builds these elements itself, outside this component's markup, sothe marker styles have to be global. One colour family throughout — theoverlay must read as a single layer, not as a legend. */- :global(.saved-mark-wrap) {- background: none;- border: none;- }:global(.saved-mark) {position: relative;display: grid;@@ -296,31 +274,4 @@transform: rotate(-45deg) scale(1.25);z-index: 500;}- /* Leaflet's default popup is a white speech bubble; over imagery it has to be- one of the app's own surfaces instead. */- :global(.saved-popup .leaflet-popup-content-wrapper) {- background: var(--bg-1);- color: var(--text-1);- border: 1px solid var(--border-strong);- border-radius: var(--r-lg);- box-shadow: var(--shadow-2);- padding: 2px;- }- :global(.saved-popup .leaflet-popup-content) {- margin: 10px 12px;- line-height: 1.4;- }- :global(.saved-popup .leaflet-popup-tip) {- background: var(--bg-1);- border: 1px solid var(--border-strong);- box-shadow: none;- }- :global(.saved-popup .leaflet-popup-close-button) {- color: var(--text-3) !important;- padding: 6px 7px 0 0 !important;- }- :global(.saved-popup .leaflet-popup-close-button:hover) {- color: var(--text-1) !important;- background: none !important;- }</style>diff --git a/frontend/src/tools/satellite/SavedOverlay.test.js b/frontend/src/tools/satellite/SavedOverlay.test.jsindex 33ca6c9..c1a4fdc 100644--- a/frontend/src/tools/satellite/SavedOverlay.test.js+++ b/frontend/src/tools/satellite/SavedOverlay.test.js@@ -5,12 +5,12 @@ const source = readFileSync(new URL('./SavedOverlay.svelte', import.meta.url), 'describe('how precisely a point is pinned', () => {it('draws a radius as a circle in metres, not a fixed pixel dot', () => {- // L.circleMarker is sized in pixels and would lie at every other zoom- expect(source).toContain("L.circle([mark.lat, mark.lon], { ...style, radius: row.radius_m })");+ // a dot is sized in pixels and would lie at every other zoom+ expect(source).toContain("kind: 'circle', at: mark, radiusM: row.radius_m");});it('prefers a traced footprint over the circle around it', () => {- expect(source).toContain('row.footprint\n ? [L.geoJSON(row.footprint');+ expect(source).toContain("row.footprint\n ? [{ id: `${id}:shape`, kind: 'geojson', geometry: row.footprint, style }]");});it('leaves a point with no precision drawing exactly as before', () => {@@ -21,8 +21,8 @@ describe('how precisely a point is pinned', () => {it('keeps the shape under the pin and out of the click path', () => {expect(source).toContain('interactive: false');- expect(source).toContain('return [...shapesFor(mark), marker];');- // one group still holds everything, so a rebuild clears shapes with their pins- expect(source).toContain('marks.flatMap((mark) => {');+ expect(source).toContain('...shapesFor(mark, at),');+ // one surface still holds everything, so a redraw clears shapes with their pins+ expect(source).toContain('surface.set(\n marks.flatMap((mark, at) => [');});});diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelteindex f1ba2ff..c6e66d8 100644--- a/frontend/src/tools/satellite/SavedPopup.svelte+++ b/frontend/src/tools/satellite/SavedPopup.svelte@@ -43,8 +43,8 @@const hiddenPostCount = (row) => Math.max(0, linkedPosts(row).length - 2);function expandPosts(event, row) {- // Leaflet closes a popup when a click reaches the map. This control changes- // only the popup's own contents, so keep the event inside the card.+ // A click that reaches the map closes the card. This control changes only+ // the card's own contents, so the event stays inside it.event.stopPropagation();if (!postsExpanded(row)) expandedPostRows = [...expandedPostRows, rowKey(row)];}@@ -114,10 +114,10 @@}function showRelations(event, row) {- // Leaflet decides whether a click was "on the map" by walking up from the- // event target to find the popup container. This control replaces itself with- // the loaded list, so by then the clicked button can already be detached from- // the document — the walk finds nothing and the map closes the card under us.+ // Same, and one thing more: this control replaces itself with the loaded+ // list, so by the time the click is judged the button can already be gone+ // from the document. Stopping it here does not depend on the button still+ // being there to be found.// Keeping the event inside the card is what makes that impossible.event?.stopPropagation();if (!relationsShown(row)) openRows = [...openRows, rowKey(row)];diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.jsindex 55a8641..6b2b00b 100644--- a/frontend/src/tools/satellite/SavedPopup.test.js+++ b/frontend/src/tools/satellite/SavedPopup.test.js@@ -158,18 +158,23 @@ describe('SavedOverlay popup wiring', () => {expect(overlay).toContain("import { mount, unmount } from 'svelte'");expect(overlay).toContain('mount(SavedPopup');expect(overlay).toContain('unmount(mounted)');- expect(overlay).toContain('onpost?.(post)');+ expect(overlay).toContain('onpost: close(onpost)');});it('opens a card for every mark, one item or a stack', () => {- expect(overlay).toContain('marker.bindPopup(() => popupContent(mark)');+ expect(overlay).toContain('content: () => popupContent(mark)');// no shortcut path that flies straight there on a single-item mark- expect(overlay).not.toContain("marker.on('click'");+ expect(overlay).not.toContain('onClick');});- it('dresses the Leaflet popup as one of the app\'s own surfaces', () => {- expect(overlay).toContain('.saved-popup .leaflet-popup-content-wrapper');- expect(overlay).toContain('background: var(--bg-1)');+ it('asks for the width its own rows need, and leaves the look to the map', () => {+ // the card's chrome is one of the app's surfaces, dressed once in+ // lib/map/engine.css; what belongs here is how wide these rows have to be+ expect(overlay).toContain("className: 'saved-popup'");+ expect(overlay).toContain('minWidth: 296');+ expect(overlay).toContain('maxWidth: 330');+ // and never the engine's own DOM, which is not this component's to name+ expect(overlay.toLowerCase()).not.toContain('popup-content');});it('marks a worked capture instead of letting a proof stack a mark on it', () => {@@ -214,7 +219,7 @@ describe('SavedPopup relations', () => {// the auto-open effect writes the state it reads, so it guards on "already// open" rather than fetching the row twiceexpect(source).toContain('if (!only || !relationCount(only) || relationsShown(only)) return;');- // the toggle keeps its click inside the card, or Leaflet closes it+ // the toggle keeps its click inside the card, or the map closes itexpect(source).toContain('event?.stopPropagation();');});@@ -227,7 +232,7 @@ describe('SavedPopup relations', () => {expect(source).toContain('await onrefresh?.()');expect(source).toContain('relationsByRow[rowKey(row)]?.length ?? Number(row.relations ?? 0)');expect(overlay).toContain('if (held && builtFor === cid) return;');- expect(overlay).toContain("map.on('popupopen', opened)");+ expect(overlay).toContain('onPopupOpen: () => (popupOpen = true)');// the layer's teardown is not the data effect's cleanup, which Svelte runs// before every re-run — including one that decides to deferexpect(overlay).toContain('function rebuild(rows, precision)');@@ -242,9 +247,10 @@ describe('SavedPopup relations', () => {it('leaves for a related entity’s own tool by closing the card first', () => {// every other row in this card closes it before navigating; a popup that// vanishes without saying it would reads as a bug- expect(overlay).toContain('onentity: (entity) => {');- expect(overlay).toContain('map.closePopup();');- expect(overlay).toContain('openEntity(entity);');+ // one closing gesture, applied to every row of the card+ expect(overlay).toContain('const close = (then) => (arg) => {');+ expect(overlay).toContain('surface.closePopup();');+ expect(overlay).toContain('onentity: close(openEntity)');});});diff --git a/frontend/src/tools/satellite/ScreenshotDialog.svelte b/frontend/src/tools/satellite/ScreenshotDialog.sveltenew file mode 100644index 0000000..b77aa0b--- /dev/null+++ b/frontend/src/tools/satellite/ScreenshotDialog.svelte@@ -0,0 +1,166 @@+<script>+ /**+ * The manual way in, for when the Capture button's extension grab can't be+ * used or the screenshot came from somewhere else entirely.+ *+ * A pasted image is not registered to any frame: its coordinates are the map+ * view at filing time, and provenance says so (`framed: false`). That is the+ * whole reason this is a separate action rather than a fallback the Capture+ * button drops into — an unregistered picture must never inherit a registered+ * frame's provenance.+ */+ import Icon from '../../components/Icon.svelte';+ import Modal from '../../components/Modal.svelte';++ let {+ /** `{ lat, lon, zoom }` the map is on, which is what a pasted image is filed at. */+ view,+ /** Format the readout the way the analyst set it (Settings → General). */+ fmtCoords,+ /** Grab the whole map view through the extension. Returns the blob, or null. */+ grab,+ /** File `blob` as a capture at the current view. */+ file,+ onclose,+ } = $props();++ let blob = $state(null);+ let preview = $state(''); // object URL for the <img>+ let busy = $state(false);+ let grabbing = $state(false);++ function reset() {+ if (preview) URL.revokeObjectURL(preview);+ blob = null;+ preview = '';+ }++ function take(candidate) {+ if (!candidate || !candidate.type?.startsWith('image/')) return;+ reset();+ blob = candidate;+ preview = URL.createObjectURL(candidate);+ }++ function close() {+ reset();+ onclose();+ }++ function onPaste(event) {+ const item = [...(event.clipboardData?.items ?? [])].find((entry) =>+ entry.type.startsWith('image/')+ );+ if (item) {+ event.preventDefault();+ take(item.getAsFile());+ }+ }++ // paste works anywhere while the dialog is open — no need to focus a zone+ $effect(() => {+ window.addEventListener('paste', onPaste);+ return () => window.removeEventListener('paste', onPaste);+ });++ /**+ * One-click grab of the whole map view into the preview: the same extension+ * frame as a framed capture, minus the crop, at native resolution. The+ * preview is what lets the analyst judge it before filing.+ */+ async function onGrab() {+ if (grabbing) return;+ grabbing = true;+ try {+ const grabbed = await grab();+ if (grabbed) take(new File([grabbed], 'screenshot.png', { type: 'image/png' }));+ } finally {+ grabbing = false;+ }+ }++ async function save() {+ if (!blob || busy) return;+ busy = true;+ try {+ if (await file(blob)) close();+ } finally {+ busy = false;+ }+ }+</script>++{#if !grabbing}+ <Modal title="File a screenshot" onclose={close} width="520px">+ <p class="shot-hint">+ The <strong>Capture</strong> button already crops this basemap off the screen+ through the usual frame. Use this when it can't:+ grab the whole map view below, or paste+ (<span class="mono">Ctrl+V</span>) / drop your own OS screenshot.+ Unlike a framed capture, this is filed at the current <em>view</em>+ (<span class="mono">{fmtCoords(view.lat, view.lon)}</span>, z{view.zoom}).+ the coordinates describe the map, not a registered crop. The Google attribution+ is burned into a footer either way; keep Google's on-screen credits inside the+ frame too.+ </p>+ <div style="display:flex;justify-content:center;margin-bottom:10px">+ <button class="btn btn-primary" onclick={onGrab} disabled={grabbing}>+ {#if grabbing}<span class="spinner"></span> Grabbing…{:else}+ <Icon name="satellite" size={14} /> Capture the view{/if}+ </button>+ </div>+ <div+ class="shot-zone"+ class:has-image={!!preview}+ role="button"+ tabindex="0"+ ondrop={(event) => {+ event.preventDefault();+ take(event.dataTransfer?.files?.[0]);+ }}+ ondragover={(event) => event.preventDefault()}+ >+ {#if preview}+ <img src={preview} alt="screenshot to file" />+ {:else}+ <span>Paste (Ctrl+V) or drop the screenshot here</span>+ {/if}+ </div>+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">+ {#if preview}+ <button class="btn" onclick={reset}>Clear</button>+ {/if}+ <button class="btn" onclick={close}>Cancel</button>+ <button class="btn btn-primary" onclick={save} disabled={!blob || busy}>+ {busy ? 'Filing…' : 'File as capture'}+ </button>+ </div>+ </Modal>+{/if}++<style>+ .shot-hint {+ font-size: var(--fs-sm);+ color: var(--text-2);+ margin: 0 0 12px;+ }+ .shot-zone {+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 180px;+ border: 1px dashed var(--border);+ border-radius: 6px;+ color: var(--text-3);+ font-size: var(--fs-sm);+ overflow: hidden;+ }+ .shot-zone.has-image {+ border-style: solid;+ }+ .shot-zone img {+ max-width: 100%;+ max-height: 320px;+ display: block;+ }+</style>diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelteindex 0289e09..02dcb58 100644--- a/frontend/src/tools/satellite/SentinelPicker.svelte+++ b/frontend/src/tools/satellite/SentinelPicker.svelte@@ -1,68 +1,43 @@<script>import Icon from '../../components/Icon.svelte';- let {- menuEl = $bindable(),- menuOpen,- toggleMenu,- layer = $bindable(),- layers,- layerHint,- layersSource,- loadLayers,- date = $bindable(),- maxcc,- setMaxcc,- maxccLabel,- filtered,- month,- monthLabel,- stepMonth,- monthGrid,- passes,- cloudClass,- cloudLabel,- passesBusy,- passesNote,- passesStale,- verifyingDate,- dateStatus,- pickDate,- clearDate,- loadPasses,- } = $props();+ /** `s2` is the store from `state/sentinel.svelte.js`: what has been asked,+ * what came back, and what is still in flight. The label helpers are pure+ * (`lib/sentinel.js`) and are handed over so this stays a view. */+ let { menuEl = $bindable(), s2, maxccLabel, monthLabel, monthGrid, cloudClass, cloudLabel } =+ $props();// The readout tracks the drag; the ceiling only moves on release. Every step// in between would be a provider id of its own, and Sentinel-2 tiles are// billed — you pay for the number you stopped on, not the ones you passed.let dragging = $state(null);- const shown = $derived(dragging ?? maxcc);+ const shown = $derived(dragging ?? s2.maxcc);</script><div class="s2-wrap" bind:this={menuEl}><buttonclass="btn btn-icon"- class:on={menuOpen}- onclick={toggleMenu}+ class:on={s2.menuOpen}+ onclick={s2.toggleMenu}title="Sentinel-2 layer and date"aria-label="Sentinel-2 layer and date"><Icon name="layers" size={14} /></button>- {#if menuOpen}+ {#if s2.menuOpen}<div class="s2-menu card"><div class="menu-row"><span class="menu-label">Layer</span>- <select class="select" bind:value={layer}>- {#each layers as entry (entry.id)}+ <select class="select" bind:value={s2.layer}>+ {#each s2.layers as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}</select></div>- {#if layerHint}<div class="menu-hint">{layerHint}</div>{/if}+ {#if s2.layerHint}<div class="menu-hint">{s2.layerHint}</div>{/if}<div class="menu-hint dim">- {layersSource === 'instance'+ {s2.layersSource === 'instance'? 'These layers come from your configuration.': 'Could not read your configuration; showing the standard layers.'}- <button class="linkish" onclick={() => loadLayers(true)}>Refresh</button>+ <button class="linkish" onclick={() => s2.loadLayers(true)}>Refresh</button></div><div class="menu-sep" aria-hidden="true"></div>@@ -79,7 +54,7 @@oninput={(e) => (dragging = Number(e.currentTarget.value))}onchange={(e) => {dragging = null;- setMaxcc(Number(e.currentTarget.value));+ s2.setMaxcc(Number(e.currentTarget.value));}}aria-label="Maximum cloud cover"/>@@ -95,48 +70,49 @@<div class="menu-row"><span class="menu-label">Date</span><div class="chips">- <button class="chip" class:on={!date} onclick={clearDate}>Most recent</button>+ <button class="chip" class:on={!s2.date} onclick={s2.clearDate}>Most recent</button></div></div><div class="cal"><div class="cal-head">- <button class="cal-nav" onclick={() => stepMonth(-1)} aria-label="Previous month">+ <button class="cal-nav" onclick={() => s2.stepMonth(-1)} aria-label="Previous month"><Icon name="chevronLeft" size={13} /></button>- <span class="cal-month">{monthLabel(month)}</span>- <button class="cal-nav" onclick={() => stepMonth(1)} aria-label="Next month">+ <span class="cal-month">{monthLabel(s2.month)}</span>+ <button class="cal-nav" onclick={() => s2.stepMonth(1)} aria-label="Next month"><Icon name="chevronRight" size={13} /></button></div>- <div class="cal-grid" class:busy={passesBusy}>+ <div class="cal-grid" class:busy={s2.passesBusy}>{#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as entry, index (index)}<span class="cal-dow" aria-hidden="true">{entry}</span>{/each}- {#each monthGrid(month) as day, index (day ?? `pad${index}`)}+ {#each monthGrid(s2.month) as day, index (day ?? `pad${index}`)}{#if !day}<span class="cal-pad" aria-hidden="true"></span>{:else}- {@const pass = passes[day]}- {@const status = dateStatus(day)}- {@const overCeiling = filtered(day)}+ {@const pass = s2.passes[day]}+ {@const status = s2.dateStatus(day)}+ {@const overCeiling = s2.filtered(day)}{@const unavailable = status === false || overCeiling}- {@const verifying = verifyingDate === day}+ {@const verifying = s2.verifyingDate === day}<buttonclass="cal-day {pass ? cloudClass(pass.cloud) : ''}"class:has={!!pass}- class:on={date === day}+ class:on={s2.date === day}class:unavailableclass:verifying- disabled={date !== day && (!pass || passesStale || passesBusy || unavailable || !!verifyingDate)}- onclick={() => pickDate(day)}+ disabled={s2.date !== day &&+ (!pass || s2.stale || s2.passesBusy || unavailable || !!s2.verifyingDate)}+ onclick={() => s2.pickDate(day)}title={overCeiling- ? `${day}: ${cloudLabel(pass.cloud)}, over the ${maxcc}% ceiling`+ ? `${day}: ${cloudLabel(pass.cloud)}, over the ${s2.maxcc}% ceiling`: unavailable? `No imagery at the crosshair on ${day}`: verifying? `Checking imagery for ${day}`- : passesStale+ : s2.stale? `Refreshing dates for this location`: pass? `${day}: ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`@@ -147,14 +123,14 @@</div></div>- {#if passesBusy}+ {#if s2.passesBusy}<div class="menu-hint dim">Reading this month's passes…</div>- {:else if passesNote}- <div class="menu-hint warn">{passesNote}</div>- {:else if passesStale}+ {:else if s2.passesNote}+ <div class="menu-hint warn">{s2.passesNote}</div>+ {:else if s2.stale}<div class="menu-hint"><span class="warn">Refreshing dates for this location.</span>- <button class="linkish" onclick={() => loadPasses(true)}>Refresh</button>+ <button class="linkish" onclick={() => s2.loadPasses(true)}>Refresh</button></div>{:else}<div class="menu-hint dim">diff --git a/frontend/src/tools/satellite/SentinelPicker.test.js b/frontend/src/tools/satellite/SentinelPicker.test.jsindex dee060f..b325b4e 100644--- a/frontend/src/tools/satellite/SentinelPicker.test.js+++ b/frontend/src/tools/satellite/SentinelPicker.test.js@@ -2,49 +2,54 @@ import { describe, expect, it, vi } from 'vitest';import { render } from 'svelte/server';import SentinelPicker from './SentinelPicker.svelte';-function props(overrides = {}) {+/** The picker reads one store (`state/sentinel.svelte.js`); this is a stand-in+ * holding the state a case would be in, with the actions stubbed. */+function props({ s2 = {}, ...overrides } = {}) {return {- menuOpen: true,- toggleMenu: vi.fn(),- layer: 'TRUE_COLOR',- layers: [{ id: 'TRUE_COLOR', label: 'True colour' }],- layerHint: '',- layersSource: 'instance',- loadLayers: vi.fn(),- date: '',- maxcc: 100,- setMaxcc: vi.fn(),+ s2: {+ menuOpen: true,+ layer: 'TRUE_COLOR',+ layers: [{ id: 'TRUE_COLOR', label: 'True colour' }],+ layerHint: '',+ layersSource: 'instance',+ date: '',+ maxcc: 100,+ month: '2026-05',+ passes: { '2026-05-11': { cloud: 4, granules: 1 } },+ passesBusy: false,+ passesNote: '',+ stale: false,+ verifyingDate: '',+ dateStatus: () => undefined,+ filtered: () => false,+ toggleMenu: vi.fn(),+ loadLayers: vi.fn(),+ stepMonth: vi.fn(),+ loadPasses: vi.fn(),+ pickDate: vi.fn(),+ clearDate: vi.fn(),+ setMaxcc: vi.fn(),+ ...s2,+ },maxccLabel: (v) => (v >= 100 ? 'Any cloud' : `Up to ${v}%`),- filtered: () => false,- month: '2026-05',monthLabel: () => 'May 2026',- stepMonth: vi.fn(),monthGrid: () => ['2026-05-11'],- passes: { '2026-05-11': { cloud: 4, granules: 1 } },cloudClass: () => 'clear',cloudLabel: () => '4% cloud',- passesBusy: false,- passesNote: '',- passesStale: false,- verifyingDate: '',- dateStatus: () => undefined,- pickDate: vi.fn(),- clearDate: vi.fn(),- loadPasses: vi.fn(),...overrides,};}describe('SentinelPicker date safety', () => {it('disables dates from the previous map location', () => {- const { body } = render(SentinelPicker, { props: props({ passesStale: true }) });+ const { body } = render(SentinelPicker, { props: props({ s2: { stale: true } }) });expect(body).toContain('Refreshing dates for this location.');expect(body).toMatch(/<button[^>]*class="cal-day[^>]*disabled[^>]*>/);});it('marks a checked date that has no imagery as unavailable', () => {const { body } = render(SentinelPicker, {- props: props({ dateStatus: () => false }),+ props: props({ s2: { dateStatus: () => false } }),});expect(body).toMatch(/class="cal-day clear [^"]*has unavailable"/);expect(body).toContain('No imagery at the crosshair on 2026-05-11');@@ -53,8 +58,14 @@ describe('SentinelPicker date safety', () => {it('greys out a pass over the cloud ceiling', () => {const { body } = render(SentinelPicker, {- props: props({ maxcc: 20, passes: { '2026-05-11': { cloud: 38, granules: 1 } },- cloudLabel: () => '38% cloud', filtered: () => true }),+ props: props({+ s2: {+ maxcc: 20,+ passes: { '2026-05-11': { cloud: 38, granules: 1 } },+ filtered: () => true,+ },+ cloudLabel: () => '38% cloud',+ }),});// above the ceiling Sentinel Hub renders nothing, so the day says why// rather than costing a tile to find out@@ -64,7 +75,7 @@ describe('SentinelPicker date safety', () => {it('shows the ceiling and only commits it on release', () => {const setMaxcc = vi.fn();- const { body } = render(SentinelPicker, { props: props({ maxcc: 20, setMaxcc }) });+ const { body } = render(SentinelPicker, { props: props({ s2: { maxcc: 20, setMaxcc } }) });expect(body).toContain('Up to 20%');expect(body).toMatch(/<input[^>]*type="range"/);// dragging must not spend a tile per step: nothing fires from rendering@@ -73,7 +84,7 @@ describe('SentinelPicker date safety', () => {it('shows which date is being checked', () => {const { body } = render(SentinelPicker, {- props: props({ verifyingDate: '2026-05-11' }),+ props: props({ s2: { verifyingDate: '2026-05-11' } }),});expect(body).toMatch(/class="cal-day clear [^"]*has verifying"/);expect(body).toContain('Checking imagery for 2026-05-11');diff --git a/frontend/src/tools/satellite/SheetPointsOverlay.render.test.js b/frontend/src/tools/satellite/SheetPointsOverlay.render.test.jsnew file mode 100644index 0000000..2fe55a5--- /dev/null+++ b/frontend/src/tools/satellite/SheetPointsOverlay.render.test.js@@ -0,0 +1,87 @@+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++/**+ * What the sheet layer asks the map to draw.+ *+ * The saved and Timeline layers are driven end to end in the browser+ * (`e2e/saved-relations.spec.js`, `e2e/timeline.spec.js`); this one is reached+ * only through a sheet's own column menu, so it is exercised here instead —+ * against the shapes it declares, which is all it produces.+ */++const drawn = [];+const surface = {+ set: (shapes) => drawn.push(shapes),+ clear: vi.fn(),+ destroy: vi.fn(),+};+vi.mock('../../lib/map/surface.js', () => ({ createSurface: () => surface }));++const { default: SheetPointsOverlay } = await import('./SheetPointsOverlay.svelte');++let held = null;++function draw(points) {+ drawn.length = 0;+ const target = document.createElement('div');+ document.body.appendChild(target);+ held = mount(SheetPointsOverlay, { target, props: { engine: {}, points } });+ flushSync();+ return drawn.at(-1);+}++afterEach(() => {+ if (held) unmount(held);+ held = null;+});++describe('a sheet column on the map', () => {+ it('draws a precise point as a pin and nothing else', () => {+ const shapes = draw([{ lat: 48.8584, lon: 2.2945, decimals: 6, label: 'Quai sud' }]);+ expect(shapes).toHaveLength(1);+ expect(shapes[0]).toMatchObject({ kind: 'marker', at: { lat: 48.8584, lon: 2.2945 } });+ expect(shapes[0].title).toBe('Quai sud');+ expect(shapes[0].html).not.toContain('sheet-mark-coarse');+ });++ it('draws how coarsely a cell was written, as the circle it is', () => {+ // "48.85, 2.35" is a claim about a kilometre, not about a building, and a+ // worklist of two-decimal coordinates looks like a worklist of addresses+ // until the circles are drawn+ const shapes = draw([{ lat: 48.85, lon: 2.29, decimals: 2, label: 'Pont nord' }]);+ expect(shapes).toHaveLength(2);+ const [area, pin] = shapes;+ // the shape first, so the pin stays on top of its own imprecision+ expect(area.kind).toBe('circle');+ expect(area.radiusM).toBeGreaterThan(500);+ expect(area.style.interactive).toBe(false); // never steals the pin's click+ expect(pin.kind).toBe('marker');+ expect(pin.html).toContain('sheet-mark-coarse');+ expect(pin.title).toContain('about');+ expect(pin.title).toContain('2 decimals');+ });++ it('names the row on hover, above the pin', () => {+ const [pin] = draw([{ lat: 1, lon: 2, decimals: 6, label: 'Rue basse' }]);+ expect(pin.tip).toEqual({ text: 'Rue basse', direction: 'top', offset: [0, -12] });+ });++ it('draws a whole column in one pass', () => {+ const shapes = draw([+ { lat: 1, lon: 2, decimals: 6, label: 'a' },+ { lat: 3, lon: 4, decimals: 1, label: 'b' },+ { lat: 5, lon: 6, decimals: 6, label: 'c' },+ ]);+ expect(shapes.filter((shape) => shape.kind === 'marker')).toHaveLength(3);+ expect(shapes.filter((shape) => shape.kind === 'circle')).toHaveLength(1);+ });++ it('takes its layer down with it: the points travel, they are never filed', () => {+ draw([{ lat: 1, lon: 2, decimals: 6, label: 'a' }]);+ unmount(held);+ held = null;+ expect(surface.destroy).toHaveBeenCalled();+ });+});diff --git a/frontend/src/tools/satellite/SheetPointsOverlay.svelte b/frontend/src/tools/satellite/SheetPointsOverlay.svelteindex f8d6ea8..3b1a2a8 100644--- a/frontend/src/tools/satellite/SheetPointsOverlay.svelte+++ b/frontend/src/tools/satellite/SheetPointsOverlay.svelte@@ -11,12 +11,12 @@* 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 { createSurface } from '../../lib/map/surface.js';import { paths } from '../../components/Icon.svelte';import { precisionMetres } from '../../lib/sheetRoles.js';- let { map = null, points = [] } = $props();- let group = null;+ let { engine = null, points = [] } = $props();+ let surface = null;const TINT = '#c58af9';@@ -32,56 +32,62 @@);}- function icon(point) {- const coarse = point.decimals <= COARSE_DECIMALS ? ' sheet-mark-coarse' : '';- return L.divIcon({+ function mark(coarse) {+ return {className: 'sheet-mark-wrap',- html: `<span class="sheet-mark${coarse}">${glyph(12)}</span>`,- iconSize: [24, 24],- iconAnchor: [12, 12],- });+ html: `<span class="sheet-mark${coarse ? ' sheet-mark-coarse' : ''}">${glyph(12)}</span>`,+ size: [24, 24],+ anchor: [12, 12],+ };}$effect(() => {- if (!map) return;- group?.remove();- group = L.layerGroup(+ if (!engine) return;+ surface ??= createSurface(engine);+ surface.set(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);+ const coarse = point.decimals <= COARSE_DECIMALS;+ const marker = {+ kind: 'marker',+ at: point,+ ...mark(coarse),+ title: coarse+ ? `${point.label} — written to ${point.decimals} decimals, about ${metres} m`+ : point.label,+ tip: { text: point.label, direction: 'top', offset: [0, -12] },+ };+ if (!coarse) return [marker];+ // the shape first, so the pin stays on top of its own imprecision+ return [+ {+ kind: 'circle',+ at: point,+ radiusM: metres,+ style: {+ stroke: TINT,+ strokeWidth: 1,+ strokeOpacity: 0.75,+ fill: TINT,+ fillOpacity: 0.08,+ interactive: false,+ },+ },+ marker,+ ];+ })+ );});$effect(() => () => {- group?.remove();- group = null;+ surface?.destroy();+ surface = 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; }+ /* The map 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) {position: relative; display: grid; width: 24px; height: 24px; place-items: center;border-radius: 50% 50% 50% 2px; transform: rotate(-45deg);diff --git a/frontend/src/tools/satellite/SunPanel.svelte b/frontend/src/tools/satellite/SunPanel.svelteindex c3364ce..aae6e1d 100644--- a/frontend/src/tools/satellite/SunPanel.svelte+++ b/frontend/src/tools/satellite/SunPanel.svelte@@ -1,7 +1,7 @@<script>// Sun & moon mode: the day's path drawn from one anchored point, with an hour// you can drag. Anchored beside the tool cluster like the measure panel, so it- // can never end up under Leaflet's own controls.+ // can never end up under the engine's own controls.//// Dragging the hour costs nothing: the whole day arrived in one response at// ten-minute steps, so the slider reads an array. Only a new date asks thediff --git a/frontend/src/tools/satellite/TemporalMapOverlay.svelte b/frontend/src/tools/satellite/TemporalMapOverlay.svelteindex 939d53b..916d5cd 100644--- a/frontend/src/tools/satellite/TemporalMapOverlay.svelte+++ b/frontend/src/tools/satellite/TemporalMapOverlay.svelte@@ -9,13 +9,13 @@* is transient.*/import { mount, unmount } from 'svelte';- import L from 'leaflet';+ import { createSurface } from '../../lib/map/surface.js';import { paths } from '../../components/Icon.svelte';import { groupTemporalMapItems } from '../../lib/temporalMap.js';import TemporalPopup from './TemporalPopup.svelte';- let { map = null, items = [], caseId = '', onopen = () => {} } = $props();- let group = null;+ let { engine = null, items = [], caseId = '', onopen = () => {} } = $props();+ let surface = null;let mounted = null;function glyph(name, size) {@@ -28,15 +28,15 @@function icon(mark) {const count = mark.items.length > 1 ? `<i class="temporal-mark-count">${mark.items.length}</i>` : '';- return L.divIcon({+ return {className: 'temporal-mark-wrap',html: `<span class="temporal-mark">${glyph('clock', 13)}${count}</span>`,- iconSize: [24, 24],- iconAnchor: [12, 12],- });+ size: [24, 24],+ anchor: [12, 12],+ };}- function popup(mark) {+ function card(mark) {const host = document.createElement('div');if (mounted) unmount(mounted);mounted = mount(TemporalPopup, {@@ -46,61 +46,65 @@items: mark.items,caseId,onopen: (item) => {- map.closePopup();+ surface.closePopup();onopen(item);},// Following a row leaves the map, so the card closes first — the same gesture// as the saved layer's, rather than a popup that vanishes without saying it// would.- onleave: () => map.closePopup(),+ onleave: () => surface.closePopup(),},});return host;}- function shape(mark) {+ /** How tightly the statement is placed, as the shape under its pin. */+ function area(mark) {const style = {- color: '#35b6a0',- weight: 1.5,- opacity: 0.9,- fillColor: '#35b6a0',+ stroke: '#35b6a0',+ strokeWidth: 1.5,+ strokeOpacity: 0.9,+ fill: '#35b6a0',fillOpacity: 0.12,interactive: false,};- if (mark.footprint) return L.geoJSON(mark.footprint, { style: () => style });+ if (mark.footprint) return { kind: 'geojson', geometry: mark.footprint, style };if (Number(mark.radius_m) > 0) {- return L.circle([mark.lat, mark.lon], { ...style, radius: Number(mark.radius_m) });+ return { kind: 'circle', at: mark, radiusM: Number(mark.radius_m), style };}return null;}$effect(() => {const marks = groupTemporalMapItems(items);- if (!map) return;- group?.remove();- group = L.layerGroup(marks.flatMap((mark) => {- const marker = L.marker([mark.lat, mark.lon], {- icon: icon(mark),- keyboard: true,- title: mark.items.length === 1- ? mark.items[0].label- : `${mark.items.length} statements at ${mark.label}`,- });- marker.bindPopup(() => popup(mark), {- className: 'temporal-popup',- minWidth: 272,- maxWidth: 320,- autoPanPadding: [24, 24],- });- // The shape first, so the pin stays on top of its own uncertainty.- const area = shape(mark);- return area ? [area, marker] : [marker];- })).addTo(map);+ if (!engine) return;+ surface ??= createSurface(engine);+ surface.set(+ marks.flatMap((mark) => [+ // the shape first, so the pin stays on top of its own uncertainty+ area(mark),+ {+ kind: 'marker',+ at: mark,+ ...icon(mark),+ title:+ mark.items.length === 1+ ? mark.items[0].label+ : `${mark.items.length} statements at ${mark.label}`,+ popup: {+ content: () => card(mark),+ className: 'temporal-popup',+ minWidth: 272,+ maxWidth: 320,+ },+ },+ ])+ );});$effect(() => () => {- group?.remove();- group = null;+ surface?.destroy();+ surface = null;if (mounted) {unmount(mounted);mounted = null;@@ -109,10 +113,9 @@</script><style>- /* Leaflet builds these elements itself, outside this component's markup, so the+ /* The map builds these elements itself, outside this component's markup, so themarker styles have to be global. The saved layer's geometry throughout — theteardrop, the badge on its corner, the lift on hover — in this layer's tint. */- :global(.temporal-mark-wrap) { border: 0; background: none; }:global(.temporal-mark) {position: relative;display: grid;@@ -147,28 +150,4 @@z-index: 500;transform: rotate(-45deg) scale(1.25);}- /* Leaflet's default popup is a white speech bubble; over imagery it has to be one- of the app's own surfaces instead. */- :global(.temporal-popup .leaflet-popup-content-wrapper) {- padding: 2px;- border: 1px solid var(--border-strong);- border-radius: var(--r-lg);- background: var(--bg-1);- box-shadow: var(--shadow-2);- color: var(--text-1);- }- :global(.temporal-popup .leaflet-popup-content) { margin: 10px 12px; line-height: 1.4; }- :global(.temporal-popup .leaflet-popup-tip) {- border: 1px solid var(--border-strong);- background: var(--bg-1);- box-shadow: none;- }- :global(.temporal-popup .leaflet-popup-close-button) {- padding: 6px 7px 0 0 !important;- color: var(--text-3) !important;- }- :global(.temporal-popup .leaflet-popup-close-button:hover) {- background: none !important;- color: var(--text-1) !important;- }</style>diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.jsnew file mode 100644index 0000000..75bed07--- /dev/null+++ b/frontend/src/tools/satellite/state/saved.svelte.js@@ -0,0 +1,265 @@+/**+ * The case's saved work, as the Map's panel reads it.+ *+ * Two indexes, not one: places, captures and filed screenshots come back in one+ * compact index when a case opens, while proofs are read only once the Proofs+ * position is opened — a case must not pay for a view it may never show. Both+ * are keyed on the case *and its revision*, because filing a proof reloads the+ * case and a stale list would still show the folder the proof just left.+ *+ * `runLocate` is the one long act here: filling in the country of everything+ * that still has none, one batch at a time because Nominatim allows one lookup+ * a second. Progress is the stored geography itself, so cancelling keeps what+ * was already resolved and a later pass picks up where this one stopped.+ *+ * @param {object} deps+ * @param {object} deps.api the app's fetch wrapper+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify+ * @param {(id: string, entity: object, folder: string) => Promise<any>} deps.assignFolder+ * @param {() => Promise<any>} deps.reloadCase+ */+import { filterSaved, isMode, pendingLocate } from '../../../lib/geoTree.js';++const GROUP_KEY = 'azimut:satelliteSavedGroup';+const LOCATE_BATCH = 10;++function loadGroup() {+ try {+ return localStorage.getItem(GROUP_KEY) === 'folders' ? 'folders' : 'geo';+ } catch {+ return 'geo'; // localStorage unavailable (private mode) — non-fatal+ }+}++export function createSavedState({ api, notify, assignFolder, reloadCase }) {+ let rows = $state([]);+ let proofs = $state([]);+ let kind = $state('all');+ let query = $state('');+ let group = $state(loadGroup());+ let locating = $state(null); // { done, total } while a pass runs+ let acceptingId = $state(null);++ let rowsFor = null; // the case id both indexes were loaded for+ let proofsFor = null; // the case id *and revision* the proofs index was read for+ let locateStopped = false;+ let locateGeneration = 0;++ /** Everything a different case must not inherit. */+ function reset() {+ rows = [];+ proofs = [];+ proofsFor = null;+ locateStopped = true;+ locateGeneration += 1;+ locating = null;+ }++ /**+ * Read the compact index for one case. Returns the teardown that makes a+ * response arriving after the case changed land nowhere.+ */+ function load(caseId) {+ if (rowsFor !== caseId) {+ rowsFor = caseId;+ reset();+ }+ if (!caseId) return () => {};+ let live = true;+ api+ .get(`/api/cases/${caseId}/satellite/index`)+ .then((answer) => {+ if (live) rows = answer;+ })+ .catch(() => {+ if (live) rows = [];+ });+ return () => {+ live = false;+ };+ }++ /** The proofs index, the first time the Proofs position is opened. */+ function loadProofs(caseId, rev) {+ const stamp = `${caseId}:${rev}`;+ if (!caseId || !isMode(kind) || proofsFor === stamp) return () => {};+ proofsFor = stamp;+ let live = true;+ api+ .get(`/api/cases/${caseId}/proofs/index`)+ .then((answer) => {+ if (live) proofs = answer;+ })+ .catch(() => {+ if (live) {+ proofs = [];+ proofsFor = null;+ }+ });+ return () => {+ live = false;+ };+ }++ async function runLocate(caseId) {+ if (locating || !caseId) return;+ const generation = ++locateGeneration;+ locateStopped = false;+ const total = pendingLocate(rows);+ locating = { done: 0, total };+ let located = 0;+ let failed = 0;+ let throttled = false;+ try {+ let remaining = total;+ while (remaining > 0 && !locateStopped && generation === locateGeneration) {+ const batch = await api.post(+ `/api/cases/${caseId}/satellite/locate?limit=${LOCATE_BATCH}`+ );+ if (generation !== locateGeneration) return;+ located += batch.located;+ failed += batch.failed;+ throttled = Boolean(batch.throttled);+ // A batch that resolved nothing means the network is down, or that+ // Nominatim put us in its penalty box — not that the next one will do+ // better: stop instead of hammering it forever.+ const stalled = batch.remaining >= remaining;+ remaining = batch.remaining;+ locating = { done: total - remaining, total };+ if (stalled || throttled) break;+ }+ if (generation !== locateGeneration) return;+ const fresh = await api.get(`/api/cases/${caseId}/satellite/index`);+ if (generation !== locateGeneration) return;+ rows = fresh;+ notify(+ throttled+ ? `Located ${located} of ${total}. OpenStreetMap is rate-limiting this address; wait a minute and run Locate again`+ : failed+ ? `Located ${located} of ${total}. ${failed} lookup(s) failed; run Locate again to retry`+ : `Located ${located} of ${total}`,+ failed || throttled ? 'warn' : 'ok'+ );+ } catch (e) {+ if (generation === locateGeneration) {+ notify(`Locate stopped: ${e.message}`, 'danger', 6000);+ }+ } finally {+ if (generation === locateGeneration) locating = null;+ }+ }++ /**+ * Accept a point a tool proposed.+ *+ * The same PATCH the sidebar sends, so the far end of the point's suggested+ * relations is accepted with it — the API keeps that invariant, and a point+ * confirmed here while the edge tying it to its capture stayed proposed would+ * be the two surfaces disagreeing about one click.+ */+ async function accept(caseId, row) {+ if (acceptingId) return;+ acceptingId = row.id;+ try {+ await api.patch(`/api/cases/${caseId}/entities/${row.id}`, { status: 'confirmed' });+ await reloadCase(); // re-reads the saved index and the case sidebar+ notify('Point accepted', 'ok', 1600);+ } catch (e) {+ notify(`Could not accept this point: ${e.message}`, 'danger');+ } finally {+ acceptingId = null;+ }+ }++ /**+ * File a saved item into a My-work folder. One PATCH through the shared+ * filing route (a capture's sidecar is the authority, a place carries the+ * folder itself), then the case reload every other edit here does.+ */+ async function move(caseId, row, folder) {+ // the row's kind *is* its entity type, bar the screenshot that rides the+ // capture type. Filing a proof as a capture would route it to PATCH /media,+ // the sidecar of an image it is not.+ const entity = {+ id: row.id,+ type: row.kind === 'place' ? 'place' : row.kind === 'proof' ? 'proof' : 'capture',+ attrs: { path: row.path },+ };+ try {+ await assignFolder(caseId, entity, folder);+ await reloadCase();+ notify(folder ? `Filed in ${folder}` : 'Removed from My work', 'ok', 1600);+ } catch (e) {+ notify(e.message, 'danger');+ }+ }++ /** Drop a saved item: a capture loses its image file, a place its entity. */+ async function remove(caseId, row) {+ return row.kind === 'place'+ ? api.del(`/api/cases/${caseId}/entities/${row.id}`)+ : api.del(`/api/cases/${caseId}/satellite?path=${encodeURIComponent(row.path)}`);+ }++ return {+ get rows() {+ return rows;+ },+ set rows(value) {+ rows = value;+ },+ get proofs() {+ return proofs;+ },+ get kind() {+ return kind;+ },+ set kind(value) {+ kind = value;+ },+ get query() {+ return query;+ },+ set query(value) {+ query = value;+ },+ get group() {+ return group;+ },+ set group(value) {+ group = value;+ try {+ localStorage.setItem(GROUP_KEY, value);+ } catch {+ /* ignore */+ }+ },+ get locating() {+ return locating;+ },+ get acceptingId() {+ return acceptingId;+ },++ /** Proofs are their own position, and read their own index. */+ get shownRows() {+ return isMode(kind) ? proofs : rows;+ },+ /** What the panel is showing, which is also what the map layer draws. */+ get shown() {+ return filterSaved(this.shownRows, { kind, query });+ },+ get pending() {+ return pendingLocate(rows);+ },++ reset,+ load,+ loadProofs,+ runLocate,+ stopLocate: () => (locateStopped = true),+ accept,+ move,+ remove,+ };+}diff --git a/frontend/src/tools/satellite/state/saved.svelte.test.js b/frontend/src/tools/satellite/state/saved.svelte.test.jsnew file mode 100644index 0000000..9c963e7--- /dev/null+++ b/frontend/src/tools/satellite/state/saved.svelte.test.js@@ -0,0 +1,271 @@+// @vitest-environment happy-dom+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createSavedState } from './saved.svelte.js';++/**+ * The Map panel's own reading of the case.+ *+ * These were assertions about the tool's source text until the store existed;+ * they are the same guarantees, now exercised against what it actually does —+ * which is what a Locate pass looping in the wrong case needs.+ */++const ROWS = [+ { id: 'e1', kind: 'place', path: null, title: 'Quai sud', geo: { state: 'ok', country: 'FR' } },+ { id: 'e2', kind: 'capture', path: 'media/a.png', title: 'a' },+ { id: 'e3', kind: 'screenshot', path: 'media/b.png', title: 'b' },+];+const PROOFS = [{ id: 'p1', kind: 'proof', path: 'proofs/x.png', name: 'x', title: 'x' }];++let api;+let notify;+let assignFolder;+let reloadCase;+let calls;++function store() {+ return createSavedState({ api, notify, assignFolder, reloadCase });+}++beforeEach(() => {+ localStorage.clear();+ calls = [];+ notify = vi.fn();+ assignFolder = vi.fn(async () => ({}));+ reloadCase = vi.fn(async () => {});+ api = {+ get: vi.fn(async (path) => {+ calls.push(path);+ if (path.includes('/proofs/index')) return PROOFS;+ return ROWS;+ }),+ post: vi.fn(async () => ({ located: 0, failed: 0, remaining: 0 })),+ patch: vi.fn(async () => ({})),+ del: vi.fn(async () => ({ trash: 'slot-1' })),+ };+});++describe('opening a case', () => {+ it('reads one compact index, not a row per capture', async () => {+ const saved = store();+ saved.load('case-1');+ await vi.waitFor(() => expect(saved.rows).toHaveLength(3));+ expect(calls).toEqual(['/api/cases/case-1/satellite/index']);+ });++ it('pays nothing for the proofs index until that position is opened', async () => {+ const saved = store();+ saved.load('case-1');+ saved.loadProofs('case-1', 3);+ await vi.waitFor(() => expect(saved.rows).toHaveLength(3));+ expect(calls.some((path) => path.includes('/proofs/index'))).toBe(false);++ saved.kind = 'proofs';+ saved.loadProofs('case-1', 3);+ await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));+ // …and the proofs position reads its own rows, not the compact index+ expect(saved.shownRows).toEqual(PROOFS);+ });++ it('re-reads the proofs index when the case is reloaded, not only when it changes', async () => {+ // filing a proof reloads the case; keying only on the id would leave the+ // panel showing the folder the proof just left+ const saved = store();+ saved.kind = 'proofs';+ saved.loadProofs('case-1', 3);+ await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));+ const before = api.get.mock.calls.length;+ saved.loadProofs('case-1', 3);+ expect(api.get).toHaveBeenCalledTimes(before); // same revision: nothing to re-read+ saved.loadProofs('case-1', 4);+ await vi.waitFor(() => expect(api.get.mock.calls.length).toBe(before + 1));+ });++ it('drops both indexes before loading a different case', async () => {+ const saved = store();+ saved.load('case-1');+ saved.kind = 'proofs';+ saved.loadProofs('case-1', 1);+ await vi.waitFor(() => expect(saved.proofs).toHaveLength(1));+ saved.load('case-2');+ expect(saved.rows).toEqual([]);+ expect(saved.proofs).toEqual([]);+ });++ it('ignores an earlier case’s answer once the case has changed', async () => {+ let release;+ api.get = vi.fn(+ () =>+ new Promise((resolve) => {+ release = () => resolve(ROWS);+ })+ );+ const saved = store();+ const stop = saved.load('case-1');+ stop(); // the case changed under the request+ release();+ await Promise.resolve();+ expect(saved.rows).toEqual([]);+ });+});++describe('what the panel is showing', () => {+ it('is what the map layer draws: the filter, never the whole index', async () => {+ const saved = store();+ saved.load('case-1');+ await vi.waitFor(() => expect(saved.rows).toHaveLength(3));+ expect(saved.shown).toHaveLength(3);+ saved.kind = 'places';+ expect(saved.shown.map((row) => row.id)).toEqual(['e1']);+ saved.kind = 'all';+ saved.query = 'quai';+ expect(saved.shown.map((row) => row.id)).toEqual(['e1']);+ });++ it('remembers which grouping the panel was left on', () => {+ const saved = store();+ expect(saved.group).toBe('geo');+ saved.group = 'folders';+ expect(localStorage.getItem('azimut:satelliteSavedGroup')).toBe('folders');+ expect(store().group).toBe('folders');+ });+});++describe('a Locate pass', () => {+ it('runs in bounded batches until the backlog is empty', async () => {+ const batches = [+ { located: 10, failed: 0, remaining: 12 },+ { located: 10, failed: 0, remaining: 2 },+ { located: 2, failed: 0, remaining: 0 },+ ];+ api.post = vi.fn(async () => batches.shift());+ const saved = store();+ saved.rows = Array.from({ length: 22 }, (_, i) => ({ id: `e${i}`, kind: 'place' }));+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(3);+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/satellite/locate?limit=10');+ expect(notify).toHaveBeenCalledWith('Located 22 of 22', 'ok');+ expect(saved.locating).toBeNull();+ });++ it('stops when a batch resolves nothing, instead of hammering forever', async () => {+ // offline, every batch comes back with the same backlog+ api.post = vi.fn(async () => ({ located: 0, failed: 4, remaining: 4 }));+ const saved = store();+ saved.rows = [{ id: 'e1', kind: 'place' }];+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(1);+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('run Locate again to retry'), 'warn');+ });++ it('says to wait when OpenStreetMap is rate-limiting the address', async () => {+ // a 429 is not a lookup failure: running the pass again is the wrong advice+ api.post = vi.fn(async () => ({ located: 1, failed: 0, remaining: 3, throttled: true }));+ const saved = store();+ saved.rows = Array.from({ length: 4 }, (_, i) => ({ id: `e${i}`, kind: 'place' }));+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(1);+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('rate-limiting'), 'warn');+ });++ it('can be stopped, and keeps what was already resolved', async () => {+ const saved = store();+ saved.rows = Array.from({ length: 30 }, (_, i) => ({ id: `e${i}`, kind: 'place' }));+ api.post = vi.fn(async () => {+ saved.stopLocate();+ return { located: 10, failed: 0, remaining: 20 };+ });+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(1);+ expect(notify).toHaveBeenCalledWith('Located 10 of 30', 'ok');+ });++ it('does not let a pass continue in another case', async () => {+ const saved = store();+ saved.rows = Array.from({ length: 30 }, (_, i) => ({ id: `e${i}`, kind: 'place' }));+ api.post = vi.fn(async () => {+ saved.load('case-2'); // the analyst opened another case mid-pass+ return { located: 10, failed: 0, remaining: 20 };+ });+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(1);+ expect(notify).not.toHaveBeenCalled(); // it says nothing about a case it left+ // and the case it left is never re-read into the panel now showing another+ expect(calls).toEqual(['/api/cases/case-2/satellite/index']);+ });++ it('refuses to start twice over', async () => {+ let release;+ api.post = vi.fn(() => new Promise((resolve) => (release = () => resolve({ located: 1, failed: 0, remaining: 0 }))));+ const saved = store();+ saved.rows = [{ id: 'e1', kind: 'place' }];+ const first = saved.runLocate('case-1');+ await saved.runLocate('case-1');+ expect(api.post).toHaveBeenCalledTimes(1);+ release();+ await first;+ });++ it('counts only what still has no country', async () => {+ const saved = store();+ saved.rows = ROWS;+ expect(saved.pending).toBe(2);+ });+});++describe('acting on a row', () => {+ it('accepts a point with the same PATCH the sidebar sends', async () => {+ const saved = store();+ await saved.accept('case-1', { id: 'e1' });+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/entities/e1', {+ status: 'confirmed',+ });+ // …then re-reads the case, or the row would keep claiming it is proposed+ expect(reloadCase).toHaveBeenCalled();+ expect(notify).toHaveBeenCalledWith('Point accepted', 'ok', 1600);+ });++ it('accepts one point at a time', async () => {+ let release;+ api.patch = vi.fn(() => new Promise((resolve) => (release = resolve)));+ const saved = store();+ const first = saved.accept('case-1', { id: 'e1' });+ expect(saved.acceptingId).toBe('e1');+ await saved.accept('case-1', { id: 'e2' });+ expect(api.patch).toHaveBeenCalledTimes(1);+ release({});+ await first;+ expect(saved.acceptingId).toBeNull();+ });++ it('files a dragged row through its own entity type', async () => {+ // a proof filed as a capture would be routed to PATCH /media, the sidecar+ // of an image the proof is not+ const saved = store();+ await saved.move('case-1', { id: 'p1', kind: 'proof', path: 'proofs/x.png' }, 'Quays');+ expect(assignFolder).toHaveBeenCalledWith(+ 'case-1',+ { id: 'p1', type: 'proof', attrs: { path: 'proofs/x.png' } },+ 'Quays'+ );+ await saved.move('case-1', { id: 'e3', kind: 'screenshot', path: 'media/b.png' }, '');+ // a screenshot rides the capture type+ expect(assignFolder).toHaveBeenLastCalledWith(+ 'case-1',+ { id: 'e3', type: 'capture', attrs: { path: 'media/b.png' } },+ ''+ );+ expect(reloadCase).toHaveBeenCalledTimes(2);+ expect(notify).toHaveBeenLastCalledWith('Removed from My work', 'ok', 1600);+ });++ it('deletes a place as an entity and a capture as a file', async () => {+ const saved = store();+ await saved.remove('case-1', { id: 'e1', kind: 'place' });+ expect(api.del).toHaveBeenCalledWith('/api/cases/case-1/entities/e1');+ await saved.remove('case-1', { id: 'e2', kind: 'capture', path: 'media/a b.png' });+ expect(api.del).toHaveBeenLastCalledWith(+ '/api/cases/case-1/satellite?path=media%2Fa%20b.png'+ );+ });+});diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.js b/frontend/src/tools/satellite/state/sentinel.svelte.jsnew file mode 100644index 0000000..9bd003b--- /dev/null+++ b/frontend/src/tools/satellite/state/sentinel.svelte.js@@ -0,0 +1,396 @@+/**+ * Sentinel-2's choices: which layer, over which day, under which cloud ceiling.+ *+ * It is the one basemap with choices in it, and the reason they need a state+ * machine rather than three variables is that every one of them costs a+ * metered request and can be asked about a place the map has already left:+ *+ * - **A day with no pass is not selectable.** Otherwise you pick a date, pay+ * for a tile and discover it was a coverage gap.+ * - **An empty month and a failed lookup are different facts**, and blurring+ * them would grey out imagery that exists.+ * - **Answers are cached by month *and* place**, because Sentinel-2's swath+ * means the answer genuinely differs a few km away — and a nudge of the map+ * is not a new question.+ * - **The ceiling is part of the question**: the same day is available under+ * 100% and a gap under 20%, so a cached answer must not outlive the number.+ *+ * The pure arithmetic (window, month grid, variant id, labels) is+ * `lib/sentinel.js`; this holds what has been asked, what came back, and what+ * is still in flight.+ *+ * @param {object} deps+ * @param {() => {lat: number, lon: number}} deps.place where the map is pointing+ * @param {() => void} deps.onBilled a metered request went out+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify+ * @param {object} deps.api the app's fetch wrapper+ */+import {+ DEFAULT_LAYER,+ DEFAULT_MAXCC,+ addMonths,+ coverageRequestPath,+ dateAfterCoverage,+ isoDay,+ latestAllowedPass,+ monthBounds,+ monthOf,+ overCloudCeiling,+ sentinelPlaceKey,+ validDay,+ validMaxcc,+ cloudLabel,+} from '../../../lib/sentinel.js';++export function createSentinelState({ place, onBilled, notify, api }) {+ let layer = $state(DEFAULT_LAYER);+ // One date, not a range: a Sentinel-2 image *is* a pass on a day. (The WMTS+ // window underneath is a range, so we send day/day — but a range is a mosaic+ // of several passes, which is not a thing you can point at and date.)+ let date = $state(''); // '' = the layer's default, i.e. the most recent pass+ // Cloud ceiling, in percent. 100 = render whatever passed overhead, which is+ // the default because the *instance* has a filter of its own (20% in the+ // standard template) and a scene above it renders as nothing at all: without+ // saying MAXCC=100 we would be hiding cloudy days without ever saying so.+ let maxcc = $state(DEFAULT_MAXCC);+ let menuOpen = $state(false);+ let layers = $state([]); // [{id,label,hint}] — catalogue until the instance is asked+ let layersSource = $state('');+ let layersAsked = false; // the instance is asked once per session, on first open+ // The month the calendar is showing, and the passes found in it:+ // { 'YYYY-MM-DD': {cloud, granules} }. A day with no entry has no imagery and+ // is not selectable — the same rule the Copernicus browser follows.+ let month = $state(monthOf(''));+ let passes = $state({});+ let passesFor = $state(''); // the month+place `passes` describes+ let passesBusy = $state(false);+ let passesNote = $state('');+ let verifyingDate = $state('');+ let coverageRev = $state(0);+ // The newest pass over this point — what "most recent" is actually showing.+ // The layer's default window renders the latest acquisition, so naming it is+ // the difference between a dated image and an undated one.+ let latest = $state('');+ let latestFor = $state(''); // the place `latest` was resolved for++ const passCache = new Map();+ const passPending = new Map();+ const coverageCache = new Map();+ let passRequestId = 0;+ let pickRequestId = 0;++ const placeKey = () => sentinelPlaceKey(place().lat, place().lon);+ const coverageKey = (day, at = placeKey(), forLayer = layer, ceiling = maxcc) =>+ `${forLayer}@${ceiling}@${day}@${at}`;++ /**+ * The catalogue costs nothing and reaches no network (the backend answers it+ * from its own list); `check` asks the user's instance what it really serves,+ * which is the only authority — a configuration can rename or drop any layer.+ */+ async function loadLayers(check = false, quiet = false) {+ try {+ const r = await api.get(`/api/satellite/sentinel/layers${check ? '?check=true' : ''}`);+ layers = r.layers ?? [];+ layersSource = r.source ?? '';+ // a layer that vanished with the list can't stay selected+ if (layers.length && !layers.some((l) => l.id === layer)) layer = layers[0].id;+ if (quiet) return;+ if (check && r.detail) notify(r.detail, 'warn', 6000);+ else if (check && r.source === 'instance') {+ notify(`${r.layers.length} layers read from your instance`, 'ok');+ }+ } catch (e) {+ notify(`Sentinel-2 layers: ${e.message}`, 'danger');+ }+ }++ /**+ * One month's passes over one place: `{ 'YYYY-MM-DD': {cloud, granules} }`,+ * or null when the lookup failed. Cached — paging back to a month already+ * seen must not spend a second request.+ */+ async function fetchMonth(forMonth, at, force = false, lat = place().lat, lon = place().lon) {+ const key = `${forMonth}@${at}`;+ if (!force && passCache.has(key)) return passCache.get(key);+ if (!force && passPending.has(key)) return passPending.get(key);+ if (force) passCache.delete(key);+ const { from, to } = monthBounds(forMonth);+ const request = (async () => {+ try {+ const r = await api.get(+ `/api/satellite/sentinel/dates?lat=${lat}&lon=${lon}&start=${from}&end=${to}`+ );+ const byDay = {};+ for (const d of r.dates) byDay[d.date] = { cloud: d.cloud, granules: d.granules };+ passCache.set(key, byDay);+ onBilled(); // the lookup is billed: keep the pill honest+ return byDay;+ } catch {+ return null;+ }+ })();+ passPending.set(key, request);+ try {+ return await request;+ } finally {+ if (passPending.get(key) === request) passPending.delete(key);+ }+ }++ /**+ * Which days Sentinel-2 actually passed over this point, and how cloudy each+ * was. One metadata request per month (~1/100th of a tile's processing+ * units), only while the picker is open.+ */+ async function loadPasses(force = false) {+ const requestId = ++passRequestId;+ const { lat, lon } = place();+ const at = placeKey();+ const key = `${month}@${at}`;+ passesBusy = true;+ passesNote = '';+ const days = await fetchMonth(month, at, force, lat, lon);+ if (requestId !== passRequestId) return;+ if (days) {+ passes = days;+ passesFor = key;+ if (!Object.keys(days).length) passesNote = 'No Sentinel-2 pass here this month.';+ } else {+ // an empty month and a failed lookup are different facts. Never blur them:+ // greying every day out because the network hiccuped would be a lie about+ // what exists.+ passes = {};+ passesFor = '';+ passesNote = 'Could not read this month’s passes. The days below do not confirm coverage.';+ }+ passesBusy = false;+ }++ function stepMonth(delta) {+ month = addMonths(month, delta);+ loadPasses();+ }++ function toggleMenu() {+ menuOpen = !menuOpen;+ if (!menuOpen) return;+ // Ask the instance what it actually serves, once per session. The built-in+ // list is only a fallback: a configuration serves whatever it was built+ // with, and offering a layer that isn't there just 400s when picked.+ if (!layersAsked) {+ layersAsked = true;+ loadLayers(true, true);+ } else if (!layers.length) {+ loadLayers(false);+ }+ loadPasses();+ }++ /**+ * Which pass "most recent" is showing. Sentinel-2 revisits every ~5 days, so+ * this month usually answers it; early in a month it may not, and one step+ * back does. Two requests at worst, once per place — the alternative is a+ * basemap that can't say what date it is showing, which for satellite+ * imagery is most of the point.+ */+ async function resolveLatest(today = isoDay(new Date())) {+ const at = placeKey();+ const ceiling = maxcc;+ const key = `${at}@${ceiling}`;+ if (latestFor === key) return;+ for (const forMonth of [monthOf(today), addMonths(monthOf(today), -1)]) {+ const days = await fetchMonth(forMonth, at);+ if (days === null) return; // lookup failed — say nothing rather than guess+ // the ceiling drops cloudy passes from the tiles, so "most recent" is the+ // newest pass it still allows, not the newest pass there is+ const found = latestAllowedPass(days, today, ceiling);+ if (found) {+ latest = found;+ latestFor = key;+ return;+ }+ }+ // no pass in ~2 months: real (deep polar winter, persistent gaps) — the+ // pill falls back to "most recent" rather than inventing a date+ latest = '';+ latestFor = key;+ }++ function clearDate() {+ pickRequestId += 1;+ verifyingDate = '';+ date = '';+ }++ /** Is this day's pass above the ceiling, i.e. filtered out of the tiles? */+ function filtered(day) {+ return overCloudCeiling(passes[day]?.cloud, maxcc);+ }++ /**+ * A new cloud ceiling. It reaches the tiles through the provider id, so the+ * only thing left to settle is a pinned date the new ceiling excludes: that+ * day renders nothing, so it goes back to most recent rather than to a blank+ * map nobody asked for.+ */+ function setMaxcc(value) {+ const ceiling = Math.round(Number(value));+ if (!validMaxcc(ceiling) || ceiling === maxcc) return;+ maxcc = ceiling;+ if (date && overCloudCeiling(passes[date]?.cloud, ceiling)) {+ const cloud = cloudLabel(passes[date].cloud);+ const day = date;+ clearDate();+ notify(`${day} is ${cloud}, over the ${ceiling}% ceiling. Back to most recent.`, 'warn');+ }+ }++ async function pickDate(day) {+ if (day === date) {+ clearDate();+ return;+ }+ if (!passes[day] || stale() || passesBusy || verifyingDate) return;+ if (filtered(day)) {+ notify(`${day} is ${cloudLabel(passes[day].cloud)}, over the ${maxcc}% ceiling.`, 'warn');+ return;+ }++ const { lat, lon } = place();+ const at = placeKey();+ const forLayer = layer;+ const ceiling = maxcc;+ const key = coverageKey(day, at, forLayer, ceiling);+ const known = coverageCache.get(key);+ if (known === true) {+ date = day;+ return;+ }+ if (known === false) {+ notify(`No imagery at the crosshair on ${day}.`, 'warn');+ return;+ }++ const requestId = ++pickRequestId;+ verifyingDate = day;+ try {+ const result = await api.get(+ coverageRequestPath({ lat, lon, layer: forLayer, date: day, maxcc: ceiling })+ );+ coverageCache.set(key, result.available === true);+ coverageRev += 1;+ onBilled();+ if (requestId !== pickRequestId) return;+ if (at !== placeKey() || forLayer !== layer || ceiling !== maxcc) {+ notify('The view changed. Pick the date again.', 'warn');+ return;+ }+ date = dateAfterCoverage(date, day, result.available);+ if (!result.available) notify(`No imagery at the crosshair on ${day}.`, 'warn');+ } catch (e) {+ if (requestId === pickRequestId) {+ notify(`Could not check imagery for ${day}: ${e.message}`, 'danger');+ }+ } finally {+ if (requestId === pickRequestId) verifyingDate = '';+ }+ }++ /**+ * The passes on screen describe the place they were fetched for; once the map+ * has moved somewhere else they are stale and must not grey out real imagery.+ */+ function stale() {+ return !!passesFor && passesFor !== `${month}@${placeKey()}`;+ }++ return {+ get layer() {+ return layer;+ },+ set layer(value) {+ layer = value;+ },+ get date() {+ return date;+ },+ get maxcc() {+ return maxcc;+ },+ get menuOpen() {+ return menuOpen;+ },+ set menuOpen(value) {+ menuOpen = value;+ },+ get layers() {+ return layers;+ },+ get layersSource() {+ return layersSource;+ },+ get month() {+ return month;+ },+ get passes() {+ return passes;+ },+ get passesBusy() {+ return passesBusy;+ },+ get passesNote() {+ return passesNote;+ },+ get verifyingDate() {+ return verifyingDate;+ },+ get latest() {+ return latest;+ },+ get layerHint() {+ return layers.find((l) => l.id === layer)?.hint ?? '';+ },+ get layerLabel() {+ return (+ layers.find((l) => l.id === layer)?.label ?? layer.replace(/_/g, ' ').toLowerCase()+ );+ },+ /** The pill is small: "false colour (infrared)" doesn't fit, "FALSE COLOR" does. */+ get layerShort() {+ return layer.replace(/_/g, ' ');+ },++ /** A half-typed date is not a date: it stays "most recent" rather than+ * becoming a request the backend would refuse. */+ get window() {+ return validDay(date) ? { from: date, to: date } : { from: '', to: '' };+ },+ /** What rides on the provider id, so the tiles, the capture and the cache+ * all key on the same choices. */+ get variant() {+ return { layer, ...this.window, maxcc };+ },+ get stale() {+ return stale();+ },+ /** The place the passes on screen were asked about. */+ get placeKey() {+ return placeKey();+ },++ dateStatus(day) {+ coverageRev; // read, so a settled check repaints the calendar+ return coverageCache.get(coverageKey(day));+ },+ filtered,+ loadLayers,+ loadPasses,+ stepMonth,+ toggleMenu,+ resolveLatest,+ clearDate,+ setMaxcc,+ pickDate,+ };+}diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.test.js b/frontend/src/tools/satellite/state/sentinel.svelte.test.jsnew file mode 100644index 0000000..c99f565--- /dev/null+++ b/frontend/src/tools/satellite/state/sentinel.svelte.test.js@@ -0,0 +1,264 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createSentinelState } from './sentinel.svelte.js';++/**+ * Every question this store asks is a billed request about a place the map may+ * already have left, so what it must get right is *when it asks* and *what it+ * refuses to claim* — not the arithmetic, which is `lib/sentinel.js`.+ */++let at;+let get;+let notify;+let billed;++function store() {+ return createSentinelState({+ place: () => at,+ onBilled: billed,+ notify,+ api: { get },+ });+}++/** `{ 'YYYY-MM-DD': {cloud, granules} }` as the dates route answers it. */+const answer = (days) => ({ dates: days.map(([date, cloud]) => ({ date, cloud, granules: 1 })) });++beforeEach(() => {+ at = { lat: 48.8584, lon: 2.2945 };+ notify = vi.fn();+ billed = vi.fn();+ get = vi.fn(async (path) => {+ if (path.includes('/sentinel/layers')) {+ return { layers: [{ id: 'TRUE_COLOR', label: 'True colour' }], source: 'instance' };+ }+ if (path.includes('/sentinel/dates')) return answer([['2026-05-11', 4], ['2026-05-16', 62]]);+ return { available: true };+ });+});++describe('asking for a month of passes', () => {+ it('bills the lookup, and says so once', async () => {+ const s2 = store();+ await s2.loadPasses();+ expect(Object.keys(s2.passes)).toEqual(['2026-05-11', '2026-05-16']);+ expect(billed).toHaveBeenCalledTimes(1);+ });++ it('pays once for a month already seen', async () => {+ const s2 = store();+ await s2.loadPasses();+ await s2.loadPasses();+ expect(get).toHaveBeenCalledTimes(1);+ });++ it('pays once for a month asked for twice at the same time', async () => {+ const s2 = store();+ await Promise.all([s2.loadPasses(), s2.loadPasses()]);+ expect(get).toHaveBeenCalledTimes(1);+ });++ it('asks again a few kilometres away, because the answer differs there', async () => {+ const s2 = store();+ await s2.loadPasses();+ at = { lat: 49.5, lon: 2.2945 };+ await s2.loadPasses();+ expect(get).toHaveBeenCalledTimes(2);+ });++ it('says a month is empty when it is', async () => {+ get = vi.fn(async () => answer([]));+ const s2 = store();+ await s2.loadPasses();+ expect(s2.passesNote).toBe('No Sentinel-2 pass here this month.');+ });++ it('never passes a failed lookup off as an empty month', async () => {+ // greying every day out because the network hiccuped would be a lie about+ // what exists+ get = vi.fn(async () => {+ throw new Error('offline');+ });+ const s2 = store();+ await s2.loadPasses();+ expect(s2.passes).toEqual({});+ expect(s2.passesNote).toContain('do not confirm coverage');+ expect(s2.stale).toBe(false); // there is nothing on screen to be stale+ });++ it('calls what is on screen stale once the map has moved off it', async () => {+ const s2 = store();+ await s2.loadPasses();+ expect(s2.stale).toBe(false);+ at = { lat: 12, lon: 34 };+ expect(s2.stale).toBe(true);+ });+});++describe('picking a day', () => {+ it('checks the crosshair before changing the map, and bills that check', async () => {+ const s2 = store();+ await s2.loadPasses();+ await s2.pickDate('2026-05-11');+ expect(s2.date).toBe('2026-05-11');+ expect(get).toHaveBeenCalledWith(expect.stringContaining('/sentinel/coverage'));+ expect(billed).toHaveBeenCalledTimes(2); // the month, then the check+ });++ it('remembers the answer, so the same day is checked once', async () => {+ const s2 = store();+ await s2.loadPasses();+ await s2.pickDate('2026-05-11');+ s2.clearDate();+ const before = get.mock.calls.length;+ await s2.pickDate('2026-05-11');+ expect(get).toHaveBeenCalledTimes(before);+ expect(s2.date).toBe('2026-05-11');+ });++ it('leaves the map where it was when the crosshair has no imagery', async () => {+ get = vi.fn(async (path) =>+ path.includes('/sentinel/dates') ? answer([['2026-05-11', 4]]) : { available: false }+ );+ const s2 = store();+ await s2.loadPasses();+ await s2.pickDate('2026-05-11');+ expect(s2.date).toBe('');+ expect(notify).toHaveBeenCalledWith('No imagery at the crosshair on 2026-05-11.', 'warn');+ });++ it('refuses a day it has no pass for', async () => {+ const s2 = store();+ await s2.loadPasses();+ await s2.pickDate('2026-05-12');+ expect(s2.date).toBe('');+ expect(get).toHaveBeenCalledTimes(1); // no check was spent on it+ });++ it('says why a cloudy day is not offered, instead of costing a tile to find out', async () => {+ const s2 = store();+ await s2.loadPasses();+ s2.setMaxcc(20);+ await s2.pickDate('2026-05-16'); // 62% cloud+ expect(s2.date).toBe('');+ expect(notify).toHaveBeenCalledWith(+ expect.stringContaining('over the 20% ceiling'),+ 'warn'+ );+ });++ it('asks the analyst again when the view moved under a slow check', async () => {+ let release;+ get = vi.fn(async (path) => {+ if (path.includes('/sentinel/dates')) return answer([['2026-05-11', 4]]);+ await new Promise((r) => (release = r));+ return { available: true };+ });+ const s2 = store();+ await s2.loadPasses();+ const picking = s2.pickDate('2026-05-11');+ at = { lat: 12, lon: 34 }; // panned away mid-flight+ release();+ await picking;+ expect(s2.date).toBe('');+ expect(notify).toHaveBeenCalledWith('The view changed. Pick the date again.', 'warn');+ });++ it('takes a pinned day back off when a new ceiling excludes it', async () => {+ const s2 = store();+ await s2.loadPasses();+ await s2.pickDate('2026-05-16'); // 62% cloud, allowed at 100+ expect(s2.date).toBe('2026-05-16');+ s2.setMaxcc(20);+ // that day now renders nothing, so it goes back to most recent rather than+ // to a blank map nobody asked for+ expect(s2.date).toBe('');+ expect(notify).toHaveBeenCalledWith(+ expect.stringContaining('Back to most recent'),+ 'warn'+ );+ });++ it('refuses a ceiling that is not one', () => {+ const s2 = store();+ s2.setMaxcc(140);+ s2.setMaxcc('abc');+ expect(s2.maxcc).toBe(100);+ });+});++describe('what the pill can claim', () => {+ it('names the most recent pass the ceiling still allows', async () => {+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ expect(s2.latest).toBe('2026-05-16');+ s2.setMaxcc(20);+ await s2.resolveLatest('2026-05-20');+ expect(s2.latest).toBe('2026-05-11'); // the cloudy pass is not rendered+ });++ it('steps back a month rather than claiming there was no pass', async () => {+ get = vi.fn(async (path) => {+ if (!path.includes('/sentinel/dates')) return { available: true };+ return path.includes('start=2026-05') ? answer([]) : answer([['2026-04-28', 3]]);+ });+ const s2 = store();+ await s2.resolveLatest('2026-05-02');+ expect(s2.latest).toBe('2026-04-28');+ });++ it('claims nothing when the lookup failed', async () => {+ get = vi.fn(async () => {+ throw new Error('offline');+ });+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ expect(s2.latest).toBe('');+ });++ it('resolves once per place and ceiling', async () => {+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ const before = get.mock.calls.length;+ await s2.resolveLatest('2026-05-20');+ expect(get).toHaveBeenCalledTimes(before);+ });++ it('carries the layer, the window and the ceiling on the provider id', async () => {+ const s2 = store();+ expect(s2.variant).toEqual({ layer: 'TRUE_COLOR', from: '', to: '', maxcc: 100 });+ await s2.loadPasses();+ await s2.pickDate('2026-05-11');+ expect(s2.variant).toEqual({+ layer: 'TRUE_COLOR',+ from: '2026-05-11',+ to: '2026-05-11',+ maxcc: 100,+ });+ });+});++describe('which layers are on offer', () => {+ it('asks the instance once a session, quietly, and takes its answer', async () => {+ const s2 = store();+ s2.toggleMenu();+ await vi.waitFor(() => expect(s2.layers).toHaveLength(1));+ expect(get).toHaveBeenCalledWith('/api/satellite/sentinel/layers?check=true');+ expect(notify).not.toHaveBeenCalled(); // the first ask says nothing+ s2.toggleMenu();+ s2.toggleMenu();+ const asks = get.mock.calls.filter(([path]) => path.includes('/layers')).length;+ expect(asks).toBe(1);+ });++ it('drops a selected layer the instance no longer serves', async () => {+ get = vi.fn(async (path) =>+ path.includes('/layers')+ ? { layers: [{ id: 'SWIR', label: 'SWIR' }], source: 'instance' }+ : answer([])+ );+ const s2 = store();+ await s2.loadLayers(true, true);+ expect(s2.layer).toBe('SWIR');+ });+});diff --git a/frontend/src/tools/settings/PublishingTab.svelte b/frontend/src/tools/settings/PublishingTab.svelteindex ebd7ebc..4df2f18 100644--- a/frontend/src/tools/settings/PublishingTab.svelte+++ b/frontend/src/tools/settings/PublishingTab.svelte@@ -16,6 +16,7 @@uploadSignature,mention = $bindable(),postTarget = $bindable(),+ postPrefill = $bindable(),signatureHandle = $bindable(),sigInput = $bindable(),} = $props();@@ -54,6 +55,22 @@{/each}</div></div>+ <div class="row">+ <div class="row-label">+ <span>Let the extension fill the composer</span>+ <span class="row-hint">+ Publish types the thread and attaches the proof, then stops. Nothing is+ ever posted. Needs the capture extension; without it, Publish opens the+ page as usual.+ </span>+ </div>+ <input+ type="checkbox"+ bind:checked={postPrefill}+ onchange={() => savePrefs({ post_prefill: postPrefill })}+ aria-label="Let the extension fill the composer"+ />+ </div></section><section class="group">diff --git a/frontend/vite.config.js b/frontend/vite.config.jsindex 7676999..786057a 100644--- a/frontend/vite.config.js+++ b/frontend/vite.config.js@@ -18,6 +18,14 @@ export default defineConfig({test: {include: ['src/**/*.test.js'],},+ // The map engine parses GeoJSON in a web worker, and asks for it by a URL it+ // builds at runtime (`new URL('./maplibre-gl-worker.mjs', import.meta.url)`).+ // No bundler can see through that, so the URL resolved to a file that was+ // never emitted and the worker silently never started — the map drew imagery+ // and nothing else. `lib/map/engine.js` hands the engine the bundled worker's+ // real URL instead; `format: 'es'` is what makes that bundle a module worker,+ // which is how the engine loads it.+ worker: { format: 'es' },build: {outDir: '../src/azimut/static',emptyOutDir: true,diff --git a/scripts/devext.py b/scripts/devext.pynew file mode 100644index 0000000..a099505--- /dev/null+++ b/scripts/devext.py@@ -0,0 +1,700 @@+#!/usr/bin/env python3+"""Load, pair and reload the capture extension in a dev browser, without clicks.++A maintainer tool, not part of the app. It drives Chrome's DevTools protocol and+Firefox's remote debugging protocol, so an edit in ``extension/`` reaches both+browsers with one command:++ python3 scripts/devext.py # both browsers: load/reload + pair+ python3 scripts/devext.py chrome # just one of them+ python3 scripts/devext.py --watch # reload on every save, until Ctrl-C+ python3 scripts/devext.py --fresh # start from an empty dev profile++Each browser gets its own dev profile, kept between runs, so the pairing token,+the last case and anything set in the popup survive a restart. The token is read+from the running app (or from its settings.json) and written straight into the+extension's storage, which is the manual paste this script exists to remove.++The dev browsers are separate instances: the everyday Chrome and Firefox keep+running untouched, with their own profiles and their own copy of the extension.++Stdlib only: it runs with any python3, no venv and no npm.+"""++from __future__ import annotations++import argparse+import base64+import json+import os+import shutil+import socket+import struct+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++REPO = Path(__file__).resolve().parent.parent+EXT = REPO / "extension"+STATE = Path.home() / ".cache" / "azimut-devext"++DEFAULT_APP_URL = os.environ.get("AZIMUT_URL", "http://127.0.0.1:8477")+DEFAULT_CHROME_PORT = 9222+DEFAULT_FIREFOX_PORT = 6080++CHROME_NAMES = (+ "google-chrome",+ "google-chrome-stable",+ "chromium",+ "chromium-browser",+ "brave-browser",+ "microsoft-edge",+)+FIREFOX_NAMES = ("firefox", "firefox-esr", "firefox-developer-edition")+MAC_APPS = {+ "chrome": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "firefox": "/Applications/Firefox.app/Contents/MacOS/firefox",+}+++@dataclass+class Options:+ """What one sync does, so `relaunch.py --ext` can ask for the same thing."""++ browsers: list[str] = field(default_factory=lambda: ["chrome", "firefox"])+ url: str = DEFAULT_APP_URL+ fresh: bool = False+ reload_tabs: bool = True+ chrome_port: int = DEFAULT_CHROME_PORT+ firefox_port: int = DEFAULT_FIREFOX_PORT+++def say(browser: str, message: str) -> None:+ print(f"[{browser}] {message}", flush=True)+++BACKGROUND_PROOF = (+ "((api) => JSON.stringify(["+ "api.runtime.getManifest().version, "+ "Math.round(Date.now() - performance.timeOrigin)"+ "]))(typeof browser !== 'undefined' ? browser : chrome)"+)+++def report_background(browser: str, answer: str | None) -> None:+ """Say what the background context is, and how long ago it started.++ An age of a second or so is the proof the sync landed: reloading the+ extension restarts its background, so anything older is code from before.+ """+ if not answer:+ say(browser, "background asleep, nothing to read back")+ return+ version, age = json.loads(answer)+ if age > 15000:+ say(browser, f"background is {age // 1000}s old: it kept the code it had")+ return+ say(browser, f"background restarted {age / 1000:.1f}s ago, running v{version}")+++def find_binary(env_var: str, names: tuple[str, ...], mac_key: str) -> str | None:+ override = os.environ.get(env_var)+ if override:+ return override+ for name in names:+ found = shutil.which(name)+ if found:+ return found+ mac = MAC_APPS[mac_key]+ return mac if Path(mac).exists() else None+++def _detached() -> dict[str, Any]:+ """Popen arguments that let the browser survive this script exiting."""+ if os.name == "nt":+ return {"creationflags": getattr(subprocess, "DETACHED_PROCESS", 0)}+ return {"start_new_session": True}+++def port_open(port: int) -> bool:+ with socket.socket() as s:+ s.settimeout(0.4)+ return s.connect_ex(("127.0.0.1", port)) == 0+++def wait_for_port(port: int, timeout: float = 30.0) -> bool:+ deadline = time.time() + timeout+ while time.time() < deadline:+ if port_open(port):+ return True+ time.sleep(0.3)+ return False+++# --- pairing token ----------------------------------------------------------+++def pairing_token(app_url: str) -> str | None:+ """The app's ingest token: from the running app, else from settings.json."""+ request = urllib.request.Request(+ f"{app_url}/api/settings/ingest-token", data=b"", method="POST"+ )+ try:+ with urllib.request.urlopen(request, timeout=3) as response:+ return json.load(response).get("ingest_token")+ except (urllib.error.URLError, OSError, ValueError):+ pass+ root = Path(os.environ.get("AZIMUT_HOME", "~/Azimut")).expanduser()+ settings = root / ".azimut" / "settings" / "settings.json"+ try:+ return json.loads(settings.read_text(encoding="utf-8")).get("ingest_token")+ except (OSError, ValueError):+ return None+++# --- a small WebSocket client (Chrome DevTools protocol) --------------------+++class WebSocket:+ """Just enough of RFC 6455 to talk CDP: text frames, one connection."""++ def __init__(self, url: str) -> None:+ rest = url.split("://", 1)[1]+ hostport, _, path = rest.partition("/")+ host, _, port = hostport.partition(":")+ self.sock = socket.create_connection((host, int(port or 80)), timeout=30)+ key = base64.b64encode(os.urandom(16)).decode()+ self.sock.sendall(+ (+ f"GET /{path} HTTP/1.1\r\n"+ f"Host: {hostport}\r\n"+ "Upgrade: websocket\r\n"+ "Connection: Upgrade\r\n"+ f"Sec-WebSocket-Key: {key}\r\n"+ "Sec-WebSocket-Version: 13\r\n\r\n"+ ).encode()+ )+ self.buf = b""+ while b"\r\n\r\n" not in self.buf:+ self.buf += self._read(1)+ head, _, self.buf = self.buf.partition(b"\r\n\r\n")+ if b"101" not in head.split(b"\r\n")[0]:+ raise RuntimeError(f"websocket refused: {head.splitlines()[0]!r}")++ def _read(self, n: int) -> bytes:+ chunk = self.sock.recv(max(n, 4096))+ if not chunk:+ raise RuntimeError("websocket closed")+ return chunk++ def _take(self, n: int) -> bytes:+ while len(self.buf) < n:+ self.buf += self._read(n - len(self.buf))+ out, self.buf = self.buf[:n], self.buf[n:]+ return out++ def send(self, text: str) -> None:+ payload = text.encode()+ header = bytearray([0x81])+ length = len(payload)+ if length < 126:+ header.append(0x80 | length)+ elif length < 1 << 16:+ header.append(0x80 | 126)+ header += struct.pack(">H", length)+ else:+ header.append(0x80 | 127)+ header += struct.pack(">Q", length)+ mask = os.urandom(4)+ masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload))+ self.sock.sendall(bytes(header) + mask + masked)++ def recv(self) -> str:+ while True:+ first, second = self._take(2)+ opcode = first & 0x0F+ length = second & 0x7F+ if length == 126:+ length = struct.unpack(">H", self._take(2))[0]+ elif length == 127:+ length = struct.unpack(">Q", self._take(8))[0]+ payload = self._take(length) if length else b""+ if opcode == 0x9: # ping: the protocol says answer it+ self.sock.sendall(b"\x8a\x80" + os.urandom(4))+ continue+ if opcode == 0x8:+ raise RuntimeError("websocket closed by browser")+ if opcode in (0x1, 0x2):+ return payload.decode("utf-8", "replace")++ def close(self) -> None:+ try:+ self.sock.close()+ except OSError:+ pass+++class Chrome:+ def __init__(self, port: int) -> None:+ with urllib.request.urlopen(+ f"http://127.0.0.1:{port}/json/version", timeout=5+ ) as response:+ endpoint = json.load(response)["webSocketDebuggerUrl"]+ self.ws = WebSocket(endpoint)+ self.n = 0++ def call(+ self, method: str, params: dict[str, Any] | None = None, session: str = ""+ ) -> dict[str, Any]:+ self.n += 1+ message: dict[str, Any] = {"id": self.n, "method": method, "params": params or {}}+ if session:+ message["sessionId"] = session+ self.ws.send(json.dumps(message))+ while True:+ answer = json.loads(self.ws.recv())+ if answer.get("id") != self.n:+ continue # an event, or a stale answer+ if "error" in answer:+ raise RuntimeError(f"{method}: {answer['error'].get('message')}")+ return answer.get("result", {})++ def close(self) -> None:+ self.ws.close()+++def chrome_sync(options: Options, token: str | None) -> None:+ binary = find_binary("AZIMUT_CHROME", CHROME_NAMES, "chrome")+ if not binary:+ say("chrome", "not found. Set AZIMUT_CHROME to its path")+ return+ profile = STATE / "chrome"+ if options.fresh:+ if port_open(options.chrome_port):+ chrome_quit(options.chrome_port, profile)+ shutil.rmtree(profile, ignore_errors=True)+ if not port_open(options.chrome_port):+ profile.mkdir(parents=True, exist_ok=True)+ subprocess.Popen(+ [+ binary,+ f"--user-data-dir={profile}",+ f"--remote-debugging-port={options.chrome_port}",+ # Chrome 137 dropped --load-extension; unpacked loading now goes+ # through the DevTools protocol, which this flag opens up.+ "--enable-unsafe-extension-debugging",+ "--no-first-run",+ "--no-default-browser-check",+ "--disable-search-engine-choice-screen",+ options.url,+ ],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ # Detached: the browser outlives the sync that started it.+ **_detached(),+ )+ if not wait_for_port(options.chrome_port):+ say("chrome", "no debug port. A dev Chrome may still hold the profile")+ return+ say("chrome", f"launched on a dev profile ({profile})")++ cdp = Chrome(options.chrome_port)+ try:+ extension_id = cdp.call("Extensions.loadUnpacked", {"path": str(EXT)})["id"]+ say("chrome", f"extension loaded from disk ({extension_id})")+ if token:+ chrome_in_extension_page(+ cdp,+ extension_id,+ [+ "chrome.storage.local.set("+ f"{json.dumps({'backendUrl': options.url, 'token': token})})"+ ],+ )+ say("chrome", "paired")+ report_background("chrome", chrome_background_proof(cdp, extension_id))+ if options.reload_tabs:+ say("chrome", f"reloaded {chrome_reload_tabs(cdp, options.url)} app tab(s)")+ finally:+ cdp.close()+++def chrome_quit(port: int, profile: Path) -> None:+ """Ask the dev Chrome to close, and wait until it has really let go.++ Its lock file outlives the debug port by a moment, and a profile replaced+ before that leaves the next launch talking to the dying instance instead of+ starting its own.+ """+ cdp = Chrome(port)+ try:+ cdp.call("Browser.close")+ except (RuntimeError, OSError):+ pass+ finally:+ cdp.close()+ deadline = time.time() + 15+ lock = profile / "SingletonLock"+ while time.time() < deadline and (port_open(port) or lock.exists()):+ time.sleep(0.2)+ time.sleep(0.5)+++def chrome_in_extension_page(+ cdp: Chrome, extension_id: str, expressions: list[str]+) -> list[Any]:+ """Run JS with the extension's own APIs, in a page opened for that alone.++ `chrome.storage` and the extension's files exist only inside an extension+ context, so the options page is opened, used and closed again.+ """+ target = cdp.call(+ "Target.createTarget", {"url": f"chrome-extension://{extension_id}/options.html"}+ )["targetId"]+ values: list[Any] = []+ try:+ time.sleep(0.8)+ session = cdp.call(+ "Target.attachToTarget", {"targetId": target, "flatten": True}+ )["sessionId"]+ for expression in expressions:+ answer = cdp.call(+ "Runtime.evaluate",+ {"expression": expression, "awaitPromise": True, "returnByValue": True},+ session,+ )+ if "exceptionDetails" in answer:+ raise RuntimeError(answer["exceptionDetails"].get("text", "evaluation failed"))+ values.append(answer["result"].get("value"))+ finally:+ cdp.call("Target.closeTarget", {"targetId": target})+ return values+++def chrome_background_proof(cdp: Chrome, extension_id: str) -> str | None:+ """Ask the extension's service worker what it is running.++ It is the context the reload restarts, and the only one whose age says+ whether the browser took the new code.+ """+ deadline = time.time() + 5+ while time.time() < deadline:+ for target in cdp.call("Target.getTargets")["targetInfos"]:+ if target["type"] != "service_worker" or extension_id not in target["url"]:+ continue+ session = cdp.call(+ "Target.attachToTarget", {"targetId": target["targetId"], "flatten": True}+ )["sessionId"]+ answer = cdp.call(+ "Runtime.evaluate",+ {"expression": BACKGROUND_PROOF, "returnByValue": True},+ session,+ )+ cdp.call("Target.detachFromTarget", {"sessionId": session})+ value = answer["result"].get("value")+ return str(value) if value is not None else None+ time.sleep(0.3)+ return None+++def chrome_reload_tabs(cdp: Chrome, app_url: str) -> int:+ """Reload the app's own tabs: content scripts only re-inject on navigation."""+ reloaded = 0+ for target in cdp.call("Target.getTargets")["targetInfos"]:+ if target["type"] != "page" or not target["url"].startswith(app_url):+ continue+ session = cdp.call(+ "Target.attachToTarget", {"targetId": target["targetId"], "flatten": True}+ )["sessionId"]+ cdp.call("Page.reload", {}, session)+ cdp.call("Target.detachFromTarget", {"sessionId": session})+ reloaded += 1+ return reloaded+++# --- Firefox remote debugging protocol --------------------------------------+++class Firefox:+ """The `<length>:<json>` protocol behind about:debugging."""++ def __init__(self, port: int) -> None:+ self.sock = socket.create_connection(("127.0.0.1", port), timeout=30)+ self.buf = b""+ self.read() # the server greets before anything is asked of it++ def read(self) -> dict[str, Any]:+ while True:+ colon = self.buf.find(b":")+ if colon != -1:+ length = int(self.buf[:colon])+ if len(self.buf) >= colon + 1 + length:+ packet = self.buf[colon + 1 : colon + 1 + length]+ self.buf = self.buf[colon + 1 + length :]+ return json.loads(packet)+ chunk = self.sock.recv(65536)+ if not chunk:+ raise RuntimeError("debugger connection closed")+ self.buf += chunk++ def call(+ self, message: dict[str, Any], event: str = "", timeout: float = 20.0+ ) -> dict[str, Any]:+ """Send one request; return its reply, or the awaited event instead."""+ data = json.dumps(message).encode()+ self.sock.sendall(str(len(data)).encode() + b":" + data)+ deadline = time.time() + timeout+ self.sock.settimeout(timeout)+ while time.time() < deadline:+ answer = self.read()+ if event:+ if answer.get("type") == event:+ return answer+ elif answer.get("from") == message["to"] and "type" not in answer:+ if "error" in answer:+ raise RuntimeError(f"{message['type']}: {answer['error']}")+ return answer+ raise RuntimeError(f"no answer to {message['type']}")++ def close(self) -> None:+ try:+ self.sock.close()+ except OSError:+ pass+++FIREFOX_PREFS = """\+// Written by scripts/devext.py: dev profile for the capture extension.+user_pref("devtools.debugger.remote-enabled", true);+user_pref("devtools.debugger.prompt-connection", false);+user_pref("devtools.chrome.enabled", true);+user_pref("browser.shell.checkDefaultBrowser", false);+user_pref("browser.aboutwelcome.enabled", false);+user_pref("datareporting.policy.dataSubmissionEnabled", false);+user_pref("extensions.autoDisableScopes", 0);+"""+++def firefox_profile_dir() -> Path:+ # The snap can only read parts of $HOME; its own writable area always works.+ snap = Path.home() / "snap" / "firefox" / "common"+ return (snap / "azimut-devext") if snap.exists() else (STATE / "firefox")+++def firefox_sync(options: Options, token: str | None) -> None:+ binary = find_binary("AZIMUT_FIREFOX", FIREFOX_NAMES, "firefox")+ if not binary:+ say("firefox", "not found. Set AZIMUT_FIREFOX to its path")+ return+ profile = firefox_profile_dir()+ if options.fresh:+ if port_open(options.firefox_port):+ # Firefox has no remote quit, and the profile is open under it.+ say("firefox", "already running. Close it first to start fresh")+ return+ shutil.rmtree(profile, ignore_errors=True)+ if not port_open(options.firefox_port):+ profile.mkdir(parents=True, exist_ok=True)+ (profile / "user.js").write_text(FIREFOX_PREFS, encoding="utf-8")+ subprocess.Popen(+ [+ binary,+ "--profile",+ str(profile),+ "--no-remote", # a second instance, beside the everyday Firefox+ "--start-debugger-server",+ str(options.firefox_port),+ options.url,+ ],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ # Detached: the browser outlives the sync that started it.+ **_detached(),+ )+ if not wait_for_port(options.firefox_port, timeout=45):+ say("firefox", "no debug port. A dev Firefox may still hold the profile")+ return+ say("firefox", f"launched on a dev profile ({profile})")++ rdp = Firefox(options.firefox_port)+ try:+ root = rdp.call({"to": "root", "type": "getRoot"})+ rdp.call(+ {+ "to": root["addonsActor"],+ "type": "installTemporaryAddon",+ "addonPath": str(EXT),+ "openDevTools": False,+ }+ )+ say("firefox", "extension installed from disk")+ if not token:+ return+ console = firefox_background_console(rdp)+ if not console:+ say("firefox", "background page not reachable. Pair by hand this once")+ return+ script = (+ "browser.storage.local.set("+ f"{json.dumps({'backendUrl': options.url, 'token': token})})"+ )+ if options.reload_tabs:+ # Filtered here rather than by `tabs.query({url})`: a match pattern+ # cannot carry a port, and the app URL always has one.+ script += (+ ".then(() => browser.tabs.query({}))"+ ".then(tabs => tabs.filter(tab => (tab.url || '').startsWith("+ f"{json.dumps(options.url)})))"+ ".then(tabs => Promise.all(tabs.map(tab => browser.tabs.reload(tab.id)))"+ ".then(() => tabs.length)).catch(() => 0)"+ )+ answer = firefox_evaluate(rdp, console, script)+ if answer is None:+ say("firefox", "could not write the token into the extension")+ return+ say("firefox", "paired")+ report_background("firefox", firefox_evaluate(rdp, console, BACKGROUND_PROOF))+ if options.reload_tabs:+ say("firefox", f"reloaded {answer} app tab(s)")+ finally:+ rdp.close()+++def firefox_evaluate(rdp: Firefox, console: str, script: str) -> Any:+ """Run one expression in the add-on's background, or None if it threw."""+ answer = rdp.call(+ {"to": console, "type": "evaluateJSAsync", "text": script, "mapped": {"await": True}},+ event="evaluationResult",+ )+ return None if answer.get("hasException") else answer.get("result")+++def firefox_background_console(rdp: Firefox) -> str | None:+ """The console actor of the add-on's background page.++ Watching the add-on announces its frames one by one; the first is devtools'+ own fallback page, the extension's own comes right after.+ """+ addons = rdp.call({"to": "root", "type": "listAddons"})["addons"]+ mine = next(+ (a for a in addons if a.get("id") == "[email protected]"), None+ )+ if not mine:+ return None+ watcher = rdp.call({"to": mine["actor"], "type": "getWatcher"})["actor"]+ rdp.call(+ {"to": watcher, "type": "watchTargets", "targetType": "frame"},+ event="target-available-form",+ )+ deadline = time.time() + 10+ rdp.sock.settimeout(10)+ while time.time() < deadline:+ try:+ packet = rdp.read()+ except (OSError, RuntimeError):+ break+ target = packet.get("target") or {}+ if target.get("url", "").startswith("moz-extension://"):+ return target.get("consoleActor")+ return None+++# --- watch mode -------------------------------------------------------------+++def fingerprint() -> tuple[tuple[str, float], ...]:+ return tuple(+ sorted(+ (str(path), path.stat().st_mtime)+ for path in EXT.rglob("*")+ if path.is_file() and not path.name.startswith(".")+ )+ )+++def sync(options: Options) -> None:+ """One pass: load the code from disk into each dev browser, and pair it."""+ token = pairing_token(options.url)+ if not token:+ print("no pairing token yet. Start Azimut once so it mints one", flush=True)+ for browser in options.browsers:+ try:+ (chrome_sync if browser == "chrome" else firefox_sync)(options, token)+ except (RuntimeError, OSError) as error:+ say(browser, f"failed: {error}")+++def watch(options: Options, stop: threading.Event | None = None) -> None:+ """Sync again on every save in extension/, until `stop` is set."""+ stop = stop or threading.Event()+ options.fresh = False # a wipe belongs to the first pass only+ seen = fingerprint()+ while not stop.wait(0.6):+ if fingerprint() == seen:+ continue+ stop.wait(0.3) # let the editor finish writing+ print(f"change at {time.strftime('%H:%M:%S')}", flush=True)+ sync(options)+ seen = fingerprint()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument(+ "browsers",+ nargs="*",+ default=[],+ metavar="{chrome,firefox,all}",+ help="which dev browser to sync (default: both)",+ )+ parser.add_argument("--url", default=DEFAULT_APP_URL, help="where the app runs")+ parser.add_argument("--watch", action="store_true", help="reload on every save")+ parser.add_argument("--fresh", action="store_true", help="wipe the dev profile first")+ parser.add_argument(+ "--no-reload-tabs",+ dest="reload_tabs",+ action="store_false",+ help="leave the open app tabs alone",+ )+ parser.add_argument("--chrome-port", type=int, default=DEFAULT_CHROME_PORT)+ parser.add_argument("--firefox-port", type=int, default=DEFAULT_FIREFOX_PORT)+ args = parser.parse_args()++ unknown = set(args.browsers) - {"chrome", "firefox", "all"}+ if unknown:+ parser.error(f"unknown browser: {', '.join(sorted(unknown))}")++ if not (EXT / "manifest.json").exists():+ print(f"no extension at {EXT}", file=sys.stderr)+ return 1++ options = Options(+ browsers=["chrome", "firefox"]+ if "all" in args.browsers or not args.browsers+ else list(dict.fromkeys(args.browsers)),+ url=args.url,+ fresh=args.fresh,+ reload_tabs=args.reload_tabs,+ chrome_port=args.chrome_port,+ firefox_port=args.firefox_port,+ )+ sync(options)+ if not args.watch:+ return 0++ print("watching extension/, Ctrl-C to stop", flush=True)+ try:+ watch(options)+ except KeyboardInterrupt:+ print()+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/relaunch.py b/scripts/relaunch.pyindex 619bd0a..a38a788 100755--- a/scripts/relaunch.py+++ b/scripts/relaunch.py@@ -8,6 +8,10 @@ without scanning process names or killing unrelated Vite/Azimut instances.When that handshake finds nothing (a server started by hand, or one whoselauncher was killed hard), the port itself is reclaimed: whoever still listenson it is stopped so the relaunch never hits "address already in use".++``--ext`` hands the capture extension to the same loop: once the server answers,+`devext.py` loads it into a dev Chrome and Firefox and pairs it with the running+app, and ``--watch-ext`` reloads it there on every save."""from __future__ import annotations@@ -318,7 +322,45 @@ def _run_process(raise-def run(*, port: int, no_browser: bool) -> int:+def _load_devext() -> Any:+ """Import the sibling script by path, so pytest can load this one by path too."""+ directory = str(Path(__file__).resolve().parent)+ if directory not in sys.path:+ sys.path.insert(0, directory)+ import devext++ return devext+++def _serve_extension(+ browsers: list[str], port: int, watch: bool, stop_requested: threading.Event+) -> None:+ """Wait for the server, then load the extension into the dev browsers.++ Pairing reads the token from the running app, so this waits for the port the+ frontend build is still delaying. A failure here never stops the app.+ """+ devext = _load_devext()+ deadline = time.monotonic() + 300+ while _port_is_free(port):+ if stop_requested.wait(0.3) or time.monotonic() > deadline:+ return+ options = devext.Options(browsers=browsers, url=f"http://127.0.0.1:{port}")+ try:+ devext.sync(options)+ if watch:+ devext.watch(options, stop_requested)+ except (RuntimeError, OSError) as exc:+ print(f"extension: {exc}", file=sys.stderr)+++def run(+ *,+ port: int,+ no_browser: bool,+ extension_browsers: list[str] | None = None,+ watch_extension: bool = False,+) -> int:if _stop_previous(STATE_PATH):print("Stopped the previous managed Azimut instance.")stopped = _free_port(port)@@ -339,6 +381,12 @@ def run(*, port: int, no_browser: bool) -> int:command = [str(_venv_python(ROOT)), "-m", "azimut.cli", "--port", str(port)]if no_browser:command.append("--no-browser")+ if extension_browsers:+ threading.Thread(+ target=_serve_extension,+ args=(extension_browsers, port, watch_extension, control.stop_requested),+ daemon=True,+ ).start()print(f"Starting Azimut on http://127.0.0.1:{port}")result = _run_process(command, ROOT, control.stop_requested)return 0 if result is None else result@@ -346,17 +394,41 @@ def run(*, port: int, no_browser: bool) -> int:control.close()+def extension_browsers(choice: str | None, watch: bool) -> list[str] | None:+ """Which dev browsers to sync, or None when --ext was not asked for."""+ if choice is None:+ return ["chrome", "firefox"] if watch else None+ return ["chrome", "firefox"] if choice == "all" else [choice]++def main() -> int:parser = argparse.ArgumentParser(description="Rebuild the frontend and relaunch the local Azimut checkout")parser.add_argument("--port", type=int, default=8477)parser.add_argument("--no-browser", action="store_true")+ parser.add_argument(+ "--ext",+ nargs="?",+ const="all",+ choices=["chrome", "firefox", "all"],+ help="load and pair the capture extension in a dev browser (see devext.py)",+ )+ parser.add_argument(+ "--watch-ext",+ action="store_true",+ help="keep reloading the extension on every save (implies --ext)",+ )args = parser.parse_args()if not 1 <= args.port <= 65535:parser.error("--port must be between 1 and 65535")try:- return run(port=args.port, no_browser=args.no_browser)+ return run(+ port=args.port,+ no_browser=args.no_browser,+ extension_browsers=extension_browsers(args.ext, args.watch_ext),+ watch_extension=args.watch_ext,+ )except RuntimeError as exc:print(f"error: {exc}", file=sys.stderr)return 1diff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 5ca6d9a..a3d63de 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.9"+__version__ = "0.3.0"# Cap the pixels Pillow will decode from a file, process-wide. A tiny,# highly-compressed image can otherwise expand to gigabytes in memory and takediff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.pyindex 6fbb7b7..4745b91 100644--- a/src/azimut/api/ingest.py+++ b/src/azimut/api/ingest.py@@ -33,11 +33,12 @@ from typing import Anyfrom urllib.parse import urlsplitfrom fastapi import APIRouter, Depends, Form, Header, HTTPException, Request, Response, UploadFile+from fastapi.responses import FileResponsefrom PIL import Imagefrom .. import __version__, configfrom ..engine import geo, mapsites, media as media_engine, satellite as satellite_engine, tiles-from ..workspace import Case+from ..workspace import Case, CaseErrorfrom . import eventsfrom .cases import get_casefrom .limits import MAX_IMAGE_BYTES@@ -387,6 +388,51 @@ def ingest_bookmark(return {"entity_id": entity["id"], "case_id": case.id, "title": label, "url": url}+# ---- reading back: the attachments a hand-off carries -------------------------++#: The two folders a post's attachments live in. The hand-off names its files by+#: relative path, and this is what keeps that from being a read of the whole case:+#: a proof PNG and case media are what a thread attaches, and a sidecar, a spec or+#: a settings file is not something the extension has any business asking for.+HANDOFF_DIRS = ("media", "proofs")++#: Ceiling for one handed-over file. It travels to the composer as a data URL in a+#: message, so this is a real limit rather than a policy — and a 40 MB clip refused+#: here is a clip the analyst attaches by hand, which is what they did before.+MAX_HANDOFF_BYTES = 24 * 1024 * 1024++[email protected]("/file", dependencies=[Depends(require_token)])+def handoff_file(case_id: str, path: str) -> Response:+ """One case attachment, for the extension to put in a composer.++ The extension holds the pairing token, so it can already file captures and list+ cases; this lets it read back the two folders a post attaches from. Narrow on+ purpose — see ``HANDOFF_DIRS``.++ The fence is on the **resolved** path, not on the string asked for.+ ``resolve_inside`` refuses traversal out of the case, which leaves+ ``media/../case.json`` — inside the case, and not an attachment. Reading the+ prefix off the request would have handed that over.+ """+ case = get_case(case_id)+ try:+ resolved = case.resolve_inside(path)+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ root = case.tool_root.resolve()+ if not any(resolved.is_relative_to(root / folder) for folder in HANDOFF_DIRS):+ raise HTTPException(status_code=403, detail="only media and proofs can be handed over")+ if not resolved.is_file():+ raise HTTPException(status_code=404, detail="file not found")+ if resolved.stat().st_size > MAX_HANDOFF_BYTES:+ raise HTTPException(+ status_code=413,+ detail=f"a handed-over file must be under {MAX_HANDOFF_BYTES // 1024 // 1024} MB",+ )+ return FileResponse(resolved, filename=resolved.name)++# ---- extension download: the packaged source, zipped on request ---------------# Repo checkout first (development), then the copy hatchling ships inside thediff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 4fb6fb8..e96909c 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -155,8 +155,8 @@ def providers() -> list[dict[str, Any]]:"attribution": p.attribution,"max_zoom": p.max_zoom,# deepest zoom with real pixels; null = same as max_zoom. The live- # map hands it to Leaflet's maxNativeZoom, which magnifies the last- # native tile instead of requesting one that doesn't exist.+ # map stops its requests there and magnifies the last native tile+ # instead of asking for one that doesn't exist."max_native_zoom": p.max_native_zoom,"needs_key": p.needs_key,"imagery": p.imagery,@@ -395,8 +395,8 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:# Past the provider's native ceiling there is nothing new upstream: Sentinel# Hub would upsample its own z14 pixels and bill every tile of it. Skip the# fetch and let the climb below magnify the native tile instead — same- # pixels, no quota. The live map already stops asking (Leaflet's- # maxNativeZoom), so this is the guard for anything that doesn't.+ # pixels, no quota. The live map already stops asking at that level, so this+ # is the guard for anything that doesn't.native_z = _native_grid_zoom(provider)beyond_native = max(0, z - native_z) if native_z is not None else 0served = None if beyond_native else _serve_tile(provider, z, x, y)diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex cbecb14..071aefb 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -100,6 +100,7 @@ class PrefsIn(BaseModel):proof_place_auto: bool | None = Nonepost_mention: str | None = None # handle a new post draft is addressed topost_target: str | None = None # social composer a new post draft starts with+ post_prefill: bool | None = None # let the extension fill that composersignature_handle: str | None = None # account handle stamped on opted-in proofs# app self-update pop-up (engine/updates.py) — check on load, and the tag# the user muted with "don't show again"@@ -127,6 +128,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:"proof_place_auto": bool(settings.get("proof_place_auto", True)),"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),"post_target": settings.get("post_target", DEFAULT_POST_TARGET),+ "post_prefill": bool(settings.get("post_prefill", True)),"signature_handle": settings.get("signature_handle", DEFAULT_SIGNATURE_HANDLE),"update_check_on_start": bool(settings.get("update_check_on_start", True)),"update_dismissed_version": settings.get("update_dismissed_version", ""),@@ -256,6 +258,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:settings["post_mention"] = body.post_mention.strip()[:64]if body.post_target is not None:settings["post_target"] = body.post_target+ if body.post_prefill is not None:+ settings["post_prefill"] = bool(body.post_prefill)if body.signature_handle is not None:settings["signature_handle"] = body.signature_handle.strip()[:64]if body.update_check_on_start is not None:@@ -567,7 +571,8 @@ class ImportedSettings(BaseModel):)proof_place_auto: bool = Truepost_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)- post_target: Literal["x", "bluesky", "mastodon"] = DEFAULT_POST_TARGET+ post_target: str = DEFAULT_POST_TARGET+ post_prefill: bool = Truesignature_handle: str = Field(default=DEFAULT_SIGNATURE_HANDLE, max_length=64)ingest_token: str = Field(default="", max_length=128, pattern=r"^[A-Za-z0-9_-]*$")update_check_on_start: bool = True@@ -599,6 +604,19 @@ class ImportedSettings(BaseModel):def strip_short_text(cls, value: str) -> str:return value.strip()+ @field_validator("post_target")+ @classmethod+ def known_target(cls, value: str) -> str:+ """A target this build no longer offers falls back rather than failing.++ Typed as a plain string for that reason: a backup written while Mastodon+ was a target would otherwise be refused *whole* — keys, presets and all —+ over one preference the analyst can set again in a click. The live PUT+ still refuses an unknown target, where the caller is the UI and a wrong+ value is a bug rather than a machine's history.+ """+ return value if value in config.POST_TARGETS else DEFAULT_POST_TARGET+class ImportIn(BaseModel):"""A previously exported backup. Only keys Azimut recognises are applied —diff --git a/src/azimut/api/sheets.py b/src/azimut/api/sheets.pyindex f769e87..fe3773b 100644--- a/src/azimut/api/sheets.py+++ b/src/azimut/api/sheets.py@@ -95,11 +95,19 @@ class SheetSaveIn(BaseModel):def _sheets(case: Any) -> list[dict[str, Any]]:- return [+ """The case's sheets, newest first.++ The same order every other list a tool opens on answers with — captures, proofs,+ sessions, drafts, media. A case builds tables one after another and the one being+ worked on is the one just made; filed order put it at the bottom of the list.+ """+ sheets = [sheet_engine.summary(case, entity)for entity in case.list_entities()if entity.get("type") == "sheet"]+ sheets.sort(key=lambda one: one.get("created_at") or "", reverse=True)+ return sheets@router.get("/{case_id}/sheets")diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 880a795..535c185 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -112,6 +112,12 @@ DEFAULT_SETTINGS: dict[str, Any] = {# The social composer a new post draft starts with. A saved draft keeps its# own target so a later preference change never rewrites it."post_target": "x",+ # Whether Publish lets the capture extension fill that composer — the thread+ # typed in, the proof and the media attached, nothing posted. The only switch+ # for it: the extension keeps none of its own, so this is where the answer+ # lives. On, because with no extension installed it changes nothing — the app+ # opens the intent page as it always did.+ "post_prefill": True,# The handle stamped onto proofs when a proof/template enables it. Empty# means no account-handle slot can render."signature_handle": "",@@ -148,7 +154,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {# frontend/src/lib/coords.js and frontend/src/lib/measure.js.COORD_FORMATS = ("dd", "dms", "mgrs")UNIT_SYSTEMS = ("metric", "imperial")-POST_TARGETS = ("x", "bluesky", "mastodon")+POST_TARGETS = ("x", "bluesky")# Documented monthly free allowances per meter, in billed requests (verified# 2026-07: Google 2D Map Tiles 100k then $0.60/1k, and ≤15k/day; Mapbox Staticdiff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.pyindex fc50682..ddac989 100644--- a/src/azimut/engine/links.py+++ b/src/azimut/engine/links.py@@ -63,15 +63,28 @@ LOST = "lost_sources"#: case already holds, rather than collected. Matched against a media item's recorded#: ``source.type``, which the browse index carries as a column.#:-#: Here rather than in either of the two modules that read it, because both would-#: otherwise keep their own copy and one of them would be wrong: the graph marks these-#: nodes and the Media Library hides these rows, and the two have to mean the same set-#: or the picture and the list disagree about what the case collected. An upload, a-#: download and a satellite capture are original material brought in, and are-#: deliberately not here. A future tool that composes case material joins by stamping-#: its own name and being added to this line.+#: Here rather than in the module that reads it, because the answer is about the+#: derivation chain and this is where that chain is defined. An upload, a download and+#: a satellite capture are original material brought in — bytes gathered rather than+#: written, which is what puts `media` and `capture` in the `collected` family+#: (ONTOLOGY §2) — and are deliberately not here. A future tool that composes case+#: material joins by stamping its own name and being added to this line.MADE_HERE: tuple[str, ...] = ("inspect",)+#: The wider set the **Media Library** holds back: not "composed out of what the case+#: holds" but "produced by the app rather than gathered by the analyst".+#:+#: Two questions, so two sets, and the difference is a capture. The graph asks the+#: first — a node that says it was made here is saying its parents are in the picture —+#: and a capture has no parents to draw: it is imagery, and the ontology files it as+#: collected. The library asks the second, which is *what did I actually bring in*, and+#: there a capture is noise: a geolocation ends with sixty of them beside the handful of+#: files the case collected, and the Satellite tool's own Saved panel is where they are+#: read. The extension's screenshot is the same act through another window — a map view+#: grabbed on purpose, filed as a capture — so it is held back with them. What stays out+#: is material that came from outside: an upload, a paste, a download.+PRODUCED_HERE: tuple[str, ...] = (*MADE_HERE, "satellite", "screenshot")+#: Exact artifact contract. These are not ordinary relations: producing tools#: record them, and the pair decides delete behaviour. A file path resolving to an#: entity outside this matrix is a producer bug, not a reason to widen the graph.diff --git a/src/azimut/engine/sheets.py b/src/azimut/engine/sheets.pyindex 1b0b530..c654f2c 100644--- a/src/azimut/engine/sheets.py+++ b/src/azimut/engine/sheets.py@@ -1448,5 +1448,9 @@ def summary(case: "Case", entity: dict[str, Any]) -> dict[str, Any]:# 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"),+ # `provenance` is what every reader of an entity writes (sqlite_backend+ # `_entity`); `prov` was a key nothing in the codebase has ever produced, so+ # this answered null on every sheet — and the newest-first sort built on it+ # sorted nothing.+ "created_at": (entity.get("provenance") or {}).get("at"),}diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex 503daac..2a724f5 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -191,7 +191,7 @@ def all_providers() -> list[Provider]:# Google Satellite via the Maps JavaScript widget — the only official# Google satellite route for EEA billing accounts (2025-07-08 policy).- # No tiles: the frontend embeds a real google.maps.Map under Leaflet, so+ # No tiles: the frontend runs a real google.maps.Map under its own map, so# capturable=False (fetch_crop has nothing to stitch — captures are the# user's own screenshots, filed with attribution burned in), cacheable is# moot, and the meter counts *map loads*, not tiles. eco_max_zoom=0 turnsdiff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex b75072d..ef7d41c 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -51,7 +51,7 @@ from .store.filters import ()from .store.migrations import _SQLITE_MIGRATIONSfrom .store.rows import (- _MADE_HERE_SQL,+ _PRODUCED_HERE_SQL,_MEDIA_CATEGORIES,_MEDIA_CATEGORY_SQL,_entity_search_text,@@ -2034,7 +2034,7 @@ class SqliteCase:# narrowing, so nothing disappears without a number.scope_where = list(base_where)if collected_only:- base_where.append(f"NOT {_MADE_HERE_SQL}")+ base_where.append(f"NOT {_PRODUCED_HERE_SQL}")# Category and GPS are two independent refinements of that base. Each# one's own facet count leaves itself out and applies the other, so a@@ -2121,7 +2121,7 @@ class SqliteCase:made_here_count = int(conn.execute("SELECT COUNT(*) FROM media_items"- f"{clause([*scope_where, *([category_sql] if category_sql else []), *(['has_gps = 1'] if gps else []), _MADE_HERE_SQL])}",+ f"{clause([*scope_where, *([category_sql] if category_sql else []), *(['has_gps = 1'] if gps else []), _PRODUCED_HERE_SQL])}",base_params,).fetchone()[0])diff --git a/src/azimut/store/rows.py b/src/azimut/store/rows.pyindex 227e35e..ee6e537 100644--- a/src/azimut/store/rows.py+++ b/src/azimut/store/rows.py@@ -76,12 +76,12 @@ _MEDIA_CATEGORY_SQL = {"other": "kind NOT IN ('image', 'video')",}-#: Rows the case **made** rather than collected, as one predicate. The set is the-#: relation layer's (`engine/links.py` MADE_HERE), so the list and the graph cannot-#: come to disagree about what a case collected.-_MADE_HERE_SQL = (+#: Rows the app **produced** rather than ones the analyst gathered, as one predicate.+#: The set is the relation layer's (`engine/links.py` PRODUCED_HERE), which is where the+#: two sets and the reason they differ by a capture are written down.+_PRODUCED_HERE_SQL = ("COALESCE(source_type, '') IN ("- + ", ".join(f"'{route}'" for route in link_engine.MADE_HERE)+ + ", ".join(f"'{route}'" for route in link_engine.PRODUCED_HERE)+ ")")diff --git a/tests/test_devext.py b/tests/test_devext.pynew file mode 100644index 0000000..b9d5273--- /dev/null+++ b/tests/test_devext.py@@ -0,0 +1,248 @@+"""The dev tool that loads the capture extension into a browser.++Nothing here starts a browser: what is worth pinning is the part written by+hand, which is the token lookup, the hand-rolled WebSocket framing and the+choices about where each profile lives.+"""++from __future__ import annotations++import importlib.util+import json+import os+import socket+import sys+import struct+import urllib.error+from pathlib import Path+from typing import Any++import pytest+++SCRIPT = Path(__file__).parents[1] / "scripts" / "devext.py"+SPEC = importlib.util.spec_from_file_location("azimut_devext", SCRIPT)+assert SPEC is not None and SPEC.loader is not None+devext = importlib.util.module_from_spec(SPEC)+# Registered before it runs: its dataclass looks itself up in sys.modules.+sys.modules[SPEC.name] = devext+SPEC.loader.exec_module(devext)+++class FakeResponse:+ def __init__(self, payload: dict[str, Any]) -> None:+ self._payload = json.dumps(payload).encode()++ def read(self) -> bytes:+ return self._payload++ def __enter__(self) -> FakeResponse:+ return self++ def __exit__(self, *_exc: object) -> None:+ return None+++def _settings_file(root: Path, payload: dict[str, Any]) -> None:+ settings = root / ".azimut" / "settings"+ settings.mkdir(parents=True)+ (settings / "settings.json").write_text(json.dumps(payload), encoding="utf-8")+++def test_token_comes_from_the_running_app(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):+ asked: list[str] = []++ def urlopen(request: Any, timeout: float = 0) -> FakeResponse:+ asked.append(request.full_url)+ assert request.get_method() == "POST"+ return FakeResponse({"ingest_token": "from-the-app"})++ _settings_file(tmp_path, {"ingest_token": "from-the-file"})+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ monkeypatch.setattr(devext.urllib.request, "urlopen", urlopen)++ assert devext.pairing_token("http://127.0.0.1:8477") == "from-the-app"+ assert asked == ["http://127.0.0.1:8477/api/settings/ingest-token"]+++def test_token_falls_back_to_settings_when_the_app_is_down(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+):+ def urlopen(*_args: Any, **_kwargs: Any) -> FakeResponse:+ raise urllib.error.URLError("nothing listening")++ _settings_file(tmp_path, {"ingest_token": "from-the-file"})+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ monkeypatch.setattr(devext.urllib.request, "urlopen", urlopen)++ assert devext.pairing_token("http://127.0.0.1:8477") == "from-the-file"+++def test_no_token_anywhere_is_reported_as_none(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+):+ def urlopen(*_args: Any, **_kwargs: Any) -> FakeResponse:+ raise urllib.error.URLError("nothing listening")++ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ monkeypatch.setattr(devext.urllib.request, "urlopen", urlopen)++ assert devext.pairing_token("http://127.0.0.1:8477") is None+++class FakeSocket:+ """A socket whose reads are scripted and whose writes are kept."""++ def __init__(self, incoming: bytes = b"") -> None:+ self.incoming = incoming+ self.sent = bytearray()++ def recv(self, size: int) -> bytes:+ chunk, self.incoming = self.incoming[:size], self.incoming[size:]+ return chunk++ def sendall(self, data: bytes) -> None:+ self.sent += data++ def close(self) -> None:+ return None+++def _websocket(incoming: bytes = b"") -> Any:+ ws = devext.WebSocket.__new__(devext.WebSocket) # no handshake, no network+ ws.sock = FakeSocket(incoming)+ ws.buf = b""+ return ws+++def _server_frame(payload: bytes, opcode: int = 0x1) -> bytes:+ """A frame as a server sends it: final, unmasked, shortest length form."""+ header = bytearray([0x80 | opcode])+ if len(payload) < 126:+ header.append(len(payload))+ elif len(payload) < 1 << 16:+ header += bytes([126]) + struct.pack(">H", len(payload))+ else:+ header += bytes([127]) + struct.pack(">Q", len(payload))+ return bytes(header) + payload+++def test_frames_it_sends_are_masked_text():+ ws = _websocket()+ ws.send("hi")++ sent = bytes(ws.sock.sent)+ assert sent[0] == 0x81 # final frame, text+ assert sent[1] == 0x80 | 2 # masked, two bytes+ mask, masked = sent[2:6], sent[6:]+ assert bytes(b ^ mask[i % 4] for i, b in enumerate(masked)) == b"hi"++[email protected]("size", [4, 200, 70000])+def test_it_reads_back_frames_of_every_length_form(size: int):+ payload = ("x" * size).encode()+ ws = _websocket(_server_frame(payload))++ assert ws.recv() == payload.decode()+++def test_a_ping_is_answered_and_the_next_frame_still_arrives():+ ws = _websocket(_server_frame(b"", opcode=0x9) + _server_frame(b'{"id":1}'))++ assert ws.recv() == '{"id":1}'+ assert bytes(ws.sock.sent)[:2] == b"\x8a\x80" # a masked, empty pong+++def test_a_closed_connection_is_an_error_not_a_hang():+ ws = _websocket(b"")++ with pytest.raises(RuntimeError):+ ws.recv()+++def test_the_browser_can_be_pointed_at_by_hand(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AZIMUT_CHROME", "/somewhere/chrome")+ monkeypatch.setattr(devext.shutil, "which", lambda _name: "/usr/bin/google-chrome")++ assert devext.find_binary("AZIMUT_CHROME", devext.CHROME_NAMES, "chrome") == (+ "/somewhere/chrome"+ )+++def test_without_an_override_the_first_browser_on_path_wins(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AZIMUT_CHROME", raising=False)+ monkeypatch.setattr(+ devext.shutil,+ "which",+ lambda name: "/usr/bin/chromium" if name == "chromium" else None,+ )++ assert devext.find_binary("AZIMUT_CHROME", devext.CHROME_NAMES, "chrome") == (+ "/usr/bin/chromium"+ )+++def test_a_missing_browser_is_reported_rather_than_guessed(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AZIMUT_FIREFOX", raising=False)+ monkeypatch.setattr(devext.shutil, "which", lambda _name: None)+ monkeypatch.setitem(devext.MAC_APPS, "firefox", "/nowhere/firefox")++ assert devext.find_binary("AZIMUT_FIREFOX", devext.FIREFOX_NAMES, "firefox") is None+++def test_the_snap_firefox_keeps_its_profile_where_it_can_read_it(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+):+ """A snap sees only part of $HOME; its own writable area always works."""+ monkeypatch.setattr(devext.Path, "home", classmethod(lambda _cls: tmp_path))+ (tmp_path / "snap" / "firefox" / "common").mkdir(parents=True)++ assert devext.firefox_profile_dir() == tmp_path / "snap/firefox/common/azimut-devext"+++def test_without_a_snap_the_profile_sits_with_the_other_dev_state(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+):+ monkeypatch.setattr(devext.Path, "home", classmethod(lambda _cls: tmp_path))+ monkeypatch.setattr(devext, "STATE", tmp_path / ".cache" / "azimut-devext")++ assert devext.firefox_profile_dir() == tmp_path / ".cache/azimut-devext/firefox"+++def test_a_saved_file_changes_the_fingerprint(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):+ (tmp_path / "background.js").write_text("one", encoding="utf-8")+ monkeypatch.setattr(devext, "EXT", tmp_path)+ before = devext.fingerprint()++ (tmp_path / "background.js").write_text("two", encoding="utf-8")+ os.utime(tmp_path / "background.js", (0, 1))++ assert devext.fingerprint() != before+++def test_a_browser_that_never_answers_is_given_up_on():+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ free_port = probe.getsockname()[1]++ assert devext.wait_for_port(free_port, timeout=0.5) is False+++def test_a_fresh_background_is_the_proof_the_reload_landed(capsys: pytest.CaptureFixture[str]):+ devext.report_background("chrome", json.dumps(["0.3.0", 640]))++ assert "restarted 0.6s ago, running v0.3.0" in capsys.readouterr().out+++def test_an_old_background_is_called_out_rather_than_celebrated(+ capsys: pytest.CaptureFixture[str],+):+ devext.report_background("firefox", json.dumps(["0.3.0", 90_000]))++ assert "kept the code it had" in capsys.readouterr().out+++def test_a_sleeping_background_says_so(capsys: pytest.CaptureFixture[str]):+ devext.report_background("chrome", None)++ assert "background asleep" in capsys.readouterr().outdiff --git a/tests/test_graph.py b/tests/test_graph.pyindex 65d22f3..f92d5c1 100644--- a/tests/test_graph.py+++ b/tests/test_graph.py@@ -1096,6 +1096,26 @@ def test_collected_material_carries_no_origin(client):assert "origin" not in node and "op" not in node+def test_a_capture_carries_no_origin_either(client):+ """The two sets differ by exactly this node (`links.PRODUCED_HERE`). A node saying+ it was made here is saying its parents are in the picture, and a capture has none:+ it is imagery, filed as collected. The Media Library still holds it back, because+ the question there is what the analyst gathered."""+ from PIL import Image++ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = _case(client, "capture origin")+ capture = media_engine.import_image(+ Case.open(cid), Image.new("RGB", (32, 24)), "map.png",+ {"type": "satellite"}, entity_type="capture", dedupe=False,+ )["item"]++ node = _node(_graph(client, cid), _entity_at(client, cid, capture["path"]))+ assert "origin" not in node and "op" not in node++def test_a_media_entity_the_index_never_saw_claims_no_origin(client):"""Unlike the kind, nothing writes the route to the entity, so there is nofallback to read — and a default here would be the drawing inventing where adiff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.pyindex bc8c6ec..851027a 100644--- a/tests/test_ingest_api.py+++ b/tests/test_ingest_api.py@@ -402,3 +402,45 @@ def test_extension_zip_serves_the_packaged_runtime_files(client):# the dev harness must not reach an installed browserassert not [n for n in names if "node_modules" in n or n.endswith(".test.js")]assert "package.json" not in names+++def _upload(client, cid, name, data):+ return client.post(+ f"/api/cases/{cid}/media/upload",+ files={"file": (name, io.BytesIO(data), "image/png")},+ ).json()["item"]+++def test_the_extension_reads_back_the_attachments_a_thread_carries(client):+ """The hand-off names files by path and the extension fetches the bytes with+ its own token, so no case file ever passes through the composer's page."""+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Hand-off"}).json()["id"]+ item = _upload(client, cid, "clip.png", _png_bytes())++ r = client.get(+ "/api/ingest/file",+ params={"case_id": cid, "path": item["path"]},+ headers={"X-Azimut-Token": token},+ )+ assert r.status_code == 200+ assert r.content == _png_bytes()+ # the same wall as every other ingest route+ assert client.get("/api/ingest/file", params={"case_id": cid, "path": item["path"]}).status_code == 401+++def test_reading_back_reaches_attachments_and_nothing_else(client):+ """A proof PNG and case media are what a post attaches. A sidecar, a spec or a+ settings file is not something a composer has any business asking for, and+ traversal is refused before the prefix is even consulted."""+ token = _token(client)+ cid = client.post("/api/cases", json={"name": "Narrow"}).json()["id"]+ headers = {"X-Azimut-Token": token}++ for path in ("case.json", "inspect/session.json", "../../secrets.txt", "media/../case.json"):+ r = client.get("/api/ingest/file", params={"case_id": cid, "path": path}, headers=headers)+ assert r.status_code == 403, path+ missing = client.get(+ "/api/ingest/file", params={"case_id": cid, "path": "proofs/nothing.png"}, headers=headers+ )+ assert missing.status_code == 404diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex b7f43ab..e8a0b23 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -9,7 +9,7 @@ import graph_readimport pytestimport time-from jobwait import job_result, wait_for_job+from jobwait import WAIT, job_result, wait_for_jobfrom PIL import Imagefrom azimut.engine.media import safe_filename@@ -409,26 +409,30 @@ def test_leaving_them_out_scopes_the_counts_too(client):assert page["facets"]["kind_counts"]["image"] == 1-def test_leaving_them_out_does_not_touch_collected_material(client):- """A satellite capture is original imagery brought into the case, not something- composed out of what the case already holds. Same for a download and an import."""+def test_a_capture_is_a_file_the_case_produced_itself(client):+ """The app drew those pixels out of tiles it fetched, and a geolocation ends with+ dozens of them. The extension's screenshot is the same act through another window,+ filed as a capture too, so it is held back with them. What stays is the material+ that came from outside."""from azimut.engine import media as media_enginefrom azimut.workspace import Casecid = client.post("/api/cases", json={"name": "Untouched"}).json()["id"]upload = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]- capture = media_engine.import_image(- Case.open(cid),- Image.new("RGB", (32, 24)),- "map.png",- {"type": "satellite"},- entity_type="capture",- dedupe=False,- )["item"]+ case = Case.open(cid)+ media_engine.import_image(+ case, Image.new("RGB", (32, 24)), "map.png",+ {"type": "satellite"}, entity_type="capture", dedupe=False,+ )+ media_engine.import_image(+ case, Image.new("RGB", (32, 24)), "maps-screen.png",+ {"type": "screenshot", "imagery_mode": "satellite"},+ entity_type="capture", dedupe=False,+ )page = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()- assert {item["path"] for item in page["items"]} == {upload["path"], capture["path"]}- assert page["facets"]["made_here_count"] == 0+ assert {item["path"] for item in page["items"]} == {upload["path"]}+ assert page["facets"]["made_here_count"] == 2def test_the_switch_reads_how_a_file_entered_not_everything_true_about_it(client):@@ -1929,7 +1933,15 @@ def test_concurrent_sidecar_merges_do_not_drop_each_other(client, monkeypatch):for t in threads:t.start()for t in threads:- t.join(timeout=10)+ # A join that gives up does not stop the thread: it goes on writing into a+ # case the teardown is about to delete, which on Windows is a locked+ # `case.db` and a temp directory that cannot be removed — reported as an+ # error against whichever test happened to be running. Ten seconds was+ # this machine's budget for forty merges; the Windows shard commits each+ # one at `synchronous = FULL` and wants the suite's own. A writer that+ # really is stuck now says so here, where the stack still means something.+ t.join(timeout=WAIT)+ assert not t.is_alive(), "a sidecar writer never finished"item = media_engine.read_item(case, rel)assert item["thumbnail"] == "media/.thumbs/x.jpg"diff --git a/tests/test_relaunch.py b/tests/test_relaunch.pyindex 94205b6..7f391ce 100644--- a/tests/test_relaunch.py+++ b/tests/test_relaunch.py@@ -191,3 +191,19 @@ def test_windows_npm_wrapper_uses_cmd(monkeypatch: pytest.MonkeyPatch):"run","build",]+++ ("choice", "watch", "expected"),+ [+ (None, False, None),+ (None, True, ["chrome", "firefox"]),+ ("all", False, ["chrome", "firefox"]),+ ("chrome", False, ["chrome"]),+ ("firefox", True, ["firefox"]),+ ],+)+def test_which_dev_browsers_the_extension_flags_ask_for(+ choice: str | None, watch: bool, expected: list[str] | None+):+ assert relaunch.extension_browsers(choice, watch) == expecteddiff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pyindex f764053..2529e85 100644--- a/tests/test_settings_backup.py+++ b/tests/test_settings_backup.py@@ -297,12 +297,14 @@ def test_import_canonicalizes_known_fields_and_ignores_future_provider_keys(clie("home_view", {"lat": 91.0, "lon": 0.0, "zoom": 12}),("eco_max_zoom", 99),("coord_format", "utm"),- ("post_target", "threads"),("update_check_on_start", 1),("tile_providers", [{"id": "bad id", "url": "https://tiles/{z}/{x}/{y}"}]),],)def test_import_rejects_malformed_known_fields_without_partial_write(client, field, value):+ """Malformed means the shape is wrong — a latitude past the pole, a negative+ count, an id with a space. A publishing target this build no longer offers is+ not that: it is a value Azimut wrote itself, and the test below restores it."""before = config.settings_path().read_bytes()response = client.post("/api/settings/import",@@ -334,3 +336,23 @@ def test_a_signature_no_gate_ever_saw_is_left_out_of_the_backup(client):# the real thing still travelspath.write_bytes(PNG)assert base64.b64decode(client.get("/api/settings/export").json()["signature_png"]) == PNG+++def test_a_backup_naming_a_dropped_target_still_restores(client):+ """Mastodon was a publishing target and is not one any more. A backup written+ while it was is a whole machine's settings — keys, presets, export folders —+ and refusing all of it over one preference the analyst re-picks in a click is+ not a portability boundary, it is a wall."""+ token = client.post("/api/settings/ingest-token").json()["ingest_token"]+ r = client.post(+ "/api/settings/import",+ json={"settings": {"post_target": "mastodon", "post_mention": "@GeoConfirmed"}},+ )+ assert r.status_code == 200, r.text+ assert sorted(r.json()["imported"]) == ["post_mention", "post_target"]+ assert client.get("/api/settings").json()["post_target"] == "x"+ assert token # and nothing else in the file was lost to the refusal++ # The live route is the other side of that: there the caller is the UI, and a+ # target it does not offer is a bug rather than a machine's history.+ assert client.put("/api/settings/prefs", json={"post_target": "mastodon"}).status_code == 422diff --git a/tests/test_sheet_from_proofs.py b/tests/test_sheet_from_proofs.pyindex ad0bf0f..ee4e2e4 100644--- a/tests/test_sheet_from_proofs.py+++ b/tests/test_sheet_from_proofs.py@@ -327,7 +327,12 @@ def test_two_sheets_built_the_same_way_are_told_apart(client):build(client, case_id)listed = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]- assert [entry["title"] for entry in listed] == [+ # Sorted, because the order is not this test's business and is not stable for+ # three sheets built in the same breath: the list answers newest first, and a+ # creation stamp is second-resolution, so whether these three separate at all+ # depends on which side of a tick they land. Ordering is covered on its own+ # (test_sheets.py, the list opens on the sheet just made).+ assert sorted(entry["title"] for entry in listed) == ["My geolocations","My geolocations-2","My geolocations-3",diff --git a/tests/test_sheet_proofs.py b/tests/test_sheet_proofs.pyindex fa4807f..7fdf189 100644--- a/tests/test_sheet_proofs.py+++ b/tests/test_sheet_proofs.py@@ -17,7 +17,7 @@ import jsonimport randomimport zlib-from jobwait import job_result+from jobwait import WAIT, job_resultfrom PIL import Imagefrom test_sheet_bridge import (@@ -793,7 +793,7 @@ def test_a_cancelled_press_keeps_the_rows_it_finished_and_leaves_no_half_row(def wait(url):if url == "https://ex.org/slow":reached.set()- held.wait(10)+ held.wait(WAIT)stub_downloads(monkeypatch, before=wait)case_id = make_case(client)@@ -810,7 +810,9 @@ def test_a_cancelled_press_keeps_the_rows_it_finished_and_leaves_no_half_row(f"/api/cases/{case_id}/sheets/{sheet['id']}/proofs", json=build_body(sheet))job_id = started.json()["job_id"]- assert reached.wait(10)+ # The press has to have started before the cancel means anything, and the+ # Windows shard spends twenty times longer getting there than this box does.+ assert reached.wait(WAIT)assert client.post(f"/api/jobs/{job_id}/cancel").json() == {"stopped": True}held.set()result = job_result(client, job_id)diff --git a/tests/test_sheets.py b/tests/test_sheets.pyindex 0818a62..21cb0bc 100644--- a/tests/test_sheets.py+++ b/tests/test_sheets.py@@ -1172,6 +1172,24 @@ def test_the_list_says_how_big_each_sheet_is(client):assert listed[0]["columns"] == 3+def test_the_list_opens_on_the_sheet_just_made(client, monkeypatch):+ """Newest first, the order every other list a tool opens on answers with —+ captures, proofs, sessions, drafts, media. A case builds tables one after+ another and the one being worked on is the one just made; filed order put it+ at the bottom, under everything the case had ever built."""+ case_id = make_case(client)+ for at, title in (+ ("2026-07-01T09:00:00Z", "First"),+ ("2026-08-10T09:00:00Z", "Second"),+ ("2026-09-02T09:00:00Z", "Third"),+ ):+ monkeypatch.setattr("azimut.sqlite_backend._now", lambda at=at: at)+ new_sheet(client, case_id, title)++ listed = client.get(f"/api/cases/{case_id}/sheets").json()["sheets"]+ assert [one["title"] for one in listed] == ["Third", "Second", "First"]++def test_renaming_a_sheet_moves_its_table_and_its_sidecar(client):case_id = make_case(client)sheet = new_sheet(client, case_id, "Candidates")diff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.pyindex 7275dc8..e5dfb78 100644--- a/tests/test_thumbnails.py+++ b/tests/test_thumbnails.py@@ -17,6 +17,8 @@ import timeimport pytestfrom PIL import Image+from jobwait import WAIT+from azimut import layoutfrom azimut.engine import media as media_enginefrom azimut.engine import thumbnails, workqueue@@ -200,14 +202,18 @@ def test_worker_wakes_and_drains_in_the_background(tmp_workspace, monkeypatch):c = Case.create("Worker")item = _register_video(c)["item"] # enqueues + wakes the worker- deadline = time.time() + 5+ # The worker's own budget, not this test's guess: five seconds is what a+ # developer's machine spends here and what a loaded ubuntu runner does not,+ # so the shard failed on a thumbnail that was still being written. Same+ # wall clock as every other job the suite waits on (`jobwait`).+ deadline = time.time() + WAITwhile time.time() < deadline:if media_engine.read_item(c, item["path"])["thumbnail"]:breaktime.sleep(0.05)refreshed = media_engine.read_item(c, item["path"])assert refreshed["thumbnail"] and c.resolve_inside(refreshed["thumbnail"]).exists()- assert workqueue.wait_until_idle()+ assert workqueue.wait_until_idle(WAIT)# -- videos shorter than the seek -----------------------------------------diff --git a/tests/test_updates.py b/tests/test_updates.pyindex 37ed0d5..bee80bb 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.9"-EXTENSION_PAYLOAD = "783876649d02d0b8b06f34fb10d01bbb23633601e86cdff5adcd7d79fda2be1c"+EXTENSION_VERSION = "0.3.0"+EXTENSION_PAYLOAD = "a72c26be5fe65eabb122ac9c8ff24fde1378f74f94bc7efecc164b208afe3c09"# 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.