Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Draw Azimut's own tools over someone else's map, and open the app on the case (#73)

OsintMeThatac8b648cba13
diff --git a/.gitignore b/.gitignore
index 2f200d8..0e7535f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,6 +24,10 @@ npm-debug.log*
playwright-report/
test-results/
+# Browser profile the map-site calibration keeps, so each consent wall is
+# dismissed once rather than every run (frontend/calibration/record.mjs)
+.calibration-profile/
+
# Editors / IDE
.idea/
*.swp
@@ -58,6 +62,10 @@ build-bin/
# Native binaries downloaded by the release workflow
packaging/vendor/
+# Signed extension, downloaded from AMO at release cut and uploaded to the
+# release. The update manifest beside it (packaging/updates.json) is tracked.
+dist-xpi/
+
# Local-only marketing/presentation assets, never pushed
.docs/
diff --git a/README.md b/README.md
index 9816a4d..a1f47d5 100644
--- a/README.md
+++ b/README.md
@@ -58,7 +58,7 @@ to fix a point on the map.*
| **Sheet** | The case's own CSVs in a plain grid: a comparison table, a worklist with its own state, or the half-facts too soft to be entities. Columns can be typed, a workbook arrives one sheet per tab, and a declared sheet promotes into entities, places and dated statements. A worklist can also be built back out of what the case holds. |
| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Public media is fetched cookie-less; a login-walled post prompts once for a browser session or an exported `cookies.txt`. Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
| **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |
-| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. Nothing uploads on its own. |
+| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. With the capture extension, pressing an engine opens it with the picture already in it. Nothing leaves the machine until you press one. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
| **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. |
@@ -234,9 +234,26 @@ A browser extension (Chrome/Edge and Firefox) captures external map sites
straight into a case: Google Maps & Earth, Bing, Yandex, OSM, Apple Maps,
Zoom Earth, Copernicus Browser and Satellites.pro, one screenshot per click
with coordinates parsed from the URL. It also powers the Capture button on
-the Google (Maps JS) basemap. Install it from **Settings → Capture extension**
-(download the zip, load unpacked, pair with the token shown there); full
-instructions in [extension/README.md](extension/README.md).
+the Google (Maps JS) basemap, fills a composer with a thread Geo Report
+prepared, and opens a reverse-image engine with a picture from the case.
+
+On a 2D map it can draw Azimut's own tools over the site: measure, the case's
+saved points, sun and moon, a search grid that opens in the app afterwards, and
+reference windows holding the case's own images and videos beside the imagery.
+The scale is measured off the map rather than assumed, so the tools switch
+themselves off — with the reason shown — on a view they cannot compute on.
+
+On Chrome, Edge and Brave, install it from **Settings → Capture extension**: the
+app writes the extension into a folder it owns, you load that folder unpacked
+once and paste the pairing token. Because the app owns the folder, later updates
+are one button — it rewrites the files and the extension restarts itself.
+
+Firefox refuses an unsigned extension and forgets an unpacked one on exit, so it
+installs the signed `azimut-capture-<version>.xpi` from the
+[latest release](https://github.com/OsintMeThat/azimut/releases/latest) instead.
+That copy is sealed, so the update button does not apply to it: Firefox reads
+Azimut's own update manifest and replaces the add-on itself. Full instructions in
+[extension/README.md](extension/README.md).
## Building & releasing
@@ -259,12 +276,55 @@ it back, and the release tag must match it.
The capture extension keeps **its own** version: the app release that last
changed a shipped file, so it lags whenever the extension is left alone.
-Settings reads "bundled newer than installed" as "go reinstall the unpacked
-folder", which is worth saying once and never for a zip that hasn't moved.
-`tests/test_updates.py` digests what `extension.zip` carries and fails either
-way — a change without a bump, or a bump without a change. When you do change
-the extension, set `extension/manifest.json` to the current app version and
-record the digest the failing test prints.
+`tests/test_updates.py` digests what the extension ships and fails either way —
+a change without a bump, or a bump without a change. When you do change the
+extension, set `extension/manifest.json` to the current app version and record
+the digest the failing test prints.
+
+Within a development cycle that version cannot move: it is already the app's own.
+So the update button compares the **digest** instead, which the installed folder
+records in its `install.json` — meaning any edit under `extension/` shows up as
+an available update immediately, with no bump and no restart. That is also the
+loop for testing the updater (`docs/superpowers/specs/2026-09-10-extension-self-update-design.md`).
+
+### Signing the extension for Firefox
+
+Firefox Release enforces extension signing with no override, so the Firefox copy
+is an XPI signed by Mozilla and served from the release. Signing is decoupled
+from publishing: `--channel unlisted` runs automated validation, puts no listing
+on addons.mozilla.org, and hands the file back.
+
+Run it **after** the release carrying that version exists, from a checkout of the
+tag, with credentials from the AMO developer hub:
+
+```bash
+export AMO_JWT_ISSUER=... AMO_JWT_SECRET=...
+python3 scripts/sign_extension.py # signs, writes packaging/updates.json
+gh release upload v0.3.0 dist-xpi/azimut-capture-0.3.0.xpi
+```
+
+Then commit `packaging/updates.json`. That file is what
+`browser_specific_settings.gecko.update_url` points at, served raw from `main`,
+and Firefox re-reads it about once a day — so a release that changed the
+extension is not delivered to Firefox users until it lands on the branch.
+
+Two rules the script enforces rather than trusts:
+
+- **It signs what the extension ships**, not the `extension/` directory —
+ `extinstall.shipped_files()`, so the XPI, the .zip and the folder the app owns
+ are the same bytes.
+- **A version is signed once.** AMO refuses a second copy of one it already has,
+ and the extension's version deliberately stays put across releases that leave
+ it alone, so the script stops with that reason instead of failing mid-upload.
+
+The add-on id in `extension/manifest.json` is permanent: AMO reserves it at the
+first signature, and changing it later is a different add-on that loses every
+pairing. `tests/test_extension_signing.py` gates the id, the update URL and the
+manifest's shape.
+
+Nothing about this touches development. `scripts/devext.py` still loads
+`extension/` straight into a dev Firefox as a temporary add-on, which needs no
+signature.
### Dependencies
diff --git a/docs/MAP_SITES.md b/docs/MAP_SITES.md
new file mode 100644
index 0000000..0abd74c
--- /dev/null
+++ b/docs/MAP_SITES.md
@@ -0,0 +1,280 @@
+# Map sites: what their URLs say, and what they really mean
+
+Azimut reads other people's maps twice: the **Open in…** panel writes a URL to
+send you to one, and the capture extension's **map tools** draw over one from
+what its address bar says. Both depend on knowing exactly what each site writes
+down, so this is the record of what each one was *observed* doing — not what its
+documentation claims.
+
+**How this was established.** Every site below was driven in a real browser:
+opened at a known level, dragged a known number of pixels, zoomed about a known
+pixel, and read back out of the address bar after each step. The recordings are
+kept in `tests/fixtures/map-sites.json` and both test suites replay them —
+`tests/test_mapsites.py` that the parse still returns those views,
+`frontend/src/lib/extensionMapFrame.test.js` that the arithmetic puts them back
+where the browser had them.
+
+**And it can be established again.** The gesture sequence is written down
+(`frontend/calibration/protocol.mjs`) and run by `npm run calibrate:maps`, so
+the day a site moves its panel or changes its URL form, the answer is a re-run
+rather than an afternoon with a browser. See *Recalibrating* at the end.
+
+## What each site writes
+
+| Site | URL | Order | Scale |
+|---|---|---|---|
+| Google Maps | `google.com/maps/@47.388462,2.352785,15z` | lat, lon | `z`, tile level, up to 2 decimals |
+| Google Maps (satellite) | `…/@47.388462,2.352785,3231m/data=!3m1!1e3` | lat, lon | `m`, **the viewport's height in metres** |
+| Google Earth | `earth.google.com/web/@47.388462,2.352785,150a,3000d,1y,0h,0t,0r` | lat, lon | `d`, camera distance; `a` ground altitude, `h/t/r` heading, tilt, roll |
+| Apple Maps | `maps.apple.com/frame?center=47.388462,2.352785&span=0.029055,0.056434&map=satellite` | lat, lon | `span`, the region in degrees (lat delta first) |
+| Bing Maps | `bing.com/maps?cp=47.388462~2.352785&lvl=15.4&style=h` | lat`~`lon | `lvl`, tile level, 1 decimal |
+| Yandex | `yandex.com/maps/?ll=2.352785,47.388462&z=15&l=sat` | **lon, lat** | `z`, tile level |
+| Copernicus Browser | `browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279` | named | `zoom`, tile level |
+| Zoom Earth | `zoom.earth/maps/satellite/#view=47.388462,2.352785,11z` | lat, lon | `z`, tile level |
+| Satellites.pro | `satellites.pro/plan/France_map#47.388462,2.352785,15` | lat, lon | third field, tile level |
+| OpenStreetMap | `openstreetmap.org/#map=15/47.38846/2.35279` | zoom, lat, lon | `map=`, tile level first |
+
+Every "tile level" above is the same number: 256-pixel tiles, one tile of the
+world at zoom 0. That was checked, not assumed — each site was dragged a known
+number of pixels and asked where it had landed, and every one of them answered
+within a tenth of a percent of the level it was quoting.
+
+## The traps
+
+**Apple never rewrites its `z`.** Open a link with `z=15`, zoom twice, and the
+address bar still says 15 while `span` has quartered. The span is the live
+number; `z` is only true for the view the link opened, and is dropped the moment
+a span appears (`engine/mapsites.py`, `_apple_maps`).
+
+**Google's satellite view states metres, not a level.** `,3231m` is how tall the
+viewport is on the ground. A 1000-pixel window at level 15 and latitude 47.39
+covers 3233 m, which is where that number comes from — so with the window's
+height it is a zoom, exact to the metre it is rounded to, and without it, it is
+nothing. Passing metres where a zoom belongs is how the old "Open in Google
+Satellite" link landed everyone at the same 2 km view whatever they were
+looking at.
+
+**Yandex writes longitude first.** Read `ll` as lat,lon and the pin lands in
+another country.
+
+**Zoom Earth opens its weather layer** unless the path says `/maps/satellite/`,
+and that layer stops at level 11: ask for 15 and it will quietly clamp.
+
+**Satellites.pro answers a bare link with a country path of its own**
+(`/plan/France_map#…`), keeping the fragment. `/plan/` is an OpenStreetMap road
+map, not imagery, so a capture from that path is not recorded as satellite.
+
+**Copernicus rewrites its URL on a zoom but not on a pan**, and rounds its
+coordinates to five decimals (about a metre). Its 2D map is Leaflet, so
+EPSG:3857; its 3D terrain viewer writes `terrainViewerSettings` into the URL,
+which is what tells the tools to stand down.
+
+**Bing rounds the zoom it writes.** Its wheel moves a third of a level and its
+URL carries one decimal, so `lvl=15.3` is really 15.334 — measured, six notches
+of it, in `tests/fixtures/map-sites.json`. A fortieth of a level is two and a
+third percent of scale: nothing at the middle of the screen, five metres at the
+edge of a 1600-pixel window at level 18. Whole levels are exact on every site
+here, Bing included; the tools work the fraction out for themselves from the
+pixel the zoom held still (`extension/mapmath.js`, `zoomFromAnchor`).
+
+**Google Earth is a globe with terrain.** `d` halves for every level zoomed in,
+which carries a measured scale through a zoom, but turning it into a ground
+scale needs a field of view no URL states. Level and close in, the tools measure
+it; pitched, they refuse.
+
+**`d` moves when nobody zoomed.** It is the distance to the ground, and the
+ground has hills in it: pan across one and Earth rewrites `d` by more than the
+one percent that otherwise means the view changed scale. Which is true — closer
+ground is drawn larger — so the ratio of two distances is a real correction and
+is applied as one. What it must not do is throw away the drag that arrived with
+it: that drag is the only way this view is ever measured, and discarding it left
+the panel asking for a pan it had already been given, for ever, over any terrain
+that was not flat. So a reading that carries nothing keeps the drag instead
+(`extension/mapoverlay.js`).
+
+**"Level" carries a tolerance, and has to.** These viewers write the camera they
+are actually holding, at full precision, and they do not come back to a clean
+zero — a turn of Earth's compass leaves a fraction of a degree of pitch behind
+it. Read as pitched, that is a tool which switches itself off whenever the view
+is turned, telling the analyst to level a view that already looks level. So a
+pitch up to `LEVEL_TILT_DEG` is a map: a pitched camera stretches the ground away
+from the centre by roughly `0.6 · tan θ` across half of Earth's 35° field, which
+is two percent at the two degrees allowed and eleven at ten. Past it the panel
+refuses, and it says so in the viewer's own words — these tools are 2D — rather
+than in the degrees it read, which name no button anyone can press.
+
+**Turning the compass is not zooming it.** Earth is also the one view whose
+`h` an analyst drags, and a scale is pixels per degree along the *world's* axes
+— so a turn changes which way the screen looks at the ground and nothing about
+how big it is drawn. Every measurement therefore undoes the bearing before it
+divides: a drag's travel, a zoom's held pixel, the offset a centre is solved
+from (`extension/mapmath.js`, `unturn`). Read raw, a drag on a map turned 30°
+measured a scale a third out, the next pan missed its prediction, and the tools
+switched themselves off — which is what turning Earth used to do. What is still
+refused is a single gesture that turned *and* zoomed: one offset, two bearings,
+and nothing in the address bar to say which did what.
+
+## Where each site draws its centre
+
+The coordinate in the address bar is not under the middle of the window. Five of
+the eight put it somewhere else, because their own chrome takes part of the
+screen and the map is centred in what is left — and this is invisible to any
+amount of scale accuracy, since a pan slides the offset along with the map.
+
+| Site | Camera centre, 1600×1000 | Why |
+|---|---|---|
+| Google Maps | 800, 500 | the map fills the window; its place panel covers it without moving it |
+| Apple Maps | 867, 500 | a left sidebar, and a region narrower than the window |
+| Bing Maps | 800, 540 | an 81 px header above the map |
+| Yandex | 1010, 510 | a 420 px results panel |
+| Copernicus Browser | 1025, 500 | a 450 px panel |
+| OpenStreetMap | 800, 527 | a 55 px header |
+| Satellites.pro | 800, 500 | full-window Leaflet |
+| Zoom Earth | 800, 500 | full window |
+
+The extension does not ship this table: a panel can be collapsed and a layout
+can change, so it **measures** the offset instead, from the one gesture that can
+see it. A zoom holds one pixel still while the centre moves underneath, which is
+enough to solve for the pixel the centre is drawn at (`extension/mapmath.js`,
+`centreFromZoom`). It is measured on the first zoom, remembered per site and per
+window shape, and re-measured on every zoom after. The table is here as the
+record of what those measurements found, and as what the tests replay.
+
+**A zoom is one gesture and several readings.** These sites ease into a zoom
+over a few hundred milliseconds and rewrite the address bar while they are doing
+it: the new level lands as the wheel turns, the centre catches up when the camera
+stops. Solved from the first of those readings, the offset comes out wherever the
+camera was passing — Yandex measured 238 px wide of its real 210. Nothing
+downstream catches it, because the reading that corrects the centre carries the
+same level and so reads as a pan, and a pan cannot see the offset: it slides with
+the map and cancels. So the answer is held for `FRAME_QUIET_MS`, re-solved from
+every reading that arrives in the meantime, and only the one the address bar
+stops on is kept. The recorder already waited for quiet rather than for a change
+(`calibration/protocol.mjs`, `settle`); the panel now does too.
+
+**A pan the site never reports measures nothing.** Copernicus rewrites its URL
+on a zoom but not on a pan, and until a URL arrives the canvas carries the
+difference. A zoom taken in that state would be solved against a view from
+before the pan, putting the centre out by the whole of it, so it is allowed to
+move the drawing and not to measure it (`mapoverlay.js`, `adrift`).
+
+**A smaller window is not a smaller offset.** Driven again at 1200×760, Yandex's
+panel was still 420 px and OpenStreetMap's header still 55, so both offsets came
+back unchanged — while Apple's sidebar collapsed and its offset moved 70 px,
+which is 21 m of ground at level 18. Nothing in any address bar says which of
+those a site is, which is the whole argument for measuring rather than tabling
+it. So an offset is filed under the window it was measured in, and the last four
+window shapes are kept: reshape the window and the panel asks for another zoom,
+put it back and the offset it already has comes straight back
+(`extension/mapoverlay.js`, `onResize`). Until one is measured for the window in
+front of the analyst, the status line says "zoom once to place it" and its
+tooltip carries the offset the panel is drawing from. The drawing itself is not
+dimmed: a wheel notch is a third of a level on some of these sites, so that wait
+runs to several gestures, and a translucent drawing through all of them reads as
+a broken tool rather than a careful one.
+
+**The browser's own zoom is a smaller window.** At 125% the page is laid out in
+fewer CSS pixels, and CSS pixels are the only unit any of this works in: the
+drawing, the pointer, the offsets above. So a zoomed browser needs no case of
+its own, and a screen with two or three dots to the pixel needs none either —
+the ratio reaches the canvas's backing store (`extension/mapdraw.js`) and
+nothing else. Both claims are held by tests rather than by this paragraph
+(`extensionMapEngine.test.js`, `e2e/map-calibration.spec.js`).
+
+**How tall the map is, is measured too.** A map centred in what its chrome
+leaves is centred by exactly half of what the chrome took, so Bing's camera
+sitting 40.5 px low *is* the measurement of its 81 px header. That matters for
+the two views that state a size rather than a level: a span and a height in
+metres are only a scale next to the number of pixels they were drawn in, so the
+panel hands the app the map's height rather than the window's
+(`extension/mapoverlay.js`, `mapHeight`), and re-reads the scale when the window
+changes.
+
+## What limits the accuracy
+
+The drawing is only ever as good as the numbers the site writes, so this is
+where the error actually comes from, worst first.
+
+| Source | Size | Where it bites |
+|---|---|---|
+| The coordinate's own rounding | Copernicus and OpenStreetMap write five decimals (~1.1 m); Apple, Bing, Yandex and Satellites.pro six (~11 cm); Google seven | everything, evenly — it moves the whole drawing |
+| A rounded zoom | Bing only, up to 2.3% until the fraction is worked out | grows outward from the middle of the screen |
+| The camera centre | measured to about a tenth of a pixel, a pixel on the two sites that round their coordinates | everything, evenly |
+| The site's own imagery | metres, sometimes, and not ours to fix | everything |
+
+At level 18 a pixel is 0.3 m and at 17 it is 0.6 m, which puts the app's own
+share of the error under a metre at the zooms anyone pins a building down at.
+`frontend/src/lib/extensionMapFrame.test.js` holds that as a gate: every
+recorded site, inside one metre of ground at level 18.
+
+What none of this covers is relief on a 3D camera, and no measurement can: a
+level camera still pushes a hilltop outward from the centre of the screen by its
+own height, and no URL says how tall the ground is.
+
+## Zoomed out, where the map becomes a globe
+
+Google and Bing stop drawing a flat map somewhere around level 8 and start
+drawing a globe, and Earth is a globe from the start; their URLs go on quoting a
+zoom either way, so the zoom is the only warning there is.
+
+Out there the drawing is **kept, dimmed, and labelled** rather than refused. A
+globe and a Mercator agree at the point they are anchored on and part company
+away from it, so the middle of the screen is right and the edges drift — which
+is exactly the trade worth making for a look at a whole region's marks at once,
+with the zoom that makes it exact one gesture away. The panel says "drifts at
+the edges out here" and the canvas drops to just over half strength, so nothing
+about it reads as placed.
+
+Two things it does not do out there: it never *measures* anything from a view
+that far out — the camera centre and the rounded-zoom correction are both taken
+in close, where the site is drawing the flattening it names — and it never stops
+refusing a pitched or panoramic camera, which has no ground plane at all.
+
+## Recalibrating
+
+Everything above is a measurement of nine sites nobody here controls, and it
+ages. Run it again when a site's drawing looks displaced, when its URL form
+changes, or every few months on principle.
+
+```
+cd frontend && npm run calibrate:maps # drives the sites, headed
+python scripts/build_map_fixture.py # parses what they wrote, solves the camera
+npm test && python -m pytest tests/test_mapsites.py
+```
+
+The whole matrix is ten runs — the nine sites, Google twice for its satellite
+view — across seven windows and two browsers: about an hour of driving, plus
+whatever each consent wall asks of you. It is merged by key, so `--sites yandex`
+an afternoon later costs a minute.
+
+The run is **headed and slow on purpose**. It opens each site at the same point
+in the Cher, drags it a fifth of the window, and zooms about two pixels in the
+right half — clear of every panel these sites have ever had — then reads the
+address bar after each step. It clicks no consent wall: when a site puts one up
+the run says which site it is waiting on and waits for you, and `--profile`
+keeps the answer for next time. A site whose address bar barely moved is named
+on the spot, while the browser is still open and you can see what it is showing.
+
+| The matrix | What it is there for |
+|---|---|
+| chromium, firefox | two engines, so nothing rests on one's wheel or drag behaviour |
+| 1600×1000, 1500×950, 1200×760, 900×600 | a responsive panel moves with the window; a fixed one does not |
+| 100% and 125% browser zoom | fewer CSS pixels in the same window, and a device ratio that must not reach the geometry |
+
+1500×950 at 125% and 1200×760 at 100% are the same 1200×760 CSS viewport from
+two different device ratios, and the recordings say so. That pair is the whole
+device-independence claim, made once and kept.
+
+**When something fails.** The build names it and keeps the rest:
+
+| It says | What moved | Where to fix it |
+|---|---|---|
+| *is not a map URL any more* | the site changed its URL form | `engine/mapsites.py`, then re-run |
+| *no zoom moved a level the URL stated* | its wheel step changed | `NOTCHES` in `calibration/protocol.mjs` |
+| *its two zooms solved centres N px apart* | the map eased the zoom, or the site is no longer drawing the flattening it is named with | drive it by hand and watch; `_PROJECTIONS` if the shape has changed |
+| *the camera solved outside the map's own canvas* | the layout changed under the solve | look at the site before trusting the number |
+
+What the protocol itself is worth is not taken on trust either: `npm run test:e2e
+-- map-calibration` drives the same sequence against a map whose header and side
+panel we chose, on both engines and at two window sizes, and the solve has to
+come back with the layout that was built in.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index ee1c279..c2e6fff 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -161,6 +161,14 @@ proof for publication.
|------|--------------|
| ✅ **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. |
+| ✅ **Extension update button** | The app owns the extension's folder, so an update is one click instead of a reinstall: it rewrites the files, the extension restarts and re-attaches to the open tab. Points the analyst at the copy to remove when two are loaded, and stages the write when a browser holds the old files. |
+| ✅ **Home** | Where the app opens, on the mark rather than a fifth rail seat. With a case it is a dashboard: what is outstanding as four tiles, the last work filed with the case's own thumbnails, the case's saved points on a map of their own — the app's engine, the keyless imagery, pan and zoom and nothing that writes — and the case by family in the Graph's own hues. The tiles are the Board's standing questions, so pressing one lands on exactly the rows it counted; a case holding nothing is offered the three ways material gets in instead. With no case it is the front door: what Azimut is, the rail as a sequence, and the first case named from the page. |
+| ✅ **Guide** | One section per workspace, between two that set up (what a case is, the capture extension) and three worked examples, and two that close: every key the app listens for, and what to do when something does not work. The `?` in the topbar opens it on the section written about the tab being stood in. Tests fail when a tool joins the rail undocumented, when a recipe names a tool that does not exist, and when a key is filed under a tab the app no longer has. |
+| ✅ **Extension map tools** | Measure, media pins, sun and moon, a search grid, and reference windows holding the case's own images and videos, drawn over the maps the extension rides on. Scale comes from what each site writes about itself, checked in a real browser first (`docs/MAP_SITES.md`); the first zoom measures where that site draws its centre, since five of them do not put it in the middle of the window; a pitched or panoramic camera switches geometry off with its reason shown, and a view zoomed out to a globe keeps drawing, dimmed, saying it drifts at the edges. A turned compass keeps its measurement — a scale is pixels per degree, and every reading undoes the bearing before it divides. |
+| ✅ **One case, every window on it** | A point saved, a grid drawn or a cell swept appears at once in the app, in a second app tab and in every map the panel is open on — no reload, no button. The app says what changed over its own nudge channel, the extension's worker holds one stream for all its panels, and each side re-reads only what the nudge names. A sweep worked from two places keeps both hands' marks: what travels is the cells that were marked, never a copy of the grid. |
+| ✅ **Engine hand-off** | A Reverse Search button opens the engine with the case picture already in its own uploader, so one press asks the question. Lens, Yandex, Bing and TinEye; the clipboard road stays underneath, for a missing extension and for a page that has moved its markup. |
+| ✅ **Signed Firefox add-on** | Firefox refuses an unsigned extension and forgets an unpacked one on exit, so it installs an AMO-signed XPI and updates itself from the manifest each release publishes. The extension reports how the browser installed it, so Settings tells the folder it owns apart from the package it cannot touch and offers no button that would rewrite sealed bytes. The browser owning that update costs two answers the app gives instead: it names a copy that is behind at once, offline, rather than waiting out the daily check, and names the one state it cannot cause — an add-on updated past the Azimut running beside it. |
+| ✅ **Map-site recalibration** | The gesture sequence that measured those sites is a command: it drives them again across two browsers, four windows and two browser zooms, and rebuilds the fixture both suites read (`docs/MAP_SITES.md`). |
---
@@ -177,7 +185,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **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. |
-| **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. |
@@ -188,7 +195,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Sky Clock** | Marks a shadow, the sun or the moon in an image or a video frame, with the horizon and north giving the angles, then renders the year as a day × hour heatmap of the slots that fit. A visible moon also carries phase and bright-limb angle, which usually cuts a year down to a few instants. |
| **Case KMZ** | One self-contained file per case: a pin per place, carrying the notes and proof images it is linked to, opened in Google Earth. Frozen rather than live, because only the web Earth remains and it follows no network link. |
| **Imagery Wayback** | Esri World Imagery archive as a date slider: one view across every published release, key-less. |
-| **Event layers** | Date-stamped overlays that support or contradict an event: NASA FIRMS thermal hotspots, archived weather and METAR. |
+| **Event layers** | Date-stamped overlays that support or contradict an event: NASA FIRMS thermal hotspots (the live pass and the archive back to 2000, each sensor's real reach asked rather than assumed), archived weather and METAR. |
| **Shot contact sheet** | Splits a video into shots (ffmpeg scene detection) and picks frames from a clickable grid of timecodes. |
| **OCR** | Reads signs and plates on import (tesseract, a native binary rather than a wheel), and detects script and language. |
| **Audio Transcript** | Transcribe and translate speech offline; flag acoustic context such as bells, adhan, aircraft or language. |
@@ -197,7 +204,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
| **Detached tool windows** | Opens a tool in its own browser window for a second screen, greyed out in the tab it left and taken back when that window closes. Cross-tool handoffs route to wherever the tool now lives, and the open case follows every window. Read surfaces open as many copies as wanted; the document editors allow one window per document. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
-| **Help and tips** | A mark the analyst clicks for the open tool's own guide: what it is for, the controls whose icon does not say it, and its shortcuts. Clicking an entry points at the real button. One panel, one entry per tool. |
Edit Provenance rests on three facts about Adobe renders, kept here so the tool
can be rebuilt from the spec alone:
@@ -282,7 +288,8 @@ 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.
+- **More on the home page:** the case's own notes beside the tiles, and panels the analyst arranges rather than a fixed grid. Each has to earn its place there rather than beside Board, Graph and Timeline, which already read the case.
+- **A stack of map overlays:** one toggle per transparent layer instead of the single labels slot, OpenRailwayMap first. A capture stitches one provider, so an overlay stays screen-only until that changes.
- **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
@@ -330,11 +337,40 @@ stops making sense.
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 address
+ the request would have served it. Filling a composer and handing a picture to a
+ reverse-image engine are the extension's only reach past localhost — eight
+ hosts, declared, where it writes what the app gave it and reads nothing — and
+ each switch that uses one is in the app (Settings → Publishing, Settings →
+ General), where the analyst already decides how a thread is published and which
+ engine gets the picture. The engine road carries the image itself rather than a
+ path, since what Reverse Search prepares is a canvas frame that exists nowhere
+ on disk, and it is the one hand-off whose page acts on what it is given: these
+ engines search as soon as they hold a picture, which is what the button was
+ pressed for. Seven of those hosts are the engine or the composer itself; the
+ eighth is `www.google.com`, which is broader than the rest and is an accepted
+ risk rather than an oversight: Lens redirects `lens.google.com` to the search
+ home page and draws its uploader there, so the grant has to cover wherever that
+ redirect lands. It buys nothing beyond that — the extension injects only into a
+ tab it opened itself, at a URL the app handed it, and reads nothing back.
+ Updating that extension writes the app's *own* bundled bytes into
+ one fixed workspace path and takes nothing off the request — no path, no
+ payload — so it sits on the settings router rather than in the ingest island,
+ where the extension-origin CORS would have reached it; the message that then
+ restarts the extension is only reachable from the app's own localhost page,
+ names the install it means, and its worst outcome is an extension that
+ restarts. The map tools widen that island by five read routes and two writes,
+ each trimmed to what a panel draws — saved points without their thumbnails or
+ link tallies, a sweep's own spec, a case's images and videos by name — and the panel
+ itself reaches them only through the worker's own allowlist, since a content
+ script's fetch would carry the map site's origin and be refused. Keeping those
+ panels in step adds one more, and it is the narrowest of them: a read-only
+ stream of what changed, never of what it says, so an event names a case and a
+ file and the panel re-reads it through the routes it already had. The worker
+ holds it and no panel is given it, which is the same fence as the rest — and
+ it is deliberately not on the relay's allowlist, being one answer that never
+ ends. The bytes of a
+ picture come back over the hand-off's own route, behind the same fence: media
+ and proofs, resolved, and nothing else in the case. A case id and an artifact name each address
one directory entry, checked against POSIX *and* Windows path rules so the
separator only one of them honours cannot walk out of the workspace. The workspace pointer is the one file written
outside the workspace, 0600 and holding a path; deleting the copy a move set
@@ -356,12 +392,19 @@ stops making sense.
compressed bytes and on the size its own directory declares once unzipped. The map's search bar answers from
a bundled gazetteer and never reaches out on a keystroke; its geocoder layer
waits for a pause, and a request the one-per-second pace cannot take is dropped
- rather than queued. The startup update check is
- the one on-mount network call: opt-out, and read-only against GitHub's
+ rather than queued. Two things reach out on mount and no
+ others. The startup update check: opt-out, and read-only against GitHub's
releases feed plus PyPI's JSON for the two downloaders, both governed by the
- same switch. Release notes are rendered through the Notebook's
+ same switch. And the home page's map of the case, which fetches basemap tiles
+ for the points the case already holds — through the same proxy as every other
+ map, from the keyless unmetered provider only, so it spends no allowance and
+ asks for nothing a case with no saved point would. Release notes are rendered through the Notebook's
DOMPurify-sanitized Markdown renderer rather than as raw HTML. The capture
- extension is compared locally, so it is answered with the switch off. Remote images embedded in a
+ extension is compared locally, so it is answered with the switch off — except
+ the Firefox copy, which Mozilla signs and the browser therefore updates itself:
+ it polls the release's update manifest on its own schedule, past any switch the
+ app has, and is recorded here as an accepted risk for the only permanent
+ Firefox install that exists. Remote images embedded in a
Notebook note contact their host whenever the preview opens; Notebook warns
about that behavior and local Case media avoids it. Notebook diagrams are the
one markup DOMPurify does not clear: Mermaid draws its SVG into the preview
diff --git a/docs/UI.md b/docs/UI.md
index 4537892..26bfe7c 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -6,7 +6,7 @@ phasing lives in [SPEC.md](SPEC.md).
## Layout anatomy
```
-┌ topbar: rose+wordmark · case switcher + Board · (spacer) · settings gear · sidebar toggle ┐
+┌ topbar: rose+wordmark (home) · case switcher + Board · (spacer) · guide mark · settings gear · sidebar toggle ┐
├ rail ┬ tab strip (only when the workspace has several tools) ┬ case sidebar ┤
│ │ tool canvas │ │
└──────┴───────────────────────────────────────────────────────┴──────────────┘
@@ -19,6 +19,7 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| Workspace | Tools today | Future tools land here |
|---|---|---|
+| **Home** (the mark) | Overview, Guide | |
| **Case** (topbar) | Board, Graph, Timeline, Sheet | v5: Orchestrator |
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
@@ -34,6 +35,95 @@ reading of the case, not a collection or examination stage.
That sidebar stays closed by default, because the board already lists the same case
and two lists side by side only ask which one is real.
+**Home is not on the rail either**, and for the same reason. It sits on the wordmark,
+which is the one affordance that needs no label and costs no seat, and it is where the
+app opens (`#overview`). Its sidebar starts closed too: the page is read rather than
+worked in, and its whole subject is the case the sidebar would be listing again.
+
+## Home
+
+Two tabs, chosen by who is looking. **Overview** is for somebody who has been here
+before; **Guide** is for somebody who has not.
+
+- **With a case open, the page is a reading, laid out as a dashboard.** The case name
+ and when it was last touched, then a two-column grid: *what is waiting* and the
+ recent work on the left, the case's points and the case by family on the right. It
+ runs to 1180px rather than a 760px reading column, because this page is scanned
+ rather than read and four counts hanging in a ribbon on a wide screen is the emptiest
+ an app can look. Below ~980px the grid stacks in that same order.
+- **What is waiting is the Board's own standing questions, priced.** *To review*,
+ *Nothing linked yet* and *Unfiled* are the same three terms the `+ Filter` menu
+ offers, worded once in `lib/entityFilter.js`; the fourth is the Timeline's undated
+ count. They are drawn as four tiles, two by two, because a number is read at a glance
+ or it is not read. Pressing one hands the **question** to the surface that answers it,
+ through the slot Board and Graph already share, so the table lands on exactly the rows
+ the number counted and the two can never disagree.
+- **A count of nothing stops being a control.** It is dimmed and says zero rather than
+ offering a press that lands on an empty table to confirm what the page already said.
+ With all four at zero the tiles give way to one line, and that line is about the four
+ questions rather than about the case: a case is never finished, so nothing on this
+ page may read as a case that is.
+- **A case holding nothing is not a case that is up to date.** With a total of zero
+ there is no reading to give, so the grid is replaced by the three ways material gets
+ in: media, files, a map capture. It is the screen a first case lands on one second
+ after being named.
+- **The fourth standing question is not in that list.** *Added this week* says what
+ happened rather than what is outstanding, so it leads the recent work instead.
+- **The recent rows carry the case's own pictures.** The catalog already attaches a
+ thumbnail to the rows that have one (`thumb`), so six frames of an afternoon's work
+ are shown rather than six filenames.
+- **The points are on a real map, and it is only a reading.** The saved index is drawn
+ as dots on the same engine the Map tool uses (`overview/PlaceMap.svelte`), framed on
+ the case, capped at 200 points, and the wheel and the drag are all it answers: no
+ capture, no basemap picker, nothing that writes. Hovering a dot names it. The
+ basemap is the keyless, unmetered imagery and nothing else, so opening the page
+ cannot spend a quota. Coming back to the tab re-reads the case, and points that
+ did not change leave the camera where it was put. The foot says how many points the
+ case holds, how many are drawn when that is fewer, and opens the Map tool. With
+ nothing placed there is no map, and the figures take the shoulder instead of leaving
+ a hole.
+- **The case by family is drawn in the Graph's own eight hues** (`--graph-<family>`),
+ each bar measured against the biggest family rather than against the total. One
+ reading of one case cannot be two palettes.
+- **It asks the case nothing new.** Five bounded reads against the open case only: the
+ catalog summary, one timeline page, the newest rows, a count of the last seven days,
+ and the compact saved index the Satellite panel already opens on. Nothing opens a
+ second case to count it, and the only thing that reaches the network is the map of
+ the case, fetching the imagery under its points.
+- **Two notices, both of them answers the startup checks already gave.** A newer release
+ folds its own body open on the page (the check returns it) with a download link, and
+ is silent when the release was muted or the check is switched off. A capture extension
+ that was never installed gets one line pointing at the tab that installs it, and the
+ line disappears the moment one is. Neither is dismissible state: both are conditions
+ that clear themselves, so nothing here is stored and nothing here nags.
+- **With no case open the page is the front door.** A fresh install lands in an empty
+ workspace, where there is nothing to summarise and nothing on screen that says what
+ the rail means: what Azimut is, the rail drawn as the sequence it is, a field that
+ names the first case, and the cases already in the workspace when there are any.
+- **The Guide is one section per workspace**, between two that set up and two that
+ close. Setting up: what a case is, and the capture extension that feeds it —
+ installing it is the first thing the first section says, because it is the one setup
+ step that changes what the app can do. Then **three worked examples**, whole jobs
+ walked tab by tab, because the sections describe tools and somebody arriving has a
+ goal; each step names the tool it happens in and opens it. Closing: **every keystroke
+ the app listens for**, grouped by where it is pressed, and **what to do when something
+ does not work**, symptom by symptom. Static text rather than a tour, and no
+ screenshots: a tour breaks on the first layout change, a screenshot is stale the
+ release after it was taken, and both fail silently. `guide.test.js` fails when a tool
+ joins a workspace and nobody wrote down what it is for, when a recipe sends the reader
+ to a tool that does not exist, and when a key is filed under a tab the app no longer
+ has.
+- **The `?` in the topbar is the way in.** It sits beside the settings gear rather than
+ in each toolbar, so there is one of it, and it opens the Guide on the section written
+ about the tool being stood in (`guideFor`). A tool no section covers opens the guide
+ at the top. It is absent on the Guide itself, which is the answer.
+- **The contents list follows the reading.** It marks whichever section is under the
+ eye as the column scrolls, measured against a line just below the top edge so a
+ heading that has only just passed is the one being read, and the last section takes
+ the foot of the page since a short final section can never reach that line. A press
+ on the list owns the mark until its scroll lands, or the one control that says *go
+ here* would point somewhere else three times on the way.
+
Rules:
- Use at most two levels: workspace → tab.
@@ -1012,7 +1102,10 @@ holding nothing placed says so in words rather than pulling the map out over unr
ground.
The marks are the saved layer's own pins in a second tint, because they are the same
-gesture on the same map. A mark's card leads with what each row is — a photograph shows
+gesture on the same map. Every one of them is a teardrop standing on the point: the
+sharp corner is the coordinate and the body hangs above it, in the app and in the
+extension alike. Anchored on its middle, as it was, a mark claimed a spot 17 px
+south of the one it was filed at — ten metres of ground at level 18. A mark's card leads with what each row is — a photograph shows
itself — and offers both ways on: the entry on the axis it came from, and the thing
itself in the tool that owns it, with a file the browser can show also opening in its
own tab. The card's own buttons hand the period to Board or Graph, or close the layer.
@@ -1186,6 +1279,12 @@ never passes for analyst work. The Save-place dialog carries the matching write:
one **Relate to…** field says why the point is being saved while the analyst still
knows.
+**The map keeps up with the other windows on the case.** A point saved, a grid
+drawn or a cell swept from the extension's panel over another map lands here
+without a reload, and the same the other way round. A sweep worked from both
+keeps both hands' marks: what is written is the cells that were marked, never the
+grid around them. A grid discarded elsewhere closes here and says so.
+
## Geo Proof
A proof is composed of panels: case images, each carrying its source. Two things
diff --git a/extension/README.md b/extension/README.md
index c24ada8..c5ac851 100644
--- a/extension/README.md
+++ b/extension/README.md
@@ -8,32 +8,221 @@ The extension sends the screenshot and page URL. Azimut parses supported sites,
coordinates, place names and imagery dates, so URL-format fixes ship with the
app.
-It supports four flows:
+It supports six flows:
- On a supported map site, the popup can capture a selected area or save its
coordinates as a place.
+- On a 2D map, it can draw Azimut's own tools over the site: measure, media
+ pins, sun and moon, a search grid, and the case's own images and videos held
+ over the map.
- On another page, it can save the URL and title as a bookmark without
downloading the page.
- On Azimut's Google basemap, the in-app Capture button requests the current
tab 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.
+ filled, and publishing stays a human act.
+- When Reverse Search opens an engine, it can hand the picture to the engine's
+ own uploader, so the search runs on the press you already made.
## Install
-Get the zip from Azimut → **Settings → Capture extension** (or use this
-folder directly from a repo checkout), unzip it somewhere permanent, then:
+Two roads, because the browsers disagree about what a permanent extension is.
-- **Chrome / Edge / Brave** (Windows, macOS, Linux): open
- `chrome://extensions`, enable **Developer mode** (top right), click
- **Load unpacked**, then pick the unzipped folder. Keep the folder in place
- because Chrome loads it there on every start.
-- **Firefox**: open `about:debugging#/runtime/this-firefox`, click
- **Load Temporary Add-on…**, pick `manifest.json` inside the unzipped folder.
- Firefox drops temporary add-ons when it closes. Reload it next session, or
- use Firefox Developer Edition / ESR with `xpinstall.signatures.required`
- set to `false` in `about:config` for a permanent install.
+### Chrome, Edge, Brave (Windows, macOS, Linux)
+
+In Azimut → **Settings → Capture extension**, press **Install**. The app writes
+the extension into a folder it owns and shows you the path. Copy that path —
+pasting it into the browser's picker works everywhere, and the folder is hidden
+under `.azimut/`, so navigating to it is the harder road.
+
+Open `chrome://extensions`, enable **Developer mode** (top right), click
+**Load unpacked**, then paste the path (`Ctrl+L` on Linux, `Cmd+Shift+G` on
+macOS, the filename box on Windows). Leave the folder where it is: Chrome loads
+it from there on every start, and it is what the update button rewrites.
+
+Settings also offers the plain **.zip** for anyone who would rather place the
+files themselves. It works the same, minus the update button: Azimut can only
+rewrite the folder it owns.
+
+### Firefox
+
+Firefox refuses an unsigned extension and drops an unpacked one when it closes,
+with no preference to turn either off outside the developer channels. So it gets
+a signed package instead: download `azimut-capture-<version>.xpi` from the
+[latest release](https://github.com/OsintMeThat/azimut/releases/latest), open
+`about:addons`, and use the gear menu → **Install Add-on From File**. It survives
+restarts, and it updates itself.
+
+The file is signed by Mozilla but listed nowhere: signing and distribution are
+separate, so the add-on is validated and installable without being published on
+addons.mozilla.org.
+
+## Update
+
+**Chrome, Edge, Brave**: Settings → **Capture extension** → **Update**, once the
+button lights up. Azimut rewrites the folder and the extension restarts and
+re-attaches itself, so nothing needs reloading — not the extension, not the page.
+Your pairing survives. Even without pressing anything it lands eventually, since
+Chrome re-reads unpacked extensions when it starts.
+
+Two things worth knowing there:
+
+- If a browser is holding the old files (Windows does this), Azimut says the
+ files are staged. Close the browser and press again.
+- Chrome derives an extension's identity from its folder, so if you already had
+ the extension loaded from a folder of your own, that copy and this one are two
+ extensions. Settings names the one to remove. Removing it loses its stored
+ pairing, so paste the token again afterwards — once.
+
+**Firefox**: nothing to press. A signed package is sealed, so Azimut cannot
+rewrite it and the Update button does not apply. Firefox reads Azimut's update
+manifest about once a day and replaces the add-on itself; your pairing survives.
+Settings says as much when it detects a copy the browser manages.
+
+Two consequences of the browser owning that update, and both are named rather
+than hidden:
+
+- Azimut can tell you the add-on is behind the moment you open it, since it ships
+ the extension and knows the version offline. Firefox applies it within the day,
+ or at once from `about:addons` → **Check for Updates**. Nothing can ask Firefox
+ to check earlier: it does not implement the API that would.
+- Firefox updates the add-on without knowing which Azimut sits beside it, so an
+ app left un-updated can end up paired with a newer add-on. Settings and the
+ extension's own options page both say so, and the answer is to update the app —
+ its newer flows report that they could not run rather than misbehave.
+
+## Map tools
+
+**Draw tools over this map**, in the popup, opens a panel over the site you are
+on. Press it again to close it. Five tools share it:
+
+| Tool | What it does |
+|---|---|
+| Measure | Distance along a clicked path, or the area it encloses. Same formulas and same wording as the app. |
+| Points | Draws the case's saved work on the map, and files a new point. |
+| Sun & moon | Plants a point and draws the day's sun and moon arcs around it, with a date and an hour slider. |
+| Grid | Drags a box or clicks out a shape, cuts it into metric cells, and marks each cleared or flagged. The grid is saved into the case and opens in the app's own Grid Search. |
+| Refs | Floats an image or a video from the case over the map, to compare against the imagery while you pan. |
+
+Only the open tool draws, and pressing it again puts it down: the map goes back to
+being a map. What you told a tool stays in it — a measured path, a planted point,
+an open sweep all come back when you pick it up again. Reference windows are the
+exception, because they are not on the map: they stay while you measure.
+
+**A reference window is scratch.** Drag it by its header, resize it from the
+corner, wheel to zoom into the image, double-click the title bar to fold it away.
+Nothing about it is filed, nothing comes back next visit, and the panel and its
+windows step out of the frame before a capture is taken — a reference floating
+over a map must never end up inside the evidence.
+
+**Add reference** lists the case's images and videos, searched, filtered by kind
+and ordered by the app rather than by this tab: what crosses is one page of a case,
+never the case. A video plays in the window, with its own controls.
+
+Two limits worth knowing. A file has to be **under 24 MB** to be handed over, which
+is the same ceiling a published thread's attachments answer to. And a video is the
+one thing here a site can refuse: an image is decoded and painted on a canvas,
+which asks the page's content policy nothing, while a video needs a URL and some
+sites will not load one. When that happens the window says so.
+
+Reference windows work where the geometric tools do not — Street View, a pitched
+camera, a globe — since nothing about holding a reference up needs the ground to
+be measurable, and they stay on screen while you use another tool.
+
+**It works from what the site writes about itself.** Every one of these maps states
+how far out it is: a tile level for most of them, a viewport height in metres for
+Google's satellite view, a span in degrees for Apple. Each of those was checked in a
+real browser before being believed — driven at two window sizes, dragged a known
+number of pixels, read back out of the address bar (`docs/MAP_SITES.md`) — and the
+drawing works from the first frame, with nothing to calibrate.
+
+**Zoom once and it knows where the map's middle is.** The coordinate in the address
+bar is not under the middle of the window on most of these sites: Yandex draws it
+210 px to the right of it, behind its results panel, Bing 40 px down under its
+header. A pan can never see that offset, because it slides along with the map — but
+a zoom can, since every one of these maps zooms about a point it holds still while
+the centre moves underneath. So the first zoom you make measures it, the panel
+remembers it for that site and that window shape, and every zoom after checks it
+again. Until then the panel says "zoom once to place it" in its status line. The
+number it settled on is in the tooltip of that line, which is where to read it
+when something lands somewhere the ground is not.
+
+**Each pan is a check.** The panel predicts where the map will land and compares
+that with what the address bar says. When the prediction drifts, geometry switches
+off and the panel says why instead of drawing something wrong.
+
+**Where the URL is not enough.** Earth states no level and no flattening, only a
+camera distance, so there the map itself is the authority: pan once and it is
+measured. Apple states a live span but a stale `z` — it carries whatever the opening
+link had and never rewrites it — so the span is read and the `z` ignored. Bing
+rounds: its wheel moves a third of a level and it writes one decimal, so the
+fraction is worked out from the same held pixel rather than read. Whole levels are
+exact everywhere, which is what a double-click lands on.
+
+Earth and 3D mode work with the camera **level**; pitched, the panel refuses them,
+because a cell would land on the wall of the building hiding it. One limit remains
+there that no measurement can remove: **relief**. A level camera still pushes a
+hilltop outward from the centre of the screen by its own height, and no URL says how
+tall the ground is. Flat country is exact; mountains are not, and the further from
+the centre of the screen, the more so.
+
+**Google Earth asks for one drag before it draws.** Its address bar states no
+scale of any kind, so the map itself is the only authority and a drag is the
+question: across *and* down, since a scale is two numbers, and letting go only
+once the map has stopped, because these viewers glide on and report where they
+landed rather than where you let go. The panel says exactly that until it has
+its answer. One drag is the whole cost — zooming, turning and panning after it
+are free.
+
+**The drawing dims while the map is still moving.** These maps glide on after you
+let go and ease into a zoom, and they say so nowhere — the address bar is rewritten
+once, at the end. A drag is followed exactly, because the map goes where the pointer
+goes; the glide and the zoom are not followed at all. Dimmed means "not right now",
+which is the honest thing for a tool whose output ends up in a case file.
+
+**Saved points are drawn without their names.** Point at a mark to read it, click
+to keep it open. Points at the same spot merge into one counted mark, the way the
+app's own Saved layer merges them.
+
+**The case stays in step, in every window onto it.** Save a point in the app and
+it appears here; mark a cell here and it appears in the app's own Grid Search and
+in any other map you have the panel open on. Nothing needs reloading and nothing
+needs pressing: the app says what changed and each side re-reads that much.
+
+A grid swept from two places at once both lands, because what travels is the
+cells you marked and never a copy of the grid — so two sweeps of different cells
+keep each other's work, and the same cell twice is simply the last mark. A grid
+discarded elsewhere closes here and says so.
+
+Street View and a pitched 3D camera have no ground plane to measure on, so the
+geometric tools are off there, and the panel says which view it wants back: the
+map rather than Street View, 2D rather than 3D. A degree or two is not pitched:
+these viewers never come back to a clean zero, and a view that looks level is
+treated as level. Placing a point
+still works wherever geometry is off, anchored on the point the address bar
+names — where the camera stands — and the panel says so.
+
+**Turning the map is fine.** Drag Google Earth's compass and the drawing turns
+with it, keeping the scale it had: what was measured is pixels per degree, and
+degrees do not care which way the screen is facing. Only tilting the camera
+switches the geometric tools off. One gesture that turns *and* zooms at the same
+time asks for a pan again, because nothing in the address bar says which of the
+two moved the scale.
+
+Zoomed far out, where these sites start drawing a globe, the tools stay on: the
+middle of the screen is still right, the edges drift, and the drawing is dimmed
+and says so rather than disappearing. It is a look at a region's work, not a
+measurement — zoom in and it is exact again. Sun & moon is the exception and is
+never dimmed: it answers which way the light came from, read at its own anchor,
+and that is right however far out you are.
+
+Where a site's own panel can be collapsed mid-session, the offset moves with it, and
+the drawing is out by that much until the next zoom measures it again. Resizing the
+window or changing the browser's zoom asks for that zoom too: some of these panels
+keep their width and some of them do not, and no address bar says which. The last
+four window shapes are kept per site, so going back to one you have already
+measured places the drawing again without asking.
## Pair (external sites only)
@@ -42,7 +231,8 @@ 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, and to read back the media and proofs a thread attaches. Rotate it in
+server, to read back the media and proofs a thread attaches, and — for the map
+tools — the saved points, search grids, images and videos of the case you pick. Rotate it in
Settings to revoke existing pairings.
## Fill the composer
@@ -64,16 +254,34 @@ 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.
+## Open a reverse-search engine
+
+Reverse Search's engine buttons open Google Lens, Yandex, Bing or TinEye with
+the case picture already in the page's own uploader, so the engine searches
+without you pasting or dragging anything.
+
+This is the one flow where the page acts on what it is given: an engine searches
+the moment it holds a picture. That is what the button was pressed for, and it
+still takes that press — nothing is sent to an engine you did not open.
+
+The switch is in the app — **Settings → General → Let the extension open the
+engine with the image**, on by default. Nothing to set here.
+
+If the engine has changed its markup, or the image is too large to carry, the
+buttons do what they always did: copy it, or save it for you to drag in. The
+image is on your clipboard either way.
+
## Permissions
| Permission | Why |
|---|---|
| `activeTab` | Reads the current URL and captures the tab only after you click the extension. |
-| `scripting` | Shows the area-selection overlay, and fills a composer you allowed. |
+| `scripting` | Shows the area-selection overlay, draws the map tools panel, fills a composer you allowed, and hands an image to an engine you opened. |
| `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. |
+| `https://lens.google.com/*`, `https://www.google.com/*`, `https://yandex.com/*`, `https://www.bing.com/*`, `https://tineye.com/*` | Gives a prepared image to the engine's uploader, when Azimut asks. Never reads those pages. `www.google.com` is there because Lens redirects to it. |
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 extension
diff --git a/extension/background.js b/extension/background.js
index 6c50099..fbaff7b 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -100,25 +100,37 @@ async function ingest(blob, meta) {
* 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 url = fileUrl(backendUrl, caseId, 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();
+ return {
+ name: path.split("/").pop(),
+ type: blob.type || "application/octet-stream",
+ data: await base64(blob),
+ };
+}
+
+/** One case attachment, addressed. */
+function fileUrl(backendUrl, caseId, path) {
+ return (
+ `${backendUrl}/api/ingest/file?case_id=${encodeURIComponent(caseId)}` +
+ `&path=${encodeURIComponent(path)}`
+ );
+}
+
+/** A blob as base64. What crosses into a page is a string: a message carries no
+ * blob, and both sides rebuild the file from this. */
+async function base64(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),
- };
+ return btoa(binary);
}
/** Resolve once the tab has finished loading, so the injection lands on a page. */
@@ -204,6 +216,173 @@ async function fillComposer(payload, backendUrl, token) {
}
}
+// --- reverse hand-off: give one prepared image to a reverse-image engine --------
+//
+// Reverse Search's engine buttons, when the app asks. The same shape as the
+// composer above — the app is answered at once and the work reports itself
+// through notifications — with one difference that is worth saying out loud:
+// **these pages search as soon as they hold a picture.** The composer is filled
+// and left; an engine is asked. Both are one press of one button in the app, and
+// neither happens without it.
+//
+// The bytes arrive from the app rather than being fetched from it: what Reverse
+// Search hands over is a frame off a canvas — a video still, adjustments baked
+// in — which exists nowhere on disk to be read back.
+
+/** The largest image this will carry into a page, in base64 characters.
+ *
+ * A ceiling the app applies first (lib/reverseSearch.js) and this one re-checks,
+ * because a message that big is a worker holding tens of megabytes to no end:
+ * every one of these engines refuses the upload long before this. */
+const MAX_REVERSE_DATA = 28 * 1024 * 1024;
+
+async function handOffReverse(payload) {
+ const image = payload.image ?? {};
+ if (!image.data) throw new Error("no image");
+ if (image.data.length > MAX_REVERSE_DATA) throw new Error("that image is too large to hand over");
+ if (!payload.url) throw new Error("no engine");
+ fillEngine(payload.url, image).catch((e) => {
+ if (!LEFT.test(e.message || "")) trouble(e.message);
+ });
+ return { ok: true, accepted: true };
+}
+
+/**
+ * Say what went wrong in a sentence the analyst can act on.
+ *
+ * A browser grants the hosts a manifest declares **when it loads the copy**, and
+ * an extension cannot ask for one later. So a copy loaded before this feature
+ * existed refuses the injection with a sentence about manifests, which reads
+ * like a bug in the app and is fixed by one reload. Everything else is passed
+ * through as it came.
+ */
+function trouble(message) {
+ const stale = /permission|access contents of the page/i.test(message);
+ notify(
+ "Azimut reverse search",
+ stale
+ ? "This extension was loaded before Azimut knew these engines. Reload it in your browser, then press the engine again. The image is on your clipboard."
+ : `${message} The image is on your clipboard.`
+ );
+}
+
+/** A page that left rather than a page that refused.
+ *
+ * An engine that takes the picture searches with it, and the injected script
+ * goes with the document it was running in — so "the frame is gone" is what
+ * success looks like from here, and it arrives as an error. Reporting it would
+ * put a failure notice on top of the results the analyst asked for. */
+const LEFT = /frame|no longer exists|destroyed|navigat|context invalidated/i;
+
+async function fillEngine(url, image) {
+ const tab = await api.tabs.create({ url, active: true });
+ await tabLoaded(tab.id);
+ // Both injections run in the page's own world, which is the only place an
+ // uploader takes what we make (see reverse.js). Nothing over there can call an
+ // extension API, so the image 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: (handed) => {
+ window.__AZIMUT_REVERSE__ = handed;
+ },
+ args: [{ image }],
+ });
+ const [done] = await api.scripting.executeScript({
+ target,
+ world: "MAIN",
+ files: ["reverse.js"],
+ });
+ if (done?.result?.error) trouble(done.result.error);
+}
+
+// --- the folder this copy was loaded from ---------------------------------------
+//
+// The app owns that folder (engine/extinstall.py) and stamps install.json into
+// it, so the question "is the extension this browser loaded the copy I control"
+// has an answer. Read from the background rather than the content script: in
+// Chrome a content-script fetch answers to the *page's* origin, so reading an own
+// resource that isn't web-accessible would be refused. It is deliberately not
+// web-accessible — no page has business reading it.
+
+/** The stamp as it was when this extension last loaded.
+ *
+ * Cached in storage.session on purpose, and that is the whole design: a fresh
+ * read of install.json reports the *folder*, which the app has already rewritten
+ * by the time it asks, so it would answer "up to date" whether or not this code
+ * ever restarted. storage.session survives a worker eviction and is cleared when
+ * the extension unloads, so what it holds is what the running code was installed
+ * from — the one claim worth verifying an update against.
+ *
+ * The manifest version can't play that role: within a development cycle it is
+ * already the app's own version and never moves when the bytes do.
+ */
+let loadedStampPromise = null;
+
+function loadedStamp() {
+ if (!loadedStampPromise) loadedStampPromise = readLoadedStamp();
+ return loadedStampPromise;
+}
+
+async function readLoadedStamp() {
+ const seeded = await api.storage.session.get("loadedStamp");
+ if (seeded.loadedStamp !== undefined) return seeded.loadedStamp;
+ let stamp = null;
+ try {
+ const r = await fetch(api.runtime.getURL("install.json"));
+ if (r.ok) stamp = await r.json();
+ } catch {
+ // No stamp: loaded from a folder the app doesn't own, which is a state the
+ // app reports rather than an error.
+ }
+ // `null` is a real answer and has to be stored as one, or every later call
+ // re-reads a file that isn't there.
+ await api.storage.session.set({ loadedStamp: stamp });
+ return stamp;
+}
+
+/** How the browser installed this copy: "development" for a folder or a
+ * temporary add-on, "normal" for a packaged one it manages itself.
+ *
+ * Firefox refuses an unsigned extension outside the developer channels, so a
+ * permanent Firefox install is a signed XPI — sealed, with no install.json and
+ * nothing the app could rewrite. Without this, such a copy looks exactly like an
+ * old manual unzip, and Settings would tell the analyst to remove the only
+ * install their browser will keep.
+ *
+ * `management.getSelf` needs no permission. Null where it is unavailable, which
+ * reads as "cannot tell" rather than as a claim.
+ */
+async function installType() {
+ try {
+ return (await api.management.getSelf()).installType ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** Re-attach the bridge to the app's own tabs.
+ *
+ * Neither browser re-injects content scripts after an extension reloads, so
+ * without this the app's tab keeps an orphaned bridge and the analyst is told to
+ * reload the page — a manual step in the feature whose point is removing one.
+ * Runs on every worker start; injecting twice is handled on the bridge side.
+ */
+async function reattachBridge() {
+ try {
+ const tabs = await api.tabs.query({ url: APP_ORIGINS.map((o) => `${o}/*`) });
+ for (const tab of tabs) {
+ api.scripting
+ .executeScript({ target: { tabId: tab.id }, files: ["bridge.js"] })
+ .catch(() => {});
+ }
+ } catch {
+ // A tab we may not inject is the pre-existing "reload this tab" case.
+ }
+}
+
function notify(title, message) {
// fire-and-forget: a failed toast must never fail a filed capture
try {
@@ -218,6 +397,305 @@ function notify(title, message) {
}
}
+// --- the map tools -------------------------------------------------------------
+//
+// The panel runs as a content script on someone else's map, so its own fetch
+// would carry that site's origin — which the app refuses, exactly as it should
+// (`server.py`, the local guard). Every call it makes is relayed here instead
+// and goes out as the extension.
+//
+// The allowlist is the point. This worker holds the pairing token, and a relay
+// that forwarded any path would hand the whole ingest surface to whatever ends
+// up running in a map tab. These are the routes the four tools need and nothing
+// else. The nudge stream is not among them and never should be: it is one answer
+// that never ends, and it is read below rather than relayed.
+const MAP_ROUTES = new Set([
+ "/api/ingest/ping",
+ "/api/ingest/cases",
+ "/api/ingest/parse",
+ "/api/ingest/saved",
+ "/api/ingest/sky",
+ "/api/ingest/grids",
+ "/api/ingest/grid",
+ "/api/ingest/grid/marks",
+ "/api/ingest/place",
+ "/api/ingest/media",
+]);
+
+//. Injected in this order: each one reads the globals the ones before it left.
+const MAP_FILES = [
+ "mapmath.js",
+ "maptheme.js",
+ "maptools.js",
+ "mapdraw.js",
+ "mapref.js",
+ "mapoverlay.js",
+];
+
+async function mapApi(msg) {
+ if (!MAP_ROUTES.has(msg.path)) throw new Error(`the map tools may not call ${msg.path}`);
+ const { backendUrl, token } = await settings();
+ if (!token) throw new Error("not paired. Open the extension options and paste the token from Azimut Settings");
+
+ const url = new URL(backendUrl + msg.path);
+ for (const [key, value] of Object.entries(msg.query || {})) {
+ if (value !== undefined && value !== null && value !== "") url.searchParams.set(key, value);
+ }
+ const init = { method: msg.method || "GET", headers: { "X-Azimut-Token": token } };
+ if (msg.body && msg.form) {
+ const form = new FormData();
+ for (const [key, value] of Object.entries(msg.body)) {
+ if (value !== undefined && value !== null) form.append(key, String(value));
+ }
+ init.body = form;
+ } else if (msg.body) {
+ init.headers["Content-Type"] = "application/json";
+ init.body = JSON.stringify(msg.body);
+ }
+
+ let r;
+ try {
+ r = await fetch(url, init);
+ } catch {
+ throw new Error("Azimut is not answering. Is the app running?");
+ }
+ if (r.status === 401) throw new Error("pairing token rejected. Pair again in the extension options");
+ const text = await r.text();
+ if (!r.ok) {
+ let detail = text;
+ try {
+ detail = JSON.parse(text).detail ?? text;
+ } catch {
+ // a proxy or a crash can answer with something that is not JSON
+ }
+ throw new Error(typeof detail === "string" ? detail : `the app refused: ${r.status}`);
+ }
+ return text ? JSON.parse(text) : null;
+}
+
+/**
+ * One of the case's files, for a reference window (`extension/mapref.js`).
+ *
+ * Not `mapApi`: that one parses what comes back as JSON, and this is bytes. The
+ * route is written in rather than allowlisted — the panel may ask for a file
+ * from the case it has open and for nothing else, and the app's own fence
+ * (`api/ingest.py`, ``handoff_file``) is what says which files those are.
+ */
+async function mapFile(caseId, path) {
+ const { backendUrl, token } = await settings();
+ if (!token) throw new Error("not paired. Open the extension options and paste the token from Azimut Settings");
+ if (!caseId) throw new Error("no case open");
+ let r;
+ try {
+ r = await fetch(fileUrl(backendUrl, caseId, path), { headers: { "X-Azimut-Token": token } });
+ } catch {
+ throw new Error("Azimut is not answering. Is the app running?");
+ }
+ if (!r.ok) throw new Error(await refusal(r));
+ const blob = await r.blob();
+ return { type: blob.type || "application/octet-stream", data: await base64(blob) };
+}
+
+/** Why the app would not hand a file over, in its own words where it gave any —
+ * the size ceiling is stated there, and a second copy of the number here is a
+ * number that goes stale. */
+async function refusal(r) {
+ if (r.status === 401) return "pairing token rejected. Pair again in the extension options";
+ let detail = "";
+ try {
+ detail = JSON.parse(await r.text()).detail;
+ } catch {
+ // a proxy or a crash can answer with something that is not JSON
+ }
+ return typeof detail === "string" && detail ? detail : `the app refused that file (${r.status})`;
+}
+
+/** How long the panel is given to say it has left the frame. */
+const PANEL_ANSWER_MS = 500;
+
+/**
+ * Take the panel out of the frame, grab, put it back.
+ *
+ * `captureVisibleTab` photographs the page as it is composited, and the map
+ * tools panel — reference windows and all — is on it. A tab with no panel
+ * open does not answer, which is not an error, and the panel is shown again
+ * whatever the grab did.
+ */
+async function withoutPanel(tabId, grab) {
+ const tell = async (hide) => {
+ try {
+ // The panel applies it on receipt and only *answers* a frame later, so a
+ // wait that runs out costs a frame of certainty and never a hidden panel.
+ // Unbounded, it would be a Capture button that spins for good.
+ await Promise.race([
+ api.tabs.sendMessage(tabId, { type: "map-chrome", hide }),
+ new Promise((resolve) => setTimeout(resolve, PANEL_ANSWER_MS)),
+ ]);
+ } catch {
+ // no panel on this tab to answer, which is the usual case
+ }
+ };
+ await tell(true);
+ try {
+ return await grab();
+ } finally {
+ await tell(false);
+ }
+}
+
+// --- the nudge stream ----------------------------------------------------------
+//
+// A panel draws a case it is also being worked from elsewhere: the app's own map
+// on one screen, this panel over a site's map on another, a second panel on a
+// third. Every one of them writes to the same files, and before this each only
+// ever saw what it had asked for — a point filed in the app appeared on a panel
+// the next time it was opened, which is a page reload in a feature whose point is
+// not needing one.
+//
+// So the app's own nudge channel is read here (`api/events.py`) and handed to the
+// panels. Here rather than in each panel, for three reasons: a content script's
+// fetch carries the map site's origin, which the app's local guard refuses; it
+// could not hold the pairing token if it wanted to; and ten tabs on one map would
+// otherwise be ten streams for one bus.
+//
+// Not through `mapApi`: that relay parses what comes back as one JSON answer, and
+// this response never ends.
+
+const SYNC_PORT = "map-sync";
+/** How long to wait before re-opening a stream that dropped, and the ceiling it
+ * backs off to. The app being restarted is the ordinary case, so the first
+ * retry is quick and a long outage costs one attempt a minute. */
+const FIRST_RETRY_MS = 1000;
+const MAX_RETRY_MS = 60000;
+
+/** The panels listening, one port each. A port dies with its tab, which is what
+ * makes this the count of panels actually open. */
+const panels = new Set();
+let streamRun = 0; // generation: a retry from a stream that was stopped stands down
+let streamAbort = null;
+let pumping = false;
+
+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * One SSE frame as an event, or null.
+ *
+ * The bus writes `: ping` comments as keepalive and one `data:` line per event
+ * (`api/events.py`). Anything else — a comment, a frame that is not our JSON — is
+ * a nudge that never happened, and a missed nudge costs a refresh.
+ */
+function frameEvent(frame) {
+ const data = frame
+ .split("\n")
+ .filter((line) => line.startsWith("data:"))
+ .map((line) => line.slice(5).trim())
+ .join("");
+ if (!data) return null;
+ try {
+ return JSON.parse(data);
+ } catch {
+ return null;
+ }
+}
+
+function fanOut(event) {
+ for (const port of panels) {
+ try {
+ port.postMessage({ type: "app-event", event });
+ } catch {
+ // the tab went while this was in hand; its disconnect is already queued
+ }
+ }
+}
+
+/** Hold the stream open, handing every event to the panels, until it ends. */
+async function readEvents(run) {
+ const { backendUrl, token } = await settings();
+ if (!token) throw new Error("not paired");
+ const controller = new AbortController();
+ streamAbort = controller;
+ const r = await fetch(`${backendUrl}/api/ingest/events`, {
+ headers: { "X-Azimut-Token": token },
+ signal: controller.signal,
+ });
+ if (r.status === 401) throw new Error("pairing token rejected");
+ if (!r.ok || !r.body) throw new Error(`the app refused the event stream (${r.status})`);
+ const reader = r.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (run === streamRun) {
+ const { value, done } = await reader.read();
+ if (done) return;
+ buffer += decoder.decode(value, { stream: true });
+ // frames are separated by a blank line, and a chunk can hold part of one
+ let cut = buffer.indexOf("\n\n");
+ while (cut >= 0) {
+ const event = frameEvent(buffer.slice(0, cut));
+ buffer = buffer.slice(cut + 2);
+ if (event) fanOut(event);
+ cut = buffer.indexOf("\n\n");
+ }
+ }
+}
+
+/**
+ * Keep a stream open while any panel is listening.
+ *
+ * Every failure here is the same failure — the app is not running, or not
+ * running yet — and the answer to it is to try again later rather than to tell
+ * anybody: the panel already says what it cannot reach, on the errand it was
+ * asked to run. What it must not do is spin: hence the backoff, and the
+ * generation check that stops a retry belonging to a stream nobody wants.
+ */
+async function pumpEvents() {
+ if (pumping) return;
+ pumping = true;
+ const run = streamRun;
+ let wait = FIRST_RETRY_MS;
+ try {
+ while (run === streamRun && panels.size) {
+ try {
+ await readEvents(run);
+ wait = FIRST_RETRY_MS; // it was open once, so the app is there
+ } catch {
+ // not reachable, not paired, or refused — the retry is the whole answer
+ }
+ if (run !== streamRun || !panels.size) return;
+ await pause(wait);
+ wait = Math.min(MAX_RETRY_MS, wait * 2);
+ }
+ } finally {
+ if (run === streamRun) pumping = false;
+ }
+}
+
+/** Nothing left listening: let the stream go rather than hold a request open
+ * against an app nobody is watching. */
+function stopEvents() {
+ streamRun += 1;
+ pumping = false;
+ try {
+ streamAbort?.abort();
+ } catch {
+ /* already gone */
+ }
+ streamAbort = null;
+}
+
+api.runtime.onConnect.addListener((port) => {
+ if (port.name !== SYNC_PORT) return;
+ panels.add(port);
+ // The panel says so every so often (`mapoverlay.js`). Two things ride on it:
+ // this worker is kept from being evicted mid-sweep, and a stream that died
+ // with an eviction is opened again without anyone touching the panel.
+ port.onMessage.addListener(() => pumpEvents());
+ port.onDisconnect.addListener(() => {
+ panels.delete(port);
+ if (!panels.size) stopEvents();
+ });
+ pumpEvents();
+});
+
// --- message routes ------------------------------------------------------------
async function handle(msg, sender) {
@@ -227,7 +705,8 @@ async function handle(msg, sender) {
if (msg.type === "capture-tab") {
if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };
try {
- return { ok: true, dataUrl: await captureActiveTab(sender.tab.windowId) };
+ const dataUrl = await withoutPanel(sender.tab.id, () => captureActiveTab(sender.tab.windowId));
+ return { ok: true, dataUrl };
} catch (e) {
// captureVisibleTab needs activeTab (or <all_urls>, which this extension
// deliberately never asks for) — a page-initiated capture is refused
@@ -257,7 +736,7 @@ async function handle(msg, sender) {
await api.storage.session.remove(key);
if (msg.type === "area-cancelled" || !meta) return { ok: true };
try {
- const dataUrl = await captureActiveTab(sender.tab.windowId);
+ const dataUrl = await withoutPanel(sender.tab.id, () => captureActiveTab(sender.tab.windowId));
const blob = await cropDataUrl(dataUrl, msg.rect, msg.viewportW);
const body = await ingest(blob, meta);
notify("Capture filed into Azimut", body.title);
@@ -279,6 +758,85 @@ async function handle(msg, sender) {
}
}
+ // The app's Reverse Search buttons, relayed by bridge.js: open the engine and
+ // give it the image. Same origin check as every other app route.
+ if (msg.type === "reverse-handoff") {
+ if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };
+ try {
+ return await handOffReverse(msg.payload ?? {});
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ }
+
+ // Popup: draw the map tools over this tab. Injecting the panel a second time
+ // closes it, which is what makes one button both open and close.
+ if (msg.type === "map-tools") {
+ try {
+ await api.scripting.executeScript({ target: { tabId: msg.tabId }, files: MAP_FILES });
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ }
+
+ // The panel, asking the app something. Content scripts cannot call it
+ // themselves; see the relay above.
+ if (msg.type === "map-api") {
+ try {
+ return { ok: true, data: await mapApi(msg) };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ }
+
+ // The panel, asking for one of the case's files — bytes rather than JSON.
+ if (msg.type === "map-file") {
+ try {
+ return { ok: true, file: await mapFile(msg.caseId, msg.path) };
+ } catch (e) {
+ return { ok: false, error: e.message };
+ }
+ }
+
+ // Settings asking what this copy is: the version the browser parsed, and the
+ // folder stamp this code was loaded from. Only the app's own origin may ask —
+ // same rule as every other route relayed by the bridge.
+ if (msg.type === "ext-state") {
+ if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };
+ return {
+ ok: true,
+ version: api.runtime.getManifest().version,
+ // Not `id`: the bridge spreads this answer next to the message's own
+ // correlation id, and a collision there would break the pairing silently.
+ extensionId: api.runtime.id,
+ loaded: await loadedStamp(),
+ installType: await installType(),
+ };
+ }
+
+ // Settings' Update button, after the app has rewritten the folder: restart so
+ // the browser re-reads it.
+ //
+ // Answering *before* reloading is not a nicety. reload() kills this worker at
+ // once, so a handler that reloads first never replies and the app is left
+ // holding a rejected port. And the reply is only "taken", never "worked": what
+ // proves the code moved is the stamp read back afterwards.
+ if (msg.type === "ext-reload") {
+ if (!sender.tab || !isAppUrl(sender.tab.url)) return { ok: false, error: "not the Azimut app" };
+ const stamp = await loadedStamp();
+ // Two copies of this extension can be loaded at once on Chrome, which
+ // derives the extension id from the folder path (see the app's Settings
+ // copy). The message names the install the app means; the other copy must
+ // keep its hands down, because restarting the wrong one is silent and looks
+ // exactly like a failed update.
+ if (msg.installId && msg.installId !== stamp?.install_id) {
+ return { ok: false, error: "another copy of the extension" };
+ }
+ setTimeout(() => api.runtime.reload(), 50);
+ return { ok: true, reloading: true };
+ }
+
return { ok: false, error: `unknown message '${msg.type}'` };
}
@@ -286,3 +844,6 @@ api.runtime.onMessage.addListener((msg, sender, sendResponse) => {
handle(msg, sender).then(sendResponse, (e) => sendResponse({ ok: false, error: e.message }));
return true; // async response
});
+
+// Worker start — including the one right after ext-reload, which is the point.
+reattachBridge();
diff --git a/extension/bridge.js b/extension/bridge.js
index eecb22e..9464e67 100644
--- a/extension/bridge.js
+++ b/extension/bridge.js
@@ -5,12 +5,18 @@
* 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 and Publish requests to the background worker and
- * hands its answer back.
+ * 2. relays the app's requests to the background worker and hands its answer
+ * back — capture, publish, reverse search, and the two the update
+ * button needs.
*
* The app keeps all judgment: registration, cropping, filing. The bridge
* never touches the backend and never sees the pairing token — the app files
* same-origin, so this path needs no pairing at all.
+ *
+ * It is injected twice over: once by the manifest at document_start, and again
+ * by the background worker after an update, so an extension that just restarted
+ * re-attaches without anyone reloading the page. Hence the generation counter —
+ * the newest instance answers and every older one stands down.
*/
(() => {
@@ -18,58 +24,80 @@
const VERSION = api.runtime.getManifest().version;
const CHANNEL = "azimut-capture-ext";
+ // Isolated-world global: a re-injection sees the previous instance's number
+ // and outranks it. A fresh world starts at 1, which is the same rule.
+ const generation = (window.__azimutBridgeGeneration || 0) + 1;
+ window.__azimutBridgeGeneration = generation;
+
+ /** Whether this instance is still the one that should answer.
+ *
+ * Two ways to stop being it: a newer injection took over, or the extension
+ * reloaded and left this context invalidated — `runtime.id` is gone at that
+ * point, and every relay from here would throw. Standing down silently is the
+ * right move either way; the live instance is already answering. */
+ const current = () => generation === window.__azimutBridgeGeneration && Boolean(api.runtime?.id);
+
+ const post = (message) => window.postMessage({ channel: CHANNEL, ...message }, location.origin);
+
document.documentElement.dataset.azimutCaptureExtension = VERSION;
+ // Injected after a reload, the app is already mounted and holding a stale
+ // version: say so rather than waiting to be asked.
+ post({ type: "bridge-hello", version: VERSION });
// The popup announces itself when opened on this tab: that click granted
// activeTab, so the app's Capture button works from now on. Relay it so the
// app can say "you're set — press Capture again".
api.runtime.onMessage.addListener((msg) => {
- if (msg?.type === "app-activated") {
- window.postMessage({ channel: CHANNEL, type: "activated" }, location.origin);
- }
+ if (msg?.type === "app-activated" && current()) post({ type: "activated" });
});
+ // What the app may ask for, and what the answer is called coming back. The
+ // worker decides every one of them; nothing here has an opinion.
+ const RELAYS = {
+ // screen pixels for the Google basemap's Capture button
+ capture: { send: () => ({ type: "capture-tab" }), reply: "capture-result" },
+ // Geo Report's Publish: 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.
+ "post-handoff": {
+ send: (msg) => ({ type: "post-handoff", payload: msg.payload }),
+ reply: "post-handoff-result",
+ },
+ // Reverse Search's engine buttons: the prepared image, and the engine page
+ // to open with it. The frame comes off a canvas in the app, so unlike the
+ // thread above it travels as bytes rather than as a path.
+ "reverse-handoff": {
+ send: (msg) => ({ type: "reverse-handoff", payload: msg.payload }),
+ reply: "reverse-handoff-result",
+ },
+ // Settings: which copy is this, and which folder was it loaded from
+ "ext-state": { send: () => ({ type: "ext-state" }), reply: "ext-state-result" },
+ // Settings' Update button, once the app has rewritten the folder
+ "ext-reload": {
+ send: (msg) => ({ type: "ext-reload", installId: msg.installId }),
+ reply: "ext-reload-result",
+ },
+ };
+
window.addEventListener("message", async (event) => {
// same page, same origin, our channel — nothing else is listened to
if (event.source !== window || event.origin !== location.origin) return;
const msg = event.data;
- if (!msg || msg.channel !== CHANNEL) return;
+ if (!msg || msg.channel !== CHANNEL || !current()) return;
if (msg.type === "ping") {
- window.postMessage(
- { channel: CHANNEL, type: "pong", id: msg.id, version: VERSION },
- location.origin
- );
+ post({ type: "pong", id: msg.id, version: VERSION });
return;
}
- if (msg.type === "capture") {
- let result;
- try {
- result = await api.runtime.sendMessage({ type: "capture-tab" });
- } catch (e) {
- result = { ok: false, error: e.message };
- }
- window.postMessage(
- { channel: CHANNEL, type: "capture-result", id: msg.id, ...result },
- 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
- );
+ const relay = RELAYS[msg.type];
+ if (!relay) return;
+ let result;
+ try {
+ result = await api.runtime.sendMessage(relay.send(msg));
+ } catch (e) {
+ result = { ok: false, error: e.message };
}
+ post({ type: relay.reply, id: msg.id, ...result });
});
})();
diff --git a/extension/manifest.json b/extension/manifest.json
index cf530cb..8dd472c 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -2,14 +2,19 @@
"manifest_version": 3,
"name": "Azimut Capture",
"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.",
+ "description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), save any other page as a bookmark, fill a social composer with a thread the app prepared, or open a reverse-image engine with a picture from the case.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": [
"http://127.0.0.1/*",
"http://localhost/*",
"https://x.com/*",
"https://twitter.com/*",
- "https://bsky.app/*"
+ "https://bsky.app/*",
+ "https://lens.google.com/*",
+ "https://www.google.com/*",
+ "https://yandex.com/*",
+ "https://www.bing.com/*",
+ "https://tineye.com/*"
],
"background": {
"service_worker": "background.js",
@@ -50,8 +55,9 @@
],
"browser_specific_settings": {
"gecko": {
- "strict_min_version": "115.0"
+ "strict_min_version": "115.0",
+ "update_url": "https://raw.githubusercontent.com/OsintMeThat/azimut/main/packaging/updates.json"
}
}
}
diff --git a/extension/mapdraw.js b/extension/mapdraw.js
new file mode 100644
index 0000000..d4d5665
--- /dev/null
+++ b/extension/mapdraw.js
@@ -0,0 +1,342 @@
+/**
+ * The canvas the tools draw on, over a map this code does not own.
+ *
+ * Deliberately ignorant: it is handed shapes in geographic coordinates and a
+ * function that turns one coordinate into a page pixel, and it knows nothing
+ * about projections, gestures or which site is underneath. Everything that can
+ * be wrong about *where* a shape lands is therefore in `mapmath.js`, and
+ * everything that can be wrong about *what* is drawn is in `maptools.js` —
+ * neither of which needs a browser to be tested.
+ *
+ * What it does own is the look, and the look is the app's: the style vocabulary
+ * here is the one `lib/map` takes (stroke, strokeWidth, strokeOpacity, dash,
+ * fill, fillOpacity), the paint comes from `maptheme.js`, and the two marks
+ * with a claim in them — a saved point, a body in the sky — are drawn the same
+ * way the app draws them.
+ *
+ * Loaded after `mapmath.js` and `maptheme.js`, left on `window.AzimutMapDraw`.
+ */
+
+(() => {
+ const THEME = window.AzimutMapTheme;
+
+ /** Past this many pixels off-screen a shape is dropped rather than drawn.
+ * A point behind the camera or on the far side of the world projects to a
+ * coordinate large enough to cost real time to rasterise, and it is not
+ * visible either way. */
+ const FAR = 20000;
+
+ /** A saved mark is this wide, like the app's (`SavedOverlay.svelte`), and its
+ * glyph rides at 13. */
+ const MARK = 24;
+ const MARK_GLYPH = 13;
+
+ /** How far the sharp corner hangs below the middle of that box once it is
+ * turned 45°, which is half a diagonal. The corner is what points at the
+ * coordinate, so the body is drawn this far *above* the point rather than
+ * around it — `lib/mapMarkers.js` states the same number for the app, and
+ * the two have to agree or the same point reads differently on each map. */
+ const MARK_TIP = (MARK / 2) * Math.SQRT2;
+
+ const near = (p) => p && Number.isFinite(p.x) && Number.isFinite(p.y)
+ && Math.abs(p.x) < FAR && Math.abs(p.y) < FAR;
+
+ /** Longest label drawn on the map. Past this the name is the popup's job. */
+ const LABEL_MAX = 34;
+ const clip = (text) => (text.length > LABEL_MAX ? `${text.slice(0, LABEL_MAX - 1)}…` : text);
+
+ function createDrawLayer(root) {
+ const canvas = document.createElement("canvas");
+ Object.assign(canvas.style, {
+ position: "fixed",
+ inset: "0",
+ width: "100%",
+ height: "100%",
+ pointerEvents: "none",
+ zIndex: "1",
+ });
+ root.appendChild(canvas);
+ const ctx = canvas.getContext("2d");
+ let width = 0;
+ let height = 0;
+
+ /** Match the backing store to the viewport and the device's pixel ratio.
+ * Skipped when nothing changed: this runs on every redraw, and
+ * reallocating a canvas clears it. */
+ function fit() {
+ const ratio = window.devicePixelRatio || 1;
+ const w = window.innerWidth;
+ const h = window.innerHeight;
+ if (w === width && h === height && canvas.width === Math.round(w * ratio)) return;
+ width = w;
+ height = h;
+ canvas.width = Math.round(w * ratio);
+ canvas.height = Math.round(h * ratio);
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ }
+
+ function clear() {
+ fit();
+ ctx.clearRect(0, 0, width, height);
+ }
+
+ /** A shape's points, projected, or null when any of them lands nowhere
+ * usable — a half-projected polygon is a wrong polygon, not most of one. */
+ function pixels(points, project) {
+ const out = [];
+ for (const point of points) {
+ const at = project(point);
+ if (!near(at)) return null;
+ out.push(at);
+ }
+ return out;
+ }
+
+ /** The four corners of a lat/lon box, in order. Projected as corners rather
+ * than as a rectangle so a rotated map draws a rotated cell. */
+ const corners = (b) => [
+ { lat: b.north, lon: b.west },
+ { lat: b.north, lon: b.east },
+ { lat: b.south, lon: b.east },
+ { lat: b.south, lon: b.west },
+ ];
+
+ function trace(points, close) {
+ ctx.beginPath();
+ ctx.moveTo(points[0].x, points[0].y);
+ for (let i = 1; i < points.length; i += 1) ctx.lineTo(points[i].x, points[i].y);
+ if (close) ctx.closePath();
+ }
+
+ function stroked(shape, points, close) {
+ if (!shape.stroke) return;
+ trace(points, close);
+ ctx.setLineDash(shape.dash || []);
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+ // A dark casing under the colour, for the few marks that have to stay
+ // readable over snow, sand and a blown-out roof alike. Off by default:
+ // under a lattice of hundreds of cells it reads as a black grid, which is
+ // the opposite of the thin bright outline the app draws.
+ if (shape.casing) {
+ ctx.save();
+ ctx.strokeStyle = "rgba(0,0,0,0.45)";
+ ctx.lineWidth = (shape.strokeWidth || 2) + 2.5;
+ ctx.globalAlpha = 0.55;
+ ctx.stroke();
+ ctx.restore();
+ }
+ ctx.globalAlpha = shape.strokeOpacity ?? 1;
+ ctx.lineWidth = shape.strokeWidth || 2;
+ ctx.strokeStyle = shape.stroke;
+ ctx.stroke();
+ ctx.globalAlpha = 1;
+ ctx.setLineDash([]);
+ }
+
+ function filled(shape, points) {
+ if (!shape.fill || !shape.fillOpacity) return;
+ trace(points, true);
+ ctx.globalAlpha = shape.fillOpacity;
+ ctx.fillStyle = shape.fill;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ /** A name on the map, in a chip that keeps it readable over imagery. Drawn
+ * only for the mark being pointed at or held open — see `maptools.js`. */
+ function label(text, at, offset = 14) {
+ if (!text) return;
+ const line = clip(String(text));
+ ctx.font = "12px system-ui, -apple-system, 'Segoe UI', sans-serif";
+ const w = ctx.measureText(line).width;
+ const x = at.x + offset;
+ const y = at.y - 10;
+ ctx.beginPath();
+ ctx.roundRect(x, y, w + 14, 21, 5);
+ ctx.fillStyle = "rgba(20,20,20,0.92)";
+ ctx.fill();
+ ctx.lineWidth = 1;
+ ctx.strokeStyle = THEME.TOKENS.borderStrong;
+ ctx.stroke();
+ ctx.fillStyle = THEME.TOKENS.text1;
+ ctx.textBaseline = "middle";
+ ctx.fillText(line, x + 7, y + 11);
+ }
+
+ function dot(shape, at) {
+ ctx.beginPath();
+ ctx.arc(at.x, at.y, shape.radius || 4, 0, Math.PI * 2);
+ if (shape.fill) {
+ ctx.globalAlpha = shape.fillOpacity ?? 1;
+ ctx.fillStyle = shape.fill;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+ if (shape.stroke) {
+ ctx.lineWidth = shape.strokeWidth || 2;
+ ctx.strokeStyle = shape.stroke;
+ ctx.stroke();
+ }
+ }
+
+ /** One of the app's 24×24 icons, centred on (0,0) of the current transform. */
+ function glyph(name, size, colour) {
+ const path = THEME.ICONS[name] ?? THEME.ICONS.alert;
+ ctx.save();
+ ctx.scale(size / 24, size / 24);
+ ctx.translate(-12, -12);
+ ctx.strokeStyle = colour;
+ ctx.lineWidth = 2;
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+ ctx.stroke(new Path2D(path));
+ ctx.restore();
+ }
+
+ /**
+ * A saved point, drawn as the app draws it: a rounded teardrop turned 45°,
+ * amber for work that carries imagery and outlined for a bare place, with
+ * the count of what is stacked underneath.
+ *
+ * The corner is the claim, so it is the corner that goes on the coordinate
+ * and the body that moves up out of the way (`MARK_TIP`).
+ */
+ function mark(shape, at) {
+ const place = !!shape.place;
+ const body = { x: at.x, y: at.y - MARK_TIP };
+ ctx.save();
+ ctx.translate(body.x, body.y);
+ ctx.save();
+ ctx.rotate(-Math.PI / 4);
+ ctx.beginPath();
+ ctx.roundRect(-MARK / 2, -MARK / 2, MARK, MARK, [MARK / 2, MARK / 2, MARK / 2, 2]);
+ ctx.fillStyle = place ? "rgba(20,20,20,0.82)" : THEME.TOKENS.accent;
+ ctx.fill();
+ ctx.lineWidth = shape.lit ? 2.5 : 1.5;
+ ctx.strokeStyle = place || shape.lit ? THEME.TOKENS.accent : "rgba(0,0,0,0.55)";
+ ctx.stroke();
+ ctx.restore();
+ glyph(shape.glyph || "pin", MARK_GLYPH, place ? THEME.TOKENS.accent : THEME.TOKENS.accentText);
+ if (shape.count > 1) {
+ const text = String(shape.count);
+ ctx.font = "700 9px system-ui, -apple-system, sans-serif";
+ const w = Math.max(15, ctx.measureText(text).width + 6);
+ ctx.beginPath();
+ ctx.roundRect(6, -MARK / 2 - 5, w, 15, 8);
+ ctx.fillStyle = "#141414";
+ ctx.fill();
+ ctx.fillStyle = "#fff";
+ ctx.textAlign = "center";
+ ctx.textBaseline = "middle";
+ ctx.fillText(text, 6 + w / 2, -MARK / 2 + 3);
+ ctx.textAlign = "start";
+ }
+ ctx.restore();
+ label(shape.label, body, MARK / 2 + 4);
+ }
+
+ /**
+ * The sun or the moon on its ray, the way `lib/moonphase.js` draws one: a
+ * disc for the sun, and for the moon the lit fraction as the terminator
+ * ellipse — which is the same shape from the same two numbers.
+ */
+ function body(shape, at) {
+ const r = shape.radius || 8;
+ ctx.save();
+ ctx.translate(at.x, at.y);
+ ctx.beginPath();
+ ctx.arc(0, 0, r + 1.5, 0, Math.PI * 2);
+ ctx.fillStyle = "rgba(0,0,0,0.45)";
+ ctx.fill();
+ if (shape.bodyKind === "moon") {
+ ctx.globalAlpha = 0.25;
+ ctx.beginPath();
+ ctx.arc(0, 0, r, 0, Math.PI * 2);
+ ctx.fillStyle = shape.colour;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ litShape(r, shape.illuminated ?? 0, shape.waxing, shape.colour);
+ } else {
+ ctx.beginPath();
+ ctx.arc(0, 0, r, 0, Math.PI * 2);
+ ctx.fillStyle = shape.colour;
+ ctx.fill();
+ }
+ ctx.beginPath();
+ ctx.arc(0, 0, r, 0, Math.PI * 2);
+ ctx.lineWidth = 1.5;
+ ctx.strokeStyle = "rgba(255,255,255,0.85)";
+ ctx.stroke();
+ ctx.restore();
+ }
+
+ /**
+ * The lit part of the moon: a half disc closed by an ellipse whose width is
+ * the phase, mirrored for a waning moon. `lib/moonphase.js` writes the same
+ * shape as an SVG arc pair, and the cross-check compares the numbers that
+ * drive both.
+ */
+ function litShape(radius, illuminated, waxing, colour) {
+ const clamped = Math.min(1, Math.max(-1, 2 * illuminated - 1));
+ const phase = Math.acos(clamped);
+ const bulge = Math.abs(Math.cos(phase)) * radius;
+ ctx.save();
+ if (!waxing) ctx.rotate(Math.PI); // the lit side falls right when waxing
+ ctx.beginPath();
+ ctx.arc(0, 0, radius, -Math.PI / 2, Math.PI / 2);
+ ctx.ellipse(0, 0, bulge, radius, 0, Math.PI / 2, -Math.PI / 2, illuminated <= 0.5);
+ ctx.closePath();
+ ctx.fillStyle = colour;
+ ctx.fill();
+ ctx.restore();
+ }
+
+ /**
+ * Redraw everything, once.
+ *
+ * @param {Array} shapes what the tools want drawn, in lat/lon
+ * @param {(point: {lat: number, lon: number}) => {x: number, y: number}} project
+ */
+ function render(shapes, project) {
+ clear();
+ for (const shape of shapes || []) {
+ if (shape.kind === "dot" || shape.kind === "mark" || shape.kind === "body") {
+ const at = project(shape.at);
+ if (!near(at)) continue;
+ if (shape.kind === "mark") mark(shape, at);
+ else if (shape.kind === "body") body(shape, at);
+ else {
+ dot(shape, at);
+ label(shape.label, at, 8);
+ }
+ continue;
+ }
+ if (shape.kind === "cell" || shape.kind === "box") {
+ const points = pixels(corners(shape.bounds), project);
+ if (!points) continue;
+ filled(shape, points);
+ stroked(shape, points, true);
+ continue;
+ }
+ const points = pixels(shape.points || [], project);
+ if (!points || points.length < 2) continue;
+ if (shape.kind === "polygon") filled(shape, points);
+ stroked(shape, points, shape.kind === "polygon");
+ if (shape.label) label(shape.label, points[points.length - 1]);
+ }
+ }
+
+ return {
+ canvas,
+ render,
+ clear,
+ fit,
+ destroy() {
+ canvas.remove();
+ },
+ };
+ }
+
+ window.AzimutMapDraw = { createDrawLayer, FAR, LABEL_MAX, MARK, MARK_TIP };
+})();
diff --git a/extension/mapmath.js b/extension/mapmath.js
new file mode 100644
index 0000000..6d62fde
--- /dev/null
+++ b/extension/mapmath.js
@@ -0,0 +1,778 @@
+/**
+ * The arithmetic behind the map tools: Web Mercator, and the geodesic measures
+ * drawn with it. No DOM, no extension API, no site knowledge — just numbers.
+ *
+ * **Why this is a second copy.** The app states these same rules in
+ * `frontend/src/lib/measure.js`, and stating a rule twice is normally how the
+ * two versions start disagreeing. There is no import across this boundary: the
+ * extension ships as plain classic scripts with no build step, deliberately, so
+ * that what the analyst loads into their browser is the file in the repo. The
+ * guard is a test instead of a module system — `extensionMapMath.test.js` runs
+ * both copies over the same points and fails on the first digit they disagree
+ * about. Add a formula here, add it to that comparison.
+ *
+ * **Nothing here reads the site's map.** Where the camera is comes from the
+ * address bar, parsed by the app (`engine/mapsites.py`); this turns that into
+ * pixels. That is the rail the whole capture path already runs on: a coordinate
+ * is what the URL says, verifiable by anyone holding the recorded link.
+ *
+ * **And the model is checked against the map, not trusted.** A named projection
+ * is a guess about someone else's renderer, and those age — a site can change
+ * flattening between two releases and the drawing would go on looking just as
+ * confident. So a pan is treated as an experiment: the pointer moved a known
+ * number of pixels, the URL then says where the centre went, and that is the
+ * local scale with no projection assumed in it. The named ones are the
+ * bootstrap and a way to put a name to what was measured; the measurement is
+ * the authority, and its residual is what says when to stop drawing.
+ *
+ * Loaded before `mapoverlay.js` and left on `window.AzimutMapMath`.
+ */
+
+(() => {
+ const TILE = 256; // the tile edge every one of these sites is scaled in
+ const R = 6378137; // WGS84 equatorial radius (m) — the one Web Mercator uses
+ //. Mercator sends the poles to infinity, so the projection is defined on a
+ //. square and cut here. This is the value every slippy map cuts at.
+ const MAX_LAT = 85.05112877980659;
+
+ const rad = (deg) => (deg * Math.PI) / 180;
+ const deg = (r) => (r * 180) / Math.PI;
+ const clampLat = (lat) => Math.max(-MAX_LAT, Math.min(MAX_LAT, lat));
+
+ /** The whole world, in CSS pixels, at this zoom. */
+ function worldSize(zoom) {
+ return TILE * Math.pow(2, zoom);
+ }
+
+ //. WGS84's first eccentricity — the whole difference between the two
+ //. Mercators below. Anchored on the view centre they agree there and drift
+ //. apart across the viewport, which measures as tens of metres at z12 and
+ //. under a metre by z17. Which one a site draws in is still never assumed:
+ //. a grid cell is metres wide.
+ const E = 0.081819190842621;
+
+ /** Geographic → world pixels, spherical Mercator (EPSG:3857). */
+ function projectSpherical(lat, lon, zoom) {
+ const size = worldSize(zoom);
+ const phi = rad(clampLat(lat));
+ return {
+ x: ((lon + 180) / 360) * size,
+ y: ((1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2) * size,
+ };
+ }
+
+ /** World pixels → geographic, spherical Mercator. */
+ function unprojectSpherical(x, y, zoom) {
+ const size = worldSize(zoom);
+ const n = Math.PI - (2 * Math.PI * y) / size;
+ return {
+ lat: deg(Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))),
+ lon: (x / size) * 360 - 180,
+ };
+ }
+
+ /**
+ * Geographic → world pixels, elliptical Mercator (EPSG:3395) — Yandex.
+ *
+ * The same map with the Earth's flattening kept in. Longitude is untouched;
+ * only the northing moves, and only by a scale factor — which is why the
+ * error from picking the wrong one grows with distance from the anchor
+ * rather than showing up as a jump.
+ */
+ function projectEllipsoidal(lat, lon, zoom) {
+ const size = worldSize(zoom);
+ const phi = rad(clampLat(lat));
+ const es = E * Math.sin(phi);
+ const t = Math.tan(Math.PI / 4 + phi / 2) * Math.pow((1 - es) / (1 + es), E / 2);
+ return {
+ x: ((lon + 180) / 360) * size,
+ y: ((1 - Math.log(t) / Math.PI) / 2) * size,
+ };
+ }
+
+ /**
+ * World pixels → geographic, elliptical Mercator.
+ *
+ * No closed form for the inverse, so it is iterated. The correction shrinks by
+ * about the eccentricity squared each round, which puts eight rounds far below
+ * a pixel anywhere on the map — and the loop leaves early once it stops moving.
+ */
+ function unprojectEllipsoidal(x, y, zoom) {
+ const size = worldSize(zoom);
+ const t = Math.exp((1 - (2 * y) / size) * Math.PI);
+ let phi = Math.PI / 2 - 2 * Math.atan(1 / t);
+ for (let i = 0; i < 8; i += 1) {
+ const es = E * Math.sin(phi);
+ const next =
+ Math.PI / 2 - 2 * Math.atan((1 / t) * Math.pow((1 - es) / (1 + es), E / 2));
+ if (Math.abs(next - phi) < 1e-12) {
+ phi = next;
+ break;
+ }
+ phi = next;
+ }
+ return { lat: deg(phi), lon: (x / size) * 360 - 180 };
+ }
+
+ // --- Equal Earth (Šavrič, Patterson & Jenny, 2018) ------------------------
+ //
+ // Here before anything needs it, on purpose. No site in the table draws in it
+ // today; the point is that the day one starts, the overlay measures the map,
+ // recognises what it is looking at and keeps drawing — instead of refusing,
+ // or worse, carrying on in Mercator. Costing one afternoon now to not be the
+ // reason a tool breaks later is the trade.
+ //
+ // Pseudocylindrical and equal-area, so unlike the two above it is not a
+ // square: the world comes out about 2.05 times wider than tall, and meridians
+ // curve, which means x depends on latitude as well as longitude. Both are
+ // handled below; what they rule out is the shortcut of treating x and y
+ // separately.
+ const EE = { a1: 1.340264, a2: -0.081106, a3: 0.000893, a4: 0.003796 };
+ const EE_M = Math.sqrt(3) / 2;
+
+ /** The polynomial in θ that both the northing and the easting are built on. */
+ function eeNorthing(t) {
+ const t2 = t * t;
+ const t6 = t2 * t2 * t2;
+ return t * (EE.a1 + EE.a2 * t2 + t6 * (EE.a3 + EE.a4 * t2));
+ }
+
+ /** …and its derivative, which is the easting's denominator. */
+ function eeSlope(t) {
+ const t2 = t * t;
+ const t6 = t2 * t2 * t2;
+ return EE.a1 + 3 * EE.a2 * t2 + t6 * (7 * EE.a3 + 9 * EE.a4 * t2);
+ }
+
+ //. Half the world's width in the projection's own units, so it can be scaled
+ //. into the same `worldSize(zoom)` box the other two use and stay comparable.
+ const EE_HALF = Math.PI / (EE_M * EE.a1);
+
+ function projectEqualEarth(lat, lon, zoom) {
+ const size = worldSize(zoom);
+ const phi = rad(Math.max(-90, Math.min(90, lat)));
+ const t = Math.asin(EE_M * Math.sin(phi));
+ const x = (rad(lon) * Math.cos(t)) / (EE_M * eeSlope(t));
+ const y = eeNorthing(t);
+ return {
+ x: ((x + EE_HALF) / (2 * EE_HALF)) * size,
+ y: size / 2 - (y / (2 * EE_HALF)) * size,
+ };
+ }
+
+ /** Inverted by Newton on the northing — six rounds put it below a pixel, and
+ * it leaves early once it stops moving. */
+ function unprojectEqualEarth(x, y, zoom) {
+ const size = worldSize(zoom);
+ const yr = ((size / 2 - y) * 2 * EE_HALF) / size;
+ const xr = (x / size) * 2 * EE_HALF - EE_HALF;
+ let t = yr;
+ for (let i = 0; i < 12; i += 1) {
+ const step = (eeNorthing(t) - yr) / eeSlope(t);
+ t -= step;
+ if (Math.abs(step) < 1e-12) break;
+ }
+ return {
+ lat: deg(Math.asin(Math.sin(t) / EE_M)),
+ lon: deg((EE_M * xr * eeSlope(t)) / Math.cos(t)),
+ };
+ }
+
+ /**
+ * The flattenings we can write down. Named by the app
+ * (`engine/mapsites.py`) to bootstrap a view before any pan has been
+ * measured, and unknown is a refusal rather than a default. Adding one here
+ * also makes it identifiable from a measurement, with nothing else to write.
+ */
+ const PROJECTIONS = {
+ webmercator: { project: projectSpherical, unproject: unprojectSpherical },
+ ellipsoidal: { project: projectEllipsoidal, unproject: unprojectEllipsoidal },
+ equalearth: { project: projectEqualEarth, unproject: unprojectEqualEarth },
+ };
+
+ function flattening(view) {
+ const pair = PROJECTIONS[view?.projection];
+ if (!pair) throw new Error(`no projection named "${view?.projection}"`);
+ return pair;
+ }
+
+ const project = (lat, lon, zoom, how = "webmercator") =>
+ PROJECTIONS[how].project(lat, lon, zoom);
+ const unproject = (x, y, zoom, how = "webmercator") =>
+ PROJECTIONS[how].unproject(x, y, zoom);
+
+ /**
+ * The way of writing `lon` that sits nearest `near`.
+ *
+ * A point a kilometre west of the antimeridian is at +179.99 and the view at
+ * -179.99; subtract them raw and the point lands most of a world away, on the
+ * far edge of the screen. The map wraps, so the nearest writing is the true
+ * one.
+ */
+ function wrapNear(lon, near) {
+ let out = lon;
+ while (out - near > 180) out -= 360;
+ while (near - out > 180) out += 360;
+ return out;
+ }
+
+ /**
+ * Where a point falls inside the map area, in CSS pixels of the page.
+ *
+ * `view` is what the URL said: `{ lat, lon, zoom, bearing }`, the camera
+ * centred on the area. `area` is that rectangle, `{ x, y, w, h }` — the
+ * calibration, not a fact about the site.
+ */
+ function toScreen(point, view, area) {
+ const flat = flattening(view);
+ const centre = flat.project(view.lat, view.lon, view.zoom);
+ const here = flat.project(point.lat, wrapNear(point.lon, view.lon), view.zoom);
+ return offsetToScreen(here.x - centre.x, here.y - centre.y, view, area);
+ }
+
+ /** The inverse: a page pixel back to a coordinate. */
+ function toLatLon(at, view, area) {
+ const flat = flattening(view);
+ const centre = flat.project(view.lat, view.lon, view.zoom);
+ const { dx, dy } = screenToOffset(at, view, area);
+ return flat.unproject(centre.x + dx, centre.y + dy, view.zoom);
+ }
+
+ /**
+ * A world-pixel offset from the centre, turned by the view's bearing.
+ *
+ * Bearing is the compass direction the map has *up* — Google Earth's `h`, and
+ * the façade's own reading. So east up means north points left, which is a
+ * turn of minus the bearing, not plus it.
+ */
+ function offsetToScreen(dx, dy, view, area) {
+ const spun = turn(dx, dy, view);
+ return { x: area.x + area.w / 2 + spun.dx, y: area.y + area.h / 2 + spun.dy };
+ }
+
+ /** A world-axis displacement in screen axes: the bearing applied, with no
+ * centre in it. `unturn` is the same turn the other way. */
+ function turn(dx, dy, view) {
+ const angle = -rad(view?.bearing || 0);
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ return { dx: dx * cos - dy * sin, dy: dx * sin + dy * cos };
+ }
+
+ /** …and back, turning the other way. */
+ function screenToOffset(at, view, area) {
+ const { dx, dy } = unturn(at.x - (area.x + area.w / 2), at.y - (area.y + area.h / 2), view);
+ return { dx, dy };
+ }
+
+ /**
+ * A screen *displacement* back in the world's own axes.
+ *
+ * The same turn `screenToOffset` applies, with no centre in it: a drag and a
+ * zoom anchor are vectors rather than points, and both are measured against
+ * coordinates, which run along the world's axes and not the screen's. On a
+ * map turned 90° a horizontal drag is a move along a meridian, and dividing
+ * its pixels by a difference of longitude answers about nothing.
+ */
+ function unturn(dx, dy, view) {
+ const turn = rad(view?.bearing || 0);
+ const cos = Math.cos(turn);
+ const sin = Math.sin(turn);
+ return { dx: dx * cos - dy * sin, dy: dx * sin + dy * cos };
+ }
+
+ /** Fold a longitude back inside ±180, the way every one of these maps does. */
+ function wrapLon(lon) {
+ return ((((lon + 180) % 360) + 360) % 360) - 180;
+ }
+
+ // --- measuring the map instead of assuming it ----------------------------
+ //
+ // Everything above is a model of how a site draws. A model is a guess, and a
+ // guess about someone else's renderer ages: a site can change flattening
+ // between two Tuesdays, and the drawing would go on looking exactly as
+ // confident as it did the week before.
+ //
+ // So the model is not the authority — the address bar is. Panning the map is
+ // an experiment: the pointer moved a known number of pixels, and the URL then
+ // says where the centre went. That is the local scale, read off the one
+ // surface we are already allowed to read, with no projection assumed anywhere
+ // in it.
+ //
+ // Over one viewport any smooth projection is near enough affine, which is why
+ // two numbers describe it: pixels per degree, each way. What that buys is
+ // independence from the whole table above — a site that switched to Equal
+ // Earth overnight would be measured, not mis-drawn.
+
+ /** How far apart two samples must be before they say anything about scale.
+ * A two-pixel nudge divided into a rounded coordinate is mostly noise. */
+ const MIN_PAN_PX = 40;
+
+ /**
+ * One pan, turned into a scale reading.
+ *
+ * Dragging the content by `dx`/`dy` moves the centre the other way, so the
+ * coordinate that is centred afterwards is the one that sat `dx`/`dy` pixels
+ * away before. Returns only the axes this pan actually exercised.
+ *
+ * The pointer's travel is turned back into the world's axes first, because
+ * that is what the two degree differences are measured along. Without it a
+ * rotated map measured a scale that was a mix of both axes, the next pan
+ * missed its prediction by hundreds of pixels, and the panel stopped drawing
+ * — which is what turning the view on Google Earth used to do.
+ */
+ function readPan(before, after, dx, dy) {
+ const out = {};
+ const turned = unturn(dx, dy, before);
+ const dLon = wrapNear(after.lon, before.lon) - before.lon;
+ const dLat = after.lat - before.lat;
+ if (Math.abs(turned.dx) >= MIN_PAN_PX && dLon) out.pxPerLon = -turned.dx / dLon;
+ if (Math.abs(turned.dy) >= MIN_PAN_PX && dLat) out.pxPerLat = -turned.dy / dLat;
+ return out;
+ }
+
+ /** How far a new reading may sit from the one held before it is taken for a
+ * gesture that overshot rather than for the map having changed scale. */
+ const MAX_SCALE_JUMP = 0.25;
+
+ const wild = (held, next) =>
+ held != null && Math.abs(next - held) / Math.abs(held) > MAX_SCALE_JUMP;
+
+ /**
+ * A scale measured from the map itself, and how well it is holding.
+ *
+ * `residual` is the honest part: each new pan is first *predicted* with what
+ * is already known, then compared with what the URL actually said. While that
+ * stays small the model describes this map; when it grows, something changed
+ * — a projection, a globe, a side panel — and the caller is expected to stop
+ * drawing rather than draw wrong.
+ */
+ function createCalibration() {
+ let pxPerLon = null;
+ let pxPerLat = null;
+ let residual = null;
+ let samples = 0;
+
+ return {
+ get scale() {
+ return pxPerLon && pxPerLat ? { pxPerLon, pxPerLat } : null;
+ },
+ get samples() {
+ return samples;
+ },
+ /** Pixels between prediction and what the address bar said, last pan.
+ * Null until there was something to predict with. */
+ get residual() {
+ return residual;
+ },
+
+ /** Record one pan. Returns the residual it produced, or null. */
+ observe(before, after, dx, dy) {
+ const read = readPan(before, after, dx, dy);
+ if (!read.pxPerLon && !read.pxPerLat) return null;
+ if (pxPerLon && pxPerLat) {
+ const dLon = wrapNear(after.lon, before.lon) - before.lon;
+ const dLat = after.lat - before.lat;
+ // scored in the world's axes, where the scale lives — the pointer's
+ // travel is turned into them rather than the prediction out of them,
+ // and a distance is the same length either way round
+ const turned = unturn(dx, dy, before);
+ residual = Math.hypot(-dLon * pxPerLon - turned.dx, -dLat * pxPerLat - turned.dy);
+ }
+ // The newest reading wins rather than being averaged in: scale is a
+ // function of zoom and latitude, so an old sample is not a second
+ // opinion about the same quantity, it is an answer about another view.
+ //
+ // Unless it is wild. These maps glide on after the finger leaves, so a
+ // pan that ends in inertia reports a move the pointer never made and
+ // reads as a scale a third larger than the real one. A zoom or a
+ // rotation — the only things that legitimately move the scale — reset
+ // this outright, so a jump this big with neither is a bad sample, and a
+ // bad sample adopted is a drawing that is wrong until the next pan.
+ if (read.pxPerLon && !wild(pxPerLon, read.pxPerLon)) pxPerLon = read.pxPerLon;
+ if (read.pxPerLat && !wild(pxPerLat, read.pxPerLat)) pxPerLat = read.pxPerLat;
+ samples += 1;
+ return residual;
+ },
+
+ /**
+ * Carry the scale through a zoom the address bar does not name.
+ *
+ * A view that quotes a camera span instead of a zoom (Google's satellite
+ * and Earth) states a number proportional to metres per pixel, so the
+ * ratio of two of them is the ratio of two scales. Without this, every
+ * zoom threw the measurement away and the panel asked for another pan.
+ */
+ rescale(factor) {
+ if (!Number.isFinite(factor) || factor <= 0) return false;
+ if (!pxPerLon || !pxPerLat) return false;
+ pxPerLon *= factor;
+ pxPerLat *= factor;
+ residual = null; // nothing has been predicted at this scale yet
+ return true;
+ },
+
+ /** A zoom or a rotation makes every reading stale at once. */
+ reset() {
+ pxPerLon = null;
+ pxPerLat = null;
+ residual = null;
+ samples = 0;
+ },
+ };
+ }
+
+ /**
+ * The zoom a measured horizontal scale implies, exactly.
+ *
+ * Mercator puts longitude on the x axis linearly — `x = (lon+180)/360 · 256·2^z`
+ * — so `pxPerLon` names the zoom and nothing else does. Both flattenings agree
+ * about it, since only the northing differs between them.
+ *
+ * This is what lets a measurement correct a *scale* without replacing the
+ * *shape*: the site table says which flattening is drawn, the map itself says
+ * how big, and the two together beat either alone. A zoom read off the address
+ * bar is rounded to a decimal — three and a half percent at the wrong moment,
+ * which is a drawing that slides as it leaves the middle of the screen.
+ */
+ function zoomFromScale(pxPerLon) {
+ if (!pxPerLon) return null;
+ return Math.log2((Math.abs(pxPerLon) * 360) / TILE);
+ }
+
+ /**
+ * The factor a zoom changed the scale by, read off the point it turned about.
+ *
+ * Every one of these maps zooms about something it keeps still — the cursor
+ * for a wheel notch, the click for a double-click. Take a point whose
+ * coordinate was known before the zoom and which is still under the same
+ * pixel afterwards, and the new scale falls straight out of where the address
+ * bar now says the centre is:
+ *
+ * pxPerLon' = (anchorX - centreX) / (anchorLon - centreLon')
+ *
+ * No projection, no tile size, no zoom level, no device pixel ratio — the two
+ * inputs are a pixel this window measured and a coordinate the site itself
+ * wrote. That is what makes it right on any screen, any browser and any map,
+ * and it is why a zoom no longer costs the analyst another pan to re-measure.
+ *
+ * Returns null when the geometry cannot answer: an anchor too near the centre
+ * divides by almost nothing, which is a refusal rather than an approximation.
+ * A rotated map is not one of those any more — the anchor's own offset is
+ * turned back into the world's axes, the same undoing a pan gets.
+ *
+ * @param {{x: number, y: number, lat: number, lon: number}} anchor the point
+ * the zoom held still, with the coordinate it had before
+ * @param {object} view where the address bar says the centre is now
+ * @param {{x,y,w,h}} area the map rectangle
+ * @param {{pxPerLon: number, pxPerLat: number}} scale what was measured before
+ */
+ function rescaleFromAnchor(anchor, view, area, scale) {
+ if (!anchor || anchor.lat == null || !scale) return null;
+ const { dx: dxPx, dy: dyPx } = screenToOffset(anchor, view, area);
+ const dLon = wrapNear(anchor.lon, view.lon) - view.lon;
+ const dLat = anchor.lat - view.lat;
+ // the better-conditioned axis wins: near the centre the division is noise,
+ // and a factor is a factor whichever way round it was read
+ const candidates = [];
+ if (Math.abs(dxPx) >= MIN_ANCHOR_PX && Math.abs(dLon) > 1e-12) {
+ candidates.push([Math.abs(dxPx), dxPx / dLon / scale.pxPerLon]);
+ }
+ if (Math.abs(dyPx) >= MIN_ANCHOR_PX && Math.abs(dLat) > 1e-12) {
+ candidates.push([Math.abs(dyPx), dyPx / dLat / scale.pxPerLat]);
+ }
+ if (!candidates.length) return null;
+ candidates.sort((a, b) => b[0] - a[0]);
+ const factor = candidates[0][1];
+ return factor > 0 && Number.isFinite(factor) && factor < 64 && factor > 1 / 64 ? factor : null;
+ }
+
+ /** How far from the centre the held point has to be before the division above
+ * says more than the address bar's own rounding does. */
+ const MIN_ANCHOR_PX = 80;
+
+ // --- where the site draws its own centre ---------------------------------
+ //
+ // Everything above answers "how big". This answers "where": which pixel of
+ // the window the coordinate in the address bar is actually under.
+ //
+ // It is not the middle of the window on every site, and the difference is not
+ // small. Measured in a browser at 1600×1000: Yandex's centre sits 210 px
+ // right of the window's, because its results panel is 420 px wide and the map
+ // is centred in what is left; Apple's sits 67 px right; Bing's 40 px down,
+ // under its header; OpenStreetMap's 27 px down, under its. Drawn on the
+ // window's centre instead, every one of those is a fixed offset on the
+ // ground — 90 m at z15 for Yandex — that no amount of scale accuracy touches,
+ // because a pan cannot see it: slide the whole map and the offset slides with
+ // it.
+ //
+ // A zoom can. Every one of these maps zooms about a point it holds still, so
+ // that point is under the same pixel before and after while the centre
+ // underneath it has moved — and the pixel that did not move is the one the
+ // arithmetic below solves for. Two coordinates the site wrote, two zooms it
+ // stated, one pixel this window counted; no assumption about panels, screens
+ // or layout anywhere in it.
+
+ /** How much the zoom has to have changed before the division below is worth
+ * doing. A tenth of a level is mostly the address bar's own rounding, and
+ * the answer comes out amplified by 1/(1−2^Δz). */
+ const MIN_ZOOM_STEP = 0.5;
+
+ /**
+ * The pixel the site's camera centre is drawn at, from a zoom about a held
+ * point — or null when this zoom cannot say.
+ *
+ * With `s = 2^zoom` and world coordinates `w()` taken at zoom 0, the held
+ * point `P` is under the same pixel `p` before and after:
+ *
+ * p = C + s₀·(w(P) − w(c₀)) = C + s₁·(w(P) − w(c₁))
+ *
+ * which fixes `w(P)`, and `C` with it. Both axes are solved the same way and
+ * independently, so a site that is off-centre one way only says so.
+ *
+ * @param {object} before the view the address bar stated before the zoom
+ * @param {object} after the view it states now
+ * @param {{x: number, y: number}} at the pixel the zoom was made about
+ */
+ function centreFromZoom(before, after, at) {
+ if (!before || !after || !at) return null;
+ // A gesture that turned *and* zoomed cannot be read: the offset below is
+ // turned by one bearing and there were two. A view held at a bearing is
+ // fine, and that is what a rotated map is between two nudges of its
+ // compass.
+ if ((before.bearing || 0) !== (after.bearing || 0)) return null;
+ if (before.zoom == null || after.zoom == null) return null;
+ if (Math.abs(after.zoom - before.zoom) < MIN_ZOOM_STEP) return null;
+ if (before.projection !== after.projection) return null;
+ if (!PROJECTIONS[before.projection]) return null; // a view nothing can be drawn on
+ const flat = flattening(before);
+ const s0 = Math.pow(2, before.zoom);
+ const s1 = Math.pow(2, after.zoom);
+ const c0 = flat.project(before.lat, before.lon, 0);
+ const c1 = flat.project(after.lat, wrapNear(after.lon, before.lon), 0);
+ // Where the held point is in the world follows from the two zooms alone —
+ // the bearing cancels, since the same turn carries both sides of `p = C +
+ // R·s·(w(P) − w(c))`. What the turn does touch is the last step: the offset
+ // taken off the held pixel is a world-axis one, and on a rotated map that
+ // is not the offset the screen sees.
+ const held = (axis) => (s0 * c0[axis] - s1 * c1[axis]) / (s0 - s1);
+ const spun = turn(s0 * (held("x") - c0.x), s0 * (held("y") - c0.y), before);
+ const centre = { x: at.x - spun.dx, y: at.y - spun.dy };
+ return Number.isFinite(centre.x) && Number.isFinite(centre.y) ? centre : null;
+ }
+
+ /**
+ * The zoom a view is really at, from the pixel a zoom held still — even when
+ * the address bar rounded the number it landed on.
+ *
+ * Bing is why. Its wheel moves a third of a level at a time and it writes one
+ * decimal, so "15.3" is really 15.3333: a fortieth of a level, which is two
+ * and a third percent of scale, which is five metres at the edge of the
+ * screen. The centre solve above cannot see it — the frame is an offset, and
+ * a scale error grows outward from it.
+ *
+ * With the frame already known, the same held point says it outright. The
+ * point sits `d` pixels from the centre both before and after, so its place
+ * in the world follows from the scale before it, and the scale after it
+ * follows from where the centre went:
+ *
+ * w(P) = w(c₀) + d/s₀ s₁ = d / (w(P) − w(c₁))
+ *
+ * Two things it will not do. It needs a `before` whose zoom is already exact,
+ * because an error there comes straight out the other side — a whole level is
+ * exact by definition, and a corrected one stays exact. And it is a
+ * correction, not a replacement: an answer more than half a level from what
+ * the site said is something else having moved, and is refused.
+ *
+ * @param {object} before the view before the zoom, at a zoom known to be true
+ * @param {object} after what the address bar says now
+ * @param {{x: number, y: number}} at the pixel the zoom was made about
+ * @param {{x: number, y: number}} centre where this site draws its camera
+ */
+ function zoomFromAnchor(before, after, at, centre) {
+ if (!before || !after || !at || !centre) return null;
+ if ((before.bearing || 0) !== (after.bearing || 0)) return null;
+ if (before.zoom == null || after.zoom == null) return null;
+ if (before.projection !== after.projection) return null;
+ if (!PROJECTIONS[before.projection]) return null;
+ const flat = flattening(before);
+ const s0 = Math.pow(2, before.zoom);
+ const c0 = flat.project(before.lat, before.lon, 0);
+ const c1 = flat.project(after.lat, wrapNear(after.lon, before.lon), 0);
+ // the held pixel's offset from the centre, in the world's axes — which is
+ // the frame the two coordinates below are measured in
+ const held = unturn(at.x - centre.x, at.y - centre.y, before);
+ const offsets = { x: held.dx, y: held.dy };
+ const solve = (axis) => {
+ const d = offsets[axis];
+ if (Math.abs(d) < MIN_ANCHOR_PX) return null;
+ const span = c0[axis] + d / s0 - c1[axis];
+ if (!span || !Number.isFinite(span)) return null;
+ const zoom = Math.log2(d / span);
+ return Number.isFinite(zoom) ? zoom : null;
+ };
+ // the axis whose anchor sits furthest from the centre divides by the most
+ const wide = Math.abs(offsets.x) >= Math.abs(offsets.y);
+ const first = wide ? solve("x") : solve("y");
+ const other = wide ? solve("y") : solve("x");
+ const zoom = first ?? other;
+ if (zoom == null) return null;
+ return Math.abs(zoom - after.zoom) <= 0.5 ? zoom : null;
+ }
+
+ /** Project through a measured scale rather than a named projection. */
+ function toScreenMeasured(point, view, area, scale) {
+ const dx = (wrapNear(point.lon, view.lon) - view.lon) * scale.pxPerLon;
+ const dy = (point.lat - view.lat) * scale.pxPerLat;
+ return offsetToScreen(dx, dy, view, area);
+ }
+
+ /** …and back. */
+ function toLatLonMeasured(at, view, area, scale) {
+ const { dx, dy } = screenToOffset(at, view, area);
+ return { lat: view.lat + dy / scale.pxPerLat, lon: wrapLon(view.lon + dx / scale.pxPerLon) };
+ }
+
+ /**
+ * Which of the flattenings we know matches what was measured — or null,
+ * meaning this map is drawn in something we cannot name.
+ *
+ * Both axes are compared, because one is not enough. Equal Earth's latitude
+ * scale crosses Mercator's somewhere in the low thirties, so at that latitude
+ * the northing alone cannot tell them apart; their easting scales differ by
+ * some seven percent everywhere, and settle it.
+ *
+ * The honest limit runs the other way. Spherical and elliptical Mercator
+ * differ by well under one percent, which is inside the noise of a coordinate
+ * the address bar has rounded — so a measurement cannot really choose between
+ * *those* two. That is what `prefer` is for: the app's site table
+ * (`engine/mapsites.py`) knows which one a site draws in, and keeps that
+ * answer unless the measurement clearly disagrees with it. Each covers the
+ * other's blind spot — the measurement catches a whole family changing under
+ * us, the table settles a difference too fine to measure.
+ *
+ * @param {object|null} scale the measured `{ pxPerLon, pxPerLat }`
+ * @param {object} view where the camera is, for the latitude the scale is at
+ * @param {object} [opts]
+ * @param {number} [opts.tolerance] accepted relative error, per axis
+ * @param {string} [opts.prefer] what the site table said, kept when it is
+ * within a hair of the best measured match
+ */
+ function identify(scale, view, { tolerance = 0.02, prefer = null } = {}) {
+ if (!scale) return null;
+ const step = 0.001; // a thousandth of a degree, well inside any viewport
+ const scored = [];
+ for (const [name, pair] of Object.entries(PROJECTIONS)) {
+ const north = pair.project(view.lat + step, view.lon, view.zoom).y
+ - pair.project(view.lat - step, view.lon, view.zoom).y;
+ const east = pair.project(view.lat, view.lon + step, view.zoom).x
+ - pair.project(view.lat, view.lon - step, view.zoom).x;
+ const expectLat = north / (2 * step);
+ const expectLon = east / (2 * step);
+ const offLat = Math.abs(expectLat - scale.pxPerLat) / Math.abs(expectLat);
+ const offLon = Math.abs(expectLon - scale.pxPerLon) / Math.abs(expectLon);
+ if (offLat <= tolerance && offLon <= tolerance) {
+ scored.push({ name, off: Math.max(offLat, offLon) });
+ }
+ }
+ if (!scored.length) return null;
+ scored.sort((a, b) => a.off - b.off);
+ const best = scored[0];
+ // The table's answer stands unless the measurement is markedly better —
+ // two candidates a fraction of a percent apart are one candidate.
+ const preferred = scored.find((entry) => entry.name === prefer);
+ if (preferred && preferred.off <= best.off * 2 + 0.002) return preferred.name;
+ return best.name;
+ }
+
+ // --- geodesic measures (mirrored from lib/measure.js) --------------------
+
+ /** Great-circle distance between two points, in metres (haversine). */
+ function haversine(a, b) {
+ const dLat = rad(b.lat - a.lat);
+ const dLon = rad(b.lon - a.lon);
+ const s =
+ Math.sin(dLat / 2) ** 2 +
+ Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(s)));
+ }
+
+ /** Total length of a clicked path, in metres. */
+ function pathLength(points) {
+ let total = 0;
+ for (let i = 1; i < points.length; i += 1) total += haversine(points[i - 1], points[i]);
+ return total;
+ }
+
+ /** Area of a closed polygon on the sphere, in square metres. */
+ function polygonArea(points) {
+ if (points.length < 3) return 0;
+ let sum = 0;
+ for (let i = 0; i < points.length; i += 1) {
+ const a = points[i];
+ const b = points[(i + 1) % points.length];
+ sum += rad(b.lon - a.lon) * (2 + Math.sin(rad(a.lat)) + Math.sin(rad(b.lat)));
+ }
+ return Math.abs((sum * R * R) / 2);
+ }
+
+ const FT_PER_M = 3.28084;
+ const FT_PER_MI = 5280;
+ const SQFT_PER_ACRE = 43560;
+ const SQMI_PER_SQM = 3.861021585e-7;
+
+ //. Written exactly as `lib/measure.js` writes them — the cross-check test
+ //. compares the two strings, not just the two numbers, because a readout that
+ //. reads differently in the extension is a second answer to one question.
+ function formatDistance(m, units = "metric") {
+ if (units === "imperial") {
+ const ft = m * FT_PER_M;
+ if (ft < FT_PER_MI) return `${ft < 10 ? ft.toFixed(1) : Math.round(ft)} ft`;
+ const mi = ft / FT_PER_MI;
+ return `${mi.toFixed(mi < 10 ? 2 : 1)} mi`;
+ }
+ if (m < 1000) return `${m < 10 ? m.toFixed(1) : Math.round(m)} m`;
+ return `${(m / 1000).toFixed(m < 10000 ? 2 : 1)} km`;
+ }
+
+ function formatArea(m2, units = "metric") {
+ if (units === "imperial") {
+ const sqft = m2 * FT_PER_M * FT_PER_M;
+ if (sqft < SQFT_PER_ACRE) return `${Math.round(sqft)} ft²`;
+ const sqmi = m2 * SQMI_PER_SQM;
+ if (sqmi < 1) return `${(sqft / SQFT_PER_ACRE).toFixed(2)} acres`;
+ return `${sqmi.toFixed(2)} mi²`;
+ }
+ if (m2 < 10000) return `${Math.round(m2)} m²`;
+ if (m2 < 1e6) return `${(m2 / 10000).toFixed(2)} ha`;
+ return `${(m2 / 1e6).toFixed(2)} km²`;
+ }
+
+ // Exported: what another file or a test actually calls. The projections'
+ // primitives are here because the round trip through them is the property
+ // that pins this file down; everything else stays inside it.
+ window.AzimutMapMath = {
+ project,
+ unproject,
+ centreFromZoom,
+ zoomFromAnchor,
+ MIN_ZOOM_STEP,
+ toScreen,
+ toLatLon,
+ toScreenMeasured,
+ toLatLonMeasured,
+ createCalibration,
+ turn,
+ unturn,
+ identify,
+ zoomFromScale,
+ rescaleFromAnchor,
+ MIN_ANCHOR_PX,
+ MIN_PAN_PX,
+ haversine,
+ pathLength,
+ polygonArea,
+ formatDistance,
+ formatArea,
+ };
+})();
diff --git a/extension/mapoverlay.js b/extension/mapoverlay.js
new file mode 100644
index 0000000..7f5a354
--- /dev/null
+++ b/extension/mapoverlay.js
@@ -0,0 +1,2121 @@
+/**
+ * The map tools panel: the surface everything else hangs off.
+ *
+ * Injected into whatever map the analyst is already on. It holds three things
+ * that have to agree with each other:
+ *
+ * 1. **A panel**, in a shadow root so the host page's CSS cannot reach it, and
+ * remembered per site — analysts do not want to re-place it every visit. It
+ * is painted in the app's own tokens and drawn with the app's own icons
+ * (`maptheme.js`), because switching between the app's map and a browser tab
+ * should not feel like switching tools.
+ * 2. **The view engine.** Where the camera is, from the app's parse of the URL,
+ * carried between two URLs by the gesture in flight, with the scale measured
+ * off the map itself and the prediction error watched. This is what turns
+ * geometry on and off, and it says why in words when it turns it off.
+ * 3. **The tools**, which are `maptools.js` and know nothing about any of the
+ * above — plus the reference windows, which `mapref.js` paints: case
+ * images and videos held over the map, chrome rather than drawing, and the
+ * one tool here that keeps working on a view no geometry can be done on.
+ *
+ * The map is not taken to be the whole window. A site with a side panel draws
+ * its centre somewhere else — Yandex 210 px to the right of the window's, Bing
+ * 40 px below it — and drawn on the window's centre instead, everything lands
+ * that far off the ground, at every zoom, for ever. There was a calibration
+ * frame here for that once, dragged by hand per site; it went, because it asked
+ * the analyst a question they should not have to answer and got it wrong more
+ * often than the offset it was correcting. It is back, measured: a zoom holds
+ * one pixel still while the centre moves under it, which is enough to solve for
+ * the pixel the centre is drawn at (`mapmath.js`, `centreFromZoom`). Measured
+ * once per site, remembered, and re-measured on every zoom after.
+ *
+ * Nothing here reaches the network directly. A content script's fetch carries
+ * the *page's* origin, which the app's own guard refuses — correctly, since
+ * that origin is google.com. Every call goes through the worker's `map-api`
+ * relay, which speaks as the extension over the routes it is allowed.
+ *
+ * Injected after mapmath.js, maptheme.js, maptools.js and mapdraw.js. Injecting
+ * it a second time closes the panel, which is what the toolbar button does.
+ */
+
+(() => {
+ const api = typeof browser !== "undefined" ? browser : chrome;
+
+ // A second injection is the button being pressed again.
+ if (window.__AZIMUT_MAP_TOOLS__) {
+ window.__AZIMUT_MAP_TOOLS__.close();
+ return;
+ }
+
+ const M = window.AzimutMapMath;
+ const T = window.AzimutMapTools;
+ const D = window.AzimutMapDraw;
+ const R = window.AzimutMapRefs;
+ const THEME = window.AzimutMapTheme;
+ if (!M || !T || !D || !R || !THEME) {
+ // The files before this one are injected in the same call and share a scope
+ // on both browsers. If that ever stops being true the panel would simply
+ // never appear, which is the hardest kind of bug to be told about.
+ console.warn("[Azimut] map tools: the panel's own scripts did not load together");
+ return;
+ }
+
+ const HOST_ID = "azimut-map-tools";
+ const storeKey = `mapTools:${location.host}`;
+ /** How often the address bar is re-read. These maps rewrite it themselves
+ * without a navigation event, so there is nothing to subscribe to. */
+ const URL_POLL_MS = 300;
+ /** How still the pointer must be before it lifts for the pan to count as a
+ * measurement rather than a fling. */
+ const FLING_PAUSE_MS = 120;
+ /** How long after a gesture the address bar is given to catch up, and how
+ * often it is re-read while waiting. */
+ const SETTLE_MS = 200;
+ const SETTLE_POLL_MS = 120;
+ /** Waiting is not forever: a site that never rewrites its URL would leave the
+ * drawing dimmed for good. */
+ const SETTLE_GIVE_UP_MS = 2500;
+ /**
+ * How often the open sweep is re-read from the case, when nothing has said to.
+ *
+ * The app says so: a mark made anywhere arrives here as a nudge, over the
+ * worker (`background.js`, the map-sync port). This is what covers the one
+ * thing a push cannot — a worker the browser evicted mid-sweep, which is
+ * noticed when its port dies and healed on the next connect, but not
+ * instantly. So it stays, and stays slow: nothing waits on it.
+ */
+ const GRID_POLL_MS = 30000;
+ /** How long before a port that died — an evicted worker, an extension that
+ * reloaded — is opened again. */
+ const SYNC_RETRY_MS = 2000;
+ /** How often the panel speaks on that port. It carries nothing; what it does
+ * is keep the worker from being evicted while a sweep is open, and give it
+ * the moment to notice a stream of its own that dropped. */
+ const WATCH_MS = 20000;
+ /** The nudges that mean the case's points moved, whoever moved them. */
+ const SAVED_EVENTS = new Set(["place", "capture", "saved"]);
+ const icon = THEME.icon;
+
+ // --- talking to the app ----------------------------------------------------
+
+ async function call(method, path, { query, body, form } = {}) {
+ const answer = await api.runtime.sendMessage({ type: "map-api", method, path, query, body, form });
+ if (!answer?.ok) throw new Error(answer?.error || "the app did not answer");
+ return answer.data;
+ }
+
+ /**
+ * One of the case's files, as bytes.
+ *
+ * A separate errand from `call` because this is not JSON: it crosses the
+ * worker boundary as base64, since a message carries strings and never a
+ * blob, and is rebuilt into one here. What `mapref.js` then does with it —
+ * decode an image, or hand a video an object URL — is its business.
+ */
+ async function fetchFile(path) {
+ const answer = await api.runtime.sendMessage({ type: "map-file", caseId: state.caseId, path });
+ if (!answer?.ok) throw new Error(answer?.error || "the app did not answer");
+ const binary = atob(answer.file.data);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
+ return new Blob([bytes], { type: answer.file.type });
+ }
+
+ // --- the state the whole panel reads ---------------------------------------
+
+ const state = {
+ parsed: null, // the app's reading of the current URL
+ view: null, // { lat, lon, zoom, bearing, projection } — parse, plus the gesture in flight
+ calibration: M.createCalibration(),
+ // Where this site draws the coordinate the address bar names, as an offset
+ // from the middle of the window. Measured off a zoom, remembered per site,
+ // and (0, 0) until one has been made.
+ frame: { x: 0, y: 0 },
+ framed: false, // whether that offset was measured or is still the default
+ caseId: "",
+ cases: [],
+ tool: null, // which tool the panel is showing, or none
+ units: "metric",
+ note: "", // the last thing that went wrong, shown in the panel
+ pinTitle: "",
+ gridTitle: "",
+ grids: null,
+ collapsed: false,
+ };
+
+ const tools = {
+ measure: T.createMeasure(),
+ pins: T.createPins(),
+ sky: T.createSky(),
+ grid: T.createGridTool(),
+ refs: T.createRefs(),
+ };
+ const ORDER = ["measure", "pins", "sky", "grid", "refs"];
+ const current = () => (state.tool ? tools[state.tool] : null);
+
+ /**
+ * The map rectangle in page pixels: the window, moved by the site's own
+ * frame so that its middle falls where the site draws its centre.
+ *
+ * The size is the window's, which is what the drawing needs it for — nothing
+ * here claims to know where a site's map stops and its chrome starts, only
+ * where the middle of the camera is.
+ */
+ function area() {
+ return {
+ x: state.frame.x,
+ y: state.frame.y,
+ w: window.innerWidth,
+ h: window.innerHeight,
+ };
+ }
+
+ /**
+ * Whether geometry is sound right now, and if not, why (maptools.js).
+ *
+ * The residual handed over is the *run* of bad ones, not the last one. These
+ * maps glide on after the finger leaves, so one pan in three lands somewhere
+ * the pointer never went and reads as a large error that is really just
+ * inertia. A projection that has actually changed misses every time.
+ */
+ const verdict = () =>
+ T.verdict(state.parsed, drift >= DRIFT_LIMIT ? modelError : null, !!state.calibration.scale);
+
+ // --- where a coordinate lands, and what a pixel is -------------------------
+
+ /**
+ * The shape from the table, the size from the address bar, and the map itself
+ * only where neither says.
+ *
+ * These are different questions with different best answers. *Which*
+ * flattening a site draws in is a fact about the site, and the app's table
+ * (`engine/mapsites.py`) knows it — measuring cannot tell spherical from
+ * elliptical Mercator anyway, they differ by under a percent. *How big* it is
+ * drawn is a number the site itself writes, in one of three ways, and every
+ * one of them was checked against a browser before being believed: a tile
+ * level, a viewport height in metres, a span in degrees (`scale_source`).
+ *
+ * This used to prefer a scale measured by panning, on the grounds that the
+ * address bar rounds its zoom. That was the wrong trade, and it is what made
+ * the drawing wrong: a drag loses a few pixels to the site's own threshold
+ * and gains a few to its glide, and a pan of 40 px measured through a URL is
+ * a scale off by a tenth — where the stated level is exact to a hundredth of
+ * a zoom. So the URL wins wherever it speaks, and the measurement is kept for
+ * the one view that states nothing at all: Earth, a free camera with no
+ * flattening to name.
+ */
+ const scale = () => (state.calibration.residual == null || state.calibration.residual <= T.RESIDUAL_LIMIT
+ ? state.calibration.scale
+ : null);
+
+ /** The flattenings whose easting is Mercator's, and so whose zoom a measured
+ * `pxPerLon` names exactly. Equal Earth's is not, and would swallow the very
+ * difference `identify` uses to recognise it. */
+ const MERCATORS = new Set(["webmercator", "ellipsoidal"]);
+
+ /** The view to project through: the parsed one, with its zoom replaced by a
+ * measured one only where the URL stated no scale to begin with. */
+ function projected() {
+ if (state.parsed?.scale_source) return state.view;
+ const s = scale();
+ if (!s || !MERCATORS.has(state.view?.projection)) return state.view;
+ const zoom = M.zoomFromScale(s.pxPerLon);
+ return zoom == null ? state.view : { ...state.view, zoom };
+ }
+
+ function toScreen(point) {
+ return state.parsed?.projection
+ ? M.toScreen(point, projected(), area())
+ : M.toScreenMeasured(point, state.view, area(), scale());
+ }
+
+ /**
+ * A page pixel back to a coordinate.
+ *
+ * The gesture in flight is undone first. While the canvas is carrying a pan
+ * the drawing and the screen are two frames apart, and on a site whose
+ * address bar lags — Copernicus rewrites its URL on a zoom but not on a pan —
+ * they can stay that way. Undoing it is exact, because a pan is a
+ * translation: the pixel that was clicked was at `(x − dx) / k` before the
+ * map moved, and that is the frame `state.view` still describes.
+ */
+ function toLatLon(at) {
+ const point = gesture
+ ? { x: (at.x - gesture.dx) / gesture.k, y: (at.y - gesture.dy) / gesture.k }
+ : at;
+ return state.parsed?.projection
+ ? M.toLatLon(point, projected(), area())
+ : M.toLatLonMeasured(point, state.view, area(), scale());
+ }
+
+ /** Metres across the shorter side of the window — what the sky arc is drawn
+ * to, so it stays inside the view on any screen. */
+ function spanMetres() {
+ const a = area();
+ const mid = a.h / 2;
+ const midX = a.w / 2;
+ try {
+ const across = M.haversine(toLatLon({ x: 0, y: mid }), toLatLon({ x: a.w, y: mid }));
+ const down = M.haversine(toLatLon({ x: midX, y: 0 }), toLatLon({ x: midX, y: a.h }));
+ return Math.min(across, down);
+ } catch {
+ return 400;
+ }
+ }
+
+ // --- the drawing -----------------------------------------------------------
+
+ const host = document.createElement("div");
+ host.id = HOST_ID;
+ Object.assign(host.style, {
+ position: "fixed",
+ inset: "0",
+ zIndex: "2147483000",
+ pointerEvents: "none",
+ });
+ const root = host.attachShadow({ mode: "open" });
+ document.documentElement.appendChild(host);
+ const layer = D.createDrawLayer(root);
+
+ let frame = 0;
+ /**
+ * What the map has done since the drawing was last projected.
+ *
+ * A pan moves the map by exactly the pixels the pointer travelled, and a
+ * wheel notch scales it about the pointer. Both are rigid transforms of what
+ * is already on screen, so the canvas is *moved* rather than redrawn: nothing
+ * is re-projected, so no error in the scale model can show up as the drawing
+ * sliding against the ground under it. It is cleared the moment the address
+ * bar says where the map actually landed, and everything is projected again
+ * from there.
+ */
+ let gesture = null; // { dx, dy, k }
+
+ /**
+ * The canvas, brought up to date — at most once a frame.
+ *
+ * A pan fires pointermove far faster than the screen refreshes, and drawing
+ * a lattice on every one of them is what makes a map feel like it is dragging
+ * something heavy behind it.
+ */
+ function redraw() {
+ if (gesture) return; // the canvas is being moved, not redrawn
+ if (frame) return;
+ frame = requestAnimationFrame(() => {
+ frame = 0;
+ paint();
+ });
+ }
+
+ /**
+ * Nothing is drawn on a view whose geometry was refused — not even the marks,
+ * which are otherwise the tool that needs no geometry at all. Placing one
+ * still works there, because a point can be filed at the coordinate the URL
+ * names without anything being projected; what cannot be done honestly is
+ * saying *where on this screen* that point is.
+ */
+ /** Move the canvas the way the map moved. Scaling is about the page origin,
+ * which is where the canvas's own pixels are measured from. */
+ function applyGesture() {
+ layer.canvas.style.transform = gesture
+ ? `translate(${gesture.dx}px, ${gesture.dy}px) scale(${gesture.k})`
+ : "";
+ layer.canvas.style.transformOrigin = "0 0";
+ }
+
+ function clearGesture() {
+ if (!gesture) return;
+ gesture = null;
+ applyGesture();
+ }
+
+ /**
+ * The map is still moving, and the drawing no longer knows where it is.
+ *
+ * These maps glide on after the finger leaves and ease into a zoom over a few
+ * hundred milliseconds, and they say nothing about it: the address bar is
+ * rewritten once, at the end. A drag can be followed exactly, because the map
+ * goes where the pointer goes — the glide afterwards and the zoom cannot.
+ *
+ * So the drawing is dimmed from the moment a gesture ends until the address
+ * bar says where the map landed. Showing a measurement over ground it is no
+ * longer on is the one thing this tool must not do, and dimming says "not
+ * right now" where freezing it in place quietly says "here".
+ */
+ function beginSettle() {
+ settling = true;
+ layer.canvas.style.opacity = "0.25";
+ clearTimeout(settle);
+ clearTimeout(giveUp);
+ settle = setTimeout(function poll() {
+ readUrl();
+ if (settling) settle = setTimeout(poll, SETTLE_POLL_MS);
+ }, SETTLE_MS);
+ giveUp = setTimeout(endSettle, SETTLE_GIVE_UP_MS);
+ }
+
+ function endSettle() {
+ if (!settling) return;
+ settling = false;
+ clearTimeout(settle);
+ clearTimeout(giveUp);
+ layer.canvas.style.opacity = confidence();
+ }
+
+ /**
+ * How sure the drawing is allowed to look.
+ *
+ * Far out the site draws a globe and this draws Mercator: right in the
+ * middle, drifting at the edges. That is the one case that dims.
+ *
+ * Not being placed yet is *not*. It was, briefly, on the grounds that an
+ * unmeasured offset is a guess — but a wheel notch is a third of a level on
+ * some of these sites, so "until the next zoom" can be several gestures long,
+ * and a drawing that is translucent for all of them reads as a broken tool
+ * rather than as a careful one. The status line says "zoom once to place it"
+ * and its tooltip carries the offset; that is where the doubt belongs.
+ */
+ function confidence() {
+ // …and neither is a tool whose answer does not drift with distance: the sky
+ // arc is read at its anchor, and `maptools.js` says so where it declares it.
+ const dims = current()?.dimsWhenFar ?? true;
+ return verdict().far && dims ? "0.55" : "";
+ }
+
+ function paint() {
+ const tool = current();
+ const say = verdict();
+ if (!tool || !state.view || !say.ok) {
+ layer.clear();
+ return;
+ }
+ // A drawing that is only roughly placed must not look like one that is
+ // placed — `confidence` says what counts as roughly.
+ if (!settling) layer.canvas.style.opacity = confidence();
+ // Only the tool that is open draws. Everything a tool has been told stays
+ // in it — a measured path, a planted point, an open sweep all come back
+ // when it is picked up again — but the map goes back to being a map, which
+ // is what putting a tool down has to mean.
+ const shapes = [...tool.shapes()];
+ if (box) shapes.push(boxShape());
+ layer.render(shapes, toScreen);
+ }
+
+ /** The rectangle being dragged out, in the app's draft style. */
+ function boxShape() {
+ const a = toLatLon(box.from);
+ const b = toLatLon(box.to);
+ return {
+ kind: "box",
+ bounds: { south: Math.min(a.lat, b.lat), north: Math.max(a.lat, b.lat), west: Math.min(a.lon, b.lon), east: Math.max(a.lon, b.lon) },
+ ...THEME.DRAFT_STYLE,
+ };
+ }
+
+ // --- the view engine -------------------------------------------------------
+ //
+ // Three inputs, in order of authority. The address bar is the truth, and the
+ // app parses it — where the camera is, and, on every site but Earth, how far
+ // out. A gesture in flight is a prediction carrying the drawing between two
+ // truths; it is replaced, never merged, the moment the URL settles. And each
+ // gesture that finishes is an experiment: a pan says whether the drawing
+ // predicted where the map would land, and a zoom says which pixel the site
+ // draws its centre at.
+
+ /**
+ * Whether `state.view.zoom` is the level the map is really at.
+ *
+ * A whole level is exact by definition: every one of these sites writes those
+ * without rounding. A fraction may not be — Bing's wheel moves a third of a
+ * level and it writes one decimal — and a zoom worked out from an anchor
+ * (`mapmath.js`) is exact again. Nothing is measured off a view that is not,
+ * because an error there would come out the other side unchanged.
+ */
+ let zoomExact = false;
+ //. What the address bar last said the zoom was, before any correction — the
+ //. only way to tell a pan at this level from a zoom to another one.
+ let lastStated = null;
+ const wholeLevel = (zoom) => zoom != null && Math.abs(zoom - Math.round(zoom)) < 0.01;
+ const middleOf = (a) => ({ x: a.x + a.w / 2, y: a.y + a.h / 2 });
+
+ /** Consecutive pans that landed away from the prediction before the tools
+ * stop drawing. One is inertia; three in a row is a different map. */
+ const DRIFT_LIMIT = 3;
+ let drift = 0;
+ /** Pixels between where the drawing said the map would land and where the
+ * address bar says it did, last pan. Null until there was one to score. */
+ let modelError = null;
+
+ let lastUrl = "";
+ let pending = null; // the pan waiting for the URL to report where it landed
+ let drag = null; // the gesture in flight
+ let lastSpan = null; // the camera span the last view stated, if it stated one
+ //. A point the zoom about to happen will keep under the same pixel: the
+ //. coordinate it had before feeds `rescaleFromAnchor`, the whole view before
+ //. feeds `centreFromZoom`.
+ let zoomAnchor = null;
+ //. A zoom too small to solve the frame from, kept in case the next one lands
+ //. on the same pixel: notches about one point are one zoom in instalments.
+ let frameChain = null;
+ let settle = 0;
+ let giveUp = 0;
+ let settling = false; // a gesture has ended and the map has not reported in
+
+ /**
+ * How tall the map itself is drawn, in CSS pixels — which is not the window
+ * on a site that keeps a header above it.
+ *
+ * Two views state their scale as a size rather than as a level (Apple's span,
+ * Google satellite's metres), and a size is only a scale next to the number of
+ * pixels it was drawn in. Hand over the window's height where the site drew
+ * the map in less of it and every distance is out by the ratio — Bing's header
+ * is eight percent of a 1000 px window.
+ *
+ * Nothing is looked up to know it. A map centred in what its chrome leaves is
+ * centred by exactly half of what the chrome took, so the offset already
+ * measured (`measureFrame`) is the measurement of the header, and a scrollbar
+ * along the bottom falls out of the same arithmetic. It is read in whole
+ * pixels and only past a couple of them: a site that draws dead centre solves
+ * to a hair either side of zero, and restating the window as 999.35 px would
+ * re-read the scale after every zoom to no purpose.
+ */
+ const MIN_CHROME_PX = 4;
+
+ function mapHeight() {
+ const chrome = 2 * Math.abs(state.frame.y);
+ if (chrome < MIN_CHROME_PX) return window.innerHeight;
+ return Math.max(1, Math.round(window.innerHeight - chrome));
+ }
+
+ //. What the last parse was told the map's height was. A view whose scale came
+ //. from a size has to be read again when that number moves, and the URL is not
+ //. what moved — resizing the window does it, and so does the first zoom that
+ //. measures a header.
+ let lastHeight = 0;
+
+ async function readUrl(force = false) {
+ // A URL read mid-gesture would replace the prediction that is carrying the
+ // drawing with a coordinate the site wrote a moment ago, which reads as the
+ // overlay stuttering against the map.
+ if (drag) return;
+ const height = mapHeight();
+ if (location.href === lastUrl && height === lastHeight && !force) return;
+ lastUrl = location.href;
+ lastHeight = height;
+ let parsed;
+ try {
+ // The height goes with the URL because it is the one fact the app cannot
+ // have and the parse needs: Apple states a span and Google's satellite
+ // view a height in metres, and both are a scale only next to the number
+ // of pixels they were drawn in (`engine/mapsites.py`).
+ parsed = await call("GET", "/api/ingest/parse", {
+ query: { url: lastUrl, height },
+ });
+ } catch (e) {
+ state.note = e.message;
+ render();
+ return;
+ }
+ adopt(parsed);
+ }
+
+ /** Take the app's reading as the new truth, and score the prediction it just
+ * settled. */
+ function adopt(parsed) {
+ const before = state.view;
+ state.parsed = parsed;
+ if (!parsed?.site || parsed.lat == null || parsed.lon == null) {
+ state.view = null;
+ frameChain = null;
+ dropHold();
+ clearGesture();
+ endSettle();
+ releaseGeometryTools();
+ render();
+ return;
+ }
+ const view = {
+ lat: parsed.lat,
+ lon: parsed.lon,
+ // A view whose URL states no scale at all — Earth — carries no zoom. The
+ // last one known is kept so the named projection has something to draw
+ // with until the scale is measured, and the measurement replaces it.
+ zoom: parsed.zoom ?? before?.zoom ?? 15,
+ bearing: parsed.bearing || 0,
+ projection: parsed.projection || "webmercator",
+ };
+ // A zoom worked out from an anchor outlives the pans that follow it: the
+ // address bar goes on quoting the same rounded number, and re-reading it
+ // would throw the correction away on the first drag.
+ if (zoomExact && before && parsed.zoom != null && parsed.zoom === lastStated) {
+ view.zoom = before.zoom;
+ }
+ lastStated = parsed.zoom;
+ // A zoom or a rotation makes every *measured* reading stale at once: a
+ // scale is a function of both, so an old sample is an answer about another
+ // map. A camera span is the exception — that number is proportional to
+ // metres per pixel, so the ratio of two of them carries a measured scale
+ // straight through a zoom the address bar never named.
+ // Both comparisons carry a threshold, because both numbers move a little
+ // when nothing has zoomed: a zoom worked out from a height in metres or a
+ // span in degrees depends on the latitude those were quoted at, so a plain
+ // pan north changes it in the fourth decimal. Read as a zoom, that threw
+ // away the pan it had just measured. The smallest real step any of these
+ // sites takes is a fifth of a level.
+ const span = state.parsed?.camera_m ?? null;
+ const turned = before && before.bearing !== view.bearing;
+ const zoomed = before && Math.abs(before.zoom - view.zoom) > 0.02;
+ const spanned =
+ span != null && lastSpan != null && Math.abs(span - lastSpan) > 0.01 * Math.abs(lastSpan);
+
+ // A zoom is the one gesture that can say where this site draws its centre,
+ // and the same gesture says what the address bar rounded off the zoom it
+ // landed on. Both are taken here, before anything is allowed to reset.
+ //
+ // Which of the two depends on what is already known, and the order keeps
+ // them out of each other's way: a frame is only ever measured from two
+ // zooms that are exact, and a zoom is only ever corrected once a frame is
+ // known. Neither is ever read out of the other's answer.
+ const near = !parsed.far && !zoomAnchor?.far && !zoomAnchor?.adrift;
+ if (zoomAnchor && (zoomed || spanned) && near) {
+ const whole = wholeLevel(view.zoom);
+ let solved = false;
+ if (zoomAnchor.exact && whole) {
+ solved = measureFrame(zoomAnchor, view);
+ } else if (zoomAnchor.exact && state.framed && parsed.scale_source === "zoom") {
+ const exact = M.zoomFromAnchor(zoomAnchor.view, view, zoomAnchor, middleOf(area()));
+ if (exact != null) {
+ view.zoom = exact;
+ solved = true;
+ }
+ }
+ zoomExact = whole || solved;
+ // A wheel notch is a third of a level on Bing and less on others, which
+ // is too little to divide by. Notches about the same pixel are one zoom
+ // arriving in instalments, so the view from the start of the run is kept
+ // and the solve tried again from there.
+ frameChain = solved
+ ? null
+ : {
+ x: zoomAnchor.x,
+ y: zoomAnchor.y,
+ view: zoomAnchor.view,
+ exact: zoomAnchor.exact,
+ far: zoomAnchor.far,
+ };
+ } else if (zoomed || spanned || before == null) {
+ zoomExact = wholeLevel(view.zoom);
+ if (!near) frameChain = null;
+ } else if (!turned) {
+ // no zoom and no rotation in this reading: the rest of an ease, or a pan
+ reframe(view);
+ }
+
+ if (!parsed.scale_source) {
+ // Nothing in the URL says how far out this is, so the map is measured.
+ if (turned || zoomed || spanned) {
+ // A turn on its own changes nothing about how big the ground is drawn.
+ // What is measured is pixels per degree along the world's own axes
+ // (`mapmath.js`), so it survives the view being turned under it —
+ // throwing it away here is what made a rotated Earth ask for another
+ // pan after every nudge of the compass, which reads as a broken tool.
+ const carried = turned && !zoomed && !spanned
+ ? true
+ : carryByAnchor(view) || carryBySpan(span);
+ if (!carried) state.calibration.reset();
+ drift = 0;
+ // The pan that landed with it is dropped only when there is still a
+ // scale for it to disagree with. Nothing carried means nothing is known,
+ // and the drag that just finished is the only reading there is.
+ //
+ // Google Earth is why, and it is the one view this can happen on. Its
+ // camera distance moves with the ground under it — pan over a hill and
+ // `d` changes by more than the threshold — so the panel read an ordinary
+ // drag as a zoom, found no scale to carry through it, and threw away the
+ // measurement that drag had just made. Every time. Which is a tool that
+ // asks for a pan it has already been given, for ever, on the one site
+ // where a pan is the only way to measure anything.
+ if (carried) pending = null;
+ }
+ if (pending && before) {
+ state.calibration.observe(pending.from, view, pending.dx, pending.dy);
+ // What the site actually draws in, settled between the table's answer
+ // and the measurement — each covers the other's blind spot
+ // (mapmath.js). Only where there is a table answer to check: a free
+ // camera names no flattening, and the measurement describes it whole.
+ if (parsed.projection) {
+ const named = M.identify(state.calibration.scale, view, { prefer: view.projection });
+ if (named) view.projection = named;
+ }
+ }
+ } else if (turned || zoomed || spanned) {
+ drift = 0;
+ pending = null;
+ }
+ lastSpan = span;
+ zoomAnchor = null;
+ const landed = pending;
+ pending = null;
+ state.view = view;
+ if (landed && before) scorePan(landed);
+ // the map has landed and been read, so the canvas goes back to being
+ // untouched, at full strength, and everything is projected from where it
+ // actually is
+ clearGesture();
+ endSettle();
+ if (tools.sky.anchor) tools.sky.fit(spanMetres());
+ // the measured zoom, not the stated one: a satellite view states none at
+ // all, and marks merge by how close together they are on screen
+ tools.pins.atZoom(projected().zoom);
+ releaseGeometryTools();
+ render();
+ }
+
+ /** The scale after a zoom, from the point that zoom held still. Exact, and
+ * free of every assumption about screens, tiles and zoom levels. */
+ function carryByAnchor(view) {
+ const factor = M.rescaleFromAnchor(zoomAnchor, view, area(), state.calibration.scale);
+ return factor != null && state.calibration.rescale(factor);
+ }
+
+ /** Failing that, the ratio of the camera spans the address bar quoted — the
+ * answer for a view that states one, and for a zoom nobody's cursor drove. */
+ function carryBySpan(span) {
+ if (span == null || lastSpan == null || span === lastSpan) return false;
+ return state.calibration.rescale(lastSpan / span);
+ }
+
+ /**
+ * Where this site draws its centre, read off the zoom that just happened.
+ *
+ * The arithmetic is `mapmath.js`; what belongs here is what to do with an
+ * answer. A camera centre outside the window is not a side panel, it is a bad
+ * sample — a zoom the map eased rather than stepped, a gesture the site read
+ * as something else — and it is dropped rather than allowed to move the
+ * drawing off the screen. Anything inside is adopted whole and remembered:
+ * the offset is a fact about this site's layout, not about this visit, and it
+ * is worth having before the first gesture of the next one.
+ */
+ /** How far a fresh reading may sit from the ones before it and still be the
+ * same layout. Past this, a panel has opened or closed and the readings
+ * before it describe a window that no longer exists. */
+ const FRAME_JUMP_PX = 25;
+ /**
+ * How long the address bar has to hold still before a zoom counts as landed.
+ *
+ * These sites ease into a zoom over a few hundred milliseconds and rewrite
+ * the URL while they are doing it: the new level arrives at the start of the
+ * ease and the centre catches up at the end. Solved from the first of those
+ * readings, the site's centre comes out hundreds of pixels from where it is.
+ *
+ * Nothing afterwards catches that. The reading that corrects the centre has
+ * the same zoom in it, so it reads as a pan, and a pan cannot see the frame —
+ * it slides with the map and cancels. The wrong offset was therefore adopted
+ * whole, saved for the next visit, and drawn with the same confidence as a
+ * good one. So the answer is held for this long instead, re-solved from every
+ * reading that arrives in the meantime, and only the one the address bar
+ * stops on is kept.
+ */
+ const FRAME_QUIET_MS = 400;
+ /** How much a window may differ and still be the window an offset was
+ * measured in. A scrollbar coming and going is a few pixels; a panel folding
+ * away is hundreds. */
+ const WINDOW_SAME_PX = 8;
+ let windowSize = { w: window.innerWidth, h: window.innerHeight };
+
+ /**
+ * The offsets measured on this site, one per window shape, most recent first.
+ *
+ * These sites fold a results panel away below a width and open it again above
+ * one, so the same site draws its centre in two or three different places
+ * depending on how wide the window is. Remembering only the last of them
+ * means every change of shape costs a zoom before anything can be placed —
+ * and, before this, meant the last one was quietly reused in a window it was
+ * never measured in.
+ */
+ const FRAMES_KEPT = 4;
+ let frames = [];
+
+ const sameWindow = (a, b) =>
+ Math.abs(a.w - b.w) <= WINDOW_SAME_PX && Math.abs(a.h - b.h) <= WINDOW_SAME_PX;
+
+ /** The offset measured in a window this shape, if one was. */
+ const frameFor = (size) => frames.find((f) => sameWindow(f, size)) ?? null;
+
+ /** An offset a window this size could actually have: a side panel takes a
+ * part of the width, never more than the window itself. */
+ const framePlausible = (f) =>
+ Number.isFinite(f?.x) &&
+ Number.isFinite(f?.y) &&
+ Math.abs(f.x) <= window.innerWidth / 2 &&
+ Math.abs(f.y) <= window.innerHeight / 2;
+ /** How many readings are averaged. Most of these sites state their zoom
+ * exactly and two zooms agree to a tenth of a pixel, so this is for the one
+ * that does not: Bing writes a single decimal of zoom, and the rounding
+ * lands a few pixels out. Independent roundings average down; a panel that
+ * actually moved does not, which is what the jump above is for. */
+ const FRAME_SAMPLES = 6;
+ let frameSamples = [];
+ /** A solved offset waiting for the address bar to stop moving, and the zoom
+ * it came from — kept so every reading in between re-solves it. */
+ let frameHold = null; // { anchor, value, touched }
+ let frameQuiet = 0;
+
+ /** Where this zoom says the site's centre is, or null if the answer is not
+ * one a side panel could explain. */
+ function solveFrame(anchor, view) {
+ const found = M.centreFromZoom(anchor.view, view, anchor);
+ if (!found) return null;
+ const w = window.innerWidth;
+ const h = window.innerHeight;
+ const next = { x: found.x - w / 2, y: found.y - h / 2 };
+ if (Math.abs(next.x) > w / 2 || Math.abs(next.y) > h / 2) return null;
+ return next;
+ }
+
+ function measureFrame(anchor, view) {
+ const next = solveFrame(anchor, view);
+ if (!next) return false;
+ frameHold = { anchor, value: next, touched: false, site: state.parsed?.site };
+ clearTimeout(frameQuiet);
+ frameQuiet = setTimeout(commitFrame, FRAME_QUIET_MS);
+ return true;
+ }
+
+ /**
+ * Another reading arrived while an answer was being held.
+ *
+ * Same zoom, moved centre, nobody's hand on the map: that is the rest of the
+ * ease, not a pan, and the anchor still describes the map it started from. So
+ * the answer is solved again from the newer reading and the wait restarts.
+ */
+ function reframe(view) {
+ if (!frameHold || frameHold.touched) return;
+ if (frameHold.site !== state.parsed?.site) return dropHold();
+ const next = solveFrame(frameHold.anchor, view);
+ if (!next) return;
+ frameHold.value = next;
+ clearTimeout(frameQuiet);
+ frameQuiet = setTimeout(commitFrame, FRAME_QUIET_MS);
+ }
+
+ /** Let go of an answer that has stopped being about anything: the tab has
+ * left this map, so there is no reading coming that could finish it. */
+ function dropHold() {
+ frameHold = null;
+ clearTimeout(frameQuiet);
+ }
+
+ function commitFrame() {
+ const held = frameHold;
+ frameHold = null;
+ if (!held) return;
+ takeFrame(held.value);
+ render();
+ }
+
+ function takeFrame(next) {
+ const far = Math.hypot(next.x - state.frame.x, next.y - state.frame.y) > FRAME_JUMP_PX;
+ frameSamples = far || !state.framed ? [next] : [...frameSamples, next].slice(-FRAME_SAMPLES);
+ const mean = {
+ x: frameSamples.reduce((sum, s) => sum + s.x, 0) / frameSamples.length,
+ y: frameSamples.reduce((sum, s) => sum + s.y, 0) / frameSamples.length,
+ };
+ const moved = Math.abs(mean.x - state.frame.x) >= 0.5 || Math.abs(mean.y - state.frame.y) >= 0.5;
+ const first = !state.framed;
+ state.framed = true;
+ if (moved) state.frame = mean;
+ // A site that draws dead centre measures to the offset it already had, and
+ // the answer is still worth keeping: without this the panel would ask for
+ // another zoom on every visit to it.
+ if (moved || first) save();
+ }
+
+ /** File the measurement under the window it was taken in. */
+ function rememberFrame() {
+ if (!state.framed) return;
+ const entry = { ...windowSize, x: state.frame.x, y: state.frame.y };
+ frames = [entry, ...frames.filter((f) => !sameWindow(f, entry))].slice(0, FRAMES_KEPT);
+ }
+
+ /**
+ * How far the map landed from where the drawing said it would, in pixels.
+ *
+ * A pan moves the map by exactly the pixels the pointer travelled, so the
+ * coordinate that was centred before must now be under the middle of the map
+ * plus those pixels. Projecting it through the view that has just arrived
+ * says whether it is — and that is a test of the whole drawing model at once:
+ * the flattening, the scale, and the zoom the URL claimed. It cannot see the
+ * frame, which slides with the map and cancels; the zoom above is what sees
+ * that.
+ */
+ function scorePan({ from, dx, dy }) {
+ let landed;
+ try {
+ landed = toScreen(from);
+ } catch {
+ return;
+ }
+ const a = area();
+ modelError = Math.hypot(
+ landed.x - (a.x + a.w / 2 + dx),
+ landed.y - (a.y + a.h / 2 + dy)
+ );
+ drift = modelError > T.RESIDUAL_LIMIT ? drift + 1 : 0;
+ }
+
+ /**
+ * Let go of the click when the view stops being one the tools can answer for.
+ *
+ * A tool armed on a 2D map stays armed through a pan, which is what makes a
+ * measure usable. It must not stay armed through a step into Street View or
+ * onto a page that is not a map at all: the canvas would go on taking the
+ * clicks with nothing able to answer them, and the map underneath would stop
+ * responding for no reason the analyst can see.
+ */
+ function releaseGeometryTools() {
+ if (!verdict().ok) {
+ for (const id of ORDER) if (tools[id].needsGeometry) tools[id].disarm();
+ }
+ syncArmed();
+ }
+
+ /**
+ * The map moved under a finger. While it is moving the URL says nothing, so
+ * the view is carried by the pixels the pointer travelled; when the pointer
+ * lifts, that same pixel count becomes the measurement.
+ */
+ function onPointerDown(event) {
+ // From here the map moves for a reason the ease cannot account for, so the
+ // answer being held stands or falls on the readings it already has.
+ if (frameHold) frameHold.touched = true;
+ if (armed() || !state.view || event.button !== 0) return;
+ if (event.composedPath().includes(host)) return;
+ // whatever the canvas was already offset by carries into this drag: a pan
+ // right after a wheel notch starts from where the zoom left it
+ drag = {
+ x: event.clientX,
+ y: event.clientY,
+ from: state.view,
+ moved: false,
+ base: gesture ?? { dx: 0, dy: 0, k: 1 },
+ };
+ }
+
+ function onPointerMove(event) {
+ if (!drag) {
+ hover(event);
+ return;
+ }
+ const dx = event.clientX - drag.x;
+ const dy = event.clientY - drag.y;
+ if (!drag.moved && Math.abs(dx) < 3 && Math.abs(dy) < 3) return;
+ drag.moved = true;
+ drag.movedAt = event.timeStamp;
+ // the map goes exactly where the pointer goes, so the canvas does too
+ gesture = { dx: drag.base.dx + dx, dy: drag.base.dy + dy, k: drag.base.k };
+ applyGesture();
+ }
+
+ function onPointerUp(event) {
+ if (!drag) return;
+ const dx = event.clientX - drag.x;
+ const dy = event.clientY - drag.y;
+ // A pan is only a measurement if the map ended up where the pointer left
+ // it. Let go while still moving and these maps fling on for a few hundred
+ // milliseconds, and the address bar reports the landing — pair that with
+ // the pixels the pointer travelled and the scale comes out too large by
+ // however far it glided. Which is a drawing that fits at the centre of the
+ // screen and drifts outward from it, the exact thing this used to do.
+ frameChain = null; // the map has moved: a run of notches is over
+ const still = event.timeStamp - (drag.movedAt ?? 0) >= FLING_PAUSE_MS;
+ if (still && (Math.abs(dx) >= M.MIN_PAN_PX || Math.abs(dy) >= M.MIN_PAN_PX)) {
+ pending = { from: drag.from, dx, dy };
+ }
+ const moved = drag.moved;
+ drag = null;
+ // the map glides on from here, and the drawing cannot follow that. A click
+ // that never moved is not a gesture and dims nothing.
+ if (moved) beginSettle();
+ }
+
+ /**
+ * A zoom, waited out rather than guessed at.
+ *
+ * A pan can be followed because the map moves exactly with the pointer. A
+ * zoom cannot: the site picks its own step, eases into it over a few hundred
+ * milliseconds, and only then rewrites the address bar. Scaling the canvas by
+ * what a wheel notch *usually* means was worse than doing nothing — the
+ * drawing arrived at the new size before the map did, then corrected itself.
+ *
+ * So the drawing dims and waits. It comes back at the scale the address bar
+ * states, which is the only one anybody knows.
+ */
+ /**
+ * A zoom, waited out — and then read, rather than re-measured.
+ *
+ * Every one of these maps zooms about a point it keeps still: the cursor for
+ * a wheel notch, the click for a double-click. That point's coordinate is
+ * known before the zoom, and it is under the same pixel afterwards, so when
+ * the address bar reports the new centre the new scale falls straight out of
+ * it (`mapmath.js`, `rescaleFromAnchor`). One pan calibrates a map; nothing
+ * after that costs the analyst another.
+ */
+ function beginZoom(at) {
+ // whatever a pan left the canvas offset by is kept rather than undone: it is
+ // no more right than it was a moment ago, and undoing it is one more jump
+ zoomAnchor = null;
+ if (at && state.view) {
+ // The view is kept whole, not just the coordinate under the pointer:
+ // solving for the site's centre needs where the camera was, and that is
+ // true even on a view whose scale nothing has measured yet.
+ const sameSpot =
+ frameChain && Math.abs(frameChain.x - at.x) <= 6 && Math.abs(frameChain.y - at.y) <= 6;
+ zoomAnchor = {
+ x: at.x,
+ y: at.y,
+ view: sameSpot ? frameChain.view : state.view,
+ exact: sameSpot ? frameChain.exact : zoomExact,
+ // Far out the site is drawing a globe and this arithmetic is Mercator,
+ // so a zoom taken out there says nothing true about where the centre
+ // is. Kept with the anchor because the zoom that ends the run may be
+ // the one that came back in close.
+ far: sameSpot ? frameChain.far : !!verdict().far,
+ // A pan the address bar never reported leaves the map somewhere
+ // `state.view` does not describe, with the canvas carrying the
+ // difference. The pixel this zoom turns about is on the screen; the
+ // view it would be solved against is the one from before that pan.
+ // Read together they put the site's centre out by the whole pan, so
+ // this zoom is allowed to move the drawing and not to measure it.
+ adrift: !!gesture,
+ };
+ if (state.calibration.scale && verdict().ok) {
+ try {
+ Object.assign(zoomAnchor, toLatLon(at));
+ } catch {
+ /* no coordinate for it; the frame solve does not need one */
+ }
+ }
+ }
+ drift = 0;
+ pending = null;
+ beginSettle();
+ }
+
+ function onWheel(event) {
+ if (!state.view || event.composedPath().includes(host)) return;
+ if (!event.deltaY) return;
+ beginZoom({ x: event.clientX, y: event.clientY });
+ }
+
+ /** Double-click is a zoom step on every one of these maps. */
+ function onDoubleClick(event) {
+ if (armed() || !state.view || event.composedPath().includes(host)) return;
+ beginZoom({ x: event.clientX, y: event.clientY });
+ }
+
+ // --- what a click means ----------------------------------------------------
+
+ /** Whether a tool is waiting for a click. While one is, the canvas takes
+ * pointer events and the map underneath never sees them; the rest of the
+ * time it is transparent to them and the map pans normally. */
+ function armed() {
+ return ORDER.some((id) => tools[id].armed);
+ }
+
+ function syncArmed() {
+ const on = armed();
+ layer.canvas.style.pointerEvents = on ? "auto" : "none";
+ layer.canvas.style.cursor = on ? "crosshair" : "";
+ }
+
+ let box = null; // the rectangle being dragged out
+
+ function canvasDown(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ // Dimmed means the drawing does not know where it is, and a click taken now
+ // would be filed against a projection the map has already left. A point in
+ // the wrong place is worse than a click that did nothing.
+ if (settling) {
+ state.note = "The map is still moving";
+ render();
+ return;
+ }
+ const at = { x: event.clientX, y: event.clientY };
+ if (tools.grid.drawing === "rect") {
+ box = { from: at, to: at };
+ return;
+ }
+ handleClick(at);
+ }
+
+ function canvasMove(event) {
+ if (!box) return;
+ box.to = { x: event.clientX, y: event.clientY };
+ redraw();
+ }
+
+ function canvasUp() {
+ if (!box) return;
+ const dragged = box;
+ const width = Math.abs(dragged.to.x - dragged.from.x);
+ const height = Math.abs(dragged.to.y - dragged.from.y);
+ box = null;
+ if (width < 12 || height < 12) {
+ // a stray click, not an area — the app draws the same line at 12 px
+ redraw();
+ return;
+ }
+ const a = toLatLon(dragged.from);
+ const b = toLatLon(dragged.to);
+ const answer = tools.grid.finishBox({ south: a.lat, north: b.lat, west: a.lon, east: b.lon });
+ state.note = answer?.error || "";
+ syncArmed();
+ render();
+ }
+
+ /**
+ * One click, handed to whichever tool asked for it.
+ *
+ * The pins tool is the only one that gets a click on a view without geometry,
+ * and it gets `null` for the coordinate rather than a guess — see its own
+ * note in `maptools.js` for why that distinction is the whole feature.
+ */
+ function handleClick(at) {
+ const sound = verdict().ok && state.view;
+ const point = sound ? toLatLon(at) : null;
+
+ if (tools.pins.dropping) {
+ const anchor = state.parsed && state.parsed.lat != null
+ ? { lat: state.parsed.lat, lon: state.parsed.lon }
+ : null;
+ if (!point && !anchor) {
+ state.note = "Nothing to file: this page has no position in it";
+ render();
+ return;
+ }
+ tools.pins.click(point, anchor);
+ render();
+ return;
+ }
+ if (!point) return;
+ if (tools.sky.placing) {
+ tools.sky.click(point);
+ tools.sky.fit(spanMetres());
+ loadSky();
+ syncArmed();
+ render();
+ return;
+ }
+ if (tools.measure.mode) {
+ tools.measure.click(point);
+ render();
+ return;
+ }
+ if (tools.grid.drawing === "polygon") {
+ tools.grid.addVertex(point);
+ render();
+ return;
+ }
+ if (tools.grid.marking) {
+ if (tools.grid.click(point)) {
+ pushMarks();
+ render();
+ }
+ }
+ }
+
+ /**
+ * Pointing at a mark names it; clicking one keeps the name open.
+ *
+ * Read off plain window events rather than by arming the canvas, because a
+ * map with the analyst's own saved work on it still has to be a map: taking
+ * the pointer to hover a pin would take it from the site's own controls too.
+ */
+ let lastHover = { x: -99, y: -99 };
+
+ /**
+ * Where a mark's body is drawn, which is not where its point is.
+ *
+ * The tip is on the coordinate and the body stands above it (`mapdraw.js`),
+ * so a pointer is over the mark a whole diagonal north of what the mark is
+ * about. Hit-testing against the coordinate would have the analyst chasing a
+ * mark that answers below itself.
+ */
+ function markBody(point) {
+ const at = toScreen(point);
+ return at && { x: at.x, y: at.y - D.MARK_TIP };
+ }
+
+ function hover(event) {
+ if (state.tool !== "pins" || !state.view || !verdict().ok || gesture) return;
+ if (event.composedPath().includes(host)) return;
+ // every mark is projected to answer this, so it is not answered for every
+ // pixel the pointer travels
+ const at = { x: event.clientX, y: event.clientY };
+ if (Math.abs(at.x - lastHover.x) < 4 && Math.abs(at.y - lastHover.y) < 4) return;
+ lastHover = at;
+ if (tools.pins.hover(tools.pins.markAt(at, markBody)?.key ?? null)) redraw();
+ }
+
+ function onClick(event) {
+ if (state.tool !== "pins" || armed() || !state.view || !verdict().ok || gesture) return;
+ if (event.composedPath().includes(host)) return;
+ const mark = tools.pins.markAt({ x: event.clientX, y: event.clientY }, markBody);
+ tools.pins.hold(mark?.key ?? null);
+ if (mark?.key === "draft") state.tool = "pins";
+ render();
+ }
+
+ // --- the tools' errands ----------------------------------------------------
+
+ async function loadCases() {
+ try {
+ state.cases = await call("GET", "/api/ingest/cases");
+ const stored = await api.storage.local.get({ lastCaseId: "" });
+ const wanted = state.cases.find((c) => c.id === stored.lastCaseId) || state.cases[0];
+ if (wanted) state.caseId = wanted.id;
+ render();
+ loadPins();
+ } catch (e) {
+ state.note = e.message;
+ render();
+ }
+ }
+
+ async function loadPins() {
+ if (!state.caseId) return;
+ try {
+ tools.pins.load(await call("GET", "/api/ingest/saved", { query: { case_id: state.caseId } }));
+ tools.pins.atZoom(state.view?.zoom);
+ render();
+ } catch (e) {
+ state.note = e.message;
+ render();
+ }
+ }
+
+ /** File the draft point as a place, the same route the popup files one with —
+ * so a point dropped here lands in the Saved panel like any other. */
+ async function placePin() {
+ const draft = tools.pins.draft;
+ if (!draft || !state.caseId) return;
+ try {
+ await call("POST", "/api/ingest/place", {
+ form: true,
+ body: {
+ url: location.href,
+ case_id: state.caseId,
+ lat: draft.lat,
+ lon: draft.lon,
+ zoom: state.view?.zoom,
+ bearing: state.view?.bearing,
+ title: state.pinTitle.trim(),
+ },
+ });
+ tools.pins.clearDraft();
+ state.pinTitle = "";
+ state.note = "";
+ await loadPins();
+ } catch (e) {
+ state.note = e.message;
+ }
+ syncArmed();
+ render();
+ }
+
+ /** What the case has to offer a reference window. Searched, filtered and
+ * ordered by the app, so a case of two thousand files never crosses the
+ * boundary to fill one grid. */
+ async function loadRefMedia({ q, kind, sort } = {}) {
+ if (!state.caseId) return { items: [], total: 0 };
+ return call("GET", "/api/ingest/media", {
+ query: { case_id: state.caseId, q, kind, sort },
+ });
+ }
+
+ async function loadSky() {
+ const anchor = tools.sky.anchor;
+ if (!anchor) return;
+ try {
+ tools.sky.accept(
+ await call("GET", "/api/ingest/sky", {
+ query: { lat: anchor.lat, lon: anchor.lon, date: tools.sky.date },
+ })
+ );
+ } catch (e) {
+ state.note = e.message;
+ }
+ render();
+ }
+
+ async function loadGrids() {
+ if (!state.caseId) return [];
+ try {
+ return await call("GET", "/api/ingest/grids", { query: { case_id: state.caseId } });
+ } catch (e) {
+ state.note = e.message;
+ return [];
+ }
+ }
+
+ /** Refresh the picker, but only for a panel that has ever opened it: a grid
+ * created elsewhere must appear in the list, and a panel that never went near
+ * the tool has no list to keep current. */
+ async function relistGrids() {
+ if (!state.grids) return;
+ state.grids = await loadGrids();
+ render();
+ }
+
+ /**
+ * The newest revision of the open sweep this panel knows of — read, written,
+ * or heard about.
+ *
+ * What it settles is which nudges are news. A panel that marks a cell hears
+ * its own mark come back as an event, and re-reading the file for it would be
+ * a request per click; a mark made in the app arrives with a revision this
+ * panel has never seen, and that one is worth a read.
+ */
+ let gridRevision = 0;
+
+ const noteRevision = (value) => {
+ const revision = Number(value);
+ if (Number.isFinite(revision)) gridRevision = Math.max(gridRevision, revision);
+ };
+
+ /**
+ * Re-read the open sweep, keeping anything this panel has not sent yet.
+ *
+ * `poll` marks the errand that nobody asked for: the slow safety net, which
+ * stays out of the way of a tab that is not being looked at and of a tool that
+ * is not open. A nudge is the opposite — something changed, and the panel is
+ * holding a copy that no longer matches — so it is read whatever tab is on top.
+ */
+ async function refreshGrid({ poll = false } = {}) {
+ if (!tools.grid.name || !state.caseId) return;
+ // marks that are still on their way are the only copy of themselves: the
+ // push that carries them re-reads the file itself once they have landed
+ if (tools.grid.dirty) return;
+ if (poll && (document.hidden || state.tool !== "grid")) return;
+ try {
+ const spec = await call("GET", "/api/ingest/grid", {
+ query: { case_id: state.caseId, name: tools.grid.name },
+ });
+ noteRevision(spec?.revision);
+ if (tools.grid.sync(spec)) render();
+ } catch {
+ // the case may have been closed or the grid deleted; the next press says so
+ }
+ }
+
+ async function openGrid(name) {
+ try {
+ const spec = await call("GET", "/api/ingest/grid", { query: { case_id: state.caseId, name } });
+ gridRevision = 0;
+ noteRevision(spec?.revision);
+ tools.grid.open(spec, name);
+ state.note = "";
+ } catch (e) {
+ state.note = e.message;
+ }
+ render();
+ }
+
+ /**
+ * Save a grid drawn here as a new one in the case.
+ *
+ * Named in the panel rather than through the browser's own prompt: a modal
+ * belongs to the page underneath, and a page is free to be in a state where
+ * it never appears.
+ */
+ async function saveGrid() {
+ if (!tools.grid.grid || !state.caseId) return;
+ const title = state.gridTitle.trim();
+ if (!title) {
+ state.note = "Name the grid first";
+ render();
+ return;
+ }
+ try {
+ const saved = await call("POST", "/api/ingest/grid", {
+ body: { case_id: state.caseId, title, spec: tools.grid.grid },
+ });
+ gridRevision = 0;
+ noteRevision(saved.revision);
+ tools.grid.saved(saved.name);
+ state.gridTitle = "";
+ state.note = "";
+ state.grids = await loadGrids();
+ } catch (e) {
+ state.note = e.message;
+ }
+ render();
+ }
+
+ /**
+ * Send the marks, not the grid.
+ *
+ * A sweep can be worked from the app and from here at the same time, over one
+ * file. Putting back a whole spec would put back the copy this tab loaded,
+ * silently undoing whatever the other one marked in between; a patch of the
+ * cells that were actually touched cannot do that (`api/satellite.py`,
+ * `apply_grid_marks`).
+ */
+ async function pushMarks() {
+ if (!tools.grid.grid || !tools.grid.name || !state.caseId) return;
+ const marks = tools.grid.takeMarks();
+ if (!Object.keys(marks).length) return;
+ try {
+ const answer = await call("POST", "/api/ingest/grid/marks", {
+ body: { case_id: state.caseId, name: tools.grid.name, marks },
+ });
+ noteRevision(answer?.revision);
+ state.note = "";
+ // the answer settles what is on disk, so read it back rather than waiting
+ // out the poll: whatever the app marked in the meantime appears now
+ refreshGrid();
+ } catch (e) {
+ // put them back: an unsent mark that has been forgotten is a cell the
+ // analyst believes is swept and nothing recorded
+ tools.grid.restoreMarks(marks);
+ state.note = e.message;
+ }
+ render();
+ }
+
+ // --- hearing about the case from elsewhere ---------------------------------
+ //
+ // This panel is one of several windows onto one case: the app's own map, this
+ // one, another map in the next tab. Everything below is about the other
+ // direction of what the tools already do — not what this panel writes, but
+ // what it is told.
+ //
+ // The nudges are the app's own (`api/events.py`), read by the worker and
+ // handed over a port (`background.js`). They say what changed and never carry
+ // it, so every one of them ends in a read through the routes the panel already
+ // uses. A port that dies takes nothing with it: the grid poll above is what
+ // covers the gap, and the port is opened again a moment later.
+
+ let sync = null; // the port to the worker, while it is up
+ let syncRetry = 0;
+ let watch = 0;
+
+ /**
+ * One nudge, applied to what this panel is holding.
+ *
+ * Only for the case that is open here — a mark on another case's sweep is
+ * true and none of this panel's business — and only where it is news. A panel
+ * that just wrote something hears it back, and re-reading a file to be told
+ * what it has just said is the request this exists to avoid.
+ */
+ function applyEvent(event) {
+ if (!event || event.case_id !== state.caseId) return;
+ if (SAVED_EVENTS.has(event.type)) {
+ loadPins();
+ return;
+ }
+ if (event.type === "grid-removed") {
+ if (tools.grid.name === event.name) {
+ tools.grid.close();
+ state.note = "This sweep was discarded elsewhere";
+ syncArmed();
+ render();
+ }
+ relistGrids();
+ return;
+ }
+ if (event.type !== "grid" && event.type !== "grid-marks") return;
+ // a grid written anywhere is a picker entry, open or not
+ if (event.type === "grid") relistGrids();
+ if (tools.grid.name !== event.name) return;
+ if (Number(event.revision) <= gridRevision) return;
+ refreshGrid();
+ }
+
+ function listen() {
+ clearTimeout(syncRetry);
+ // A browser that hands out no ports is one where nothing is listening; the
+ // poll is the whole answer there, and the panel works as it did before.
+ if (!api.runtime?.connect) return;
+ try {
+ sync = api.runtime.connect({ name: "map-sync" });
+ } catch {
+ sync = null;
+ syncRetry = setTimeout(listen, SYNC_RETRY_MS);
+ return;
+ }
+ sync.onMessage.addListener((msg) => {
+ if (msg?.type === "app-event") applyEvent(msg.event);
+ });
+ // The worker is a service worker: the browser is free to evict it, and the
+ // port goes with it. Opening another one is what brings it back.
+ sync.onDisconnect.addListener(() => {
+ sync = null;
+ syncRetry = setTimeout(listen, SYNC_RETRY_MS);
+ });
+ }
+
+ function keepWatching() {
+ if (!sync) return;
+ try {
+ sync.postMessage({ type: "watch" });
+ } catch {
+ // it disconnected between the check and the send; the listener re-opens it
+ }
+ }
+
+ // --- the panel -------------------------------------------------------------
+
+ const panel = document.createElement("div");
+ panel.className = "panel";
+ root.appendChild(panel);
+
+ const t = THEME.TOKENS;
+ const style = document.createElement("style");
+ style.textContent = `
+ :host { all: initial; }
+ .panel {
+ position: fixed; top: 76px; right: 16px; width: 284px; box-sizing: border-box;
+ font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
+ color: ${t.text1}; background: ${t.bg1};
+ border: 1px solid ${t.border}; border-radius: 10px;
+ box-shadow: 0 12px 32px rgba(0,0,0,.5);
+ pointer-events: auto; overflow: hidden;
+ /* Over the drawing (1) and over every reference window, which are
+ numbered from 2 and restacked so they stay small: the panel is how a
+ window is closed, and one that could be buried under a reference
+ would be unreachable. */
+ z-index: 1000;
+ }
+ .panel.collapsed .body { display: none; }
+ header {
+ display: flex; align-items: center; gap: 6px; padding: 7px 8px 7px 11px;
+ background: ${t.bg2}; border-bottom: 1px solid ${t.border};
+ cursor: move; user-select: none;
+ }
+ header .name {
+ flex: 1; font-size: 11px; font-weight: 600;
+ letter-spacing: .08em; text-transform: uppercase; color: ${t.text2};
+ }
+ /* Everything the panel holds has to fit the panel, and one thing in it is
+ a name the case chose: a forty-word video title used to size this grid,
+ push the tab strip and the buttons out past the panel's own width, and
+ lose whatever it clipped. So every box down to the name itself is told it
+ may shrink: a minmax floor of zero and a zero flex basis, rather than the
+ auto minimums a grid track and a flex item take by default, which are the
+ content's own width and no smaller. */
+ .body { padding: 9px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 9px; }
+ .status { display: flex; gap: 6px; align-items: flex-start; font-size: 11.5px; color: ${t.text2}; }
+ .status svg { flex: none; margin-top: 1px; }
+ .status.off { color: ${t.warn}; }
+ button, select, input {
+ font: inherit; color: ${t.text1}; background: ${t.bg2};
+ border: 1px solid ${t.border}; border-radius: 7px;
+ padding: 5px 8px; cursor: pointer;
+ }
+ button {
+ display: inline-flex; align-items: center; justify-content: center; gap: 6px;
+ line-height: 1.2;
+ }
+ button:hover:not([disabled]) { background: ${t.bg3}; border-color: ${t.borderStrong}; }
+ button[data-on="1"] {
+ background: ${t.accent}; border-color: ${t.accent}; color: ${t.accentText};
+ }
+ button[disabled] { opacity: .4; cursor: default; }
+ .tabs { display: grid; grid-template-columns: repeat(${ORDER.length}, minmax(0, 1fr)); gap: 4px; }
+ .tabs button { flex-direction: column; gap: 3px; padding: 6px 2px; font-size: 10px; }
+ .icon { flex: none; width: 26px; padding: 4px 0; background: none; border-color: transparent; color: ${t.text2}; }
+ .icon:hover:not([disabled]) { color: ${t.text1}; }
+ input { cursor: text; width: 100%; box-sizing: border-box; }
+ input[type=range] { padding: 0; accent-color: ${t.accent}; }
+ select { width: 100%; }
+ .row { display: flex; gap: 5px; }
+ .row > * { flex: 1 1 0; min-width: 0; }
+ .readout {
+ font-size: 15px; font-variant-numeric: tabular-nums; color: ${t.text1};
+ padding: 6px 8px; background: ${t.bg0}; border-radius: 7px;
+ border: 1px solid ${t.border};
+ }
+ .readout.small { font-size: 12.5px; }
+ /* a name, a note or a coordinate can arrive as one unbroken run of
+ characters, and a word that cannot be broken is a box that cannot shrink */
+ .readout, .note, .hint { overflow-wrap: anywhere; }
+ .note { font-size: 11px; color: ${t.danger}; }
+ .ref-row { display: flex; align-items: center; gap: 4px; min-width: 0; }
+ .ref-row .ref-name {
+ flex: 1 1 0; min-width: 0; gap: 5px; padding: 4px 6px; font-size: 11.5px;
+ justify-content: flex-start; background: none; border-color: transparent;
+ color: ${t.text2}; overflow: hidden; white-space: nowrap;
+ }
+ .ref-row .ref-name svg { flex: none; }
+ .ref-row .ref-name > span {
+ display: block; flex: 1 1 0; min-width: 0; overflow: hidden; text-overflow: ellipsis;
+ }
+ .ref-row .ref-name:hover:not([disabled]) { color: ${t.text1}; background: ${t.bg2}; }
+ .hint { font-size: 11px; color: ${t.text3}; }
+ `;
+ root.appendChild(style);
+
+ /**
+ * The reference windows, painted by `mapref.js`.
+ *
+ * Created after the panel's own stylesheet so the look it states is the one
+ * the windows build on. It is handed two errands and told nothing else: read
+ * what the case has to offer, and fetch one file's bytes. The file that talks
+ * to the app stays this one.
+ */
+ const refLayer = R.create({
+ root,
+ refs: tools.refs,
+ file: fetchFile,
+ search: loadRefMedia,
+ onchange: () => render(),
+ onnote: (message) => {
+ state.note = message;
+ render();
+ },
+ });
+
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
+ const button = (act, name, label, on, extra = "") =>
+ `<button data-act="${act}"${on ? ' data-on="1"' : ""}${extra}>${name ? icon(name) : ""}${label ? `<span>${esc(label)}</span>` : ""}</button>`;
+
+ function toolBody() {
+ const tool = current();
+ if (!tool) return `<div class="hint">Pick a tool. The map stays yours until you do.</div>`;
+ const readout = tool.readout(state.units) ?? "";
+ // A tool that computes cannot be armed on a view that refuses geometry.
+ // Disabled rather than restated: the status line above has already given
+ // the reason, and saying it twice in one panel is one reason too many.
+ const off = tool.needsGeometry && !verdict().ok ? " disabled" : "";
+
+ if (state.tool === "measure") {
+ return `
+ <div class="row">
+ ${button("measure-distance", "ruler", "Distance", tool.mode === "distance", off)}
+ ${button("measure-area", "polygon", "Area", tool.mode === "area", off)}
+ </div>
+ <div class="readout">${esc(readout)}</div>
+ <div class="row">
+ ${button("measure-undo", "undo", "Undo")}
+ ${button("measure-clear", "x", "Clear")}
+ </div>`;
+ }
+
+ if (state.tool === "pins") {
+ const draft = tool.draft;
+ return `
+ ${button("pin-drop", "pin", tool.dropping ? "Click the map" : "Place a point", tool.dropping)}
+ <div class="readout small">${esc(readout)}</div>
+ ${draft ? `
+ <input data-act="pin-title" placeholder="Name this point" value="${esc(state.pinTitle)}">
+ <div class="hint">${draft.lat.toFixed(5)}, ${draft.lon.toFixed(5)}</div>
+ <div class="row">
+ ${button("pin-save", "check", "File it")}
+ ${button("pin-cancel", "trash", "Discard")}
+ </div>` : `<div class="hint">Point at a mark to name it, click to keep it open.</div>`}`;
+ }
+
+ if (state.tool === "sky") {
+ const clock = tool.day?.curve?.clock || [];
+ return `
+ ${button("sky-place", "crosshair", tool.anchor ? "Move the point" : "Plant the point", tool.placing, off)}
+ ${tool.anchor ? `<input type="date" data-act="sky-date" value="${esc(tool.date ?? "")}">` : ""}
+ <div class="readout">${esc(readout)}</div>
+ ${clock.length ? `
+ <input type="range" data-act="sky-scrub" min="0" max="${clock.length - 1}" value="${tool.index}">
+ <div class="hint">${esc(skyLine(tool))}</div>` : ""}
+ ${tool.anchor ? button("sky-clear", "x", "Clear") : ""}`;
+ }
+
+ if (state.tool === "refs") {
+ return `
+ ${button("ref-add", "image", "Add reference")}
+ <div class="readout small">${esc(readout)}</div>
+ ${tool.open.length
+ ? tool.open
+ .map((viewer) => `
+ <div class="ref-row">
+ ${button("ref-focus", viewer.kind === "video" ? "video" : "image", viewer.title || "Reference", false, ` class="ref-name" data-ref="${esc(viewer.id)}" title="${esc(viewer.title || "Reference")}"`)}
+ ${button("ref-fold", viewer.collapsed ? "chevronDown" : "chevronUp", "", false, ` class="icon" data-ref="${esc(viewer.id)}" title="${viewer.collapsed ? "Unfold" : "Fold"}"`)}
+ ${button("ref-close", "x", "", false, ` class="icon" data-ref="${esc(viewer.id)}" title="Close"`)}
+ </div>`)
+ .join("")
+ : `<div class="hint">Hold a case image or video over the map while you pan. Nothing is filed or captured.</div>`}`;
+ }
+
+ const cover = tool.coverage;
+ return `
+ ${tool.grid ? "" : `
+ <div class="row">
+ ${button("grid-rect", "square", "Box", tool.drawing === "rect", off)}
+ ${button("grid-poly", "polygon", "Shape", tool.drawing === "polygon", off)}
+ </div>
+ ${tool.drawing === "polygon" ? `<div class="row">
+ ${button("grid-close-shape", "check", "Close shape")}
+ ${button("grid-undo-vertex", "undo", "Undo")}
+ </div>` : ""}
+ <label class="hint">Cell size, metres
+ <input data-act="grid-cell" type="number" min="10" step="10" value="${tool.cellM}">
+ </label>`}
+ <div class="readout small">${esc(readout)}</div>
+ ${tool.grid ? `
+ <div class="row">
+ ${button("grid-mark", "check", "Mark cells", tool.marking, off)}
+ ${button("grid-hide", tool.hidden ? "eyeOff" : "eye", tool.hidden ? "Show" : "Hide", tool.hidden)}
+ </div>
+ ${tool.name ? `
+ <div class="hint">Saved as ${esc(tool.name)}${tool.dirty ? " · sending marks" : ""}</div>
+ ${button("grid-close", "x", "Close")}
+ ` : `
+ <input data-act="grid-title" placeholder="Name this grid" value="${esc(state.gridTitle)}">
+ <div class="row">
+ ${button("grid-save", "save", "Save to case")}
+ ${button("grid-close", "trash", "Discard")}
+ </div>`}
+ ${cover ? `<div class="hint">${cover.total} cells at ${tool.grid.cell_m} m</div>` : ""}
+ ` : `
+ <select data-act="grid-open">
+ <option value="">Open a saved grid…</option>
+ ${(state.grids || []).map((g) => `<option value="${esc(g.name)}">${esc(g.title)}</option>`).join("")}
+ </select>`}`;
+ }
+
+ /** The one line under the sky slider: what is up, and how high. */
+ function skyLine(tool) {
+ const curve = tool.day?.curve;
+ if (!curve) return "";
+ const parts = [];
+ for (const key of ["sun", "moon"]) {
+ const alt = curve[`${key}_altitude`]?.[tool.index];
+ const az = curve[`${key}_azimuth`]?.[tool.index];
+ if (!Number.isFinite(alt)) continue;
+ const lit = key === "moon" ? curve.moon_illuminated?.[tool.index] : null;
+ parts.push(
+ `${key} ${Math.round(alt)}°, az ${Math.round(az)}°` +
+ (lit != null ? `, ${Math.round(lit * 100)}% lit` : "")
+ );
+ }
+ return parts.join(" · ");
+ }
+
+ function render() {
+ const seen = verdict();
+ panel.innerHTML = `
+ <header>
+ <span class="name">Azimut</span>
+ ${button("collapse", state.collapsed ? "chevronDown" : "chevronUp", "", false, ' class="icon" title="Fold"')}
+ ${button("close", "x", "", false, ' class="icon" title="Close"')}
+ </header>
+ <div class="body">
+ <div class="status ${seen.ok ? "" : "off"}">
+ ${icon(seen.ok ? "satellite" : "alert", 14)}<span${frameTitle()}>${esc(seen.ok ? sound() : seen.why)}</span>
+ </div>
+ <select data-act="case">
+ ${state.cases.map((c) => `<option value="${esc(c.id)}"${c.id === state.caseId ? " selected" : ""}>${esc(c.name)}</option>`).join("")}
+ </select>
+ <div class="tabs">
+ ${ORDER.map((id) => button("tab", tools[id].icon, tools[id].label, state.tool === id, ` data-tab="${id}"`)).join("")}
+ </div>
+ ${toolBody()}
+ ${state.note ? `<div class="note">${esc(state.note)}</div>` : ""}
+ </div>`;
+ panel.classList.toggle("collapsed", state.collapsed);
+ paint();
+ }
+
+ /** The status line when geometry is on: where, what it is drawing in, and
+ * whether it knows yet which pixel this site's centre is under. */
+ function sound() {
+ const view = projected();
+ const how = state.parsed?.scale_source
+ ? `${state.parsed.scale_source} from the URL`
+ : scale()
+ ? "measured off the map"
+ : "from the site table";
+ const zoom = view.zoom != null ? ` · z${view.zoom.toFixed(2)}` : "";
+ const drawn = state.parsed?.projection ?? "no named projection";
+ const framed = state.framed ? "" : " · zoom once to place it";
+ const far = verdict().far ? " · drifts at the edges out here" : "";
+ return `${state.parsed.site}${zoom} · ${drawn} (${how})${framed}${far}`;
+ }
+
+ /** The offset itself, on the line that talks about it. It is the number to
+ * read out when a drawing lands somewhere the ground is not, and there is
+ * nowhere else in the panel it appears. */
+ function frameTitle() {
+ if (!state.framed) return "";
+ const { x, y } = state.frame;
+ return ` title="centre at ${x.toFixed(0)}, ${y.toFixed(0)} from the middle of a ${windowSize.w}×${windowSize.h} window"`;
+ }
+
+ // --- what the panel's controls do ------------------------------------------
+
+ panel.addEventListener("click", async (event) => {
+ const target = event.target.closest("[data-act]");
+ if (!target) return;
+ const act = target.dataset.act;
+ state.note = "";
+
+ if (act === "close") return close();
+ if (act === "collapse") {
+ state.collapsed = !state.collapsed;
+ save();
+ return render();
+ }
+ if (act === "tab") {
+ // Pressing the open tool puts it down. Every mode in this panel toggles,
+ // and a tool you cannot put down is one that keeps taking your clicks.
+ const wanted = target.dataset.tab;
+ // Leaving a tool puts it down too. An armed tool that is no longer on
+ // screen still takes every click on the map, with nothing drawn to
+ // explain why the map has stopped answering.
+ for (const id of ORDER) if (id !== wanted || state.tool === wanted) tools[id].disarm();
+ // The picker belongs to the tab; the windows do not, and putting the tool
+ // down leaves them where they are — a reference is for looking at while
+ // measuring, not instead of it.
+ if (wanted !== "refs") refLayer.closePicker();
+ if (state.tool === wanted) {
+ state.tool = null;
+ } else {
+ state.tool = wanted;
+ if (wanted === "grid" && !state.grids) state.grids = await loadGrids();
+ }
+ syncArmed();
+ save();
+ return render();
+ }
+
+ if (act === "measure-distance" || act === "measure-area") {
+ tools.measure.setMode(act === "measure-distance" ? "distance" : "area");
+ syncArmed();
+ return render();
+ }
+ if (act === "measure-undo") {
+ tools.measure.undo();
+ return render();
+ }
+ if (act === "measure-clear") {
+ tools.measure.clear();
+ return render();
+ }
+
+ if (act === "pin-drop") {
+ tools.pins.toggleDrop();
+ syncArmed();
+ return render();
+ }
+ if (act === "pin-save") return placePin();
+ if (act === "pin-cancel") {
+ tools.pins.clearDraft();
+ state.pinTitle = "";
+ syncArmed();
+ return render();
+ }
+
+ if (act === "sky-place") {
+ tools.sky.togglePlacing();
+ syncArmed();
+ return render();
+ }
+ if (act === "sky-clear") {
+ tools.sky.clear();
+ syncArmed();
+ return render();
+ }
+
+ if (act === "ref-add") {
+ refLayer.openPicker();
+ return render();
+ }
+ if (act === "ref-focus") {
+ tools.refs.focus(target.dataset.ref);
+ return refLayer.sync();
+ }
+ if (act === "ref-fold") {
+ tools.refs.fold(target.dataset.ref);
+ refLayer.sync();
+ return render();
+ }
+ if (act === "ref-close") {
+ tools.refs.close(target.dataset.ref);
+ refLayer.sync();
+ return render();
+ }
+
+ if (act === "grid-rect" || act === "grid-poly") {
+ tools.grid.draw(act === "grid-rect" ? "rect" : "polygon");
+ syncArmed();
+ return render();
+ }
+ if (act === "grid-close-shape") {
+ const answer = tools.grid.finishPolygon();
+ state.note = answer?.error || "";
+ syncArmed();
+ return render();
+ }
+ if (act === "grid-undo-vertex") {
+ tools.grid.undoVertex();
+ return render();
+ }
+ if (act === "grid-mark") {
+ tools.grid.toggleMark();
+ syncArmed();
+ return render();
+ }
+ if (act === "grid-hide") {
+ tools.grid.toggleHidden();
+ return render();
+ }
+ if (act === "grid-save") return saveGrid();
+ if (act === "grid-close") {
+ await pushMarks();
+ tools.grid.close();
+ state.gridTitle = "";
+ state.grids = await loadGrids();
+ syncArmed();
+ return render();
+ }
+ });
+
+ panel.addEventListener("change", async (event) => {
+ const act = event.target.dataset.act;
+ if (act === "case") {
+ state.caseId = event.target.value;
+ api.storage.local.set({ lastCaseId: state.caseId });
+ // whatever was half-placed belonged to the case that was open when it was
+ // clicked, and filing it into this one would be filing it somewhere else
+ tools.pins.disarm();
+ state.pinTitle = "";
+ tools.grid.close();
+ // the windows were holding the other case's media
+ refLayer.closePicker();
+ tools.refs.clear();
+ refLayer.sync();
+ state.grids = await loadGrids();
+ await loadPins();
+ syncArmed();
+ return render();
+ }
+ if (act === "sky-date") {
+ tools.sky.onDay(event.target.value || null);
+ return loadSky();
+ }
+ if (act === "grid-open" && event.target.value) return openGrid(event.target.value);
+ if (act === "grid-cell") {
+ const metres = Number(event.target.value);
+ if (metres >= 10) tools.grid.cellM = metres;
+ }
+ });
+
+ panel.addEventListener("input", (event) => {
+ const act = event.target.dataset.act;
+ if (act === "pin-title") state.pinTitle = event.target.value;
+ if (act === "grid-title") state.gridTitle = event.target.value;
+ if (act === "sky-scrub") {
+ tools.sky.index = Number(event.target.value);
+ // repainted without re-rendering: rebuilding the panel under a slider
+ // being dragged takes the slider out from under the pointer
+ const line = panel.querySelector(".hint");
+ if (line) line.textContent = skyLine(tools.sky);
+ const readout = panel.querySelector(".readout");
+ if (readout) readout.textContent = tools.sky.readout() ?? "";
+ redraw();
+ }
+ });
+
+ // Dragging the panel by its header. Remembered per site, because a panel that
+ // covers the sidebar on one map covers the map itself on another.
+ panel.addEventListener("pointerdown", (event) => {
+ if (!event.target.closest("header") || event.target.closest("[data-act]")) return;
+ const start = { x: event.clientX, y: event.clientY };
+ const rect = panel.getBoundingClientRect();
+ const move = (e) => {
+ panel.style.left = `${rect.left + e.clientX - start.x}px`;
+ panel.style.top = `${rect.top + e.clientY - start.y}px`;
+ panel.style.right = "auto";
+ };
+ const up = () => {
+ window.removeEventListener("pointermove", move, true);
+ window.removeEventListener("pointerup", up, true);
+ save();
+ };
+ window.addEventListener("pointermove", move, true);
+ window.addEventListener("pointerup", up, true);
+ });
+
+ // --- what is remembered, per site ------------------------------------------
+
+ function save() {
+ rememberFrame();
+ const rect = panel.getBoundingClientRect();
+ api.storage.local.set({
+ [storeKey]: {
+ panel: { top: rect.top, left: rect.left },
+ collapsed: state.collapsed,
+ tool: state.tool,
+ // where this site draws its centre, so the next visit starts placed —
+ // each with the window it was measured in, because that is what makes
+ // it an answer rather than a number
+ frames,
+ },
+ });
+ }
+
+ async function restore() {
+ const stored = (await api.storage.local.get({ [storeKey]: null }))[storeKey];
+ if (!stored) return;
+ state.collapsed = !!stored.collapsed;
+ if (stored.tool && tools[stored.tool]) state.tool = stored.tool;
+ if (Array.isArray(stored.frames)) {
+ // Anything that could not fit inside this window describes a layout that
+ // is gone, and is dropped outright.
+ frames = stored.frames.filter(framePlausible).slice(0, FRAMES_KEPT);
+ // One of them was measured in a window this shape, or none was. Failing
+ // a match the most recent is still the best guess there is, so it is
+ // drawn from — but it does not count as measured, and the panel asks for
+ // the zoom that would settle it rather than standing behind a number from
+ // a window that no longer exists.
+ const here = frameFor(windowSize);
+ const best = here ?? frames[0];
+ if (best) {
+ state.frame = { x: best.x, y: best.y };
+ state.framed = !!here;
+ frameSamples = here ? [state.frame] : [];
+ }
+ }
+ if (stored.panel) {
+ // clamped back inside the window: a panel remembered on a wide screen
+ // must not open off the edge of a narrow one
+ panel.style.top = `${Math.max(0, Math.min(window.innerHeight - 60, stored.panel.top))}px`;
+ panel.style.left = `${Math.max(0, Math.min(window.innerWidth - 120, stored.panel.left))}px`;
+ panel.style.right = "auto";
+ }
+ }
+
+ // --- out of the frame ------------------------------------------------------
+
+ /**
+ * The panel and its windows, taken out of the shot.
+ *
+ * `captureVisibleTab` photographs the page as it is composited, and this panel
+ * is on it — so a capture filed from a tab with the tools open used to carry
+ * them. A reference image floating over the map would be worse than
+ * untidy: it would look like part of the ground.
+ *
+ * The worker asks before it grabs and again after (`background.js`). Two
+ * frames are waited out before answering, because a `display: none` set this
+ * frame is still in the one the compositor is holding — `overlay.js` waits the
+ * same two, for the same reason.
+ */
+ function onCaptureFrame(msg, sender, sendResponse) {
+ if (msg?.type !== "map-chrome") return false;
+ host.style.display = msg.hide ? "none" : "";
+ requestAnimationFrame(() => requestAnimationFrame(() => sendResponse({ ok: true })));
+ return true;
+ }
+ api.runtime.onMessage.addListener(onCaptureFrame);
+
+ /**
+ * The window changed size, so what was measured about this site's layout may
+ * not hold any more.
+ *
+ * A fixed side panel keeps its pixel offset when the window is resized and a
+ * panel measured in percentages does not, and nothing in the address bar says
+ * which this one is. The offset is kept — it is still the best answer there
+ * is — but it stops counting as measured, so the panel asks for the zoom that
+ * would settle it rather than quietly standing behind a number from a window
+ * that no longer exists.
+ *
+ * The scale is re-read rather than kept, and that is not the same decision. On
+ * the two views that state a size instead of a level, the zoom was worked out
+ * against the height the map was drawn in, so a window that changed height
+ * quietly changed the scale. `readUrl` notices on the next poll, because the
+ * height it was last told is part of what makes a reading current.
+ */
+ function onResize() {
+ const moved =
+ Math.abs(window.innerWidth - windowSize.w) > WINDOW_SAME_PX ||
+ Math.abs(window.innerHeight - windowSize.h) > WINDOW_SAME_PX;
+ rememberFrame(); // file what was measured under the window it was measured in
+ windowSize = { w: window.innerWidth, h: window.innerHeight };
+ if (moved) {
+ // A window dragged back to a shape this site was already measured in is
+ // placed again without asking for another zoom, which is what keeping
+ // more than one of them is for.
+ const known = frameFor(windowSize);
+ if (known) {
+ state.frame = { x: known.x, y: known.y };
+ state.framed = true;
+ frameSamples = [state.frame];
+ render();
+ return;
+ }
+ if (state.framed && (state.frame.x || state.frame.y)) {
+ state.framed = false;
+ render();
+ return;
+ }
+ }
+ redraw();
+ }
+
+ // --- lifecycle -------------------------------------------------------------
+
+ const listeners = [
+ [window, "pointerdown", onPointerDown, true],
+ [window, "pointermove", onPointerMove, true],
+ [window, "pointerup", onPointerUp, true],
+ [window, "click", onClick, true],
+ [window, "dblclick", onDoubleClick, true],
+ [window, "wheel", onWheel, { capture: true, passive: true }],
+ [window, "resize", onResize, false],
+ [layer.canvas, "pointerdown", canvasDown, false],
+ [layer.canvas, "pointermove", canvasMove, false],
+ [layer.canvas, "pointerup", canvasUp, false],
+ ];
+ for (const [node, type, fn, opts] of listeners) node.addEventListener(type, fn, opts);
+ const poll = setInterval(() => readUrl(), URL_POLL_MS);
+ const gridPoll = setInterval(() => refreshGrid({ poll: true }), GRID_POLL_MS);
+ watch = setInterval(keepWatching, WATCH_MS);
+ listen();
+
+ function close() {
+ clearInterval(poll);
+ clearInterval(gridPoll);
+ clearInterval(watch);
+ clearTimeout(syncRetry);
+ try {
+ sync?.disconnect();
+ } catch {
+ /* already gone */
+ }
+ sync = null;
+ clearTimeout(giveUp);
+ clearTimeout(settle);
+ clearTimeout(frameQuiet);
+ if (frame) cancelAnimationFrame(frame);
+ for (const [node, type, fn, opts] of listeners) node.removeEventListener(type, fn, opts);
+ api.runtime.onMessage.removeListener(onCaptureFrame);
+ refLayer.destroy();
+ layer.destroy();
+ host.remove();
+ delete window.__AZIMUT_MAP_TOOLS__;
+ }
+
+ window.__AZIMUT_MAP_TOOLS__ = { close, state, tools };
+
+ (async () => {
+ await restore();
+ render();
+ try {
+ state.units = (await call("GET", "/api/ingest/ping")).units || "metric";
+ } catch (e) {
+ state.note = e.message;
+ }
+ await loadCases();
+ await readUrl(true);
+ })();
+})();
diff --git a/extension/mapref.js b/extension/mapref.js
new file mode 100644
index 0000000..74fe954
--- /dev/null
+++ b/extension/mapref.js
@@ -0,0 +1,705 @@
+/**
+ * The reference windows: the case's own images and videos, over the map.
+ *
+ * The app's Satellite tab can hold the shot being geolocated against the
+ * imagery, in a small pane that moves and zooms independently of the map
+ * (`tools/RefViewer.svelte`, `lib/refViewers.js`). This is that, over someone
+ * else's map. It is the pane that makes the rest of the panel worth opening:
+ * measuring a courtyard means nothing until it is the courtyard in the image.
+ *
+ * Two things about it are not obvious:
+ *
+ * - **An image is painted, never linked.** A map site's content policy is free
+ * to refuse a `data:` or `blob:` image, and several do. So the bytes arrive as
+ * bytes, are decoded with `createImageBitmap` and drawn on a canvas, which
+ * asks no policy anything. A **video cannot be painted** — the element wants a
+ * URL — so it gets a `blob:` one, and it is the single thing here a site is in
+ * a position to refuse. When one does, the window says so rather than sitting
+ * there black.
+ * - **It reaches nothing itself.** `file()` and `search()` are handed in by
+ * `mapoverlay.js`, which stays the only file that knows an extension API
+ * exists.
+ *
+ * Where a pane sits and how far into an image it is zoomed is `maptools.js`,
+ * checked against the app's own arithmetic. This is the pointer and DOM glue,
+ * and the picker that chooses what to open.
+ *
+ * Loaded after `maptheme.js` and `maptools.js`, left on `window.AzimutMapRefs`.
+ */
+
+(() => {
+ const THEME = window.AzimutMapTheme;
+ const T = window.AzimutMapTools;
+ const icon = THEME.icon;
+ const t = THEME.TOKENS;
+
+ /** How long after the last keystroke the case is searched. */
+ const TYPING_MS = 220;
+
+ const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);
+ const bounds = () => ({ w: window.innerWidth, h: window.innerHeight });
+
+ /** Every gesture in here is one pointer down, some moves and a release. */
+ function drag(move) {
+ const up = () => {
+ window.removeEventListener("pointermove", move, true);
+ window.removeEventListener("pointerup", up, true);
+ };
+ window.addEventListener("pointermove", move, true);
+ window.addEventListener("pointerup", up, true);
+ }
+
+ /**
+ * A pointer gesture that belongs to this pane and not to the map under it.
+ *
+ * The panel's own engine already ignores anything inside the shadow root, but
+ * the *site* does not: dragging a window by its header would drag the map with
+ * it. Cancelling the default on `pointerdown` is what stops that — no
+ * compatibility mouse event follows, and a map that never sees a mousedown
+ * never starts panning.
+ */
+ function mine(event) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ /**
+ * The style sheet for the windows and the picker.
+ *
+ * It goes in the panel's own shadow root, after the panel's, so the base rules
+ * there (`button`, `header`, `.icon`, `.hint`) are the ones these build on —
+ * one look, stated once.
+ */
+ function styles() {
+ return `
+ .rw {
+ position: fixed; display: flex; flex-direction: column; overflow: hidden;
+ /* stated here rather than inherited: the host resets everything, so a
+ window that names no font is drawn in the browser's default serif */
+ font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
+ color: ${t.text1}; background: ${t.bg1};
+ border: 1px solid ${t.border}; border-radius: 10px;
+ box-shadow: 0 12px 32px rgba(0,0,0,.5);
+ pointer-events: auto; user-select: none;
+ }
+ .rw.folded { height: auto !important; }
+ .rw header { padding: 5px 6px 5px 8px; cursor: grab; }
+ .rw header:active { cursor: grabbing; }
+ .rw .rw-title {
+ flex: 1; min-width: 0; font-size: 11.5px; font-weight: 600; color: ${t.text1};
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .rw-body {
+ flex: 1; min-height: 0; position: relative; overflow: hidden; background: ${t.bg0};
+ }
+ .rw-body.pannable { cursor: grab; }
+ .rw-body.pannable:active { cursor: grabbing; }
+ .rw-body canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
+ .rw-body video { position: absolute; inset: 0; width: 100%; height: 100%; background: #000; }
+ .rw-wait {
+ position: absolute; inset: 0; display: grid; place-items: center;
+ padding: 0 12px; text-align: center; font-size: 11.5px; color: ${t.text3};
+ }
+ .rw-foot {
+ display: flex; align-items: center; justify-content: flex-end; gap: 4px;
+ padding: 3px 5px; border-top: 1px solid ${t.border};
+ }
+ .rw-zoom {
+ min-width: 44px; padding: 3px 4px; font-size: 11px; color: ${t.text2};
+ background: none; border-color: transparent;
+ }
+ .rw-zoom:hover:not([disabled]) { color: ${t.accent}; background: ${t.bg3}; }
+ .rw-resize {
+ position: absolute; right: 0; bottom: 0; width: 16px; height: 16px;
+ cursor: nwse-resize;
+ background: linear-gradient(135deg, transparent 55%, ${t.borderStrong} 55%,
+ ${t.borderStrong} 65%, transparent 65%, transparent 77%, ${t.borderStrong} 77%,
+ ${t.borderStrong} 87%, transparent 87%);
+ }
+ .pick {
+ position: fixed; top: 64px; left: 50%; transform: translateX(-50%);
+ width: min(470px, 92vw); max-height: 68vh; display: flex; flex-direction: column;
+ font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; color: ${t.text1};
+ background: ${t.bg1}; border: 1px solid ${t.borderStrong}; border-radius: 10px;
+ box-shadow: 0 16px 48px rgba(0,0,0,.6); pointer-events: auto; overflow: hidden;
+ z-index: 1001; /* the one thing that goes over the panel, while it is up */
+ }
+ .pick header { cursor: default; }
+ .pick .body { padding: 10px; gap: 8px; overflow: auto; }
+ .pick-filters { display: flex; gap: 6px; }
+ .pick-filters select { flex: 1; }
+ .pick-grid {
+ display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: 8px;
+ }
+ .pick-item {
+ flex-direction: column; align-items: stretch; gap: 4px; padding: 0;
+ background: none; border-color: transparent; text-align: left;
+ }
+ .pick-item:hover:not([disabled]) { background: none; border-color: transparent; }
+ .pick-thumb {
+ position: relative; aspect-ratio: 4 / 3; display: grid; place-items: center;
+ background: ${t.bg2}; border: 1px solid ${t.border}; border-radius: 7px;
+ overflow: hidden; color: ${t.text3};
+ }
+ .pick-thumb canvas { width: 100%; height: 100%; display: block; }
+ .pick-kind {
+ position: absolute; right: 4px; bottom: 4px; display: grid; place-items: center;
+ padding: 2px; border-radius: 5px; color: #fff; background: rgba(16,16,16,.75);
+ }
+ .pick-item:hover .pick-thumb { border-color: ${t.accent}; }
+ .pick-name {
+ font-size: 11px; color: ${t.text2};
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ }
+ .pick-item:hover .pick-name { color: ${t.accent}; }
+ `;
+ }
+
+ /**
+ * The windows and their picker.
+ *
+ * @param {object} deps
+ * @param {ShadowRoot} deps.root where the panel already lives
+ * @param {object} deps.refs the tool holding which windows are open (maptools)
+ * @param {(path: string) => Promise<Blob>} deps.file one case file's bytes
+ * @param {(params: object) => Promise<object>} deps.search what the case offers
+ * @param {() => void} deps.onchange the open list moved; the panel re-reads it
+ * @param {(message: string) => void} deps.onnote something to say in the panel
+ */
+ function create({ root, refs, file, search, onchange, onnote }) {
+ const style = document.createElement("style");
+ style.textContent = styles();
+ root.appendChild(style);
+
+ const panes = new Map(); // viewer id -> { el, body, viewer, bitmap | video, ... }
+ const thumbs = new Map(); // media path -> ImageBitmap | null (null = none to show)
+ let picker = null;
+ let typing = 0;
+ let searching = 0; // the search whose answer is still the current one
+
+ // --- one window ----------------------------------------------------------
+
+ function mount(viewer) {
+ const moving = viewer.kind === "video";
+ const el = document.createElement("div");
+ el.className = "rw";
+ el.innerHTML = `
+ <header>
+ ${icon("grip", 13)}
+ <span class="rw-title" title="${esc(viewer.title)}">${esc(viewer.title || "Reference")}</span>
+ <button class="icon" data-rw="fold" title="Fold">${icon("chevronUp", 13)}</button>
+ <button class="icon" data-rw="close" title="Close">${icon("x", 13)}</button>
+ </header>
+ <div class="rw-body">
+ ${moving ? "" : "<canvas></canvas>"}
+ <div class="rw-wait">Loading…</div>
+ </div>
+ ${moving ? "" : `
+ <div class="rw-foot">
+ <button class="icon" data-rw="out" title="Zoom out">${icon("minimize", 12)}</button>
+ <button class="rw-zoom" data-rw="reset" title="Fit the image">100%</button>
+ <button class="icon" data-rw="in" title="Zoom in">${icon("plus", 13)}</button>
+ </div>`}
+ <div class="rw-resize" title="Resize"></div>`;
+ root.appendChild(el);
+
+ const pane = {
+ el,
+ viewer,
+ moving, // a video, which shows itself rather than being painted
+ folded: false, // what the fold button is currently drawn as
+ bitmap: null,
+ url: null, // the object URL a video is playing from, to be revoked
+ head: el.querySelector("header"),
+ body: el.querySelector(".rw-body"),
+ canvas: el.querySelector("canvas"),
+ wait: el.querySelector(".rw-wait"),
+ zoom: el.querySelector(".rw-zoom"),
+ };
+ wire(pane);
+
+ file(viewer.path).then(
+ (blob) => (moving ? play(pane, blob) : show(pane, blob)),
+ (e) => refuse(pane, e.message)
+ );
+ return pane;
+ }
+
+ /** An image: decoded once, then painted at whatever zoom the window holds. */
+ async function show(pane, blob) {
+ try {
+ pane.bitmap = await createImageBitmap(blob);
+ } catch {
+ return refuse(pane, "that file is not an image this browser can read");
+ }
+ pane.wait.remove();
+ paint(pane);
+ }
+
+ /**
+ * A video, handed to the element through an object URL.
+ *
+ * The one thing in this panel a map site can veto: the URL is `blob:`, and a
+ * page whose policy narrows `media-src` will refuse it. The refusal arrives
+ * as an `error` on the element, which is why it is listened for — an empty
+ * black box that never says anything is the worst version of this.
+ */
+ function play(pane, blob) {
+ const video = document.createElement("video");
+ pane.url = URL.createObjectURL(blob);
+ video.controls = true;
+ video.preload = "metadata";
+ video.addEventListener("loadeddata", () => pane.wait.remove());
+ video.addEventListener("error", () =>
+ refuse(pane, "this site will not play a video. Open it in Azimut")
+ );
+ video.src = pane.url;
+ pane.body.appendChild(video);
+ pane.video = video;
+ }
+
+ /** The window stays, saying why it is empty. A pane that vanished would look
+ * like a misclick rather than a file the app could not hand over. */
+ function refuse(pane, message) {
+ if (!pane.wait.isConnected) pane.body.appendChild(pane.wait);
+ pane.wait.textContent = message;
+ pane.video?.remove();
+ onnote(message);
+ }
+
+ function wire(pane) {
+ const { el, head, body } = pane;
+
+ el.addEventListener("pointerdown", () => {
+ refs.focus(pane.viewer.id);
+ for (const other of panes.values()) place(other);
+ }, true);
+
+ el.addEventListener("click", (event) => {
+ const act = event.target.closest("[data-rw]")?.dataset.rw;
+ if (!act) return;
+ const viewer = pane.viewer;
+ if (act === "close") {
+ refs.close(viewer.id);
+ sync();
+ onchange();
+ return;
+ }
+ if (act === "fold") {
+ viewer.collapsed = !viewer.collapsed;
+ place(pane);
+ onchange();
+ return;
+ }
+ if (act === "reset") {
+ viewer.scale = 1;
+ viewer.ox = 0;
+ viewer.oy = 0;
+ } else {
+ const size = { w: body.clientWidth, h: body.clientHeight };
+ const at = { x: size.w / 2, y: size.h / 2 };
+ Object.assign(viewer, T.zoomAt(viewer, act === "in" ? 1.25 : 1 / 1.25, at, size));
+ }
+ paint(pane);
+ });
+
+ // Double-clicking a title bar folds it: the affordance every window has,
+ // and the map must not take the second click as a zoom.
+ head.addEventListener("dblclick", (event) => {
+ if (event.target.closest("button")) return;
+ mine(event);
+ refs.fold(pane.viewer.id);
+ place(pane);
+ onchange();
+ });
+
+ head.addEventListener("pointerdown", (event) => {
+ if (event.button !== 0 || event.target.closest("button")) return;
+ mine(event);
+ const start = { x: event.clientX, y: event.clientY };
+ const from = { x: pane.viewer.x, y: pane.viewer.y };
+ drag((move) => {
+ const viewer = pane.viewer;
+ const height = viewer.collapsed ? pane.head.offsetHeight : viewer.h;
+ const at = T.clampWindow(
+ from.x + move.clientX - start.x,
+ from.y + move.clientY - start.y,
+ viewer.w,
+ height,
+ bounds()
+ );
+ viewer.x = at.x;
+ viewer.y = at.y;
+ place(pane);
+ });
+ });
+
+ el.querySelector(".rw-resize").addEventListener("pointerdown", (event) => {
+ if (event.button !== 0) return;
+ mine(event);
+ const start = { x: event.clientX, y: event.clientY };
+ const from = { w: pane.viewer.w, h: pane.viewer.h };
+ drag((move) => {
+ const viewer = pane.viewer;
+ const size = T.clampSize(
+ from.w + move.clientX - start.x,
+ from.h + move.clientY - start.y,
+ viewer.x,
+ viewer.y,
+ bounds()
+ );
+ viewer.w = size.w;
+ viewer.h = size.h;
+ // the pane got bigger under an image that was panned to an edge
+ Object.assign(viewer, T.clampPan(viewer.ox, viewer.oy, viewer.scale, body.clientWidth, body.clientHeight));
+ place(pane);
+ });
+ });
+
+ body.addEventListener("pointerdown", (event) => {
+ // A video's own controls take the pointer: cancelling the default here
+ // would kill the scrub bar. Stopping it is enough to keep the map still.
+ if (pane.moving) return event.stopPropagation();
+ if (event.button !== 0 || pane.viewer.scale <= 1) return;
+ mine(event);
+ const start = { x: event.clientX, y: event.clientY };
+ const from = { ox: pane.viewer.ox, oy: pane.viewer.oy };
+ drag((move) => {
+ Object.assign(
+ pane.viewer,
+ T.clampPan(
+ from.ox + move.clientX - start.x,
+ from.oy + move.clientY - start.y,
+ pane.viewer.scale,
+ body.clientWidth,
+ body.clientHeight
+ )
+ );
+ paint(pane);
+ });
+ });
+
+ body.addEventListener(
+ "wheel",
+ (event) => {
+ // Not passive: a wheel over the image zooms the image, and the map
+ // underneath must not zoom with it. Over a video it does neither.
+ mine(event);
+ if (pane.moving) return;
+ const rect = body.getBoundingClientRect();
+ const at = { x: event.clientX - rect.left, y: event.clientY - rect.top };
+ const size = { w: rect.width, h: rect.height };
+ Object.assign(pane.viewer, T.zoomAt(pane.viewer, event.deltaY < 0 ? 1.15 : 1 / 1.15, at, size));
+ paint(pane);
+ },
+ { passive: false }
+ );
+ }
+
+ /** Where the window is, how big, and how high in the stack. */
+ function place(pane) {
+ const { el, viewer } = pane;
+ el.style.left = `${viewer.x}px`;
+ el.style.top = `${viewer.y}px`;
+ el.style.width = `${viewer.w}px`;
+ el.style.height = `${viewer.h}px`;
+ // above the drawing layer (1), below the panel — restacking is what keeps
+ // that true however many windows have been opened
+ el.style.zIndex = String(1 + viewer.z);
+ el.classList.toggle("folded", viewer.collapsed);
+ for (const part of [pane.body, el.querySelector(".rw-foot"), el.querySelector(".rw-resize")]) {
+ if (part) part.style.display = viewer.collapsed ? "none" : "";
+ }
+ // Only when it actually turns over. `place` runs on every pointer down in
+ // the window (focus restacks them all), and rewriting this button's glyph
+ // took the node out of the DOM between the press and the release — which
+ // is a chevron that swallows its own click and never folds anything.
+ if (pane.folded !== viewer.collapsed) {
+ pane.folded = viewer.collapsed;
+ const fold = el.querySelector('[data-rw="fold"]');
+ fold.innerHTML = icon(viewer.collapsed ? "chevronDown" : "chevronUp", 13);
+ fold.title = viewer.collapsed ? "Unfold" : "Fold";
+ }
+ if (!viewer.collapsed) paint(pane);
+ }
+
+ /**
+ * The image, at the zoom and offset the window holds.
+ *
+ * The app fits its `<img>` with `object-fit: contain` and then applies the
+ * zoom as a transform from the pane's own top-left. Same two steps here, in
+ * the same order, so a window opened in either place shows the same thing.
+ */
+ function paint(pane) {
+ const { canvas, bitmap, viewer, body } = pane;
+ if (pane.moving) return; // a video draws itself
+ const w = body.clientWidth;
+ const h = body.clientHeight;
+ if (!w || !h) return;
+ const ratio = window.devicePixelRatio || 1;
+ if (canvas.width !== Math.round(w * ratio) || canvas.height !== Math.round(h * ratio)) {
+ canvas.width = Math.round(w * ratio);
+ canvas.height = Math.round(h * ratio);
+ }
+ const ctx = canvas.getContext("2d");
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.clearRect(0, 0, w, h);
+ pane.zoom.textContent = `${Math.round(viewer.scale * 100)}%`;
+ body.classList.toggle("pannable", viewer.scale > 1);
+ if (!bitmap) return;
+ const fit = Math.min(w / bitmap.width, h / bitmap.height);
+ const fw = bitmap.width * fit;
+ const fh = bitmap.height * fit;
+ ctx.translate(viewer.ox, viewer.oy);
+ ctx.scale(viewer.scale, viewer.scale);
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(bitmap, (w - fw) / 2, (h - fh) / 2, fw, fh);
+ }
+
+ /** The windows on screen, matched to the windows the tool holds. */
+ function sync() {
+ const open = refs.open;
+ const live = new Set(open.map((viewer) => viewer.id));
+ for (const [id, pane] of panes) {
+ if (live.has(id)) continue;
+ drop(pane);
+ panes.delete(id);
+ }
+ for (const viewer of open) {
+ let pane = panes.get(viewer.id);
+ if (!pane) {
+ pane = mount(viewer);
+ panes.set(viewer.id, pane);
+ }
+ pane.viewer = viewer;
+ place(pane);
+ }
+ }
+
+ /** One window, off the screen and out of memory: a decoded image and a
+ * video's object URL both outlive the node that showed them. */
+ function drop(pane) {
+ pane.bitmap?.close?.();
+ if (pane.url) URL.revokeObjectURL(pane.url);
+ pane.el.remove();
+ }
+
+ // --- the picker ----------------------------------------------------------
+
+ /** The two narrowings the picker offers, and what they are called. The case
+ * is searched, filtered and ordered by the app — a browser tab holds one
+ * page of a case, never the case. */
+ const KINDS = [["", "Images and videos"], ["image", "Images"], ["video", "Videos"]];
+ const SORTS = [["newest", "Newest first"], ["oldest", "Oldest first"], ["name", "By name"]];
+
+ function openPicker() {
+ if (picker) return;
+ const el = document.createElement("div");
+ el.className = "pick";
+ const options = (pairs, chosen) =>
+ pairs
+ .map(([value, label]) => `<option value="${value}"${value === chosen ? " selected" : ""}>${label}</option>`)
+ .join("");
+ const chosen = { q: "", kind: "", sort: "newest" };
+ el.innerHTML = `
+ <header>
+ <span class="name">Add reference</span>
+ <button class="icon" data-pick="close" title="Close">${icon("x", 13)}</button>
+ </header>
+ <div class="body">
+ <input data-pick="q" placeholder="Search media…" autocomplete="off">
+ <div class="pick-filters">
+ <select data-pick="kind">${options(KINDS, chosen.kind)}</select>
+ <select data-pick="sort">${options(SORTS, chosen.sort)}</select>
+ </div>
+ <div class="pick-grid"></div>
+ <div class="hint">Loading…</div>
+ </div>`;
+ root.appendChild(el);
+ picker = {
+ el,
+ grid: el.querySelector(".pick-grid"),
+ hint: el.querySelector(".hint"),
+ items: [],
+ ...chosen,
+ };
+
+ el.addEventListener("click", (event) => {
+ if (event.target.closest('[data-pick="close"]')) return closePicker();
+ const index = event.target.closest("[data-index]")?.dataset.index;
+ if (index == null) return;
+ const item = picker.items[Number(index)];
+ if (!item) return;
+ refs.add(item);
+ closePicker();
+ sync();
+ onchange();
+ });
+ el.addEventListener("input", (event) => {
+ if (event.target.dataset.pick !== "q") return;
+ clearTimeout(typing);
+ picker.q = event.target.value;
+ typing = setTimeout(fill, TYPING_MS);
+ });
+ el.addEventListener("change", (event) => {
+ const which = event.target.dataset.pick;
+ if (which !== "kind" && which !== "sort") return;
+ picker[which] = event.target.value;
+ fill();
+ });
+ // A pointer down inside the picker is not a gesture on the map
+ el.addEventListener("pointerdown", (event) => event.stopPropagation());
+ window.addEventListener("keydown", onKey, true);
+ el.querySelector("input").focus();
+ fill();
+ }
+
+ function closePicker() {
+ if (!picker) return;
+ clearTimeout(typing);
+ window.removeEventListener("keydown", onKey, true);
+ picker.el.remove();
+ picker = null;
+ onchange();
+ }
+
+ function onKey(event) {
+ if (event.key !== "Escape") return;
+ event.stopPropagation();
+ closePicker();
+ }
+
+ /** Read the case and draw the choice. An answer that is no longer the
+ * current search is dropped: typing one letter more must not be undone by
+ * the answer to the word before it. */
+ async function fill() {
+ if (!picker) return;
+ const mine = (searching += 1);
+ const { q, kind, sort } = picker;
+ let answer;
+ try {
+ answer = await search({ q, kind, sort });
+ } catch (e) {
+ if (!picker || mine !== searching) return;
+ picker.grid.innerHTML = "";
+ picker.hint.textContent = e.message;
+ return;
+ }
+ if (!picker || mine !== searching) return;
+ picker.items = answer.items || [];
+ if (!picker.items.length) {
+ picker.grid.innerHTML = "";
+ picker.hint.textContent = q
+ ? "No media matches this search."
+ : "No images or videos in this case yet. Import one in the Media Library first.";
+ return;
+ }
+ picker.grid.innerHTML = picker.items
+ .map(
+ (item, index) => `
+ <button class="pick-item" data-index="${index}" title="${esc(item.title || item.filename)}">
+ <span class="pick-thumb" data-thumb="${index}" data-key="${esc(item.thumbnail)}">
+ ${icon(item.kind === "video" ? "video" : "image", 22)}
+ ${item.kind === "video" ? `<span class="pick-kind">${icon("video", 11)}</span>` : ""}
+ </span>
+ <span class="pick-name">${esc(item.title || item.filename)}</span>
+ </button>`
+ )
+ .join("");
+ const total = answer.total ?? picker.items.length;
+ picker.hint.textContent =
+ total > picker.items.length
+ ? `${picker.items.length} of ${total} — search to narrow it down`
+ : `${total} file${total === 1 ? "" : "s"}`;
+ paintThumbs();
+ }
+
+ /** Thumbnails, one request each, drawn as they land. The file itself is
+ * fetched only when one is picked: a case of two hundred images must not
+ * cross the message boundary to fill a grid. */
+ function paintThumbs() {
+ const open = picker;
+ for (const [index, item] of open.items.entries()) {
+ if (!item.thumbnail) continue;
+ const slot = open.grid.querySelector(`[data-thumb="${index}"]`);
+ if (!slot) continue;
+ const seen = thumbs.get(item.thumbnail);
+ if (seen) {
+ drawThumb(slot, seen);
+ continue;
+ }
+ if (seen === null) continue; // asked once, and it was not there
+ thumbnail(item.thumbnail).then(
+ (bitmap) => {
+ thumbs.set(item.thumbnail, bitmap);
+ if (picker !== open) return;
+ // the grid may have been rebuilt by a later search: the tile is only
+ // this image's if it still says so
+ const tile = open.grid.querySelector(`[data-thumb="${index}"]`);
+ if (tile?.dataset.key === item.thumbnail) drawThumb(tile, bitmap);
+ },
+ () => thumbs.set(item.thumbnail, null)
+ );
+ }
+ }
+
+ /** The app draws a thumbnail for a video too, so the tile for one is a frame
+ * of it rather than a placeholder. */
+ const thumbnail = (path) => file(path).then(createImageBitmap);
+
+ /** One thumbnail, cropped to fill its tile the way the app's grid does. */
+ function drawThumb(slot, bitmap) {
+ if (!slot || slot.querySelector("canvas")) return;
+ const badge = slot.querySelector(".pick-kind");
+ const canvas = document.createElement("canvas");
+ const rect = slot.getBoundingClientRect();
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = Math.max(1, Math.round(rect.width * ratio));
+ canvas.height = Math.max(1, Math.round(rect.height * ratio));
+ const cover = Math.max(canvas.width / bitmap.width, canvas.height / bitmap.height);
+ const w = bitmap.width * cover;
+ const h = bitmap.height * cover;
+ canvas
+ .getContext("2d")
+ .drawImage(bitmap, (canvas.width - w) / 2, (canvas.height - h) / 2, w, h);
+ slot.innerHTML = "";
+ slot.appendChild(canvas);
+ if (badge) slot.appendChild(badge); // the video mark rides over the frame
+ }
+
+ // --- lifecycle -----------------------------------------------------------
+
+ /** A window remembered on a wide screen must not sit off a narrow one. */
+ function onResize() {
+ for (const pane of panes.values()) {
+ const viewer = pane.viewer;
+ const size = T.clampSize(viewer.w, viewer.h, 0, 0, bounds());
+ viewer.w = size.w;
+ viewer.h = size.h;
+ Object.assign(viewer, T.clampWindow(viewer.x, viewer.y, viewer.w, viewer.h, bounds()));
+ place(pane);
+ }
+ }
+ window.addEventListener("resize", onResize);
+
+ return {
+ sync,
+ openPicker,
+ closePicker,
+ get picking() {
+ return !!picker;
+ },
+ destroy() {
+ closePicker();
+ window.removeEventListener("resize", onResize);
+ for (const pane of panes.values()) drop(pane);
+ panes.clear();
+ for (const bitmap of thumbs.values()) bitmap?.close?.();
+ thumbs.clear();
+ style.remove();
+ },
+ };
+ }
+
+ window.AzimutMapRefs = { create };
+})();
diff --git a/extension/maptheme.js b/extension/maptheme.js
new file mode 100644
index 0000000..a4b6a4c
--- /dev/null
+++ b/extension/maptheme.js
@@ -0,0 +1,119 @@
+/**
+ * The app's own look, over someone else's map.
+ *
+ * Every value here is a copy of one the app already states — the design tokens
+ * in `frontend/src/app.css`, the icon set in `components/Icon.svelte`, the cell
+ * and ray styles the map tools paint with. The extension cannot import any of
+ * them (flat classic scripts, no build step), so they are written a second time
+ * and `frontend/src/lib/extensionMapTheme.test.js` reads both sides and fails on
+ * the first one that drifts.
+ *
+ * That is the whole point of the file: an analyst switching between the app's
+ * map and a browser tab should not be able to tell which one they are looking
+ * at, and "looks about right" is exactly the kind of thing that rots quietly.
+ */
+
+(() => {
+ /** Palette — `app.css`, the dark theme, which is the one the panel is. */
+ const TOKENS = {
+ bg0: "#151515",
+ bg1: "#1c1c1c",
+ bg2: "#252525",
+ bg3: "#2f2f2f",
+ border: "rgba(255, 255, 255, 0.09)",
+ borderStrong: "rgba(255, 255, 255, 0.18)",
+ text1: "#e3e3e3",
+ text2: "#9f9f9f",
+ text3: "#6c6c6c",
+ accent: "#e8a33d",
+ accentHover: "#f4b558",
+ accentText: "#141414",
+ ok: "#66b578",
+ warn: "#d9a53f",
+ danger: "#d97070",
+ info: "#6f9fd8",
+ skySun: "#bd8721",
+ skyMoon: "#4a93cc",
+ };
+
+ /**
+ * Status → cell paint, from `state/grid.svelte.js`.
+ *
+ * Unchecked is a bright thin outline so the lattice reads 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: { 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 },
+ };
+
+ /** The area of interest, and the one being dragged out. */
+ const AOI_STYLE = { stroke: "#f5a623", strokeWidth: 1.5, strokeOpacity: 0.9, dash: [5, 4] };
+ const DRAFT_STYLE = { stroke: "#f5a623", strokeWidth: 1.5, strokeOpacity: 0.95, dash: [5, 4] };
+
+ /** Measure, from `state/measure.svelte.js`. */
+ const MEASURE_STROKE = { stroke: "#f5a623", strokeWidth: 2.5, strokeOpacity: 0.95 };
+ const MEASURE_FILL = { fill: "#f5a623", fillOpacity: 0.15 };
+ const MEASURE_DOT = { radius: 4, stroke: "#fff", strokeWidth: 2, fill: "#f5a623", fillOpacity: 1 };
+
+ /** The 24x24 stroke icons of `components/Icon.svelte`, the ones this panel
+ * draws. Same paths, same viewBox, same stroke rules. */
+ const ICONS = {
+ ruler: "M4 15.5 15.5 4l4.5 4.5L8.5 20 4 15.5Zm3.5-.5 1.5 1.5m1-4.5 1.5 1.5m1-4.5L14 11",
+ pin: "M12 21s-7-6.1-7-11a7 7 0 0 1 14 0c0 4.9-7 11-7 11Zm0-8.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",
+ sun: "M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10ZM12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1",
+ moon: "M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z",
+ grid: "M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm9 0h7v7h-7v-7Z",
+ polygon: "M12 3.5 20 9.5l-3 9.5H7L4 9.5l8-6Z",
+ square: "M5 5h14a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z",
+ x: "M6 6l12 12M18 6 6 18",
+ chevronDown: "m6 9 6 6 6-6",
+ chevronUp: "m6 15 6-6 6 6",
+ eye: "M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Zm9.5-3a3 3 0 1 1 0 6 3 3 0 0 1 0-6Z",
+ eyeOff: "M9.9 9.9a3 3 0 1 0 4.2 4.2M10.7 5.7A9.8 9.8 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17.8 17.8 0 0 1-2.2 3M6.6 6.6C4 8.4 2.5 12 2.5 12S6 18.5 12 18.5c1.5 0 2.9-.4 4.1-1.1M3 3l18 18",
+ save: "M5 3h11l3 3v14a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm3 0v5h7V3M7 21v-7h10v7",
+ trash: "M4 7h16m-2 0-1 13H7L6 7m3 0V5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2m-6 4v6m4-6v6",
+ undo: "M8 5 4 9l4 4M4 9h10a6 6 0 0 1 0 12h-4",
+ check: "m4.5 12.5 5 5 10-11",
+ plus: "M12 5v14m-7-7h14",
+ minus: "M5 12h14",
+ crosshair: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0-1v4m0 12v4M2 12h4m12 0h4",
+ satellite: "M9 4.2 3.6 6.4a1 1 0 0 0-.6.9v11.2a1 1 0 0 0 1.4.9L9 17.4l6 2.4 5.4-2.2a1 1 0 0 0 .6-.9V5.5a1 1 0 0 0-1.4-.9L15 6.6 9 4.2Zm0 0v13.2M15 6.6v13.2",
+ proof: "M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm11.5 0v7m-3.5-3.5h7",
+ screen: "M4 5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm5 15h6m-3-4v4",
+ alert: "M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01",
+ folder: "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z",
+ image: "M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm2 12 4-4a1 1 0 0 1 1.4 0l4.6 4M9 9.5h.01",
+ video: "M4 6h11a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm12 4 5-3v10l-5-3",
+ grip: "M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01",
+ minimize: "M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3M3 16h3a2 2 0 0 1 2 2v3m8 0v-3a2 2 0 0 1 2-2h3",
+ };
+
+ /** One icon as an inline SVG string, for the panel's own markup. */
+ function icon(name, size = 16) {
+ return (
+ `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor"` +
+ ` stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">` +
+ `<path d="${ICONS[name] ?? ICONS.alert}"/></svg>`
+ );
+ }
+
+ /** Which glyph a saved row is drawn with — `SavedOverlay.svelte`'s own map.
+ * A stack holding more than one kind falls back to the place glyph. */
+ const SAVED_GLYPH = { place: "pin", capture: "satellite", screenshot: "screen", proof: "proof" };
+
+ window.AzimutMapTheme = {
+ TOKENS,
+ CELL_STYLE,
+ AOI_STYLE,
+ DRAFT_STYLE,
+ MEASURE_STROKE,
+ MEASURE_FILL,
+ MEASURE_DOT,
+ ICONS,
+ SAVED_GLYPH,
+ icon,
+ };
+})();
diff --git a/extension/maptools.js b/extension/maptools.js
new file mode 100644
index 0000000..b97a955
--- /dev/null
+++ b/extension/maptools.js
@@ -0,0 +1,1338 @@
+/**
+ * The five tools, as state machines with no DOM and no network in them.
+ *
+ * Each one holds what has been clicked, answers `shapes()` with what should be
+ * drawn in geographic coordinates, and `readout()` with the line the panel
+ * shows. Turning shapes into pixels is `mapdraw.js`; fetching anything is
+ * `mapoverlay.js`, which is also the only file that knows an extension API
+ * exists. Split that way so the part with the rules in it can be tested against
+ * numbers instead of against a browser.
+ *
+ * The fifth, `createRefs`, draws no shape and takes no click on the map: it
+ * holds the floating panes a reference is compared from (`mapref.js` paints
+ * them). It lives here because what it does hold — where a pane sits, how far
+ * into the image it is zoomed — is arithmetic, and arithmetic belongs where
+ * it can be checked against the app's own.
+ *
+ * **Much of this is a second copy, and deliberately only as much of one as it
+ * needs.** The measures are `lib/measure.js`, the lattice is
+ * `lib/gridSearch.js`, the sky arc is `lib/skyOverlay.js`, the mark grouping is
+ * `lib/savedMarkers.js`. The extension ships as classic scripts with no build
+ * step and cannot import a line of it, so each is written again here and
+ * `frontend/src/lib/extensionMapTools.test.js` runs both over the same input and
+ * fails on the first digit they disagree about. What is *not* copied is the
+ * editing: polygon reshaping, resize handles, review mode and pruning stay the
+ * app's. This writes a grid the app then opens with all of that available.
+ *
+ * Loaded after `mapmath.js` and `maptheme.js`, left on `window.AzimutMapTools`.
+ */
+
+(() => {
+ const M = window.AzimutMapMath;
+ const THEME = window.AzimutMapTheme;
+
+ //. Matches lib/gridSearch.js — a display lattice, not a geodesic one.
+ const M_PER_DEG_LAT = 111320;
+ const MIN_COS = 0.01;
+ /** The app's ceiling, restated: past this a lattice is a grey smear, not a
+ * thing anyone sweeps cell by cell. */
+ const MAX_CELLS = 20000;
+
+ /** Prediction error, in pixels, past which one pan counts as having landed
+ * somewhere the model did not expect. Generous, because these maps glide on
+ * after the finger leaves and a single overshoot says nothing; what makes
+ * the tools stop is a run of them (`mapoverlay.js`). */
+ const RESIDUAL_LIMIT = 110;
+
+ /** Why a view cannot carry the geometric tools, and what to do about it.
+ * Keyed by `engine/mapsites.py`'s `view_kind`; an unknown kind falls back to
+ * the general sentence. Each one names the way out in the words the viewer
+ * itself uses — a pitch in degrees is the app's reading of the camera, not a
+ * button anyone can find, so the sentence says 2D and 3D instead. */
+ const REFUSALS = {
+ streetview: "These tools work on the map, not in Street View",
+ tilted: "These tools work in 2D only, so turn 3D off",
+ };
+
+ function refusal(parsed) {
+ return REFUSALS[parsed.view_kind] || "This view is not a map to measure on";
+ }
+
+ /**
+ * What to do about a view nothing has measured yet — said as the thing to do,
+ * rather than as the state it is in.
+ *
+ * "Pan once" was true and useless. A drag is a measurement only if it moved
+ * far enough on *both* axes — a scale is two numbers and a sideways drag gives
+ * one of them — and only if the map ended where the pointer left it, which
+ * means pausing before letting go, since these viewers glide on and report the
+ * landing. Neither condition was anywhere on screen, so a drag that did not
+ * count looked exactly like one that did, and the line asking for a pan came
+ * back after every one of them.
+ */
+ const MEASURE_ME = "Drag the map across and down, pausing before you let go";
+
+ /** …and the one thing that is said rather than refused. This far out the map
+ * is a globe: the middle of the screen is still right, the edges are not,
+ * and zooming in is what makes them right. Seeing a region's work at a
+ * glance is worth that, so the drawing stays and the panel dims it. */
+ const FAR = "Zoomed out: marks drift from the middle of the screen";
+
+ /**
+ * Whether geometry is sound on this view, and if not, the sentence to show.
+ *
+ * `engine/mapsites.py` owns the URL formats and decides most of it. What is
+ * added here is the one thing only a browser can do: measure.
+ *
+ * What the app adds is `scale_source`: which number in the URL says how far
+ * out this view is, if any. All three are the site's own arithmetic — a tile
+ * level, a viewport height in metres, a span in degrees — and all three were
+ * checked against a browser before being believed (`docs/MAP_SITES.md`). Where
+ * one of them speaks, the drawing works from the first frame.
+ *
+ * Where none does, the map itself is the only authority and one pan asks it.
+ * That is now a single view: **Earth**, a free camera with no flattening to
+ * name — level, it is a plain uniform scaling of the ground, and a
+ * measurement describes it completely.
+ *
+ * The answer carries `far` as well as `ok`: a view far enough out that the
+ * site has gone to a globe still draws, because a region's worth of marks is
+ * worth seeing at a glance, but it says so and the panel dims it.
+ *
+ * @param {object|null} parsed the app's reading of the current URL
+ * @param {number|null} residual pixels between prediction and address bar
+ * @param {boolean} measured whether a scale has been read off the map yet
+ */
+ function verdict(parsed, residual, measured = false) {
+ if (!parsed || !parsed.site) return { ok: false, why: "This page is not a map Azimut can read" };
+ if (parsed.lat == null || parsed.lon == null) {
+ return { ok: false, why: "No position in the address bar yet, so move the map once" };
+ }
+ if (parsed.view_kind && parsed.view_kind !== "map" && parsed.view_kind !== "globe") {
+ return { ok: false, why: refusal(parsed) };
+ }
+ if (residual != null && residual > RESIDUAL_LIMIT) {
+ return {
+ ok: false,
+ why: `The map landed ${Math.round(residual)} px from where it was predicted. Pan once to measure it again`,
+ };
+ }
+ if (!parsed.view_kind) {
+ return { ok: false, why: "This view is not one Azimut can compute on" };
+ }
+ const far = !!parsed.far;
+ const drawn = { ok: true, why: far ? FAR : "", far };
+ // The URL is enough wherever it states a scale. Everywhere else — Earth,
+ // and any view whose address bar has not said how far out it is yet — the
+ // map itself is the only authority, and one drag asks it.
+ if (parsed.geometry && parsed.scale_source) return drawn;
+ return measured ? drawn : { ok: false, why: MEASURE_ME };
+ }
+
+ // --- measure ---------------------------------------------------------------
+
+ /**
+ * Distance along a clicked path, or the area it encloses.
+ *
+ * One mode armed at a time and one list of points, because that is what the
+ * readout is a reading of — the same rule the app's own measure tool follows,
+ * for the same reason: two half-drawn measures with a readout naming one of
+ * them is a picture that lies.
+ */
+ function createMeasure() {
+ let mode = null; // null | 'distance' | 'area'
+ let points = [];
+
+ return {
+ id: "measure",
+ label: "Measure",
+ icon: "ruler",
+ needsGeometry: true,
+ /** Whether this tool is waiting for a click on the map. While any tool
+ * is, the overlay takes pointer events away from the page underneath —
+ * so it has to be one question, asked the same way of all four. */
+ get armed() {
+ return mode !== null;
+ },
+ get mode() {
+ return mode;
+ },
+ get points() {
+ return points;
+ },
+ setMode(next) {
+ mode = mode === next ? null : next;
+ points = [];
+ return mode;
+ },
+ /** Stop waiting for a click. Called when the view stops being one this
+ * tool can work on — the points are kept, since going back to a 2D map
+ * brings them back rather than making them wrong. */
+ disarm() {
+ mode = null;
+ },
+ clear() {
+ points = [];
+ },
+ click(at) {
+ if (!mode) return false;
+ points = [...points, at];
+ return true;
+ },
+ /** Undo one click — a slipped point should not cost the whole path. */
+ undo() {
+ points = points.slice(0, -1);
+ },
+ shapes() {
+ if (!points.length) return [];
+ const out = [];
+ if (points.length >= 2) {
+ out.push(
+ mode === "area"
+ ? { kind: "polygon", points, ...THEME.MEASURE_STROKE, ...THEME.MEASURE_FILL }
+ : { kind: "line", points, ...THEME.MEASURE_STROKE, casing: true }
+ );
+ }
+ for (const at of points) out.push({ kind: "dot", at, ...THEME.MEASURE_DOT });
+ return out;
+ },
+ readout(units) {
+ if (!mode) return null;
+ if (points.length < 2) return "Click points on the map";
+ if (mode === "distance") return M.formatDistance(M.pathLength(points), units);
+ return points.length >= 3 ? M.formatArea(M.polygonArea(points), units) : "…";
+ },
+ };
+ }
+
+ // --- media pins ------------------------------------------------------------
+
+ /** Decimal places to key marks on at a given zoom — `lib/savedMarkers.js`.
+ * Five is about a metre: at street zoom only items at genuinely the same spot
+ * merge, and zooming out coarsens the key so a country's worth of pins is a
+ * handful of counted marks instead of a smear. */
+ function markerPrecision(zoom) {
+ const z = Number(zoom);
+ if (!Number.isFinite(z)) return 5;
+ if (z < 5) return 0;
+ if (z < 8) return 1;
+ if (z < 11) return 2;
+ if (z < 14) return 3;
+ if (z < 16) return 4;
+ return 5;
+ }
+
+ /** Group rows into marks by rounded coordinate. Rows with no position are
+ * left out; each mark keeps the order its items arrived in. */
+ function groupSavedMarkers(rows, precision = 5) {
+ const marks = new Map();
+ for (const row of rows ?? []) {
+ if (row.lat == null || row.lon == null) continue;
+ const lat = Number(row.lat);
+ const lon = Number(row.lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ const key = `${lat.toFixed(precision)},${lon.toFixed(precision)}`;
+ const mark = marks.get(key);
+ if (mark) {
+ mark.items.push(row);
+ mark.kinds.add(row.kind);
+ } else {
+ marks.set(key, { key, lat, lon, items: [row], kinds: new Set([row.kind]) });
+ }
+ }
+ return [...marks.values()].map((mark) => ({
+ key: mark.key,
+ lat: mark.lat,
+ lon: mark.lon,
+ items: mark.items,
+ kinds: [...mark.kinds],
+ }));
+ }
+
+ /**
+ * The case's geolocated work, over someone else's map — and a new point
+ * dropped onto it.
+ *
+ * The one tool that runs on every view, because nothing in it is computed:
+ * the analyst says where. What *does* change with the view is which
+ * coordinate a new pin may claim. On a flat map it is the pixel that was
+ * clicked. On a tilted or panoramic camera there is no sound way from a pixel
+ * to the ground, so the pin takes the point the address bar already named —
+ * where the camera stands — and the panel says so rather than quietly filing
+ * something else.
+ *
+ * **Nothing is labelled until it is pointed at.** A case with fifty saved
+ * points drew fifty names across the map, which is a screenshot of nothing.
+ * Points at the same spot merge into one counted mark, exactly as the app's
+ * Saved layer merges them, and the name belongs to the mark under the pointer
+ * or the one held open by a click.
+ */
+ function createPins() {
+ let rows = [];
+ let zoom = null;
+ let marks = [];
+ let dropping = false;
+ let draft = null; // { lat, lon, anchoredOn: 'pixel' | 'view' }
+ let hovered = null; // mark key under the pointer
+ let held = null; // mark key clicked open
+
+ const regroup = () => {
+ marks = groupSavedMarkers(rows, markerPrecision(zoom));
+ };
+
+ const nameOf = (mark) =>
+ mark.items.length > 1 ? `${mark.items.length} saved here` : mark.items[0].title || "Untitled";
+
+ return {
+ id: "pins",
+ label: "Points",
+ icon: "pin",
+ needsGeometry: false,
+ get armed() {
+ return dropping;
+ },
+ get rows() {
+ return rows;
+ },
+ get marks() {
+ return marks;
+ },
+ get dropping() {
+ return dropping;
+ },
+ get draft() {
+ return draft;
+ },
+ get hovered() {
+ return hovered;
+ },
+ get held() {
+ return held;
+ },
+ /** The case's saved index, filtered to what can actually be drawn. */
+ load(index) {
+ rows = (index ?? []).filter(
+ (row) => Number.isFinite(row.lat) && Number.isFinite(row.lon)
+ );
+ regroup();
+ },
+ /** Marks merge by a precision that follows the zoom, so this is re-run
+ * whenever the view changes scale. */
+ atZoom(next) {
+ if (markerPrecision(next) === markerPrecision(zoom)) {
+ zoom = next;
+ return false;
+ }
+ zoom = next;
+ regroup();
+ return true;
+ },
+ toggleDrop() {
+ dropping = !dropping;
+ if (!dropping) draft = null;
+ return dropping;
+ },
+ disarm() {
+ dropping = false;
+ draft = null;
+ },
+ /**
+ * A click, while dropping is armed. `at` is the clicked pixel turned into
+ * a coordinate, or null when the view cannot do that honestly; `view` is
+ * the point the URL named, which is the fallback and never a guess.
+ */
+ click(at, view) {
+ if (!dropping) return false;
+ draft = at
+ ? { lat: at.lat, lon: at.lon, anchoredOn: "pixel" }
+ : { lat: view.lat, lon: view.lon, anchoredOn: "view" };
+ held = "draft";
+ return true;
+ },
+ clearDraft() {
+ draft = null;
+ dropping = false;
+ if (held === "draft") held = null;
+ },
+ /** The mark nearest `at` within `radius` screen pixels, or null.
+ * `project` is passed in because only the overlay knows the view. */
+ markAt(at, project, radius = 16) {
+ let best = null;
+ let closest = radius * radius;
+ const all = draft ? [...marks, { key: "draft", lat: draft.lat, lon: draft.lon }] : marks;
+ for (const mark of all) {
+ const p = project(mark);
+ if (!p || !Number.isFinite(p.x)) continue;
+ const gap = (p.x - at.x) ** 2 + (p.y - at.y) ** 2;
+ if (gap <= closest) {
+ closest = gap;
+ best = mark;
+ }
+ }
+ return best;
+ },
+ hover(key) {
+ if (hovered === key) return false;
+ hovered = key;
+ return true;
+ },
+ /** Clicking a mark opens its name; clicking it again, or elsewhere,
+ * closes it. */
+ hold(key) {
+ held = held === key ? null : key;
+ return held;
+ },
+ shapes() {
+ const out = marks.map((mark) => {
+ const only = mark.kinds.length === 1 ? mark.kinds[0] : "place";
+ const shown = mark.key === hovered || mark.key === held;
+ return {
+ kind: "mark",
+ at: { lat: mark.lat, lon: mark.lon },
+ glyph: THEME.SAVED_GLYPH[only] ?? "pin",
+ // a bare place carries no imagery: the app outlines it rather than
+ // filling it, so a stack of captures never hides behind one
+ place: only === "place",
+ count: mark.items.length,
+ lit: shown,
+ label: shown ? nameOf(mark) : "",
+ };
+ });
+ if (draft) {
+ out.push({
+ kind: "mark",
+ at: { lat: draft.lat, lon: draft.lon },
+ glyph: "pin",
+ place: true,
+ count: 1,
+ lit: true,
+ label: held === "draft" || hovered === "draft" ? "New point" : "",
+ });
+ }
+ return out;
+ },
+ readout() {
+ if (draft) {
+ return draft.anchoredOn === "view"
+ ? "Filing the point this view is centred on"
+ : "Filing the point you clicked";
+ }
+ if (dropping) return "Click the map to place a point";
+ if (!rows.length) return "Nothing placed in this case yet";
+ const merged = rows.length - marks.length;
+ return merged > 0 ? `${rows.length} here, in ${marks.length} marks` : `${rows.length} on this map`;
+ },
+ };
+ }
+
+ // --- sun and moon ----------------------------------------------------------
+
+ /**
+ * Runs of consecutive samples with the body above the horizon —
+ * `lib/skyOverlay.js`.
+ *
+ * The arc the body actually sweeps, not the whole 24 hours: drawn end to end,
+ * the line would close the circle through the bearings the body holds while
+ * it is down, which says nothing about where the light came from.
+ */
+ function upRuns(altitudes) {
+ const runs = [];
+ let run = null;
+ (altitudes ?? []).forEach((altitude, i) => {
+ if (altitude >= 0) {
+ run = run ?? [];
+ run.push(i);
+ } else if (run) {
+ runs.push(run);
+ run = null;
+ }
+ });
+ if (run) runs.push(run);
+ return runs.filter((r) => r.length > 1);
+ }
+
+ /** Which samples carry an hour tick, and which are the long ones. On the
+ * hour, and only while the body is up. */
+ function hourTicks(minutes, altitudes) {
+ const ticks = [];
+ (minutes ?? []).forEach((minute, i) => {
+ if (minute % 60 || altitudes[i] < 0) return;
+ ticks.push({ index: i, long: minute % 180 === 0 });
+ });
+ return ticks;
+ }
+
+ /** Where the body's mark rides on its ray, as a fraction of the radius: at
+ * the horizon on the arc, at the zenith on the anchor. */
+ function markScale(altitude) {
+ return (90 - altitude) / 90;
+ }
+
+ const isBelow = (altitude) => altitude < 0;
+
+ /**
+ * Which sample of the day is the moment the answer was computed for.
+ *
+ * The payload carries the whole day as arrays and the current instant as a
+ * wall-clock reading, but not the index joining them — so it is found here,
+ * by the clock, in the point's own zone. Falls back to the middle of the day
+ * rather than to zero: an unreadable moment should open on noon, not on the
+ * dark before dawn.
+ */
+ function nowIndex(payload) {
+ const clock = payload?.curve?.clock;
+ if (!Array.isArray(clock) || !clock.length) return 0;
+ const at = /T(\d{2}):(\d{2})/.exec(payload?.moment?.local ?? "");
+ if (!at) return Math.floor(clock.length / 2);
+ const minutes = Number(at[1]) * 60 + Number(at[2]);
+ let best = 0;
+ let closest = Infinity;
+ for (let i = 0; i < clock.length; i += 1) {
+ const [h, m] = clock[i].split(":").map(Number);
+ const gap = Math.abs(h * 60 + m - minutes);
+ if (gap < closest) {
+ closest = gap;
+ best = i;
+ }
+ }
+ return best;
+ }
+
+ /**
+ * The day's sun and moon, drawn from a planted anchor.
+ *
+ * Anchored rather than following the view, because the question is "where do
+ * the shadows fall *here*" and a path that slid with every pan would answer
+ * it about somewhere else. The arithmetic is the app's (`/api/geo/sky`
+ * returns the whole day in one response), so scrubbing the hour costs nothing
+ * and asks nobody.
+ *
+ * The picture is the app's too: the arc each body sweeps while it is up, an
+ * hour tick on the hour, the current ray from the anchor, and the body itself
+ * riding that ray between the centre — which stands for the zenith — and the
+ * arc, which stands for the horizon.
+ */
+ function createSky() {
+ let anchor = null;
+ let placing = false;
+ let day = null; // the whole-day payload, exactly as /api/geo/sky returns it
+ let on = null; // the local day being read, or null for the one it is there
+ let index = 0;
+ let reach = 400; // metres the arc is drawn at; set from the view
+
+ const at = (azimuth, scale = 1) => destination(anchor, azimuth, reach * scale);
+
+ return {
+ id: "sky",
+ label: "Sun & moon",
+ icon: "sun",
+ needsGeometry: true,
+ /**
+ * Zoomed out, this one is not drawn in doubt.
+ *
+ * What dims a drawing out there is that a Mercator and a globe part
+ * company away from the middle of the screen, so a mark lands somewhere
+ * the ground is not. This tool has no marks: it answers where the light
+ * came from, and a bearing is read off the anchor, which is the one place
+ * the two projections still agree. The radius the arc is drawn at is the
+ * part that drifts, and nobody reads a distance off a sun path.
+ *
+ * So it stays at full strength, and the status line goes on saying the
+ * view is zoomed out. Dimming it only had the analyst zooming in until the
+ * picture looked solid, for an answer that was already right.
+ */
+ dimsWhenFar: false,
+ get armed() {
+ return placing;
+ },
+ get anchor() {
+ return anchor;
+ },
+ get placing() {
+ return placing;
+ },
+ get day() {
+ return day;
+ },
+ /** Which local day is on screen, as the date field writes it. Read back
+ * from the answer rather than kept from the request, so the field shows
+ * the day *at the point* — which is not always the analyst's own. */
+ get date() {
+ return on ?? day?.date ?? null;
+ },
+ /** Read another day for the planted point. */
+ onDay(value) {
+ on = value;
+ day = null;
+ },
+ get index() {
+ return index;
+ },
+ set index(value) {
+ index = Math.max(0, Math.min((day?.curve?.clock?.length ?? 1) - 1, value));
+ },
+ /** How far the arc reaches, off the shorter side of the view: a radius
+ * set by the diagonal runs off the top and bottom of a wide window. */
+ fit(spanMetres) {
+ reach = Math.max(50, spanMetres * 0.22);
+ },
+ togglePlacing() {
+ placing = !placing;
+ return placing;
+ },
+ disarm() {
+ placing = false;
+ },
+ click(point) {
+ if (!placing) return false;
+ anchor = point;
+ day = null;
+ placing = false;
+ return true;
+ },
+ /** The answer for the planted point. The slider lands on the moment the
+ * payload was computed for, so the first thing drawn is now. */
+ accept(payload) {
+ day = payload;
+ index = nowIndex(payload);
+ },
+ clear() {
+ anchor = null;
+ day = null;
+ on = null;
+ placing = false;
+ },
+ shapes() {
+ if (!anchor) return [];
+ const out = [];
+ const curve = day?.curve;
+ if (curve) {
+ for (const body of [
+ { key: "sun", colour: THEME.TOKENS.skySun },
+ { key: "moon", colour: THEME.TOKENS.skyMoon },
+ ]) {
+ const altitude = curve[`${body.key}_altitude`] ?? [];
+ const azimuth = curve[`${body.key}_azimuth`] ?? [];
+ // Thin and translucent: the imagery underneath is what is read.
+ const thin = { stroke: body.colour, strokeWidth: 2.5, strokeOpacity: 0.9 };
+ for (const run of upRuns(altitude)) {
+ out.push({ kind: "line", points: run.map((i) => at(azimuth[i])), ...thin });
+ }
+ for (const tick of hourTicks(curve.minutes, altitude)) {
+ out.push({
+ kind: "line",
+ points: [at(azimuth[tick.index], 0.94), at(azimuth[tick.index], tick.long ? 1.1 : 1.03)],
+ ...thin,
+ });
+ }
+ const now = altitude[index];
+ if (!Number.isFinite(now)) continue;
+ const below = isBelow(now);
+ out.push({
+ kind: "line",
+ points: [anchor, at(azimuth[index])],
+ stroke: body.colour,
+ strokeWidth: 3.5,
+ strokeOpacity: below ? 0.6 : 1,
+ dash: below ? [6, 6] : null,
+ });
+ // 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.
+ if (!below) {
+ out.push({
+ kind: "body",
+ at: at(azimuth[index], markScale(now)),
+ colour: body.colour,
+ bodyKind: body.key,
+ illuminated: curve.moon_illuminated?.[index] ?? 0,
+ waxing: !!day?.moon?.waxing,
+ });
+ }
+ }
+ }
+ out.push({ kind: "dot", at: anchor, radius: 4, stroke: "#fff", strokeWidth: 2, fill: THEME.TOKENS.accent, fillOpacity: 1 });
+ return out;
+ },
+ readout() {
+ if (placing) return "Click the map to plant the point";
+ if (!anchor) return "Plant a point to read its sky";
+ if (!day) return "Reading…";
+ const clock = day.curve?.clock?.[index] ?? "";
+ // the day is named beside the hour: the slider scrubs one day, and a
+ // reading with no date on it is a reading of no day in particular
+ return day.date ? `${day.date} ${clock}` : clock;
+ },
+ };
+ }
+
+ /** The point reached from `from` on a bearing after `metres` — mirrors
+ * `lib/measure.js`'s `destination`, and the cross-check test says so. */
+ function destination(from, bearing, metres) {
+ const R = 6378137;
+ const rad = (d) => (d * Math.PI) / 180;
+ const d = metres / R;
+ const br = rad(bearing);
+ const lat1 = rad(from.lat);
+ const lon1 = rad(from.lon);
+ const lat2 = Math.asin(
+ Math.sin(lat1) * Math.cos(d) + Math.cos(lat1) * Math.sin(d) * Math.cos(br)
+ );
+ const lon2 =
+ lon1 +
+ Math.atan2(
+ Math.sin(br) * Math.sin(d) * Math.cos(lat1),
+ Math.cos(d) - Math.sin(lat1) * Math.sin(lat2)
+ );
+ return { lat: (lat2 * 180) / Math.PI, lon: (((lon2 * 180) / Math.PI + 540) % 360) - 180 };
+ }
+
+ // --- grid search -----------------------------------------------------------
+
+ /** Cell size in degrees at a reference latitude. Mirrors lib/gridSearch.js. */
+ function degSteps(refLat, cellM) {
+ const latStep = cellM / M_PER_DEG_LAT;
+ const cos = Math.max(MIN_COS, Math.cos((refLat * Math.PI) / 180));
+ return { latStep, lonStep: cellM / (M_PER_DEG_LAT * cos) };
+ }
+
+ const cellKey = (i, j) => `${i}:${j}`;
+
+ function normalizeBounds(b) {
+ return {
+ south: Math.min(b.south, b.north),
+ north: Math.max(b.south, b.north),
+ west: Math.min(b.west, b.east),
+ east: Math.max(b.west, b.east),
+ };
+ }
+
+ /** Bounding box of an area of interest (rect bounds or polygon vertices). */
+ function aoiBounds(aoi) {
+ if (aoi.type === "rect") return aoi.bounds;
+ const lats = aoi.vertices.map((v) => v[0]);
+ const lons = aoi.vertices.map((v) => v[1]);
+ return {
+ south: Math.min(...lats),
+ west: Math.min(...lons),
+ north: Math.max(...lats),
+ east: Math.max(...lons),
+ };
+ }
+
+ /** Ray-casting point-in-polygon on [lat, lon] vertices. */
+ function pointInPolygon(pt, vertices) {
+ let inside = false;
+ const x = pt.lon;
+ const y = pt.lat;
+ for (let a = 0, b = vertices.length - 1; a < vertices.length; b = a++) {
+ const xi = vertices[a][1];
+ const yi = vertices[a][0];
+ const xj = vertices[b][1];
+ const yj = vertices[b][0];
+ const hit = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
+ if (hit) inside = !inside;
+ }
+ return inside;
+ }
+
+ const orient = (p, q, r) =>
+ (q.lon - p.lon) * (r.lat - p.lat) - (q.lat - p.lat) * (r.lon - p.lon);
+
+ function segsCross(a, b, c, d) {
+ const o1 = orient(a, b, c);
+ const o2 = orient(a, b, d);
+ const o3 = orient(c, d, a);
+ const o4 = orient(c, d, b);
+ return o1 > 0 !== o2 > 0 && o3 > 0 !== o4 > 0;
+ }
+
+ /** Does a cell rectangle touch the polygon at all? Any overlap counts, so the
+ * whole drawn shape gets tiled — no bare strip along a slanted edge. */
+ function rectIntersectsPolygon(b, vertices) {
+ const box = [
+ { lat: b.south, lon: b.west },
+ { lat: b.south, lon: b.east },
+ { lat: b.north, lon: b.east },
+ { lat: b.north, lon: b.west },
+ ];
+ for (const c of box) if (pointInPolygon(c, vertices)) return true;
+ for (const v of vertices) {
+ if (v[0] >= b.south && v[0] <= b.north && v[1] >= b.west && v[1] <= b.east) return true;
+ }
+ for (let i = 0; i < vertices.length; i += 1) {
+ const pa = { lat: vertices[i][0], lon: vertices[i][1] };
+ const next = vertices[(i + 1) % vertices.length];
+ const pb = { lat: next[0], lon: next[1] };
+ for (let e = 0; e < 4; e += 1) {
+ if (segsCross(pa, pb, box[e], box[(e + 1) % 4])) return true;
+ }
+ }
+ return false;
+ }
+
+ /** Close a polygon ring for drawing: the first point repeated at the end,
+ * but only once there are three — a shape still being drawn stays open. */
+ function closeRing(points) {
+ return points.length >= 3 ? [...points, points[0]] : points;
+ }
+
+ /**
+ * A fresh grid over an area, in the app's own `azimut_grid: 1` spec.
+ *
+ * The lattice is pinned to the area's south-west corner rather than to the
+ * area itself, which is what lets the app resize the shape later without a
+ * mark sliding off the cell it was put on.
+ */
+ function createGrid(aoi, cellM) {
+ const b = aoiBounds(aoi);
+ const refLat = (b.south + b.north) / 2;
+ const { latStep, lonStep } = degSteps(refLat, cellM);
+ return {
+ azimut_grid: 1,
+ cell_m: cellM,
+ anchor: { lat: b.south, lon: b.west },
+ lat_step: latStep,
+ lon_step: lonStep,
+ aoi,
+ statuses: {},
+ };
+ }
+
+ function cellRange(grid) {
+ const b = aoiBounds(grid.aoi);
+ return {
+ iMin: Math.floor((b.south - grid.anchor.lat) / grid.lat_step),
+ iMax: Math.ceil((b.north - grid.anchor.lat) / grid.lat_step) - 1,
+ jMin: Math.floor((b.west - grid.anchor.lon) / grid.lon_step),
+ jMax: Math.ceil((b.east - grid.anchor.lon) / grid.lon_step) - 1,
+ };
+ }
+
+ function cellBounds(grid, i, j) {
+ const south = grid.anchor.lat + i * grid.lat_step;
+ const west = grid.anchor.lon + j * grid.lon_step;
+ return { south, west, north: south + grid.lat_step, east: west + grid.lon_step };
+ }
+
+ /** Every cell inside the area, row-major. A rectangle keeps its whole
+ * bounding box; a polygon keeps every cell that overlaps it. */
+ function cellsInAoi(grid) {
+ const { iMin, iMax, jMin, jMax } = cellRange(grid);
+ const poly = grid.aoi.type === "polygon" ? grid.aoi.vertices : null;
+ const out = [];
+ for (let i = iMin; i <= iMax; i += 1) {
+ for (let j = jMin; j <= jMax; j += 1) {
+ if (poly && !rectIntersectsPolygon(cellBounds(grid, i, j), poly)) continue;
+ out.push([i, j]);
+ }
+ }
+ return out;
+ }
+
+ function estimateCells(grid) {
+ const { iMin, iMax, jMin, jMax } = cellRange(grid);
+ return Math.max(0, iMax - iMin + 1) * Math.max(0, jMax - jMin + 1);
+ }
+
+ function coverage(grid) {
+ const cells = cellsInAoi(grid);
+ let cleared = 0;
+ let flagged = 0;
+ for (const [i, j] of cells) {
+ const status = grid.statuses[cellKey(i, j)];
+ if (status === "cleared") cleared += 1;
+ else if (status === "flagged") flagged += 1;
+ }
+ const done = cleared + flagged;
+ return {
+ total: cells.length,
+ cleared,
+ flagged,
+ unchecked: cells.length - done,
+ percent: cells.length ? Math.round((done / cells.length) * 100) : 0,
+ };
+ }
+
+ /** Left-click cycle: unchecked → cleared → flagged → unchecked. */
+ function cycleStatus(current) {
+ if (!current) return "cleared";
+ if (current === "cleared") return "flagged";
+ return null;
+ }
+
+ /**
+ * Sweeping an area cell by cell, over a map the app does not own.
+ *
+ * Draws both shapes the app draws — a dragged rectangle and a clicked
+ * polygon — because an area of interest is rarely a rectangle and tiling the
+ * bounding box of a quay or a valley means sweeping water and hillside. What
+ * it does not carry is the *editing*: reshaping a saved area, dragging its
+ * corners, running the review cursor. Those stay one implementation, in the
+ * app, and this writes the file the app opens.
+ */
+ function createGridTool() {
+ let grid = null;
+ let name = null;
+ let drawing = null; // null | 'rect' | 'polygon'
+ let vertices = []; // the polygon being clicked out, [lat, lon] pairs
+ let marking = false;
+ let hidden = false;
+ //. Cells marked since the last time the case was told: "i:j" -> status, or
+ //. null for one that was cleared back to unchecked. Kept as a patch rather
+ //. than as a copy of the grid on purpose — see `pushMarks` in
+ //. mapoverlay.js for what a whole-spec save would quietly undo.
+ let unsent = {};
+
+ function adopt(aoi, cellM) {
+ const candidate = createGrid(aoi, cellM);
+ const cells = estimateCells(candidate);
+ if (cells > MAX_CELLS) {
+ return {
+ error: `${cells.toLocaleString("en-US")} cells is past the ${MAX_CELLS.toLocaleString("en-US")} limit. Use a bigger cell or a smaller area`,
+ };
+ }
+ grid = candidate;
+ name = null;
+ unsent = {};
+ return { grid };
+ }
+
+ return {
+ id: "grid",
+ label: "Search grid",
+ icon: "grid",
+ needsGeometry: true,
+ cellM: 500,
+ get armed() {
+ return drawing !== null || marking;
+ },
+ get grid() {
+ return grid;
+ },
+ get name() {
+ return name;
+ },
+ get drawing() {
+ return drawing;
+ },
+ get vertices() {
+ return vertices;
+ },
+ get marking() {
+ return marking;
+ },
+ get hidden() {
+ return hidden;
+ },
+ /** Whether there are marks the case has not been told about yet. */
+ get dirty() {
+ return Object.keys(unsent).length > 0;
+ },
+ get coverage() {
+ return grid ? coverage(grid) : null;
+ },
+
+ /** Arm one of the two shapes, or put it down. */
+ draw(shape) {
+ drawing = drawing === shape ? null : shape;
+ vertices = [];
+ if (drawing) marking = false;
+ return drawing;
+ },
+ /** Marking is a mode rather than a plain click, because the map
+ * underneath still has to be pannable while a sweep is open. */
+ toggleMark() {
+ marking = !marking;
+ if (marking) drawing = null;
+ return marking;
+ },
+ toggleHidden() {
+ hidden = !hidden;
+ return hidden;
+ },
+ disarm() {
+ drawing = null;
+ marking = false;
+ vertices = [];
+ },
+
+ /** One corner of the polygon being clicked out. */
+ addVertex(point) {
+ if (drawing !== "polygon") return false;
+ vertices = [...vertices, [point.lat, point.lon]];
+ return true;
+ },
+ undoVertex() {
+ vertices = vertices.slice(0, -1);
+ },
+
+ /**
+ * Close a dragged box into a lattice.
+ *
+ * The one refusal is an area that would draw more cells than anybody
+ * sweeps, and it comes with the count — freezing the tab and leaving the
+ * analyst to guess why is the alternative. There is no floor to check:
+ * the lattice covers a box by rounding its edges outward, so even a box
+ * smaller than one cell is one cell.
+ */
+ finishBox(bounds) {
+ drawing = null;
+ if (!bounds) return null;
+ return adopt({ type: "rect", bounds: normalizeBounds(bounds) }, this.cellM);
+ },
+
+ /** Close the clicked polygon. Three corners is the fewest that enclose
+ * anything; fewer is a line, and a line has no area to sweep. */
+ finishPolygon() {
+ const drawn = vertices;
+ drawing = null;
+ vertices = [];
+ if (drawn.length < 3) return { error: "A shape needs at least three corners" };
+ return adopt({ type: "polygon", vertices: drawn }, this.cellM);
+ },
+
+ /** Adopt a grid read back from the case. */
+ open(spec, savedName) {
+ grid = spec;
+ name = savedName;
+ unsent = {};
+ },
+
+ /**
+ * Take the case's copy of the open grid as the truth again.
+ *
+ * The same sweep is worked from the app at the same time, and a panel
+ * that only ever sent its own marks showed a sweep frozen at the moment
+ * it was opened. The file wins, with one exception: marks made here that
+ * have not been sent yet go back on top, because they are the only copy
+ * of themselves.
+ */
+ sync(spec) {
+ if (!grid || !spec) return false;
+ const statuses = { ...(spec.statuses || {}) };
+ for (const [key, status] of Object.entries(unsent)) {
+ if (status) statuses[key] = status;
+ else delete statuses[key];
+ }
+ grid = { ...spec, statuses };
+ return true;
+ },
+
+ close() {
+ grid = null;
+ name = null;
+ unsent = {};
+ drawing = null;
+ marking = false;
+ vertices = [];
+ },
+
+ saved(savedName) {
+ name = savedName;
+ // the spec that was just written carried every mark in it
+ unsent = {};
+ },
+
+ /** The marks made since the last call, handed over. Emptied here: the
+ * caller now owns them, and puts them back with `restoreMarks` if the
+ * case never heard about them. */
+ takeMarks() {
+ const marks = unsent;
+ unsent = {};
+ return marks;
+ },
+
+ /** Marks back from a failed send, without stepping on any made since. */
+ restoreMarks(marks) {
+ unsent = { ...marks, ...unsent };
+ },
+
+ /** Which cell a coordinate falls in, or null when it is outside. */
+ cellAt(point) {
+ if (!grid) return null;
+ const i = Math.floor((point.lat - grid.anchor.lat) / grid.lat_step);
+ const j = Math.floor((point.lon - grid.anchor.lon) / grid.lon_step);
+ const { iMin, iMax, jMin, jMax } = cellRange(grid);
+ if (i < iMin || i > iMax || j < jMin || j > jMax) return null;
+ if (grid.aoi.type === "polygon" && !rectIntersectsPolygon(cellBounds(grid, i, j), grid.aoi.vertices)) {
+ return null;
+ }
+ return [i, j];
+ },
+
+ click(point) {
+ const cell = this.cellAt(point);
+ if (!cell) return false;
+ const key = cellKey(cell[0], cell[1]);
+ const next = cycleStatus(grid.statuses[key]);
+ if (next) grid.statuses[key] = next;
+ else delete grid.statuses[key];
+ unsent[key] = next;
+ return true;
+ },
+
+ shapes() {
+ const out = [];
+ if (drawing === "polygon" && vertices.length) {
+ const points = vertices.map(([lat, lon]) => ({ lat, lon }));
+ out.push({ kind: "line", points: closeRing(points), ...THEME.DRAFT_STYLE });
+ for (const at of points) {
+ out.push({ kind: "dot", at, radius: 3.5, fill: THEME.AOI_STYLE.stroke, fillOpacity: 1, stroke: "#fff", strokeWidth: 1.5 });
+ }
+ }
+ if (!grid || hidden) return out;
+ for (const [i, j] of cellsInAoi(grid)) {
+ const status = grid.statuses[cellKey(i, j)] || "unchecked";
+ out.push({ kind: "cell", bounds: cellBounds(grid, i, j), ...THEME.CELL_STYLE[status] });
+ }
+ // No outline around a finished grid. The lattice *is* the area once it
+ // exists, and a dashed ring around it is a second line saying the same
+ // thing over imagery that has to stay readable. The draft ring above is
+ // different: while the shape is being drawn it is the only thing there
+ // is to see.
+ return out;
+ },
+
+ readout() {
+ if (drawing === "rect") return "Drag a box over the area to sweep";
+ if (drawing === "polygon") {
+ return vertices.length < 3
+ ? `Click the corners of the area (${vertices.length})`
+ : `${vertices.length} corners — close the shape when it fits`;
+ }
+ if (!grid) return "No grid open";
+ const seen = coverage(grid);
+ if (marking) return `${seen.percent}% swept — click cells to mark them`;
+ return `${seen.percent}% swept · ${seen.cleared} cleared · ${seen.flagged} flagged`;
+ },
+ };
+ }
+
+ // --- reference windows -----------------------------------------------------
+
+ /**
+ * The case's own images and videos, held over someone else's map.
+ *
+ * The tool that is not a map tool. It projects nothing, takes no click on the
+ * map and draws no shape: a reference window is a small floating pane holding
+ * the shot being geolocated, so it can be eyeballed against the imagery
+ * while the map pans under it. Three things follow from that, and they are the
+ * reason it is written here rather than folded into the panel:
+ *
+ * - **It works where geometry does not.** Street View, a pitched camera, a
+ * zoomed-out globe: none of them can carry a measurement, and all of them
+ * are worth holding a reference against. So `needsGeometry` is false and
+ * nothing here consults the verdict.
+ * - **The windows stay when another tool is picked up.** "Only the open tool
+ * draws" is a rule about the map, and these are not on the map — putting
+ * the reference down while measuring is exactly what nobody wants.
+ * - **They are scratch, and the extension keeps them so.** Nothing is filed,
+ * nothing is remembered between visits, and the panel and its windows are
+ * taken out of the frame before a capture (`background.js`) — a reference
+ * floating over a map must never end up inside the evidence.
+ *
+ * A video counts as a reference: the frame to place is often in one, and the
+ * window plays it. That is the one thing here a map site can refuse — see
+ * `mapref.js` — so the window says so rather than showing an empty box.
+ *
+ * The geometry below is `lib/refViewers.js`, copied for the same reason
+ * everything else here is; `extensionMapTools.test.js` runs the two over the
+ * same input. Window placement, the corner drag and the cursor-anchored image
+ * zoom are all in it.
+ */
+ const MIN_SCALE = 1; // 1 = the image fits the window; no zooming out past fit
+ const MAX_SCALE = 8;
+ const DEFAULT_W = 320;
+ const DEFAULT_H = 260;
+ const MIN_W = 200;
+ const MIN_H = 150;
+ /** New windows step down-right so the one underneath stays grabbable, and wrap
+ * before they walk off the screen. */
+ const STAGGER = 26;
+ const STAGGER_WRAP = 6;
+
+ const clamp = (value, lo, hi) => Math.min(hi, Math.max(lo, value));
+
+ /** A fresh window on one picked file ({ path, kind, title, filename }). */
+ function createViewer(id, media, spawn = {}) {
+ return {
+ id,
+ path: media.path,
+ kind: media.kind === "video" ? "video" : "image",
+ title: media.title || media.filename || "",
+ x: spawn.x ?? 60,
+ y: spawn.y ?? 60,
+ w: spawn.w ?? DEFAULT_W,
+ h: spawn.h ?? DEFAULT_H,
+ z: spawn.z ?? 1,
+ collapsed: false,
+ scale: 1, // image zoom (1 = fit)
+ ox: 0, // image pan offset in content px
+ oy: 0,
+ };
+ }
+
+ /** One more than the top window's z — what a newly focused one gets. */
+ function nextZ(viewers) {
+ return viewers.reduce((top, viewer) => Math.max(top, viewer.z), 0) + 1;
+ }
+
+ /**
+ * Re-number z so `id` sits on top, keeping the values small and gap-free
+ * (1..n) rather than letting the newest window climb without bound — which is
+ * what eventually puts one over the panel. Returns id → new z.
+ */
+ function restack(viewers, id) {
+ const others = viewers.filter((viewer) => viewer.id !== id).sort((a, b) => a.z - b.z);
+ const z = new Map();
+ others.forEach((viewer, i) => z.set(viewer.id, i + 1));
+ z.set(id, others.length + 1);
+ return z;
+ }
+
+ /** Keep a window of `w`×`h` fully inside `bounds` ({ w, h }). */
+ function clampWindow(x, y, w, h, bounds) {
+ return {
+ x: clamp(x, 0, Math.max(0, bounds.w - w)),
+ y: clamp(y, 0, Math.max(0, bounds.h - h)),
+ };
+ }
+
+ /** Clamp a corner drag to the min size and to what fits below and right of it. */
+ function clampSize(w, h, x, y, bounds) {
+ return {
+ w: clamp(w, MIN_W, Math.max(MIN_W, bounds.w - x)),
+ h: clamp(h, MIN_H, Math.max(MIN_H, bounds.h - y)),
+ };
+ }
+
+ /**
+ * Keep the zoomed image covering its `w`×`h` pane, so no gap opens at an
+ * edge. At fit scale this pins the offset to 0; deeper in it allows panning by
+ * as much as the image overflows.
+ */
+ function clampPan(ox, oy, scale, w, h) {
+ return {
+ ox: clamp(ox, Math.min(0, w - scale * w), 0),
+ oy: clamp(oy, Math.min(0, h - scale * h), 0),
+ };
+ }
+
+ /**
+ * Zoom `view` by `factor` about `cursor` (pane pixels from its top-left),
+ * keeping the point under the cursor still. Returns the new { scale, ox, oy }.
+ */
+ function zoomAt(view, factor, cursor, size) {
+ const scale = clamp(view.scale * factor, MIN_SCALE, MAX_SCALE);
+ const ratio = scale / view.scale; // what the clamp actually allowed
+ const ox = cursor.x - ratio * (cursor.x - view.ox);
+ const oy = cursor.y - ratio * (cursor.y - view.oy);
+ return { scale, ...clampPan(ox, oy, scale, size.w, size.h) };
+ }
+
+ function createRefs() {
+ let open = [];
+ let spawned = 0; // id source, so two windows on one file stay distinct
+
+ return {
+ id: "refs",
+ label: "Refs",
+ icon: "image",
+ needsGeometry: false,
+ get armed() {
+ return false; // it never waits for a click on the map
+ },
+ /** The windows, in the order they were spawned. */
+ get open() {
+ return open;
+ },
+
+ /** Spawn a window on one picked file, on top of the others. */
+ add(item) {
+ const step = (open.length % STAGGER_WRAP) * STAGGER;
+ const viewer = createViewer(`ref-${++spawned}`, item, {
+ x: 60 + step,
+ y: 60 + step,
+ z: nextZ(open),
+ });
+ open.push(viewer);
+ return viewer;
+ },
+
+ /** Bring one to the front, re-numbering the rest. */
+ focus(id) {
+ const z = restack(open, id);
+ for (const viewer of open) viewer.z = z.get(viewer.id);
+ },
+
+ close(id) {
+ open = open.filter((viewer) => viewer.id !== id);
+ },
+
+ /** Every window down — what changing case does, since the files were the
+ * other case's. */
+ clear() {
+ open = [];
+ },
+
+ disarm() {},
+
+ shapes() {
+ return []; // nothing of this is on the map
+ },
+
+ /** Fold one away to its header, or unfold it. */
+ fold(id) {
+ const viewer = open.find((window) => window.id === id);
+ if (viewer) viewer.collapsed = !viewer.collapsed;
+ return viewer;
+ },
+
+ readout() {
+ if (!open.length) return "Nothing held over the map";
+ return open.length === 1 ? "1 reference open" : `${open.length} references open`;
+ },
+ };
+ }
+
+ window.AzimutMapTools = {
+ MAX_CELLS,
+ RESIDUAL_LIMIT,
+ MEASURE_ME,
+ verdict,
+ createMeasure,
+ createPins,
+ createSky,
+ createGridTool,
+ createRefs,
+ // the shared arithmetic, exported so the cross-checks can reach it
+ markerPrecision,
+ groupSavedMarkers,
+ upRuns,
+ hourTicks,
+ markScale,
+ nowIndex,
+ degSteps,
+ createGrid,
+ cellKey,
+ cellRange,
+ cellBounds,
+ cellsInAoi,
+ estimateCells,
+ coverage,
+ cycleStatus,
+ aoiBounds,
+ pointInPolygon,
+ rectIntersectsPolygon,
+ closeRing,
+ destination,
+ createViewer,
+ nextZ,
+ restack,
+ clampWindow,
+ clampSize,
+ clampPan,
+ zoomAt,
+ };
+})();
diff --git a/extension/options.js b/extension/options.js
index c6efe05..d30fef9 100644
--- a/extension/options.js
+++ b/extension/options.js
@@ -1,10 +1,31 @@
/** Options: store the backend URL + pairing token, and prove them with one
* /api/ingest/ping — the same call the popup will make, so "test passed"
- * means the real flow works. */
+ * means the real flow works.
+ *
+ * That ping also answers a question only the signed Firefox add-on can raise.
+ * Everywhere else the extension comes out of the app and so can never lead it,
+ * but Firefox updates a signed add-on from Azimut's release manifest without
+ * knowing which Azimut is installed — so an old app can end up paired with a
+ * newer add-on. Nothing can stop that from the browser's side; what it can do
+ * is name it here, where both numbers are already on screen, instead of leaving
+ * the analyst with features that report they could not run. */
const api = typeof browser !== "undefined" ? browser : chrome;
const $ = (id) => document.getElementById(id);
+/** Is version `a` above version `b`? Numeric per part, so 0.10.0 beats 0.9.0.
+ * Mirrors lib/extBridge.js and engine/updates.py, which answer the same question
+ * on the app's side. */
+function above(a, b) {
+ const parts = (v) =>
+ String(v || "").replace(/^v/i, "").split(".").map((n) => parseInt(n, 10) || 0);
+ const [x, y] = [parts(a), parts(b)];
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
+ if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
+ }
+ return false;
+}
+
function status(text, kind = "info") {
const el = $("status");
el.hidden = !text;
@@ -31,6 +52,15 @@ async function init() {
return;
}
const body = await r.json();
+ const mine = api.runtime.getManifest().version;
+ if (above(mine, body.version)) {
+ status(
+ `Paired with Azimut ${body.version}, older than this add-on (${mine}). ` +
+ `Update Azimut, or newer features will report that they could not run.`,
+ "warn",
+ );
+ return;
+ }
status(`Paired with Azimut ${body.version}.`, "ok");
} catch {
status(`No Azimut at ${backendUrl}. Is the app running?`, "error");
diff --git a/extension/popup.html b/extension/popup.html
index f615c32..611dc18 100644
--- a/extension/popup.html
+++ b/extension/popup.html
@@ -64,6 +64,7 @@
<div class="actions stacked">
<button id="capture-area" class="primary">Select area to capture…</button>
<button id="save-place">Save this place</button>
+ <button id="map-tools">Draw tools over this map</button>
</div>
</section>
diff --git a/extension/popup.js b/extension/popup.js
index d6cf162..c6ccf41 100644
--- a/extension/popup.js
+++ b/extension/popup.js
@@ -36,6 +36,29 @@ const origin = (url) => {
}
};
+/**
+ * How tall the map is drawn in the tab, in CSS pixels, or null.
+ *
+ * Read by injecting one expression, which `activeTab` allows the moment this
+ * popup is opened — and it stays a number about the window, never anything
+ * about the page: the coordinates of a capture are still only ever what the
+ * address bar says. A page that refuses the injection simply has no height,
+ * and the two sites that need one come back without a zoom rather than a
+ * guessed one.
+ */
+async function mapHeight(tabId) {
+ try {
+ const [result] = await api.scripting.executeScript({
+ target: { tabId },
+ func: () => window.innerHeight,
+ });
+ const height = Number(result?.result);
+ return Number.isFinite(height) && height > 0 ? Math.round(height) : null;
+ } catch {
+ return null;
+ }
+}
+
async function loadCases(select, stored) {
const { backendUrl, token } = stored;
let cases;
@@ -96,11 +119,17 @@ async function init() {
return;
}
- // everything about the URL is the app's judgment, not ours
+ // everything about the URL is the app's judgment, not ours — except how tall
+ // the map is drawn, which only this side can see. Apple states the span its
+ // view covers and Google's satellite mode the metres its viewport is high;
+ // next to the window's height the app turns either into the zoom the capture
+ // is filed with, and without it neither has one at all.
+ const height = await mapHeight(tab.id);
let parsed;
try {
const r = await fetch(
- `${stored.backendUrl}/api/ingest/parse?url=${encodeURIComponent(tab.url)}`,
+ `${stored.backendUrl}/api/ingest/parse?url=${encodeURIComponent(tab.url)}`
+ + (height ? `&height=${height}` : ""),
{ headers: { "X-Azimut-Token": stored.token } }
);
if (r.status === 401) {
@@ -223,6 +252,15 @@ async function init() {
if (r?.ok) window.close(); // the overlay takes over; a notification reports the result
else status(r?.error || "could not start the selection", "error");
});
+
+ // The map tools panel. One button both ways: injecting it again is how it
+ // closes (extension/mapoverlay.js), so the popup never has to know whether
+ // the panel is currently up.
+ $("map-tools").addEventListener("click", async () => {
+ const r = await api.runtime.sendMessage({ type: "map-tools", tabId: tab.id });
+ if (r?.ok) window.close();
+ else status(r?.error || "could not open the map tools", "error");
+ });
}
init().catch((e) => status(e.message, "error"));
diff --git a/extension/reverse.js b/extension/reverse.js
new file mode 100644
index 0000000..7b99173
--- /dev/null
+++ b/extension/reverse.js
@@ -0,0 +1,238 @@
+/**
+ * Hand one prepared image to a reverse-image engine, and stop there.
+ *
+ * Injected into the engine's tab by the background worker, once, after the app's
+ * Reverse Search button asked for it. It gives the picture to the page's own
+ * file input, the way its Browse button does, and then it is the site's picture:
+ * these engines search as soon as they hold one. That is the whole point of the
+ * button the analyst pressed, and it is the one thing this file does that
+ * `handoff.js` next door refuses to — a composer is left for the analyst to
+ * send, an engine is asked a question.
+ *
+ * **Runs in the page's own world**, for the reason that file spells out: the
+ * `DataTransfer` an extension builds belongs to the other side of that boundary
+ * and a page is free to ignore it, where here the file is the page's own object.
+ * The price is the same too — no extension API on this side, so the image
+ * arrives on `window.__AZIMUT_REVERSE__` and the report is this script's return
+ * value.
+ *
+ * **It knows four other sites' markup, and it will age.** So it is written to
+ * fail shallow: every step reports how far it got, nothing throws into the page,
+ * and the image the app copied to the clipboard is the answer to all of it.
+ */
+
+(() => {
+ // Per engine: where a file goes, and where a paste or a drop lands. Several
+ // selectors per role, oldest last — a renamed class costs the run, a spare
+ // that still matches saves it.
+ //
+ // **Nothing is ever pressed.** On every one of these pages the visible upload
+ // button *is* the file dialog: it calls `click()` on the hidden input, and a
+ // native picker opened over the analyst's work is worse than doing nothing.
+ // So each engine is reached by the uploader it already carries.
+ const SITES = [
+ {
+ // Lens, which is not where it says it is: `lens.google.com` answers with a
+ // redirect to `www.google.com/?olud`, and the uploader is on *that* page.
+ // Both hostnames, since the redirect is the site's to change.
+ //
+ // **Named, not merely image-typed, and not in a dialog.** Lens draws its
+ // uploader inline on the home page — no `role="dialog"` anywhere near it,
+ // which is what an earlier reading of this page got wrong — and it is one
+ // hidden input appended straight to `body`, late, carrying the name
+ // search-by-image has always used: `encoded_image`. The name is the whole
+ // entry. The same document also serves the search box's own "add files"
+ // inputs, which accept pictures too and are marked with a `jsname`;
+ // handing one of those the picture played an upload animation and
+ // searched nothing at all, so the fallback steps around them.
+ match: /(^|\.)(lens\.)?google\.com$/,
+ inputs: [
+ 'input[type="file"][name="encoded_image"]',
+ 'input[type="file"][accept*="image/"]:not([jsname])',
+ ],
+ // Nothing finer than the document for either: the drop zone's own classes
+ // are generated, and Lens listens for both up at the page.
+ paste: ['body'],
+ drop: ['body'],
+ },
+ {
+ // Yandex's home page, not its image search: the camera on `/images/` opens
+ // nothing at all — for a real click as much as for ours — while the home
+ // page keeps its picker in the document from the first paint, named. So
+ // there is nothing to press here, which is just as well: pressing that
+ // camera is what opens the file dialog.
+ match: /(^|\.)yandex\.(com|ru|by|kz|com\.tr|eu)$/,
+ inputs: ['#image-search', 'input[type="file"].image-search__picker', 'input[type="file"]'],
+ },
+ {
+ // Bing's search-by-image view keeps one named input in the page, hidden
+ // behind its Browse button.
+ match: /(^|\.)bing\.com$/,
+ inputs: ['#sb_fileinput', 'input[type="file"][accept*="image"]', 'input[type="file"]'],
+ },
+ {
+ // TinEye draws its own picker at run time, so the input can arrive a
+ // moment after the document does — and it has no panel to open, only the
+ // button that is the file dialog itself. Dropping is the road left.
+ match: /(^|\.)tineye\.com$/,
+ inputs: ['input[type="file"][name="image"]', 'input[type="file"]'],
+ drop: ['[class*="drop" i]', 'main', 'body'],
+ },
+ ];
+
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+ 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 [];
+ };
+
+ /** An input the page is offering, rather than one it is holding back. */
+ const usable = (node) => node.disabled !== true && node.getAttribute?.("aria-disabled") !== "true";
+
+ /** Poll for what the page has not drawn yet. An engine is an app inside an
+ * app: "load finished" says nothing about the uploader existing. */
+ async function waitFor(predicate, timeoutMs) {
+ const until = Date.now() + timeoutMs;
+ for (;;) {
+ const hit = predicate();
+ if (hit) return hit;
+ if (Date.now() > until) return null;
+ await sleep(200);
+ }
+ }
+
+ /**
+ * Rebuild the handed-over image on this side.
+ *
+ * Base64 rather than a `data:` URL because this runs in the page's world,
+ * where a read over the network answers to the page's own CSP — and these are
+ * exactly the sites that allow none. `atob` asks the network for nothing.
+ */
+ function toFile(image) {
+ const binary = atob(image.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], image.name || "image.png", { type: image.type || "image/png" });
+ }
+
+ /**
+ * Give the file to the page's own input, the way its picker does.
+ *
+ * Assignment first, then `change`: the site's validation, its thumbnail, its
+ * search. Read back **before** the site is told and never after — an uploader
+ * empties the input as soon as it has read it, so a later reading calls the
+ * one road that worked a refusal.
+ */
+ function hand(input, transfer) {
+ input.files = transfer.files;
+ if (!input.files?.length) return false;
+ input.dispatchEvent(new Event("change", { bubbles: true }));
+ return true;
+ }
+
+ /**
+ * Whether a paste made here carries the `DataTransfer` it was built with.
+ *
+ * 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 pasting a picture in
+ * on Firefox, and the drop below is that browser's road. Asked of a throwaway
+ * event rather than of a browser name — the same question `handoff.js` asks.
+ */
+ const CARRIES_FILES = (() => {
+ try {
+ const probe = new DataTransfer();
+ return new ClipboardEvent("paste", { clipboardData: probe }).clipboardData === probe;
+ } catch {
+ return false;
+ }
+ })();
+
+ /** Paste the file in, the way Ctrl+V in an open dialog does. */
+ function pasteInto(target, transfer) {
+ target.focus?.();
+ target.dispatchEvent(
+ new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: transfer })
+ );
+ return true;
+ }
+
+ /** The other road: drop the file on the page, the way dragging it in does. */
+ function drop(target, transfer) {
+ for (const kind of ["dragenter", "dragover", "drop"]) {
+ target.dispatchEvent(
+ new DragEvent(kind, { bubbles: true, cancelable: true, dataTransfer: transfer })
+ );
+ }
+ return true;
+ }
+
+ async function run() {
+ const site = SITES.find((one) => one.match.test(location.hostname));
+ if (!site) return { handed: false, error: "Azimut does not know this engine." };
+
+ const image = window.__AZIMUT_REVERSE__?.image;
+ delete window.__AZIMUT_REVERSE__; // the page keeps nothing of the case
+ if (!image?.data) return { handed: false };
+
+ const transfer = new DataTransfer();
+ transfer.items.add(toFile(image));
+
+ /**
+ * The ways in, in the order a person would try them, and **every one of them
+ * is tried**: nothing here can tell whether the engine took the picture.
+ *
+ * That sounds wasteful and is not, because of what an engine does when it
+ * takes one — it searches, which means it leaves. This script goes with the
+ * document, so a road that worked is the last road that runs. What follows a
+ * road that did nothing is the next road, on a page still sitting there.
+ */
+ const roads = [
+ async () => {
+ // The patience goes where the reason for it is: an uploader is drawn
+ // after the document, and Lens's arrives seconds late, appended to the
+ // body once the page has decided what it is.
+ const input = await waitFor(() => found(site.inputs, usable)[0], 8000);
+ return Boolean(input) && hand(input, transfer);
+ },
+ async () => {
+ if (!site.paste || !CARRIES_FILES) return false;
+ const target = found(site.paste)[0];
+ return Boolean(target) && pasteInto(target, transfer);
+ },
+ async () => {
+ if (!site.drop) return false;
+ const zone = found(site.drop)[0];
+ return Boolean(zone) && drop(zone, transfer);
+ },
+ ];
+
+ let offered = false;
+ for (const road of roads) {
+ if (!(await road())) continue;
+ offered = true;
+ // Long enough for a page that took it to start leaving with it.
+ await sleep(1500);
+ }
+ // Offered is all that is claimed. Whether the engine liked the picture is its
+ // own state, drawn its own way, and it is on screen in front of the analyst —
+ // every reading of it from here would be a guess.
+ return offered ? { handed: true } : { handed: false, error: "Could not give the image to this engine." };
+ }
+
+ // The value the injection hands back to the worker, which is what says whether
+ // the analyst needs telling anything.
+ return run().catch((e) => ({
+ handed: false,
+ error: e?.message || "The engine refused the image.",
+ }));
+})();
diff --git a/extension/ui.css b/extension/ui.css
index 126fc8a..0eebb19 100644
--- a/extension/ui.css
+++ b/extension/ui.css
@@ -9,6 +9,7 @@
--accent-text: #141414;
--border: #333;
--ok: #58b368;
+ --warn: #d9a441;
--error: #e5484d;
}
@@ -71,6 +72,7 @@ button:disabled { opacity: 0.55; cursor: default; }
.status { padding: 7px 9px; border-radius: 6px; background: var(--bg-2); border: 1px solid var(--border); }
.status.ok { border-color: var(--ok); }
+.status.warn { border-color: var(--warn); }
.status.error { border-color: var(--error); }
footer {
diff --git a/frontend/calibration/fake-map.html b/frontend/calibration/fake-map.html
new file mode 100644
index 0000000..ce23ec7
--- /dev/null
+++ b/frontend/calibration/fake-map.html
@@ -0,0 +1,161 @@
+<!doctype html>
+<!--
+ A slippy map with nothing behind it, for proving the calibration protocol
+ without a network.
+
+ The recorder's whole claim is that driving a map with a known gesture and
+ reading its address bar afterwards recovers where that map draws its camera.
+ Against a real site that claim can only be checked against itself. Here the
+ layout is *chosen* — a header of `head` pixels, a side panel of `panel` — so
+ the answer is known before the question is asked, and `e2e/map-calibration.spec.js`
+ drives this page exactly as `record.mjs` drives openstreetmap.org.
+
+ It behaves the way the real one does in the two ways that matter: the camera
+ is the centre of what the chrome leaves, not of the window, and the address
+ bar is rewritten when a gesture ends rather than while it is running. The
+ coordinates are rounded to five decimals, as OpenStreetMap rounds its own.
+
+ Query: ?head=<px>&panel=<px>. Fragment: #map=<zoom>/<lat>/<lon>, which is
+ OpenStreetMap's own form, so `engine/mapsites.py` reads this page for real.
+-->
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Fake slippy map</title>
+<style>
+ html, body { margin: 0; height: 100%; overflow: hidden; background: #0b0b0c; color: #ddd;
+ font: 13px system-ui, sans-serif; }
+ #head { position: fixed; top: 0; left: 0; right: 0; background: #1b2430; display: flex;
+ align-items: center; padding: 0 12px; box-sizing: border-box; }
+ #panel { position: fixed; left: 0; bottom: 0; background: #161c24; box-sizing: border-box;
+ padding: 10px; }
+ #map { position: fixed; right: 0; bottom: 0; overflow: hidden; }
+ canvas { display: block; width: 100%; height: 100%; }
+</style>
+</head>
+<body>
+<div id="head">fake map</div>
+<div id="panel"></div>
+<div id="map"><canvas></canvas></div>
+<script>
+(() => {
+ const params = new URLSearchParams(location.search);
+ const HEAD = Number(params.get('head') ?? 0);
+ const PANEL = Number(params.get('panel') ?? 0);
+ document.getElementById('head').style.height = `${HEAD}px`;
+ document.getElementById('panel').style.width = `${PANEL}px`;
+ document.getElementById('panel').style.top = `${HEAD}px`;
+ const mapEl = document.getElementById('map');
+ mapEl.style.top = `${HEAD}px`;
+ mapEl.style.left = `${PANEL}px`;
+
+ const TILE = 256;
+ const MAX_LAT = 85.05112877980659;
+ const rad = (d) => (d * Math.PI) / 180;
+ const deg = (r) => (r * 180) / Math.PI;
+ const size = (z) => TILE * 2 ** z;
+
+ const project = (lat, lon, z) => ({
+ x: ((lon + 180) / 360) * size(z),
+ y: ((1 - Math.log(Math.tan(rad(lat)) + 1 / Math.cos(rad(lat))) / Math.PI) / 2) * size(z),
+ });
+ const unproject = (x, y, z) => {
+ const n = Math.PI - (2 * Math.PI * y) / size(z);
+ return {
+ lat: deg(Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))),
+ lon: (x / size(z)) * 360 - 180,
+ };
+ };
+
+ const read = () => {
+ const m = /map=(\d+(?:\.\d+)?)\/(-?\d+(?:\.\d+)?)\/(-?\d+(?:\.\d+)?)/.exec(location.hash);
+ return m
+ ? { zoom: Number(m[1]), lat: Number(m[2]), lon: Number(m[3]) }
+ : { zoom: 15, lat: 47.388462, lon: 2.352785 };
+ };
+ let view = read();
+
+ /** Five decimals, the way OpenStreetMap writes them — about a metre, and the
+ * floor under everything a measurement of this page can claim. */
+ const write = () => {
+ location.hash = `map=${view.zoom}/${view.lat.toFixed(5)}/${view.lon.toFixed(5)}`;
+ draw();
+ };
+
+ const canvas = mapEl.querySelector('canvas');
+ function draw() {
+ const ratio = window.devicePixelRatio || 1;
+ const w = mapEl.clientWidth;
+ const h = mapEl.clientHeight;
+ canvas.width = Math.round(w * ratio);
+ canvas.height = Math.round(h * ratio);
+ const ctx = canvas.getContext('2d');
+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
+ ctx.fillStyle = '#10161d';
+ ctx.fillRect(0, 0, w, h);
+ // a graticule, so a screenshot of a failing run shows something moving
+ const centre = project(view.lat, view.lon, view.zoom);
+ ctx.strokeStyle = '#243447';
+ ctx.beginPath();
+ for (let step = -4; step <= 4; step += 1) {
+ const line = project(view.lat, view.lon + step * 0.01, view.zoom);
+ const across = project(view.lat + step * 0.01, view.lon, view.zoom);
+ ctx.moveTo(w / 2 + (line.x - centre.x), 0);
+ ctx.lineTo(w / 2 + (line.x - centre.x), h);
+ ctx.moveTo(0, h / 2 + (across.y - centre.y));
+ ctx.lineTo(w, h / 2 + (across.y - centre.y));
+ }
+ ctx.stroke();
+ }
+
+ /** Where the map draws its camera, in window pixels — the answer the
+ * calibration is supposed to arrive at without being told. */
+ window.__TRUE_CENTRE__ = () => ({
+ x: PANEL + (window.innerWidth - PANEL) / 2,
+ y: HEAD + (window.innerHeight - HEAD) / 2,
+ });
+
+ // --- gestures ---------------------------------------------------------------
+
+ let drag = null;
+ window.addEventListener('mousedown', (e) => {
+ drag = { x: e.clientX, y: e.clientY, from: { ...view } };
+ });
+ window.addEventListener('mousemove', (e) => {
+ if (!drag) return;
+ // the map moves with the pointer; the address bar hears about it at the end
+ const at = project(drag.from.lat, drag.from.lon, drag.from.zoom);
+ const now = unproject(at.x - (e.clientX - drag.x), at.y - (e.clientY - drag.y), drag.from.zoom);
+ view = { ...view, ...now };
+ draw();
+ });
+ window.addEventListener('mouseup', () => {
+ if (!drag) return;
+ drag = null;
+ write();
+ });
+ window.addEventListener('wheel', (e) => {
+ // one level a notch, about the pixel the pointer is over
+ const step = e.deltaY < 0 ? 1 : -1;
+ const middle = window.__TRUE_CENTRE__();
+ const dx = e.clientX - middle.x;
+ const dy = e.clientY - middle.y;
+ const at = project(view.lat, view.lon, view.zoom);
+ const held = unproject(at.x + dx, at.y + dy, view.zoom);
+ const zoom = Math.max(2, Math.min(20, view.zoom + step));
+ const after = project(held.lat, held.lon, zoom);
+ const centre = unproject(after.x - dx, after.y - dy, zoom);
+ view = { zoom, lat: Math.max(-MAX_LAT, Math.min(MAX_LAT, centre.lat)), lon: centre.lon };
+ write();
+ }, { passive: true });
+
+ window.addEventListener('resize', draw);
+ window.addEventListener('hashchange', () => {
+ view = read();
+ draw();
+ });
+ write();
+})();
+</script>
+</body>
+</html>
diff --git a/frontend/calibration/protocol.mjs b/frontend/calibration/protocol.mjs
new file mode 100644
index 0000000..5d65af8
--- /dev/null
+++ b/frontend/calibration/protocol.mjs
@@ -0,0 +1,276 @@
+/**
+ * The protocol the map sites were calibrated with, written down so it can be
+ * run again.
+ *
+ * The map tools draw over someone else's map from what its address bar says,
+ * and two things about each site have to be known for that to land on the
+ * ground: what its URL means (`engine/mapsites.py`) and where in the window it
+ * draws the coordinate that URL names (`extension/mapmath.js`, `centreFromZoom`).
+ * Neither is documented by anybody. Both were measured, in a browser, and
+ * `tests/fixtures/map-sites.json` is that measurement.
+ *
+ * A measurement ages. Sites move their panels, change their URL forms and
+ * re-lay-out for narrow windows, and the day one does, the drawing is quietly
+ * wrong rather than loudly broken. So the measurement is not a one-off: this is
+ * the gesture sequence that produced the fixture, and `record.mjs` runs it
+ * again — same place, same drags, same notches, at every window size and
+ * browser zoom the matrix names.
+ *
+ * What it does *not* do is decide anything. It drives and it writes down what
+ * the address bar said; turning that into views is `engine/mapsites.py`'s job,
+ * through `scripts/build_map_fixture.py`, because a second URL parser is the
+ * one thing this project cannot afford.
+ */
+
+import { mapLinks } from '../src/lib/maplinks.js';
+
+/** Where every recording is taken: open country in the Cher, far from anything
+ * a map site puts a panel over, and the same point the fixture already holds
+ * so a new run can be diffed against the old one. */
+export const PLACE = { lat: 47.388462, lon: 2.352785, zoom: 15 };
+
+/**
+ * The windows to record in, and the browser zoom to record them at.
+ *
+ * `w`/`h` is the window as the operating system sees it; the browser's own zoom
+ * divides that into CSS pixels, which is the only unit the drawing works in. So
+ * a 1600 px window at 125% is a 1280 px viewport, and the pair at 1500×950 and
+ * 1200×760 below is deliberate: both come out at 1200×760 CSS pixels, from
+ * different device ratios. Where a site's own layout is concerned they are the
+ * same window, and the fixture says so.
+ */
+export const VIEWPORTS = [
+ { w: 1600, h: 1000, pageZoom: 1 },
+ { w: 1600, h: 1000, pageZoom: 1.25 },
+ { w: 1500, h: 950, pageZoom: 1.25 }, // 1200×760 CSS, at 1.25 dots to the pixel
+ { w: 1200, h: 760, pageZoom: 1 }, // 1200×760 CSS, at 1
+ { w: 1200, h: 760, pageZoom: 1.25 },
+ { w: 900, h: 600, pageZoom: 1 },
+ { w: 900, h: 600, pageZoom: 1.25 },
+];
+
+/** How far a level is, in wheel notches, on each site.
+ *
+ * Bing's wheel moves a third of a level — the reason `zoomFromAnchor` exists —
+ * so it takes three to arrive somewhere its URL states exactly. Everyone else
+ * steps a whole level a notch. A site that changes this shows up in the build
+ * as a zoom too small to solve from, naming itself. */
+const NOTCHES = { 'bing-maps': 3 };
+
+/** Which `mapLinks` entry opens which site of `engine/mapsites.py`, and what
+ * the recording is called. Earth is driven like the rest and left out of the
+ * fixture by the build: a free camera states no scale to check. */
+const FROM_LINKS = [
+ ['google', 'google-maps', 'google-maps'],
+ ['google_sat', 'google-maps', 'google-maps satellite'],
+ ['apple', 'apple-maps', 'apple-maps'],
+ ['bing', 'bing-maps', 'bing-maps'],
+ ['yandex', 'yandex-maps', 'yandex-maps'],
+ ['sentinel', 'copernicus-browser', 'copernicus-browser'],
+ ['zoom_earth', 'zoom-earth', 'zoom-earth'],
+ ['satellites_pro', 'satellites-pro', 'satellites-pro'],
+ ['google_earth', 'google-earth', 'google-earth'],
+];
+
+/** The map the extension draws on that the app never links out to, because it
+ * is already a tile provider inside it. Its opening URL is written here for
+ * that reason: nothing else in the app writes one. */
+const EXTRA = [
+ {
+ id: 'openstreetmap',
+ site: 'openstreetmap',
+ label: 'openstreetmap',
+ url: `https://www.openstreetmap.org/#map=${PLACE.zoom}/${PLACE.lat}/${PLACE.lon}`,
+ },
+];
+
+/** The sites to drive: the app's own "Open in…" panel, as it writes them — so a
+ * link the app hands out that stopped working is caught here too — plus the one
+ * it does not link to. */
+export function sites() {
+ const links = new Map(mapLinks(PLACE.lat, PLACE.lon, PLACE.zoom).map((l) => [l.id, l]));
+ return [
+ ...FROM_LINKS.map(([id, site, label]) => ({ id, site, label, url: links.get(id).url })),
+ ...EXTRA,
+ ].map((site) => ({ ...site, notches: NOTCHES[site.site] ?? 1 }));
+}
+
+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+
+/**
+ * Wait for the address bar to stop moving.
+ *
+ * These maps rewrite their own URL when a gesture ends, some of them a few
+ * hundred milliseconds after it ends, and one of them (Copernicus) not at all
+ * for a pan. So this waits for quiet rather than for a change, and reports
+ * whether anything moved.
+ *
+ * The long timeout is for the operator: a first visit can land on a consent
+ * wall, a cookie banner or a login, and none of that is something a script
+ * should click on someone's behalf. The run is headed, it says what it is
+ * waiting for, and it waits.
+ */
+export async function settle(page, { quiet = 900, timeout = 120_000, say } = {}) {
+ const started = Date.now();
+ let last = page.url();
+ let still = 0;
+ let warned = false;
+ for (;;) {
+ await sleep(150);
+ const now = page.url();
+ if (now === last) {
+ still += 150;
+ if (still >= quiet) return now;
+ } else {
+ last = now;
+ still = 0;
+ }
+ if (!warned && Date.now() - started > 8000) {
+ warned = true;
+ say?.(`still waiting on ${new URL(last).host} — dismiss whatever it is showing`);
+ }
+ if (Date.now() - started > timeout) return last;
+ }
+}
+
+/**
+ * Drag the map by a known number of pixels.
+ *
+ * The pause before the button comes up is the whole reason this is a function
+ * and not two lines: these maps glide on after a fast release, and a pan that
+ * ends in a glide reports a move the pointer never made. Held still first, the
+ * map lands where it was left.
+ */
+async function panBy(page, from, by) {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ for (let step = 1; step <= 12; step += 1) {
+ await page.mouse.move(from.x + (by.dx * step) / 12, from.y + (by.dy * step) / 12);
+ await sleep(16);
+ }
+ await sleep(400); // let go still, or the glide is measured instead of the drag
+ await page.mouse.up();
+}
+
+/** Zoom about one pixel, in the notches that site takes to move a whole level. */
+async function zoomAt(page, at, notches) {
+ await page.mouse.move(at.x, at.y);
+ for (let notch = 0; notch < notches; notch += 1) {
+ await page.mouse.wheel(0, -120);
+ await sleep(180);
+ }
+}
+
+/**
+ * One site, zoomed a notch at a time over a single pixel.
+ *
+ * For the one site that rounds the zoom it writes. Bing's wheel moves a third of
+ * a level and its URL carries one decimal, so two notches out of every three
+ * land on a number the address bar cannot state — two and a third percent of
+ * scale, five metres at the edge of a 1600 px window at level 18. The tools work
+ * the fraction out from the pixel the zoom held still (`mapmath.js`,
+ * `zoomFromAnchor`), and this is the recording that says they still can.
+ *
+ * Driven from a whole level so the run starts somewhere exact, and long enough
+ * to cross two more of them: the whole ones are what the solve is anchored on
+ * and the ones between are what it has to recover.
+ */
+export async function driveNotches(page, site, { at, count = 6, say = () => {}, quiet } = {}) {
+ const view = page.viewportSize();
+ const spot = at ?? { x: Math.round(view.width * 0.72), y: Math.round(view.height * 0.38) };
+ const steps = [];
+ await page.goto(site.url, { waitUntil: 'commit' });
+ steps.push({ url: await settle(page, { say, quiet }) });
+ for (let notch = 0; notch < count; notch += 1) {
+ say(`${site.label}: notch ${notch + 1} of ${count} over ${spot.x}, ${spot.y}`);
+ await zoomAt(page, spot, 1);
+ steps.push({ url: await settle(page, { say, quiet }) });
+ }
+ return {
+ site: site.site,
+ window: { w: view.width, h: view.height },
+ at: spot,
+ step: 1 / site.notches,
+ steps,
+ };
+}
+
+/**
+ * The biggest canvas on the page, if it covers enough of the window to be the
+ * map — an independent witness to where the map is, owed to nobody's
+ * arithmetic.
+ *
+ * It is a witness and not the answer: a site is free to draw its camera
+ * somewhere other than the middle of its own canvas, and several stretch the
+ * canvas under their chrome. So the fixture keeps it, and the tests ask only
+ * that the solved centre falls inside it.
+ */
+async function canvasRect(page) {
+ return page.evaluate(() => {
+ const area = window.innerWidth * window.innerHeight;
+ let best = null;
+ for (const node of document.querySelectorAll('canvas')) {
+ const box = node.getBoundingClientRect();
+ if (box.width * box.height < area * 0.25) continue;
+ if (!best || box.width * box.height > best.w * best.h) {
+ best = { x: box.left, y: box.top, w: box.width, h: box.height };
+ }
+ }
+ return best;
+ });
+}
+
+/**
+ * One site, driven once: open, drag, zoom about one pixel, zoom about another.
+ *
+ * The two zooms are the measurement. Each one holds a pixel still while the
+ * camera moves underneath it, which is enough to solve for the pixel the camera
+ * is drawn at, and two of them far apart are what say the answer is real rather
+ * than a coincidence of one gesture.
+ *
+ * Returns the raw observation only: URLs, pixels, and the window they were made
+ * in. Nothing here parses a URL.
+ */
+export async function drive(page, site, { say = () => {}, quiet } = {}) {
+ const view = page.viewportSize();
+ const steps = [];
+ const record = (url) => steps.push({ url });
+
+ say(`${site.label}: opening`);
+ await page.goto(site.url, { waitUntil: 'commit' });
+ record(await settle(page, { say, quiet }));
+
+ const by = { dx: -Math.round(view.width * 0.2), dy: Math.round(view.height * 0.2) };
+ say(`${site.label}: dragging ${by.dx}, ${by.dy}`);
+ await panBy(page, { x: Math.round(view.width * 0.62), y: Math.round(view.height * 0.55) }, by);
+ record(await settle(page, { say, quiet }));
+
+ // Both zooms are taken in the right half and clear of the top, because a
+ // gesture over a site's own chrome is not a gesture on its map: Yandex keeps
+ // 420 px of results down the left and Bing an 81 px header across the top,
+ // and a notch there moves nothing. Far enough apart to be two measurements,
+ // and neither of them anywhere a panel has ever been.
+ const zooms = [];
+ for (const spot of [
+ { x: 0.62, y: 0.3 },
+ { x: 0.8, y: 0.74 },
+ ]) {
+ const at = { x: Math.round(view.width * spot.x), y: Math.round(view.height * spot.y) };
+ say(`${site.label}: ${site.notches} notch(es) over ${at.x}, ${at.y}`);
+ await zoomAt(page, at, site.notches);
+ const from = steps.length - 1;
+ record(await settle(page, { say, quiet }));
+ zooms.push({ from, to: steps.length - 1, at });
+ }
+
+ return {
+ site: site.site,
+ label: site.label,
+ link: site.url,
+ window: { w: view.width, h: view.height },
+ pan: { from: 0, to: 1, ...by },
+ zooms,
+ canvas: await canvasRect(page),
+ steps,
+ };
+}
diff --git a/frontend/calibration/record.mjs b/frontend/calibration/record.mjs
new file mode 100644
index 0000000..1e96b0b
--- /dev/null
+++ b/frontend/calibration/record.mjs
@@ -0,0 +1,184 @@
+/**
+ * Re-measure the map sites, in a real browser.
+ *
+ * npm run calibrate:maps # the whole matrix, headed
+ * npm run calibrate:maps -- --sites yandex,apple --browsers chromium
+ * npm run calibrate:maps -- --viewports 1600x1000@1
+ *
+ * Writes `tests/fixtures/map-sites.raw.json`: the URLs each site wrote about
+ * itself after each gesture, and nothing else. `scripts/build_map_fixture.py`
+ * turns that into `tests/fixtures/map-sites.json` by parsing it with the app's
+ * own parser, which is the only thing allowed to read a map URL.
+ *
+ * It is headed on purpose. A first visit to half these sites lands on a consent
+ * wall, and clicking one on an analyst's behalf is not a script's business — so
+ * the run says what it is waiting for and waits. `--profile` keeps a browser
+ * profile between runs, so each wall is dismissed once rather than every time.
+ *
+ * Nothing about it is fast, and it is not meant to be: this is a measurement,
+ * taken by hand, the day a site has moved or before a release that cares. The
+ * whole matrix is ten runs across seven windows and two browsers, which is
+ * about an hour of driving plus whatever the consent walls ask of you. Every
+ * entry is merged into the file by key, so a run that covers one site at one
+ * size leaves the rest of the recording alone and can be picked up again.
+ */
+
+import { chromium, firefox } from '@playwright/test';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join, resolve } from 'node:path';
+
+import { PLACE, VIEWPORTS, drive, driveNotches, sites } from './protocol.mjs';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = join(here, '../..');
+const OUT = join(root, 'tests/fixtures/map-sites.raw.json');
+
+const ENGINES = { chromium, firefox };
+
+function options(argv) {
+ const flags = {};
+ for (let i = 0; i < argv.length; i += 1) {
+ if (!argv[i].startsWith('--')) continue;
+ const name = argv[i].slice(2);
+ const next = argv[i + 1];
+ flags[name] = next && !next.startsWith('--') ? next : 'yes';
+ }
+ return flags;
+}
+
+const flags = options(process.argv.slice(2));
+const wanted = {
+ browsers: (flags.browsers ?? 'chromium,firefox').split(','),
+ sites: flags.sites ? flags.sites.split(',') : null,
+ viewports: flags.viewports
+ ? flags.viewports.split(',').map((text) => {
+ const [size, zoom] = text.split('@');
+ const [w, h] = size.split('x').map(Number);
+ return { w, h, pageZoom: Number(zoom ?? 1) };
+ })
+ : VIEWPORTS,
+ headless: flags.headless === 'yes',
+ rounding: flags.rounding === 'yes',
+ profile: flags.profile ?? join(root, '.calibration-profile'),
+ out: flags.out ? resolve(process.cwd(), flags.out) : OUT,
+};
+
+const key = (entry) =>
+ `${entry.browser}|${entry.window.w}x${entry.window.h}@${entry.pageZoom}|${entry.label}`;
+
+function existing(path) {
+ try {
+ return JSON.parse(readFileSync(path, 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+const say = (line) => process.stdout.write(` ${line}\n`);
+
+async function run() {
+ const table = sites().filter((site) => !wanted.sites || wanted.sites.includes(site.id));
+ const before = existing(wanted.out);
+ const held = new Map((before?.recorded ?? []).map((e) => [key(e), e]));
+ let rounding = before?.rounding ?? null;
+ const failed = [];
+
+ // The rounding run measures a site's own wheel step, which no window size can
+ // change, so it is taken once rather than across the matrix.
+ const viewports = wanted.rounding ? wanted.viewports.slice(0, 1) : wanted.viewports;
+ for (const browser of wanted.rounding ? wanted.browsers.slice(0, 1) : wanted.browsers) {
+ const engine = ENGINES[browser];
+ if (!engine) throw new Error(`no browser called "${browser}"`);
+ for (const viewport of viewports) {
+ // The browser's own zoom is a smaller viewport at a higher device ratio,
+ // which is exactly what it is: CSS pixels are what a page is laid out in,
+ // and 125% means fewer of them in the same window.
+ const width = Math.round(viewport.w / viewport.pageZoom);
+ const height = Math.round(viewport.h / viewport.pageZoom);
+ process.stdout.write(
+ `\n${browser} ${viewport.w}×${viewport.h} at ${viewport.pageZoom}× → ${width}×${height} CSS px\n`
+ );
+ mkdirSync(wanted.profile, { recursive: true });
+ const context = await engine.launchPersistentContext(`${wanted.profile}/${browser}`, {
+ headless: wanted.headless,
+ viewport: { width, height },
+ deviceScaleFactor: viewport.pageZoom,
+ args: browser === 'chromium' ? [`--window-size=${viewport.w},${viewport.h}`] : [],
+ });
+ const page = context.pages()[0] ?? (await context.newPage());
+ if (wanted.rounding) {
+ // The one site that rounds the zoom it writes, notch by notch.
+ for (const site of table.filter((s) => s.notches > 1)) {
+ try {
+ rounding = { browser, pageZoom: viewport.pageZoom, ...(await driveNotches(page, site, { say })) };
+ say(`${site.label}: ${rounding.steps.length} URLs, one notch apart`);
+ } catch (e) {
+ failed.push(`${browser} rounding ${site.label}: ${e.message}`);
+ }
+ }
+ await context.close();
+ continue;
+ }
+ for (const site of table) {
+ try {
+ const seen = await drive(page, site, { say });
+ const entry = {
+ browser,
+ pageZoom: viewport.pageZoom,
+ deviceScaleFactor: viewport.pageZoom,
+ ...seen,
+ };
+ held.set(key(entry), entry);
+ // A site that wrote the same URL four times did not move: its map
+ // failed to load, or something is over it waiting to be dismissed.
+ // Said here rather than left for the build, because the browser is
+ // still open and the operator is still watching.
+ const moved = new Set(seen.steps.map((step) => step.url)).size;
+ say(`${site.label}: ${seen.steps.length} URLs, ${moved} of them different`);
+ if (moved < 3) {
+ failed.push(`${browser} ${width}×${height} ${site.label}: the address bar barely moved`);
+ say(`${site.label}: it did not move — drive it by hand and see what it is showing`);
+ }
+ } catch (e) {
+ failed.push(`${browser} ${width}×${height} ${site.label}: ${e.message}`);
+ say(`${site.label}: FAILED — ${e.message}`);
+ }
+ }
+ await context.close();
+ }
+ }
+
+ const recorded = [...held.values()].sort(
+ (a, b) =>
+ a.label.localeCompare(b.label) ||
+ b.window.w - a.window.w ||
+ a.pageZoom - b.pageZoom ||
+ a.browser.localeCompare(b.browser)
+ );
+ writeFileSync(
+ wanted.out,
+ `${JSON.stringify(
+ {
+ what: 'Every URL these map sites wrote about themselves, driven through one gesture sequence.',
+ how: 'frontend/calibration/protocol.mjs — open, drag a known number of pixels, zoom about two known pixels. Run it again with `npm run calibrate:maps`.',
+ why: 'The raw half of tests/fixtures/map-sites.json. Nothing here has been parsed: scripts/build_map_fixture.py does that, with the app’s own parser.',
+ place: PLACE,
+ recorded,
+ ...(rounding ? { rounding } : {}),
+ },
+ null,
+ 1
+ )}\n`
+ );
+ process.stdout.write(`\n${recorded.length} recordings → ${wanted.out}\n`);
+ if (failed.length) {
+ process.stdout.write(`${failed.length} did not finish:\n${failed.map((f) => ` ${f}`).join('\n')}\n`);
+ }
+ process.stdout.write('next: python scripts/build_map_fixture.py\n');
+}
+
+run().catch((e) => {
+ process.stderr.write(`${e.stack}\n`);
+ process.exit(1);
+});
diff --git a/frontend/e2e/home-guide.spec.js b/frontend/e2e/home-guide.spec.js
new file mode 100644
index 0000000..c6b0612
--- /dev/null
+++ b/frontend/e2e/home-guide.spec.js
@@ -0,0 +1,71 @@
+import { expect, test } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+/**
+ * The home page and the guide, in a real browser.
+ *
+ * `Overview.render.test.js` and `Guide.render.test.js` cover what each tab does on
+ * its own. This covers the two things a DOM with no layout cannot answer: that the
+ * map of the case comes up on the free imagery and puts the points where they are,
+ * and that the `?` in the topbar reaches the section written about the tab it was
+ * pressed from — a route that runs through the topbar, `lib/navigate.js` and a tab
+ * that mounts on arrival.
+ */
+
+const summary = {
+ total: 148,
+ by_type: { media: 82, place: 31, claim: 18, person: 12 },
+ by_status: { confirmed: 136, suggested: 12 },
+ by_folder: { work: 96 },
+ by_source: {},
+ linked_to: {},
+ unlinked: 4,
+ countable: 0,
+};
+
+// Two points a few hundred metres apart, one north-west of the other.
+const savedIndex = [
+ { id: 'p1', key: 'p1', kind: 'place', title: 'North gate', lat: 49.9951, lon: 36.2304 },
+ { id: 'p2', key: 'p2', kind: 'capture', title: 'Depot roof', lat: 49.9889, lon: 36.2401 },
+];
+
+test('draws the case on the free imagery, and presses through to the map', async ({ page }) => {
+ const tiles = [];
+ page.on('request', (request) => {
+ const { pathname } = new URL(request.url());
+ if (pathname.startsWith('/api/tiles/')) tiles.push(pathname);
+ });
+ await installAppFixture(page, { savedIndex, summary });
+ await page.goto('/#overview');
+
+ await awaitMapReady(page);
+ // The one basemap it may ever ask for: keyless and unmetered, so arriving on the
+ // home page cannot spend anybody's quota however many cases are opened.
+ await expect.poll(() => tiles.length).toBeGreaterThan(0);
+ expect(tiles.every((path) => path.startsWith('/api/tiles/esri-world-imagery/'))).toBe(true);
+ // whose terms are met the way the Map tool meets them: the credit line, in full
+ await expect(page.locator('.plate')).toContainText('Browser fixture');
+
+ await page.locator('.plate .foot').click();
+ expect(page.url()).toContain('#satellite');
+});
+
+test('the ? reaches the section written about the tab it was pressed from', async ({ page }) => {
+ await installAppFixture(page, { savedIndex, summary });
+ await page.goto('/#satellite');
+
+ await page.locator('.topbar button[title="Guide: Satellite"]').click();
+ await expect(page.locator('#guide-map')).toBeVisible();
+ await expect(page.locator('.contents .jump.on')).toHaveText(/Map/);
+ // silent on the guide itself, which is the answer
+ await expect(page.locator('.topbar button[title^="Guide"]')).toHaveCount(0);
+});
+
+test('a recipe step opens the tab it names', async ({ page }) => {
+ await installAppFixture(page, { savedIndex, summary });
+ await page.goto('/#guide');
+
+ await page.locator('.contents .jump', { hasText: 'Worked examples' }).click();
+ await page.locator('.recipe', { hasText: 'Geolocate a photo' }).locator('.step-tool', { hasText: 'Satellite' }).click();
+ expect(page.url()).toContain('#satellite');
+});
diff --git a/frontend/e2e/map-calibration.spec.js b/frontend/e2e/map-calibration.spec.js
new file mode 100644
index 0000000..e6dd01c
--- /dev/null
+++ b/frontend/e2e/map-calibration.spec.js
@@ -0,0 +1,142 @@
+/**
+ * The calibration protocol, run against a map whose layout is already known.
+ *
+ * `frontend/calibration/record.mjs` drives the real map sites and writes down
+ * what their address bars said; `tests/fixtures/map-sites.json` is the result,
+ * and both test suites lean on it. So the protocol itself has to be worth
+ * trusting — and against a real site there is nothing to check it with, since
+ * the site is the only thing that knows where it drew its camera.
+ *
+ * Here there is. `calibration/fake-map.html` is a slippy map with a header and
+ * a side panel of sizes we chose, served in place of openstreetmap.org so the
+ * app's own parser reads it for real. Drive it with the same gestures the
+ * recorder uses, solve for the camera with the same arithmetic the extension
+ * uses, and the answer has to be the layout we built in.
+ *
+ * It runs on both engines and at two window sizes on purpose: the claim under
+ * test is that the measurement does not depend on the browser, the window or
+ * the screen, and the way to hold that claim is to make it every time.
+ */
+import { test, expect } from '@playwright/test';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import { drive } from '../calibration/protocol.mjs';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const root = join(here, '../..');
+const fake = readFileSync(join(here, '../calibration/fake-map.html'), 'utf8');
+const mapmath = readFileSync(join(root, 'extension/mapmath.js'), 'utf8');
+
+/** The extension's own arithmetic, in this process. */
+const math = (() => {
+ const scope = { window: {} };
+ new Function('window', mapmath)(scope.window);
+ return scope.window.AzimutMapMath;
+})();
+
+/** The fake's URL, read back. Our own page and our own form — the real ones are
+ * read by `engine/mapsites.py` and by nothing else. */
+function viewOf(url) {
+ const [, zoom, lat, lon] = /map=([\d.]+)\/(-?[\d.]+)\/(-?[\d.]+)/.exec(url);
+ return {
+ lat: Number(lat),
+ lon: Number(lon),
+ zoom: Number(zoom),
+ bearing: 0,
+ projection: 'webmercator',
+ };
+}
+
+/** A header and a side panel of our choosing, wearing OpenStreetMap's host. */
+const CHROME = { head: 60, panel: 300 };
+const site = {
+ id: 'openstreetmap',
+ site: 'openstreetmap',
+ label: 'fake-map',
+ notches: 1,
+ url: `https://www.openstreetmap.org/?head=${CHROME.head}&panel=${CHROME.panel}#map=15/47.38846/2.35279`,
+};
+
+async function serve(page) {
+ await page.route('https://www.openstreetmap.org/**', (route) =>
+ route.fulfill({ contentType: 'text/html; charset=utf-8', body: fake })
+ );
+}
+
+/** Solve for the camera from each zoom the run recorded, as the panel does. */
+function cameras(recording) {
+ return recording.zooms.map((zoom) =>
+ math.centreFromZoom(
+ viewOf(recording.steps[zoom.from].url),
+ viewOf(recording.steps[zoom.to].url),
+ zoom.at
+ )
+ );
+}
+
+for (const shape of [
+ { name: 'a full window', viewport: { width: 1280, height: 800 }, ratio: 1 },
+ { name: 'a small window on a dense screen', viewport: { width: 720, height: 480 }, ratio: 1.25 },
+]) {
+ test.describe(shape.name, () => {
+ test.use({ viewport: shape.viewport, deviceScaleFactor: shape.ratio });
+
+ test('recovers the layout it was never told about', async ({ page }) => {
+ await serve(page);
+ const recording = await drive(page, site, { quiet: 300 });
+
+ // the gestures actually moved the map: four URLs, all different
+ expect(new Set(recording.steps.map((s) => s.url)).size).toBe(4);
+
+ const truth = await page.evaluate(() => window.__TRUE_CENTRE__());
+ for (const solved of cameras(recording)) {
+ expect(solved).not.toBeNull();
+ // A fifth decimal of latitude is about a metre, which is three pixels
+ // at level 17 — this page rounds its URL the way OpenStreetMap does, so
+ // that rounding is the floor under the answer and not the arithmetic.
+ expect(Math.abs(solved.x - truth.x)).toBeLessThan(3);
+ expect(Math.abs(solved.y - truth.y)).toBeLessThan(3);
+ }
+
+ // …and the layout we built in is the one that comes out
+ const [first] = cameras(recording);
+ expect(Math.abs(first.x - recording.window.w / 2 - CHROME.panel / 2)).toBeLessThan(3);
+ expect(Math.abs(first.y - recording.window.h / 2 - CHROME.head / 2)).toBeLessThan(3);
+ });
+
+ test('writes down a window in CSS pixels, whatever the screen is made of', async ({ page }) => {
+ await serve(page);
+ await page.goto(site.url);
+ const seen = await page.evaluate(() => ({
+ width: window.innerWidth,
+ height: window.innerHeight,
+ ratio: window.devicePixelRatio,
+ }));
+ // The window the recording is written in is the CSS one, on both engines
+ // and at either ratio — which is what makes a recording taken on one
+ // machine mean anything on another.
+ expect({ width: seen.width, height: seen.height }).toEqual(shape.viewport);
+ expect(seen.ratio).toBe(shape.ratio);
+ });
+ });
+}
+
+test.describe('when a site moves its furniture', () => {
+ test.use({ viewport: { width: 1280, height: 800 } });
+
+ test('measures the new layout rather than the one on file', async ({ page }) => {
+ await serve(page);
+ const wide = await drive(page, site, { quiet: 300 });
+ const moved = await drive(
+ page,
+ { ...site, url: 'https://www.openstreetmap.org/?head=0&panel=520#map=15/47.38846/2.35279' },
+ { quiet: 300 }
+ );
+ const [before] = cameras(wide);
+ const [after] = cameras(moved);
+ expect(Math.abs(after.x - before.x - (520 - CHROME.panel) / 2)).toBeLessThan(4);
+ expect(Math.abs(after.y - before.y + CHROME.head / 2)).toBeLessThan(4);
+ });
+});
diff --git a/frontend/package.json b/frontend/package.json
index ff5ae07..b3988d2 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -10,6 +10,7 @@
"test": "vitest run",
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
+ "calibrate:maps": "node calibration/record.mjs",
"check": "svelte-check --output human --threshold warning"
},
"devDependencies": {
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 2602e7b..939eb1f 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -15,12 +15,15 @@
import { startEvents, onEvent } from './lib/events.js';
import {
CASE_WORKSPACE,
+ HOME_WORKSPACE,
WORKSPACES,
TOOL_LABELS,
sidebarOpenForWorkspace,
workspaceOf,
toolFromHash,
} from './lib/workspaces.js';
+ import { guideFor } from './lib/guide.js';
+ import { openGuide } from './lib/navigate.js';
import { createToolLoader } from './lib/toolLoader.js';
import { loadEntityTypes } from './lib/entityTypes.svelte.js';
import Icon from './components/Icon.svelte';
@@ -35,10 +38,13 @@
import { analysisSearch, leaveAnalysisView } from './lib/analysisSearch.svelte.js';
// The rail holds the pipeline workspaces (docs/UI.md §3); tools are tabs
- // inside them. Two workspaces sit in the topbar rather than the rail: the
- // case, which is what the stages file into, and Settings, which is app
- // plumbing and not part of the working flow at all.
+ // inside them. Three workspaces sit in the topbar rather than the rail: home,
+ // which is where the app opens and is not a stage either; the case, which is
+ // what the stages file into; and Settings, which is app plumbing and not part
+ // of the working flow at all.
const TOOLS = [
+ { id: 'overview', label: TOOL_LABELS.overview, load: () => import('./tools/Overview.svelte') },
+ { id: 'guide', label: TOOL_LABELS.guide, load: () => import('./tools/Guide.svelte') },
{ id: 'board', label: TOOL_LABELS.board, load: () => import('./tools/Board.svelte') },
{ id: 'graph', label: TOOL_LABELS.graph, load: () => import('./tools/Graph.svelte') },
{ id: 'timeline', label: TOOL_LABELS.timeline, load: () => import('./tools/Timeline.svelte') },
@@ -66,6 +72,10 @@
let toolErrors = $state.raw({});
const TOOL_IDS = ALL_TOOLS.map((t) => t.id);
const toolLabel = (id) => ALL_TOOLS.find((t) => t.id === id)?.label ?? id;
+ // Name the tab the `?` will answer about, so the press is not a leap into a document.
+ const guideTitle = $derived(
+ guideFor(uiState.tool) ? `Guide: ${toolLabel(uiState.tool)}` : 'Read the guide'
+ );
// deep links: tool ids (#media, #proof, …) plus workspace aliases
// (#compose, #compose/post) — see lib/workspaces.js
@@ -176,14 +186,30 @@
toast(`Place saved from ${ev.site}: ${ev.title}`, 'ok', 5000);
if (caseState.current?.id === ev.case_id) reloadCase();
});
+ // The case's saved work, moved from another window onto it: a second app tab,
+ // or the map panel the extension draws over someone else's map. Silent, unlike
+ // the three above — the analyst did this themselves, just not here — and the
+ // reload is what puts it on the map and in the Saved panel.
+ onEvent('saved', (ev) => {
+ if (caseState.current?.id === ev.case_id) reloadCase();
+ });
</script>
<div class="shell">
<header class="topbar">
- <div class="brand">
+ <!-- The mark is the way home. It costs no rail seat and needs no label, which is
+ the whole reason home lives here: the rail reads as a sequence of stages and
+ an overview is not one of them, exactly as the case is not. -->
+ <button
+ class="brand"
+ class:topbar-active={activeWs?.id === HOME_WORKSPACE.id}
+ title="Home"
+ aria-label="Home"
+ onclick={() => openWorkspace(HOME_WORKSPACE)}
+ >
<Logo size={27} />
<span class="brand-name"><Wordmark height={13} /></span>
- </div>
+ </button>
<div class="case-group">
<CaseSwitcher />
<button
@@ -197,6 +223,20 @@
</button>
</div>
<div class="spacer"></div>
+ <!-- The one mark that answers "what is this tab I am standing in". It sits beside
+ the gear rather than in each toolbar so there is one of it, and it opens the
+ Guide on the section written about the current tool. Silent on the Guide
+ itself, which is the answer. -->
+ {#if uiState.tool !== 'guide'}
+ <button
+ class="btn btn-ghost btn-sm"
+ title={guideTitle}
+ aria-label={guideTitle}
+ onclick={() => openGuide(uiState.tool)}
+ >
+ <Icon name="help" size={16} />
+ </button>
+ {/if}
<button
class="btn btn-ghost btn-sm dotted"
class:topbar-active={uiState.tool === 'settings'}
@@ -315,7 +355,13 @@
display: flex;
align-items: center;
gap: 11px;
- padding-right: 6px;
+ padding: 4px 8px 4px 4px;
+ margin-left: -4px;
+ border-radius: var(--r-sm);
+ transition: background 0.15s var(--ease);
+ }
+ .brand:hover {
+ background: var(--bg-2);
}
.brand-name {
display: flex;
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 79e5dc0..de38ed0 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -126,6 +126,10 @@
angle: 'M5 4v15h15M5 19 20 6',
sun: 'M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10ZM12 1v3M12 20v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M1 12h3M20 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1',
moon: 'M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8Z',
+ // The guide, wherever it is asked for. A question mark rather than a book: the
+ // press means "what is this tab", not "open a document".
+ help: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-2.3 6.4a2.3 2.3 0 0 1 4.5.7c0 1.5-2.2 2-2.2 3.4M12 16.7h.01',
+ keyboard: 'M3 7h18a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1Zm3.5 3.2h.01m3.2 0h.01m3.2 0h.01m3.2 0h.01M8 13.8h8',
};
</script>
diff --git a/frontend/src/lib/entityFilter.js b/frontend/src/lib/entityFilter.js
index ce36b12..88842a5 100644
--- a/frontend/src/lib/entityFilter.js
+++ b/frontend/src/lib/entityFilter.js
@@ -84,7 +84,7 @@ export const QUESTIONS = [
{
id: 'loose',
label: 'Nothing linked yet',
- hint: 'in the case, connected to nothing — the unexploited material',
+ hint: 'in the case, and connected to nothing at all',
terms: { connections: 'none' },
},
{
diff --git a/frontend/src/lib/entityTypes.svelte.js b/frontend/src/lib/entityTypes.svelte.js
index 2316a44..170b46c 100644
--- a/frontend/src/lib/entityTypes.svelte.js
+++ b/frontend/src/lib/entityTypes.svelte.js
@@ -66,6 +66,13 @@ export function familyReads(family) {
return registry.types.find((entry) => entry.family === family)?.family_reads ?? '';
}
+/** A family as a screen writes it. The registry stores the slug, and the Board, the
+ * Graph and the home page each used to capitalise their own copy of it. */
+export function familyTitle(family) {
+ const slug = String(family ?? '');
+ return slug.charAt(0).toUpperCase() + slug.slice(1);
+}
+
/** The icon that stands for a type, or null until the registry lands.
*
* The registry is where this lives, so adding a type is still one entry in
diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.js
index 3b3d46f..479cb12 100644
--- a/frontend/src/lib/extBridge.js
+++ b/frontend/src/lib/extBridge.js
@@ -119,6 +119,42 @@ export function handOffPost(payload, { timeoutMs = 2000, win = window } = {}) {
});
}
+/**
+ * Hand a prepared image to the extension, which opens the engine and gives it
+ * the picture.
+ *
+ * Same contract as the thread above, and the same reason for the short timeout:
+ * the app is holding a click, and a slow no would spend it and open nothing.
+ * Resolving means the extension **took** it, never that the engine liked it — it
+ * has not opened the tab yet. A rejection means the app still owns the hand-off
+ * and does what it always did: open the page, with the image on the clipboard or
+ * saved to disk.
+ *
+ * Unlike the thread, the bytes go through here. What Reverse Search prepares is
+ * a frame off a canvas — a video still, adjustments baked in — so there is no
+ * path for the extension to read it back from.
+ */
+export function handOffReverse(payload, { timeoutMs = 2000, win = window } = {}) {
+ return new Promise((resolve, reject) => {
+ const id = `rev-${++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 !== 'reverse-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: 'reverse-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 capture
@@ -133,3 +169,135 @@ export function onActivated(cb, win = window) {
win.addEventListener('message', onMessage);
return () => win.removeEventListener('message', onMessage);
}
+
+/**
+ * Subscribe to a bridge announcing itself: the manifest injected it at
+ * document_start, or the background re-injected it after an update. Either way
+ * the version it carries is the one now running. Returns an unsubscribe function.
+ */
+export function onBridgeHello(cb, win = window) {
+ const onMessage = (event) => {
+ if (event.origin !== win.location.origin) return;
+ const msg = event.data;
+ if (msg && msg.channel === CHANNEL && msg.type === 'bridge-hello') cb(msg.version || null);
+ };
+ win.addEventListener('message', onMessage);
+ return () => win.removeEventListener('message', onMessage);
+}
+
+/**
+ * Every live bridge on this tab, as `[{version}]`.
+ *
+ * `ping` is the one message every version of the extension has ever answered,
+ * which is exactly why detection hangs off it rather than off `ext-state`: a
+ * copy installed before the update button existed cannot answer the newer
+ * message, and asking only that would report an extension the analyst is plainly
+ * running as "not detected".
+ *
+ * Counting is the other half of its job. Two copies can be loaded at once (see
+ * `extensionState`), and a copy too old to identify itself still answers here —
+ * so the number of pongs is the honest answer to "how many extensions are on
+ * this channel", where the number of `ext-state` replies is only "how many can
+ * the app manage".
+ *
+ * Never rejects: silence means nothing is installed, which is an answer.
+ */
+export function pingExtensions({ timeoutMs = 700, win = window } = {}) {
+ return new Promise((resolve) => {
+ const id = `ping-${++seq}`;
+ const found = [];
+ function onMessage(event) {
+ if (event.origin !== win.location.origin) return;
+ const msg = event.data;
+ if (!msg || msg.channel !== CHANNEL || msg.type !== 'pong' || msg.id !== id) return;
+ found.push({ version: msg.version || null });
+ }
+ win.addEventListener('message', onMessage);
+ setTimeout(() => {
+ win.removeEventListener('message', onMessage);
+ resolve(found);
+ }, timeoutMs);
+ win.postMessage({ channel: CHANNEL, type: 'ping', id }, win.location.origin);
+ });
+}
+
+/**
+ * Every copy of the extension loaded on this tab that can identify itself, each
+ * with the version the browser parsed, its extension id, and the install stamp
+ * the *running* code was loaded from (`engine/extinstall.py` writes it; null
+ * means a folder the app doesn't own).
+ *
+ * A copy older than this message answers nothing here. That is not "absent" —
+ * `pingExtensions` is what says whether anything is loaded at all.
+ *
+ * Collects for the whole window instead of resolving on the first answer, which
+ * is the one thing this cannot do. Chrome derives the extension id from the
+ * folder path, so someone who loads the app-owned copy without removing their old
+ * unzip is running two extensions: same name, same channel, same message id, two
+ * replies. Resolving on the first would report a coin toss, and the caller needs
+ * to know there are two so it can say which to remove.
+ *
+ * Resolves to `[]` when nothing answers — not installed, or too old to know this
+ * message. Never rejects: "no extension" is an answer, not a failure.
+ */
+export function extensionState({ timeoutMs = 700, win = window } = {}) {
+ return new Promise((resolve) => {
+ const id = `state-${++seq}`;
+ const found = [];
+ function onMessage(event) {
+ if (event.origin !== win.location.origin) return;
+ const msg = event.data;
+ if (!msg || msg.channel !== CHANNEL || msg.type !== 'ext-state-result' || msg.id !== id) return;
+ if (msg.ok) {
+ found.push({
+ version: msg.version || null,
+ extensionId: msg.extensionId || null,
+ loaded: msg.loaded ?? null,
+ // "development" for a folder or a temporary add-on, "normal" for a
+ // packaged copy the browser manages. Null from a copy predating it.
+ installType: msg.installType ?? null,
+ });
+ }
+ }
+ win.addEventListener('message', onMessage);
+ setTimeout(() => {
+ win.removeEventListener('message', onMessage);
+ resolve(found);
+ }, timeoutMs);
+ win.postMessage({ channel: CHANNEL, type: 'ext-state', id }, win.location.origin);
+ });
+}
+
+/**
+ * Ask the copy installed at `installId` to restart, so the browser re-reads the
+ * folder the app just rewrote.
+ *
+ * The `installId` is not decoration: with two copies loaded, an unaddressed
+ * reload restarts whichever answers first, which is silent and looks exactly
+ * like an update that didn't take. A copy that isn't the one named ignores it.
+ *
+ * Resolving means the message was *taken*, never that the new code is running —
+ * the extension dies mid-reply by design. What proves the update landed is
+ * reading the stamp back afterwards, so a timeout here is inconclusive rather
+ * than fatal and the caller verifies either way.
+ */
+export function reloadExtension(installId, { timeoutMs = 2000, win = window } = {}) {
+ return new Promise((resolve, reject) => {
+ const id = `reload-${++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 !== 'ext-reload-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: 'ext-reload', id, installId }, win.location.origin);
+ });
+}
diff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.js
index 02c4e99..b492e7f 100644
--- a/frontend/src/lib/extBridge.test.js
+++ b/frontend/src/lib/extBridge.test.js
@@ -1,6 +1,9 @@
// @vitest-environment happy-dom
import { describe, it, expect, afterEach } from 'vitest';
-import { extensionVersion, extensionOutdated, captureTab, handOffPost, onActivated } from './extBridge.js';
+import {
+ extensionVersion, extensionOutdated, captureTab, handOffPost, handOffReverse, onActivated,
+ extensionState, pingExtensions, reloadExtension, onBridgeHello,
+} 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
@@ -141,3 +144,200 @@ describe('handOffPost', () => {
off();
});
});
+
+// And the same again for a reverse-image hand-off, which is the other thing a
+// click can stand down for.
+function fakeReverseBridge(answer) {
+ const onMessage = (event) => {
+ const msg = event.data;
+ if (!msg || msg.channel !== 'azimut-capture-ext' || msg.type !== 'reverse-handoff') return;
+ window.postMessage(
+ { channel: 'azimut-capture-ext', type: 'reverse-handoff-result', id: msg.id, ...answer(msg) },
+ window.location.origin
+ );
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+}
+
+describe('handOffReverse', () => {
+ const payload = { url: 'https://lens.google.com/', image: { name: 'a.png', type: 'image/png', data: '' } };
+
+ it('resolves as soon as the extension takes it, tab unopened', async () => {
+ const off = fakeReverseBridge(() => ({ ok: true, accepted: true }));
+ await expect(handOffReverse(payload)).resolves.toBe(true);
+ off();
+ });
+
+ it('carries the engine and the image through to the bridge', async () => {
+ let seen = null;
+ const off = fakeReverseBridge((msg) => {
+ seen = msg.payload;
+ return { ok: true, accepted: true };
+ });
+ await handOffReverse(payload);
+ expect(seen).toEqual(payload);
+ off();
+ });
+
+ it('rejects when the extension declines, so the app opens the engine itself', async () => {
+ const off = fakeReverseBridge(() => ({ ok: false, error: 'that image is too large to hand over' }));
+ await expect(handOffReverse(payload)).rejects.toThrow('too large');
+ off();
+ });
+
+ it('rejects on silence, which is what no extension installed looks like', async () => {
+ await expect(handOffReverse(payload, { timeoutMs: 120 })).rejects.toThrow('did not answer');
+ });
+
+ it('ignores a reply meant for another request', async () => {
+ const off = fakeReverseBridge((msg) => ({ ok: true, id: `${msg.id}-not` }));
+ await expect(handOffReverse(payload, { timeoutMs: 120 })).rejects.toThrow('did not answer');
+ off();
+ });
+});
+
+// A fake bridge for the update routes: same shape as the one above, generalised
+// over the request/reply pair so two of them can be mounted at once — which is
+// the case that matters, because two copies of the extension can be loaded in
+// one tab.
+function fakeRelay(requestType, replyType, answer) {
+ const onMessage = (event) => {
+ const msg = event.data;
+ if (!msg || msg.channel !== 'azimut-capture-ext' || msg.type !== requestType) return;
+ window.postMessage(
+ { channel: 'azimut-capture-ext', type: replyType, id: msg.id, ...answer(msg) },
+ window.location.origin
+ );
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+}
+
+const state = (installId, payload, extensionId = 'ext-a') => () => ({
+ ok: true,
+ version: '0.3.0',
+ extensionId,
+ loaded: { install_id: installId, payload },
+});
+
+describe('extensionState', () => {
+ it('collects every copy that answers, not just the first', async () => {
+ // Chrome derives the extension id from the folder path, so the analyst who
+ // loads the app's copy without removing their old unzip is running two
+ // extensions on one channel. Resolving on the first reply would report a
+ // coin toss, and the caller could not say which one to remove.
+ const mine = fakeRelay('ext-state', 'ext-state-result', state('mine', 'digest', 'ext-a'));
+ const theirs = fakeRelay('ext-state', 'ext-state-result', () => ({
+ ok: true, version: '0.2.0', extensionId: 'ext-b', loaded: null,
+ }));
+
+ const found = await extensionState({ timeoutMs: 80 });
+
+ expect(found).toHaveLength(2);
+ expect(found.map((r) => r.extensionId).sort()).toEqual(['ext-a', 'ext-b']);
+ expect(found.find((r) => r.extensionId === 'ext-a').loaded.install_id).toBe('mine');
+ mine();
+ theirs();
+ });
+
+ it('resolves empty when nothing answers, because that is an answer', async () => {
+ // not installed, or too old to know this message: neither is a failure
+ await expect(extensionState({ timeoutMs: 60 })).resolves.toEqual([]);
+ });
+
+ it('ignores a reply correlated to someone else', async () => {
+ const off = fakeRelay('ext-state', 'ext-state-result', (msg) => ({
+ ok: true, version: '0.3.0', extensionId: 'ext-a', loaded: null, id: `${msg.id}-not`,
+ }));
+ await expect(extensionState({ timeoutMs: 60 })).resolves.toEqual([]);
+ off();
+ });
+
+ it('drops a copy that refused', async () => {
+ const off = fakeRelay('ext-state', 'ext-state-result', () => ({ ok: false, error: 'nope' }));
+ await expect(extensionState({ timeoutMs: 60 })).resolves.toEqual([]);
+ off();
+ });
+});
+
+describe('reloadExtension', () => {
+ it('names the install it means, so another copy stays put', async () => {
+ let asked = null;
+ const off = fakeRelay('ext-reload', 'ext-reload-result', (msg) => {
+ asked = msg.installId;
+ return { ok: true, reloading: true };
+ });
+ await expect(reloadExtension('mine')).resolves.toBe(true);
+ expect(asked).toBe('mine');
+ off();
+ });
+
+ it('rejects when the copy that answers is not the one named', async () => {
+ const off = fakeRelay('ext-reload', 'ext-reload-result', () => ({
+ ok: false, error: 'another copy of the extension',
+ }));
+ await expect(reloadExtension('mine')).rejects.toThrow('another copy');
+ off();
+ });
+
+ it('rejects on silence, which the caller treats as inconclusive', async () => {
+ // The extension dies mid-reply by design, so a timeout here says nothing
+ // about whether the update landed — Settings verifies by probing after.
+ await expect(reloadExtension('mine', { timeoutMs: 60 })).rejects.toThrow('did not answer');
+ });
+});
+
+describe('onBridgeHello', () => {
+ it('fires with the version a freshly injected bridge announces', async () => {
+ const seen = [];
+ const off = onBridgeHello((v) => seen.push(v));
+ window.postMessage(
+ { channel: 'azimut-capture-ext', type: 'bridge-hello', version: '0.4.0' },
+ window.location.origin
+ );
+ await new Promise((r) => setTimeout(r, 10));
+ expect(seen).toEqual(['0.4.0']);
+ off();
+ window.postMessage(
+ { channel: 'azimut-capture-ext', type: 'bridge-hello', version: '0.5.0' },
+ window.location.origin
+ );
+ await new Promise((r) => setTimeout(r, 10));
+ expect(seen).toEqual(['0.4.0']);
+ });
+});
+
+describe('pingExtensions', () => {
+ it('counts a copy too old to answer anything newer', async () => {
+ // `ping` is the only message every shipped version has ever answered. An
+ // extension installed before the update button knows nothing of `ext-state`,
+ // so detection that asked only that reported it as absent — the bug this
+ // pins. Here the old bridge answers ping and stays silent on the rest.
+ const oldBridge = fakeRelay('ping', 'pong', () => ({ version: '0.2.0' }));
+
+ const [bridges, managed] = await Promise.all([
+ pingExtensions({ timeoutMs: 80 }),
+ extensionState({ timeoutMs: 80 }),
+ ]);
+
+ expect(bridges).toEqual([{ version: '0.2.0' }]);
+ expect(managed).toEqual([]);
+ oldBridge();
+ });
+
+ it('counts both copies when two are loaded', async () => {
+ const a = fakeRelay('ping', 'pong', () => ({ version: '0.3.0' }));
+ const b = fakeRelay('ping', 'pong', () => ({ version: '0.2.0' }));
+ await expect(pingExtensions({ timeoutMs: 80 })).resolves.toHaveLength(2);
+ a();
+ b();
+ });
+
+ it('resolves empty on silence, and ignores a reply meant for someone else', async () => {
+ await expect(pingExtensions({ timeoutMs: 60 })).resolves.toEqual([]);
+ const off = fakeRelay('ping', 'pong', (msg) => ({ version: '0.3.0', id: `${msg.id}-not` }));
+ await expect(pingExtensions({ timeoutMs: 60 })).resolves.toEqual([]);
+ off();
+ });
+});
diff --git a/frontend/src/lib/extInstall.js b/frontend/src/lib/extInstall.js
new file mode 100644
index 0000000..8ff0120
--- /dev/null
+++ b/frontend/src/lib/extInstall.js
@@ -0,0 +1,120 @@
+/**
+ * Which capture extension this browser is running, and whether the app can
+ * update it.
+ *
+ * The app owns a folder (`engine/extinstall.py`) and stamps an install id and a
+ * payload digest into it. An extension loaded from that folder reports the stamp
+ * it was loaded from, so three questions get separate answers: is anything
+ * installed, is it the copy the app controls, and is it behind what the app
+ * ships.
+ *
+ * A fourth answer sits beside them on Firefox, which refuses an unsigned
+ * extension: the permanent install there is a signed XPI the browser manages and
+ * updates itself, so the app can report it and must not offer to rewrite it.
+ *
+ * Two probes, and the split matters. `ping` has been answered by every version
+ * of the extension ever shipped, so it is what counts live copies. `ext-state`
+ * is newer, so only a copy that carries the update code answers it — an install
+ * that predates this feature is loaded, visible, and silent there. Judging
+ * "installed" by `ext-state` alone would report the extension the analyst is
+ * plainly using as absent, which is the one thing this screen must never say.
+ *
+ * Pure on purpose — the probing and the writing live in Settings, and the rules
+ * are the part worth testing on their own.
+ *
+ * The digest, not the version, decides "behind". The bundled version deliberately
+ * stays put when a release leaves the extension alone, and within a development
+ * cycle it is already the app's own version and cannot move at all — so a version
+ * comparison is blind exactly when the bytes are changing. (The rail's dot still
+ * compares versions, in `staleness.js`: across releases the two agree, and it
+ * has no bridge to ask.)
+ */
+
+import { extensionOutdated } from './extBridge.js';
+
+/**
+ * @param {{path?: string, staged?: boolean, bundled?: {version?: string|null, payload?: string|null}, folder?: {install_id?: string, version?: string|null, payload?: string|null}|null}|null} server
+ * What `GET /api/settings/extension` reported.
+ * @param {{bridges?: Array<{version: string|null}>|null, managed?: Array<{version: string|null, extensionId: string|null, loaded: object|null}>|null}} probes
+ * `bridges` = every copy that answered `ping`. `managed` = those that also
+ * answered `ext-state`.
+ */
+export function classify(server, { bridges, managed } = {}) {
+ const folder = server?.folder ?? null;
+ const bundledPayload = server?.bundled?.payload ?? null;
+ const live = bridges ?? [];
+ const answered = managed ?? [];
+ // The app's folder is identified by the id it minted, so a copy loaded from
+ // anywhere else cannot claim to be it.
+ const owned = folder?.install_id
+ ? answered.find((r) => r.loaded?.install_id === folder.install_id) ?? null
+ : null;
+ // Copies that named themselves and are not ours — we can say which id to
+ // remove. Anything else loaded is counted but cannot be named: a copy too old
+ // to answer `ext-state` has no way to report its id.
+ const others = answered.filter((r) => r !== owned);
+ const unnamed = Math.max(0, live.length - answered.length);
+ // A copy the browser installed as a package rather than read out of a folder.
+ // On Firefox that is the signed XPI, which is the only permanent install it
+ // allows and which nothing here can rewrite — so it must not be mistaken for a
+ // stale unzip and answered with "remove it and load the folder instead".
+ const sealed = !owned && answered.some((r) => r.installType === 'normal');
+ const bundledVersion = server?.bundled?.version ?? null;
+ const detectedVersion = owned?.version ?? others[0]?.version ?? live[0]?.version ?? null;
+ return {
+ // absent: nothing is loaded. signed: a packaged copy, updated by the browser
+ // from the app's own update manifest. foreign: something is loaded from a
+ // folder that isn't ours — an old manual unzip, a dev checkout, or a copy
+ // predating this feature. duplicate: ours is loaded and so is something
+ // else, which is Chrome deriving the extension id from the folder path.
+ status: !live.length
+ ? 'absent'
+ : owned
+ ? others.length || unnamed
+ ? 'duplicate'
+ : 'owned'
+ : sealed
+ ? 'signed'
+ : 'foreign',
+ path: server?.path ?? '',
+ staged: Boolean(server?.staged),
+ bundledVersion,
+ installed: owned,
+ others,
+ // How many loaded copies could not identify themselves. Non-zero means the
+ // analyst has an extension the app cannot manage or name, so the copy has to
+ // describe it rather than point at an id.
+ unnamed,
+ // The version to show when we have no stamp to read one from.
+ detectedVersion,
+ // The running copy leads what this build ships. Only Firefox can produce it:
+ // it updates a signed add-on from the release manifest without knowing which
+ // Azimut is installed, where every other road hands the extension out of the
+ // app and so can never get ahead of it. Nothing here can refuse that update —
+ // the browser owns it — so the app names it instead, and the analyst is told
+ // to move the app rather than left with features reporting they could not run.
+ ahead: extensionOutdated(bundledVersion, detectedVersion),
+ // Installed from our folder, but from an older payload than the app ships.
+ // Unknown (false) when nothing owned answered: there is nothing to update
+ // yet, only something to install.
+ updateAvailable: Boolean(owned && bundledPayload && owned.loaded?.payload !== bundledPayload),
+ // The folder itself is current — so an update that reports `staged` is
+ // distinguishable from one that never wrote anything.
+ folderCurrent: Boolean(folder && bundledPayload && folder.payload === bundledPayload),
+ installId: folder?.install_id ?? null,
+ };
+}
+
+/**
+ * Did the reload land? Compares the stamp the freshly probed copy was loaded
+ * from against what the app ships.
+ *
+ * Separate from `classify` because it answers a narrower question at a specific
+ * moment, and because the honest answer is often "no" for a boring reason: the
+ * extension restarts asynchronously, so the first probe after a reload can still
+ * be the old context. The caller retries.
+ */
+export function reloadLanded(server, probes) {
+ const verdict = classify(server, probes);
+ return Boolean(verdict.installed) && !verdict.updateAvailable;
+}
diff --git a/frontend/src/lib/extInstall.test.js b/frontend/src/lib/extInstall.test.js
new file mode 100644
index 0000000..3003b8e
--- /dev/null
+++ b/frontend/src/lib/extInstall.test.js
@@ -0,0 +1,201 @@
+import { describe, it, expect } from 'vitest';
+import { classify, reloadLanded } from './extInstall.js';
+
+// Five states and one comparison, and every one of them has a wrong answer that
+// looks plausible: reporting a foreign copy as updatable, missing that two are
+// loaded, trusting the version where only the digest moves, or telling a Firefox
+// analyst to remove the signed copy their browser will actually keep.
+
+const server = ({ installId = 'mine', folderPayload = 'new', bundled = 'new', ...rest } = {}) => ({
+ path: '/home/a/Azimut/.azimut/extension',
+ staged: false,
+ bundled: { version: '0.3.0', payload: bundled },
+ folder: installId ? { install_id: installId, version: '0.3.0', payload: folderPayload } : null,
+ ...rest,
+});
+
+const responder = (installId, payload, extensionId = 'ext-a', installType = null) => ({
+ version: '0.3.0',
+ extensionId,
+ loaded: installId ? { install_id: installId, payload } : null,
+ installType,
+});
+
+/** Both probes for a set of copies that can all identify themselves: each one
+ * answers `ping` and `ext-state`. */
+const probes = (managed) => ({ bridges: managed.map((m) => ({ version: m.version })), managed });
+
+describe('classify', () => {
+ it('reads nothing answering as nothing installed', () => {
+ const v = classify(server(), probes([]));
+ expect(v.status).toBe('absent');
+ expect(v.updateAvailable).toBe(false);
+ expect(v.installed).toBe(null);
+ // The path is still reported: it is what the analyst has to paste to install.
+ expect(v.path).toContain('.azimut/extension');
+ });
+
+ it('recognises the copy loaded from the folder it stamped', () => {
+ const v = classify(server(), probes([responder('mine', 'new')]));
+ expect(v.status).toBe('owned');
+ expect(v.updateAvailable).toBe(false);
+ expect(v.installed.extensionId).toBe('ext-a');
+ expect(v.installId).toBe('mine');
+ });
+
+ it('offers the update on the digest, not the version', () => {
+ // Within a development cycle the bundled version is already the app's own and
+ // cannot go up, so a version comparison is blind exactly when the bytes move.
+ const v = classify(server({ bundled: 'new' }), probes([responder('mine', 'old')]));
+ expect(v.status).toBe('owned');
+ expect(v.updateAvailable).toBe(true);
+ });
+
+ it('reads a copy with no stamp as one the app does not own', () => {
+ const v = classify(server(), probes([responder(null, null, 'ext-b')]));
+ expect(v.status).toBe('foreign');
+ // Nothing to update: there is something to install, which is a different
+ // sentence and a different button.
+ expect(v.updateAvailable).toBe(false);
+ expect(v.installed).toBe(null);
+ expect(v.others).toHaveLength(1);
+ });
+
+ it('reads a stamp from a different folder as foreign too', () => {
+ // Two Azimut installs, or a folder restored from a backup: the id is what
+ // decides, never the mere presence of a stamp.
+ const v = classify(server({ installId: 'mine' }), probes([responder('someone-else', 'new', 'ext-b')]));
+ expect(v.status).toBe('foreign');
+ });
+
+ it('reads a packaged copy as one the browser owns, not as a stale unzip', () => {
+ // Firefox's permanent install is a signed XPI: no stamp to read, and nothing
+ // the app could rewrite. Called foreign, the screen would tell the analyst to
+ // remove the only install their browser keeps.
+ const v = classify(server(), probes([responder(null, null, 'ext-b', 'normal')]));
+ expect(v.status).toBe('signed');
+ expect(v.updateAvailable).toBe(false);
+ expect(v.installed).toBe(null);
+ });
+
+ it('keeps the folder it owns ahead of a packaged copy loaded beside it', () => {
+ const v = classify(
+ server(),
+ probes([responder('mine', 'new'), responder(null, null, 'ext-b', 'normal')]),
+ );
+ expect(v.status).toBe('duplicate');
+ });
+
+ it('names a copy that leads the app, which only Firefox can produce', () => {
+ // A signed add-on is updated by the browser from the release manifest, which
+ // knows nothing about the Azimut installed beside it. Every other road hands
+ // the extension out of the app, so this is the one state the app cannot cause
+ // and cannot refuse — only report.
+ const v = classify(
+ { ...server(), bundled: { version: '0.3.0', payload: 'new' } },
+ probes([{ ...responder(null, null, 'ext-b', 'normal'), version: '0.4.0' }]),
+ );
+ expect(v.status).toBe('signed');
+ expect(v.ahead).toBe(true);
+ });
+
+ it('is not ahead when the running copy matches or trails what we ship', () => {
+ expect(classify(server(), probes([responder('mine', 'new')])).ahead).toBe(false);
+ const trailing = classify(
+ { ...server(), bundled: { version: '0.4.0', payload: 'new' } },
+ probes([{ ...responder(null, null, 'ext-b', 'normal'), version: '0.3.0' }]),
+ );
+ expect(trailing.ahead).toBe(false);
+ });
+
+ it('leaves a copy too old to say how it was installed as foreign', () => {
+ // The field arrived with the signed road. Absent means "cannot tell", and the
+ // unpacked folder is what every copy before it was.
+ const v = classify(server(), probes([responder(null, null, 'ext-b', null)]));
+ expect(v.status).toBe('foreign');
+ });
+
+ it('spots two copies loaded at once and keeps them apart', () => {
+ const v = classify(server(), probes([
+ responder('mine', 'old', 'ext-a'),
+ responder(null, null, 'ext-b'),
+ ]));
+ expect(v.status).toBe('duplicate');
+ // The owned one is still what the update targets — the point of naming it.
+ expect(v.installed.extensionId).toBe('ext-a');
+ expect(v.updateAvailable).toBe(true);
+ expect(v.others.map((o) => o.extensionId)).toEqual(['ext-b']);
+ });
+
+ it('does not claim an update when the app ships no extension', () => {
+ // An unusual build with no bundled payload has nothing to offer, so it says
+ // nothing rather than offering an update to null.
+ const v = classify(server({ bundled: null }), probes([responder('mine', 'old')]));
+ expect(v.updateAvailable).toBe(false);
+ });
+
+ it('separates the folder being current from the running copy being current', () => {
+ // This is what tells "written but the browser held the old files" apart from
+ // "nothing was written".
+ const v = classify(server({ folderPayload: 'new', bundled: 'new', staged: true }), probes([
+ responder('mine', 'old'),
+ ]));
+ expect(v.folderCurrent).toBe(true);
+ expect(v.updateAvailable).toBe(true);
+ expect(v.staged).toBe(true);
+ });
+
+ // The regression that shipped: an extension installed before the update button
+ // existed runs the old bridge, which has no `ext-state` route. It answers
+ // `ping` and nothing else. Judged on `ext-state` alone it read as "not
+ // detected" — on a browser visibly running it.
+ it('recognises a copy too old to identify itself', () => {
+ const v = classify(server({ installId: null }), {
+ bridges: [{ version: '0.2.0' }],
+ managed: [],
+ });
+ expect(v.status).toBe('foreign');
+ expect(v.detectedVersion).toBe('0.2.0');
+ // It cannot be named, only counted: an old bridge has no way to report an id.
+ expect(v.unnamed).toBe(1);
+ expect(v.others).toHaveLength(0);
+ expect(v.updateAvailable).toBe(false);
+ });
+
+ it('still spots a duplicate when the second copy cannot name itself', () => {
+ // Loading the app folder without removing the old install: ours answers both
+ // probes, theirs only the first. The count is what catches it.
+ const v = classify(server(), {
+ bridges: [{ version: '0.3.0' }, { version: '0.2.0' }],
+ managed: [responder('mine', 'new', 'ext-a')],
+ });
+ expect(v.status).toBe('duplicate');
+ expect(v.installed.extensionId).toBe('ext-a');
+ expect(v.unnamed).toBe(1);
+ });
+
+ it('survives a server read that failed and a probe that never ran', () => {
+ expect(classify(null, {}).status).toBe('absent');
+ expect(classify(null, {}).path).toBe('');
+ });
+});
+
+describe('reloadLanded', () => {
+ it('is true once the running copy reports the payload the app ships', () => {
+ expect(reloadLanded(server({ bundled: 'new' }), probes([responder('mine', 'new')]))).toBe(true);
+ });
+
+ it('is false while the old context is still the one answering', () => {
+ // The restart is asynchronous and re-injects the bridge when it lands, so the
+ // first probe after a reload can still reach the context going away.
+ expect(reloadLanded(server({ bundled: 'new' }), probes([responder('mine', 'old')]))).toBe(false);
+ });
+
+ it('is false when nothing answers, which is the reload not being back yet', () => {
+ expect(reloadLanded(server(), probes([]))).toBe(false);
+ });
+
+ it('is false for a foreign copy, which no reload of ours could have changed', () => {
+ expect(reloadLanded(server(), probes([responder(null, null, 'ext-b')]))).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.js
index 5677cd2..0fe0733 100644
--- a/frontend/src/lib/extension.test.js
+++ b/frontend/src/lib/extension.test.js
@@ -5,7 +5,7 @@
// This keeps the extension test-covered from the existing frontend harness
// instead of a second npm project inside extension/.
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
@@ -27,7 +27,10 @@ function makeChrome(overrides = {}) {
},
tabs: {
captureVisibleTab: vi.fn(async () => 'data:image/png;base64,xyz'),
+ // the map tools panel, when one is open on that tab
+ sendMessage: vi.fn(async () => ({ ok: true })),
create: vi.fn(async () => ({ id: 7 })),
+ query: vi.fn(async () => [{ id: 11 }, { id: 12 }]),
// the worker waits for "complete"; the stub says so on the next tick
onUpdated: {
addListener: vi.fn((cb) => setTimeout(() => cb(7, { status: 'complete' }), 0)),
@@ -36,10 +39,15 @@ function makeChrome(overrides = {}) {
},
scripting: { executeScript: vi.fn() },
notifications: { create: vi.fn() },
+ // How the browser installed this copy. Needs no permission, and separates a
+ // folder the app rewrites from a signed package it cannot touch.
+ management: { getSelf: vi.fn(async () => ({ installType: 'development' })) },
runtime: {
getManifest: () => ({ version: '9.9.9' }),
getURL: (p) => `chrome-extension://id/${p}`,
onMessage: { addListener: vi.fn() },
+ // the panels' end of the nudge stream: one port per open panel
+ onConnect: { addListener: vi.fn() },
},
...overrides,
};
@@ -67,7 +75,7 @@ function load({ chrome = makeChrome(), fetchImpl, imageBitmap, canvasLog } = {})
'createImageBitmap',
'OffscreenCanvas',
'btoa',
- `${source}\n;return { cropDataUrl, ingest, handle, settings, handOff };`
+ `${source}\n;return { cropDataUrl, ingest, handle, settings, handOff, handOffReverse, loadedStamp, reattachBridge, frameEvent, panels, pumpEvents, stopEvents };`
);
return factory(
chrome,
@@ -170,12 +178,43 @@ describe('handle: capture-tab (the app relay)', () => {
const { handle } = load({ chrome });
const res = await handle(
{ type: 'capture-tab' },
- { tab: { url: 'http://127.0.0.1:8477/', windowId: 7 } }
+ { tab: { id: 3, url: 'http://127.0.0.1:8477/', windowId: 7 } }
);
expect(res).toEqual({ ok: true, dataUrl: 'data:image/png;base64,xyz' });
expect(chrome.tabs.captureVisibleTab).toHaveBeenCalledWith(7, { format: 'png' });
});
+ it('takes the map tools panel out of the frame, and puts it back', async () => {
+ // captureVisibleTab photographs the page as composited, injected chrome
+ // included — a reference photograph floating over the map would land in the
+ // case looking like part of the ground
+ const order = [];
+ const chrome = makeChrome();
+ chrome.tabs.sendMessage = vi.fn(async (id, msg) => order.push(['tell', id, msg.hide]));
+ chrome.tabs.captureVisibleTab = vi.fn(async () => {
+ order.push(['grab']);
+ return 'data:image/png;base64,xyz';
+ });
+ const { handle } = load({ chrome });
+
+ await handle({ type: 'capture-tab' }, { tab: { id: 3, url: 'http://127.0.0.1:8477/', windowId: 7 } });
+ expect(order).toEqual([['tell', 3, true], ['grab'], ['tell', 3, false]]);
+ });
+
+ it('captures a tab with no panel on it all the same', async () => {
+ const chrome = makeChrome();
+ // no listener on that tab: the browser rejects, and that is not an error
+ chrome.tabs.sendMessage = vi.fn(async () => {
+ throw new Error('Could not establish connection');
+ });
+ const { handle } = load({ chrome });
+ const res = await handle(
+ { type: 'capture-tab' },
+ { tab: { id: 3, url: 'http://127.0.0.1:8477/', windowId: 7 } }
+ );
+ expect(res.ok).toBe(true);
+ });
+
it('rejects unknown message types', async () => {
const { handle } = load({});
const res = await handle({ type: 'nope' }, { tab: null });
@@ -183,6 +222,65 @@ describe('handle: capture-tab (the app relay)', () => {
});
});
+describe('the map tools panel’s own scripts', () => {
+ it('injects files that exist, with the panel last', () => {
+ // they are flat classic scripts sharing one scope: each reads the globals
+ // the ones before it left, and a name that is not on disk fails as a panel
+ // that simply never appears
+ const listed = /const MAP_FILES = \[([\s\S]*?)\];/.exec(source)[1];
+ const files = [...listed.matchAll(/"([^"]+)"/g)].map((m) => m[1]);
+ expect(files.at(-1)).toBe('mapoverlay.js');
+ for (const name of files) {
+ expect(existsSync(join(here, '../../../extension/', name)), name).toBe(true);
+ }
+ });
+});
+
+describe('handle: map-file (a picture for a reference window)', () => {
+ const png = () => ({
+ type: 'image/png',
+ arrayBuffer: async () => new Uint8Array([0xff, 0x00, 0x10]).buffer,
+ });
+
+ it('reads one case file with the pairing token and carries it as base64', async () => {
+ // a message carries a string, never a blob: the panel decodes it back into a
+ // bitmap and paints it, which is what gets a picture past a map site's CSP
+ const fetchImpl = vi.fn(async () => ({ ok: true, status: 200, blob: async () => png() }));
+ const { handle } = load({ fetchImpl });
+
+ const res = await handle({ type: 'map-file', caseId: 'case-1', path: 'media/roof.png' }, {});
+ expect(res).toEqual({ ok: true, file: { type: 'image/png', data: btoa('\xff\x00\x10') } });
+ expect(fetchImpl.mock.calls[0][0]).toBe(
+ 'http://127.0.0.1:8477/api/ingest/file?case_id=case-1&path=media%2Froof.png'
+ );
+ expect(fetchImpl.mock.calls[0][1].headers['X-Azimut-Token']).toBe('tok-123');
+ });
+
+ it('says which refusal it was, rather than leaving an empty window', async () => {
+ // the app states the size ceiling itself, so its own sentence is passed
+ // through rather than a second copy of the number kept over here
+ for (const [status, body, message] of [
+ [401, '', /pairing token rejected/],
+ [413, '{"detail":"a handed-over file must be under 24 MB"}', /under 24 MB/],
+ [404, 'not json at all', /refused that file \(404\)/],
+ ]) {
+ const fetchImpl = vi.fn(async () => ({ ok: false, status, text: async () => body }));
+ const { handle } = load({ fetchImpl });
+ const res = await handle({ type: 'map-file', caseId: 'case-1', path: 'media/roof.png' }, {});
+ expect(res.ok).toBe(false);
+ expect(res.error).toMatch(message);
+ }
+ });
+
+ it('refuses to ask for a file with no case open', async () => {
+ const fetchImpl = vi.fn();
+ const { handle } = load({ fetchImpl });
+ const res = await handle({ type: 'map-file', caseId: '', path: 'media/roof.png' }, {});
+ expect(res).toEqual({ ok: false, error: 'no case open' });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
+
/** 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) {
@@ -227,7 +325,14 @@ describe('handOff: filling a composer the app prepared', () => {
// 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());
+ // Wait for the *filler* specifically. The worker also re-injects bridge.js
+ // into the app's tabs when it starts, so "executeScript was called" is no
+ // longer the same question as "the composer was filled".
+ await settle(() =>
+ expect(chrome.scripting.executeScript).toHaveBeenCalledWith(
+ expect.objectContaining({ world: 'MAIN', files: ['handoff.js'] })
+ )
+ );
// 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',
@@ -237,7 +342,9 @@ describe('handOff: filling a composer the app prepared', () => {
// 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);
+ const [setter, filler] = chrome.scripting.executeScript.mock.calls
+ .map(([one]) => one)
+ .filter((call) => call.world === 'MAIN');
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 —
@@ -303,3 +410,427 @@ describe('handOff: filling a composer the app prepared', () => {
expect(res.ok).toBe(false);
});
});
+
+describe('handOffReverse: opening an engine with the image', () => {
+ const image = { name: 'reverse-bridge.png', type: 'image/png', data: btoa('\x89PNG') };
+ const payload = { url: 'https://lens.google.com/', image };
+
+ it('answers at once, then opens the engine and gives the page the image', async () => {
+ const chrome = makeChrome();
+ const { handOffReverse } = load({ chrome });
+ chrome.scripting.executeScript = vi.fn(async () => [{ result: { handed: true } }]);
+
+ // answered while the click is still fresh enough for the app to open the tab
+ // itself if the answer had been no
+ expect(await handOffReverse(payload)).toEqual({ ok: true, accepted: true });
+
+ await settle(() =>
+ expect(chrome.scripting.executeScript).toHaveBeenCalledWith(
+ expect.objectContaining({ world: 'MAIN', files: ['reverse.js'] })
+ )
+ );
+ expect(chrome.tabs.create).toHaveBeenCalledWith({ url: payload.url, active: true });
+ const [setter, filler] = chrome.scripting.executeScript.mock.calls
+ .map(([one]) => one)
+ .filter((call) => call.world === 'MAIN');
+ // The image travels as base64 on a global, for the same two reasons the
+ // thread does: an uploader ignores what an extension's world makes, and
+ // nothing on that side can call an extension API.
+ expect(setter.args).toEqual([{ image }]);
+ expect(filler).toEqual({ target: { tabId: 7 }, world: 'MAIN', files: ['reverse.js'] });
+ });
+
+ it('needs no pairing, since the app sent the bytes rather than a path', async () => {
+ const chrome = makeChrome();
+ chrome.storage.local.get = vi.fn(async (d) => ({ ...d, token: '' }));
+ const { handOffReverse } = load({ chrome });
+
+ await expect(handOffReverse(payload)).resolves.toEqual({ ok: true, accepted: true });
+ });
+
+ it('refuses an image too large to carry into a page', async () => {
+ const { handOffReverse } = load();
+ const huge = { ...image, data: 'A'.repeat(29 * 1024 * 1024) };
+
+ await expect(handOffReverse({ ...payload, image: huge })).rejects.toThrow(/too large/);
+ });
+
+ it('refuses a hand-off with nothing in it', async () => {
+ const { handOffReverse } = load();
+
+ await expect(handOffReverse({ url: payload.url })).rejects.toThrow(/no image/);
+ await expect(handOffReverse({ image })).rejects.toThrow(/no engine/);
+ });
+
+ it('says what the engine would not take, since the app was answered long before', async () => {
+ const chrome = makeChrome();
+ const { handOffReverse } = load({ chrome });
+ chrome.scripting.executeScript = vi.fn(async () => [
+ { result: { handed: false, error: 'Could not give the image to this engine.' } },
+ ]);
+
+ await handOffReverse(payload);
+
+ await settle(() =>
+ expect(chrome.notifications.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining('Could not give the image to this engine.'),
+ })
+ )
+ );
+ });
+
+ it('tells the analyst to reload a copy loaded before it knew these engines', async () => {
+ // A browser grants the manifest's hosts when it loads the copy, and an
+ // extension cannot ask for one later — so the refusal is about a reload,
+ // whatever wording the browser put on it.
+ const chrome = makeChrome();
+ const { handOffReverse } = load({ chrome });
+ chrome.scripting.executeScript = vi.fn(async () => {
+ throw new Error(
+ 'Cannot access contents of the page. Extension manifest must request permission to access the respective host.'
+ );
+ });
+
+ await handOffReverse(payload);
+
+ await settle(() =>
+ expect(chrome.notifications.create).toHaveBeenCalledWith(
+ expect.objectContaining({ message: expect.stringContaining('Reload it in your browser') })
+ )
+ );
+ });
+
+ it('refuses a hand-off asked for by anything but the local app', async () => {
+ const { handle } = load();
+ const res = await handle(
+ { type: 'reverse-handoff', payload },
+ { tab: { url: 'https://evil.example/' } }
+ );
+ expect(res.ok).toBe(false);
+ });
+});
+
+// --- the update routes ---------------------------------------------------------
+//
+// What these pin is the difference between two claims the app must not confuse:
+// the folder on disk (which the app has already rewritten by the time it asks)
+// and the folder the *running* code was loaded from. Only the second one proves
+// an update landed, and storage.session is what separates them.
+
+const APP_TAB = { tab: { url: 'http://127.0.0.1:8477/', windowId: 1 } };
+const STAMP = { install_id: 'abc123', version: '0.3.0', payload: 'digest-new' };
+
+/** A chrome stub whose session storage behaves like the real one: it remembers. */
+function stampChrome({ session = {}, stampOnDisk = STAMP, ok = true, management } = {}) {
+ const store = { ...session };
+ const chrome = makeChrome({
+ ...(management === undefined ? {} : { management }),
+ storage: {
+ local: { get: vi.fn(async (d) => ({ ...d })), set: vi.fn() },
+ session: {
+ get: vi.fn(async (key) => (key in store ? { [key]: store[key] } : {})),
+ set: vi.fn(async (patch) => Object.assign(store, patch)),
+ remove: vi.fn(),
+ },
+ },
+ runtime: {
+ getManifest: () => ({ version: '0.3.0' }),
+ getURL: (p) => `chrome-extension://theid/${p}`,
+ id: 'theid',
+ onMessage: { addListener: vi.fn() },
+ onConnect: { addListener: vi.fn() },
+ reload: vi.fn(),
+ },
+ });
+ const fetchImpl = vi.fn(async () => ({ ok, json: async () => stampOnDisk }));
+ return { chrome, fetchImpl, store };
+}
+
+describe('handle: ext-state', () => {
+ it('refuses a page that is not the local app', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-state' }, { tab: { url: 'https://evil.example/' } });
+ expect(res.ok).toBe(false);
+ });
+
+ it('reports the running version, the extension id and the stamp it loaded from', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-state' }, APP_TAB);
+ expect(res).toEqual({
+ ok: true,
+ version: '0.3.0',
+ extensionId: 'theid',
+ loaded: STAMP,
+ installType: 'development',
+ });
+ // Not `id`: the bridge spreads this answer next to the message's correlation
+ // id, and a collision there would silently break every reply pairing.
+ expect(res.id).toBeUndefined();
+ });
+
+ it('names a packaged copy as one the browser manages', async () => {
+ // Firefox's permanent install is a signed XPI: no install.json to read, and
+ // sealed. Without this the app would read it as a stale unzip and offer to
+ // replace it with a folder Firefox forgets on the way out.
+ const { chrome, fetchImpl } = stampChrome({
+ ok: false,
+ management: { getSelf: async () => ({ installType: 'normal' }) },
+ });
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-state' }, APP_TAB);
+ expect(res.installType).toBe('normal');
+ expect(res.loaded).toBeNull();
+ });
+
+ it('answers null where the browser will not say', async () => {
+ const { chrome, fetchImpl } = stampChrome({ management: {} });
+ const { handle } = load({ chrome, fetchImpl });
+ expect((await handle({ type: 'ext-state' }, APP_TAB)).installType).toBeNull();
+ });
+
+ it('answers from storage.session once seeded, so a rewritten folder cannot fake an update', async () => {
+ // The stamp on disk is what the app just wrote; the session holds what this
+ // code was loaded from. Reporting the former would always say "up to date".
+ const { chrome, fetchImpl } = stampChrome({
+ session: { loadedStamp: { install_id: 'abc123', payload: 'digest-old' } },
+ });
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-state' }, APP_TAB);
+ expect(res.loaded.payload).toBe('digest-old');
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('reads install.json once per load and remembers a missing one', async () => {
+ const { chrome, fetchImpl } = stampChrome({ ok: false });
+ const { handle } = load({ chrome, fetchImpl });
+ expect((await handle({ type: 'ext-state' }, APP_TAB)).loaded).toBeNull();
+ expect((await handle({ type: 'ext-state' }, APP_TAB)).loaded).toBeNull();
+ // `null` is a real answer and is stored as one, or every call re-reads a
+ // file that is not there.
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(chrome.storage.session.set).toHaveBeenCalledWith({ loadedStamp: null });
+ });
+
+ it('treats an unreadable install.json as no stamp', async () => {
+ const { chrome } = stampChrome();
+ const fetchImpl = vi.fn(async () => {
+ throw new Error('nope');
+ });
+ const { handle } = load({ chrome, fetchImpl });
+ expect((await handle({ type: 'ext-state' }, APP_TAB)).loaded).toBeNull();
+ });
+});
+
+describe('handle: ext-reload', () => {
+ it('answers before restarting, because the restart kills the reply', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-reload', installId: 'abc123' }, APP_TAB);
+ expect(res).toEqual({ ok: true, reloading: true });
+ expect(chrome.runtime.reload).not.toHaveBeenCalled();
+ await new Promise((r) => setTimeout(r, 80));
+ expect(chrome.runtime.reload).toHaveBeenCalled();
+ });
+
+ it('leaves another copy alone when the app names a different install', async () => {
+ // Chrome derives the extension id from the folder path, so two copies can
+ // be loaded at once. Restarting the wrong one looks exactly like a failed
+ // update, and says nothing.
+ const { chrome, fetchImpl } = stampChrome();
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-reload', installId: 'someone-else' }, APP_TAB);
+ expect(res.ok).toBe(false);
+ await new Promise((r) => setTimeout(r, 80));
+ expect(chrome.runtime.reload).not.toHaveBeenCalled();
+ });
+
+ it('refuses a page that is not the local app', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { handle } = load({ chrome, fetchImpl });
+ const res = await handle({ type: 'ext-reload' }, { tab: { url: 'https://evil.example/' } });
+ expect(res.ok).toBe(false);
+ expect(chrome.runtime.reload).not.toHaveBeenCalled();
+ });
+});
+
+describe('reattachBridge', () => {
+ it('re-injects the bridge into the app tabs, so an update needs no page reload', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { reattachBridge } = load({ chrome, fetchImpl });
+ chrome.scripting.executeScript.mockResolvedValue([]);
+ await reattachBridge();
+ expect(chrome.tabs.query).toHaveBeenCalledWith({
+ url: ['http://127.0.0.1/*', 'http://localhost/*'],
+ });
+ expect(chrome.scripting.executeScript).toHaveBeenCalledWith({
+ target: { tabId: 11 },
+ files: ['bridge.js'],
+ });
+ });
+
+ it('shrugs off a tab it may not inject', async () => {
+ const { chrome, fetchImpl } = stampChrome();
+ const { reattachBridge } = load({ chrome, fetchImpl });
+ chrome.scripting.executeScript.mockRejectedValue(new Error('cannot access'));
+ await expect(reattachBridge()).resolves.toBeUndefined();
+ });
+});
+
+/**
+ * The nudge stream, and the panels it is held open for.
+ *
+ * A panel drawn over someone else's map is working a case the app is also
+ * writing to, and it cannot read the app's own channel: its fetch would carry
+ * the map site's origin, which the app refuses. So this worker holds one stream
+ * for every open panel (`api/events.py`, `/api/ingest/events`) and hands each
+ * event over the port the panel opened.
+ *
+ * The stream stands in for the real one exactly where it matters: it never ends.
+ * A reader parked on a `read()` that does not resolve is what the live one looks
+ * like between two events, and it is the state the worker spends its life in.
+ */
+describe('the nudge stream', () => {
+ /** A response whose body yields these frames and then holds, as the app's does. */
+ function streaming(frames, { ok = true, status = 200 } = {}) {
+ let at = 0;
+ const encoder = new TextEncoder();
+ return {
+ ok,
+ status,
+ body: {
+ getReader: () => ({
+ read: () =>
+ at < frames.length
+ ? Promise.resolve({ value: encoder.encode(frames[at++]), done: false })
+ : new Promise(() => {}), // open, waiting for the next event
+ }),
+ },
+ };
+ }
+
+ /** One panel's end of the port. */
+ function panel(name = 'map-sync') {
+ const port = {
+ name,
+ heard: [],
+ messages: [],
+ disconnects: [],
+ onMessage: { addListener: (cb) => port.messages.push(cb) },
+ onDisconnect: { addListener: (cb) => port.disconnects.push(cb) },
+ postMessage: vi.fn((msg) => port.heard.push(msg)),
+ };
+ return port;
+ }
+
+ /** The worker, with the listener the panels connect through. */
+ function worker(fetchImpl, chrome = makeChrome()) {
+ const loaded = load({ chrome, fetchImpl });
+ return {
+ ...loaded,
+ connect: chrome.runtime.onConnect.addListener.mock.calls[0][0],
+ /** A panel gone: its tab closed, or it was folded away. */
+ leave: (port) => {
+ for (const cb of port.disconnects) cb();
+ },
+ };
+ }
+
+ it('reads one event per frame and ignores the keepalive comments', () => {
+ const { frameEvent } = load({});
+ expect(frameEvent('data: {"type":"saved","case_id":"c1"}')).toEqual({
+ type: 'saved',
+ case_id: 'c1',
+ });
+ expect(frameEvent(': ping')).toBe(null);
+ expect(frameEvent('data: not json at all')).toBe(null);
+ expect(frameEvent('')).toBe(null);
+ });
+
+ it('hands every event to every panel, over one stream', async () => {
+ const fetchImpl = vi.fn(async () =>
+ streaming([': connected\n\n', 'data: {"type":"saved","case_id":"c1"}\n\n'])
+ );
+ const w = worker(fetchImpl);
+ const a = panel();
+ const b = panel();
+ w.connect(a);
+ w.connect(b);
+ await vi.waitFor(() => expect(a.heard).toHaveLength(1));
+ await vi.waitFor(() => expect(b.heard).toHaveLength(1));
+ expect(a.heard[0]).toEqual({
+ type: 'app-event',
+ event: { type: 'saved', case_id: 'c1' },
+ });
+ // one bus, one request: ten tabs on one map are not ten streams
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ expect(fetchImpl.mock.calls[0][0]).toBe('http://127.0.0.1:8477/api/ingest/events');
+ expect(fetchImpl.mock.calls[0][1].headers['X-Azimut-Token']).toBe('tok-123');
+ w.leave(a);
+ w.leave(b);
+ });
+
+ it('reassembles an event split across two chunks', async () => {
+ const fetchImpl = vi.fn(async () =>
+ streaming(['data: {"type":"grid-marks","case', '_id":"c1","revision":4}\n\n'])
+ );
+ const w = worker(fetchImpl);
+ const p = panel();
+ w.connect(p);
+ await vi.waitFor(() => expect(p.heard).toHaveLength(1));
+ expect(p.heard[0].event).toEqual({ type: 'grid-marks', case_id: 'c1', revision: 4 });
+ w.leave(p);
+ });
+
+ it('opens nothing until a panel asks, and lets go when the last one leaves', async () => {
+ const fetchImpl = vi.fn(async () => streaming([': connected\n\n']));
+ const w = worker(fetchImpl);
+ expect(fetchImpl).not.toHaveBeenCalled(); // a worker with no panel holds no request
+ const p = panel();
+ w.connect(p);
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalled());
+ const { signal } = fetchImpl.mock.calls[0][1];
+ expect(signal.aborted).toBe(false);
+ w.leave(p);
+ expect(signal.aborted).toBe(true);
+ });
+
+ it('ignores a port that is not a panel', () => {
+ const fetchImpl = vi.fn(async () => streaming([]));
+ const w = worker(fetchImpl);
+ w.connect(panel('something-else'));
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it('asks for nothing while the extension is unpaired', async () => {
+ const chrome = makeChrome();
+ chrome.storage.local.get = vi.fn(async (defaults) => ({
+ ...defaults,
+ backendUrl: 'http://127.0.0.1:8477',
+ token: '',
+ }));
+ const fetchImpl = vi.fn(async () => streaming([]));
+ const w = worker(fetchImpl, chrome);
+ const p = panel();
+ w.connect(p);
+ await vi.waitFor(() => expect(chrome.storage.local.get).toHaveBeenCalled());
+ expect(fetchImpl).not.toHaveBeenCalled();
+ w.leave(p);
+ });
+
+ it('opens the stream again when a panel speaks on a port that outlived it', async () => {
+ // an evicted worker comes back with the port but no stream: the panel's own
+ // heartbeat is what tells it to look again
+ const fetchImpl = vi.fn(async () => streaming([': connected\n\n']));
+ const w = worker(fetchImpl);
+ const p = panel();
+ w.connect(p);
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(1));
+ w.stopEvents();
+ for (const cb of p.messages) cb({ type: 'watch' });
+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2));
+ w.leave(p);
+ });
+});
diff --git a/frontend/src/lib/extensionBridge.test.js b/frontend/src/lib/extensionBridge.test.js
new file mode 100644
index 0000000..04f7263
--- /dev/null
+++ b/frontend/src/lib/extensionBridge.test.js
@@ -0,0 +1,184 @@
+// @vitest-environment happy-dom
+/**
+ * Tests for the capture extension's bridge content script (extension/bridge.js).
+ *
+ * Like extension.test.js next door, the bridge has no exports: the suite stubs
+ * `chrome`, evaluates the source against the test document and reads what it
+ * posts back.
+ *
+ * Two things here are easy to get wrong and silent when wrong. The relay spreads
+ * the worker's answer next to the message's own correlation id, so a field named
+ * `id` on either side breaks every reply pairing. And the bridge is injected
+ * twice over — once by the manifest, once by the worker after an update — so an
+ * older instance that keeps answering would race the live one.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const source = readFileSync(join(here, '../../../extension/bridge.js'), 'utf8');
+
+const CHANNEL = 'azimut-capture-ext';
+
+function makeChrome(sendMessage = vi.fn(async () => ({ ok: true }))) {
+ return {
+ runtime: {
+ id: 'theid',
+ getManifest: () => ({ version: '0.3.0' }),
+ onMessage: { addListener: vi.fn() },
+ sendMessage,
+ },
+ };
+}
+
+/** Evaluate bridge.js against this document. Returns the posted messages. */
+function inject(chrome = makeChrome()) {
+ const posted = [];
+ const spy = vi.spyOn(window, 'postMessage').mockImplementation((data) => {
+ posted.push(data);
+ // happy-dom does not deliver postMessage the way a browser does, and the
+ // bridge only listens to `event.source === window`, so the round trip is
+ // driven by hand below.
+ });
+ new Function('chrome', 'browser', source)(chrome, undefined);
+ spy.mockRestore();
+ return posted;
+}
+
+/** Deliver a page message the way the app's own postMessage would. */
+async function fromPage(message, { origin = window.location.origin } = {}) {
+ const posted = [];
+ const spy = vi.spyOn(window, 'postMessage').mockImplementation((d) => posted.push(d));
+ window.dispatchEvent(
+ new MessageEvent('message', { data: { channel: CHANNEL, ...message }, origin, source: window })
+ );
+ await new Promise((r) => setTimeout(r, 0));
+ spy.mockRestore();
+ return posted;
+}
+
+beforeEach(() => {
+ document.documentElement.removeAttribute('data-azimut-capture-extension');
+ // The generation counter is deliberately *not* reset. happy-dom keeps every
+ // listener an earlier test registered, so resetting it would realign those
+ // stale instances with the fresh one and they would all answer at once. A real
+ // tab has the same requirement for the same reason — the counter only ever
+ // goes up — so leaving it alone is what makes this environment behave like one.
+});
+
+describe('announcing itself', () => {
+ it('stamps the version on <html> and says hello', () => {
+ const posted = inject();
+ expect(document.documentElement.dataset.azimutCaptureExtension).toBe('0.3.0');
+ // The hello is what lets Settings follow an update with no page reload: the
+ // app is already mounted and holding a stale version by then.
+ expect(posted).toContainEqual({ channel: CHANNEL, type: 'bridge-hello', version: '0.3.0' });
+ });
+
+ it('answers a ping with its version', async () => {
+ inject();
+ const posted = await fromPage({ type: 'ping', id: 'p1' });
+ expect(posted).toContainEqual({ channel: CHANNEL, type: 'pong', id: 'p1', version: '0.3.0' });
+ });
+});
+
+describe('relaying to the worker', () => {
+ it('keeps the correlation id when the answer carries fields of its own', async () => {
+ // The worker reports the extension id as `extensionId` for exactly this
+ // reason: an answer field called `id` would overwrite the one the app is
+ // waiting on, and every reply would look unrelated.
+ const chrome = makeChrome(
+ vi.fn(async () => ({ ok: true, version: '0.3.0', extensionId: 'theid', loaded: null }))
+ );
+ inject(chrome);
+ const posted = await fromPage({ type: 'ext-state', id: 'state-1' });
+ expect(posted).toContainEqual({
+ channel: CHANNEL,
+ type: 'ext-state-result',
+ id: 'state-1',
+ ok: true,
+ version: '0.3.0',
+ extensionId: 'theid',
+ loaded: null,
+ });
+ });
+
+ it('passes the named install through, so the wrong copy is not restarted', async () => {
+ const sendMessage = vi.fn(async () => ({ ok: true, reloading: true }));
+ inject(makeChrome(sendMessage));
+ await fromPage({ type: 'ext-reload', id: 'r1', installId: 'abc123' });
+ expect(sendMessage).toHaveBeenCalledWith({ type: 'ext-reload', installId: 'abc123' });
+ });
+
+ it('carries a reverse-image hand-off to the worker and its answer back', async () => {
+ const payload = { url: 'https://lens.google.com/', image: { name: 'a.png', type: 'image/png', data: 'AA' } };
+ const sendMessage = vi.fn(async () => ({ ok: true, accepted: true }));
+ inject(makeChrome(sendMessage));
+ const posted = await fromPage({ type: 'reverse-handoff', id: 'rev-1', payload });
+ expect(sendMessage).toHaveBeenCalledWith({ type: 'reverse-handoff', payload });
+ expect(posted).toContainEqual(
+ expect.objectContaining({ type: 'reverse-handoff-result', id: 'rev-1', ok: true })
+ );
+ });
+
+ it('reports a dead worker as a refusal rather than hanging', async () => {
+ const sendMessage = vi.fn(async () => {
+ throw new Error('Extension context invalidated');
+ });
+ inject(makeChrome(sendMessage));
+ const posted = await fromPage({ type: 'capture', id: 'c1' });
+ expect(posted).toContainEqual(
+ expect.objectContaining({ type: 'capture-result', id: 'c1', ok: false })
+ );
+ });
+
+ it('ignores a foreign origin, a foreign channel and an unknown type', async () => {
+ const sendMessage = vi.fn(async () => ({ ok: true }));
+ inject(makeChrome(sendMessage));
+ await fromPage({ type: 'capture', id: 'x' }, { origin: 'https://evil.example' });
+ expect(sendMessage).not.toHaveBeenCalled();
+ const spy = vi.spyOn(window, 'postMessage').mockImplementation(() => {});
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ data: { channel: 'someone-else', type: 'capture', id: 'x' },
+ origin: window.location.origin,
+ source: window,
+ })
+ );
+ spy.mockRestore();
+ await fromPage({ type: 'no-such-relay', id: 'x' });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('two instances in one tab', () => {
+ it('lets the newest injection answer and the older one stand down', async () => {
+ const first = vi.fn(async () => ({ ok: true, from: 'first' }));
+ const second = vi.fn(async () => ({ ok: true, from: 'second' }));
+ inject(makeChrome(first));
+ inject(makeChrome(second)); // the worker re-injecting after an update
+
+ const posted = await fromPage({ type: 'capture', id: 'c1' });
+
+ expect(second).toHaveBeenCalled();
+ expect(first).not.toHaveBeenCalled();
+ // and exactly one answer goes back, not two racing on the same id
+ expect(posted.filter((m) => m.type === 'capture-result')).toHaveLength(1);
+ });
+
+ it('stands down once its own context is invalidated', async () => {
+ // After the extension reloads, the old content script keeps its listener but
+ // `runtime.id` is gone, and every relay from it would throw.
+ const orphaned = vi.fn(async () => ({ ok: true }));
+ const chrome = makeChrome(orphaned);
+ inject(chrome);
+ delete chrome.runtime.id;
+
+ const posted = await fromPage({ type: 'capture', id: 'c1' });
+
+ expect(orphaned).not.toHaveBeenCalled();
+ expect(posted).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/lib/extensionMapDraw.test.js b/frontend/src/lib/extensionMapDraw.test.js
new file mode 100644
index 0000000..e8123d4
--- /dev/null
+++ b/frontend/src/lib/extensionMapDraw.test.js
@@ -0,0 +1,226 @@
+// @vitest-environment happy-dom
+/**
+ * The extension's canvas layer (extension/mapdraw.js).
+ *
+ * It has one rule with a claim in it, and the rest is paint: a shape whose
+ * points do not all project is dropped rather than drawn short. Half a measured
+ * path is not most of a measurement — it is a wrong one, drawn confidently, in
+ * a tool whose output is meant to end up in a case file.
+ *
+ * The paint is worth pinning too, because the whole point of it is to be the
+ * app's: a lattice of hundreds of cells must not carry the dark casing that
+ * makes a single measured line readable, or it reads as a black grid over the
+ * imagery.
+ *
+ * The canvas is faked because happy-dom has no 2D context. What is asserted is
+ * the sequence of calls, which is what says whether something was drawn.
+ */
+import { describe, expect, it, beforeEach, beforeAll } 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 read = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+
+let ext;
+let calls;
+
+/** A 2D context that records what it was asked to do. */
+function fakeContext() {
+ const record = (name) => (...args) => calls.push([name, ...args]);
+ const ctx = {
+ measureText: () => ({ width: 20 }),
+ };
+ for (const name of [
+ 'setTransform', 'clearRect', 'beginPath', 'moveTo', 'lineTo', 'closePath',
+ 'stroke', 'fill', 'fillRect', 'fillText', 'strokeRect', 'arc', 'ellipse',
+ 'roundRect', 'save', 'restore', 'setLineDash', 'translate', 'rotate', 'scale',
+ ]) {
+ ctx[name] = record(name);
+ }
+ return ctx;
+}
+
+beforeAll(() => {
+ const scope = { window: globalThis.window };
+ new Function('window', read('maptheme.js'))(scope.window);
+ new Function('window', read('mapdraw.js'))(scope.window);
+ ext = scope.window.AzimutMapDraw;
+ window.HTMLCanvasElement.prototype.getContext = fakeContext;
+ // the icon glyphs are drawn as paths; happy-dom has no Path2D
+ globalThis.Path2D = class {
+ constructor(d) {
+ this.d = d;
+ }
+ };
+});
+
+let layer;
+
+beforeEach(() => {
+ calls = [];
+ document.body.innerHTML = '';
+ layer = ext.createDrawLayer(document.body);
+});
+
+const named = (name) => calls.filter(([call]) => call === name);
+
+/** Straight through: one degree is one pixel, so the test states pixels. */
+const flat = (point) => ({ x: point.lon, y: point.lat });
+
+const LINE = { kind: 'line', stroke: '#f5a623', strokeWidth: 2.5 };
+
+describe('drawing over someone else’s map', () => {
+ it('sits over the page without taking its clicks', () => {
+ expect(layer.canvas.style.position).toBe('fixed');
+ expect(layer.canvas.style.pointerEvents).toBe('none');
+ });
+
+ it('traces a line through every point it was given', () => {
+ layer.render([{ ...LINE, points: [{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }] }], flat);
+ expect(named('moveTo')).toEqual([['moveTo', 2, 1]]);
+ expect(named('lineTo')).toEqual([['lineTo', 4, 3]]);
+ expect(named('stroke')).toHaveLength(1);
+ });
+
+ it('casings a line only when it is asked to', () => {
+ // the measure gets a dark casing so it reads over snow and over a blown-out
+ // roof; a lattice of cells asking for the same thing draws a black grid
+ layer.render([{ ...LINE, casing: true, points: [{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }] }], flat);
+ expect(named('stroke')).toHaveLength(2);
+ });
+
+ it('drops a shape one of whose points projects nowhere', () => {
+ const broken = (point) => (point.lat === 3 ? { x: NaN, y: NaN } : flat(point));
+ layer.render([{ ...LINE, points: [{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }] }], broken);
+ expect(named('moveTo')).toEqual([]);
+ expect(named('stroke')).toEqual([]);
+ });
+
+ it('drops a shape that projects absurdly far off screen', () => {
+ const far = (point) => (point.lat === 3 ? { x: ext.FAR + 1, y: 0 } : flat(point));
+ layer.render([{ ...LINE, points: [{ lat: 1, lon: 2 }, { lat: 3, lon: 4 }] }], far);
+ expect(named('stroke')).toEqual([]);
+ });
+
+ it('closes a polygon and fills it', () => {
+ layer.render(
+ [{
+ kind: 'polygon',
+ stroke: '#f5a623',
+ fill: '#f5a623',
+ fillOpacity: 0.15,
+ points: [{ lat: 0, lon: 0 }, { lat: 0, lon: 1 }, { lat: 1, lon: 1 }],
+ }],
+ flat
+ );
+ expect(named('fill')).toHaveLength(1);
+ expect(named('closePath')).toHaveLength(2); // once to fill, once to stroke
+ });
+
+ it('leaves an unchecked cell unfilled', () => {
+ // the app's unchecked style is a bright thin outline and no fill at all;
+ // filling it at zero opacity would still cost a fill per cell
+ layer.render(
+ [{ kind: 'cell', bounds: { south: 0, west: 0, north: 1, east: 1 }, stroke: '#fff', fill: '#fff', fillOpacity: 0 }],
+ flat
+ );
+ expect(named('fill')).toEqual([]);
+ expect(named('stroke')).toHaveLength(1);
+ });
+
+ it('draws a cell as its four projected corners', () => {
+ layer.render(
+ [{ kind: 'cell', bounds: { south: 0, west: 0, north: 1, east: 2 }, stroke: '#fff' }],
+ flat
+ );
+ expect(named('moveTo')).toEqual([['moveTo', 0, 1]]);
+ expect(named('lineTo')).toEqual([
+ ['lineTo', 2, 1],
+ ['lineTo', 2, 0],
+ ['lineTo', 0, 0],
+ ]);
+ });
+
+ it('draws a saved mark as the app’s turned teardrop', () => {
+ layer.render([{ kind: 'mark', at: { lat: 100, lon: 50 }, glyph: 'pin', count: 1 }], flat);
+ expect(named('rotate')[0]).toEqual(['rotate', -Math.PI / 4]);
+ expect(named('roundRect')).toHaveLength(1);
+ expect(named('fillText')).toEqual([]); // no count badge for a lone mark
+ });
+
+ /**
+ * The sharp corner of the teardrop is what points at the coordinate, and a
+ * rotation puts that corner half a diagonal below the middle of the box. Drawn
+ * around the point, as it was, every mark claimed a spot 17 px south of the
+ * one it was filed at — ten metres at zoom 18.
+ */
+ it('stands the teardrop above the point, so its corner is on it', () => {
+ layer.render([{ kind: 'mark', at: { lat: 100, lon: 50 }, glyph: 'pin', count: 1 }], flat);
+ expect(named('translate')).toContainEqual(['translate', 50, 100 - ext.MARK_TIP]);
+ expect(ext.MARK_TIP).toBeCloseTo((ext.MARK / 2) * Math.SQRT2, 6);
+ });
+
+ it('counts what is stacked under a mark', () => {
+ layer.render([{ kind: 'mark', at: { lat: 1, lon: 2 }, glyph: 'pin', count: 7 }], flat);
+ expect(named('fillText')).toContainEqual(expect.arrayContaining(['fillText', '7']));
+ });
+
+ it('names a mark only when it is given a name', () => {
+ layer.render([{ kind: 'mark', at: { lat: 1, lon: 2 }, glyph: 'pin', count: 1, label: 'Gate' }], flat);
+ expect(named('fillText')).toContainEqual(expect.arrayContaining(['fillText', 'Gate']));
+ });
+
+ it('shortens a name rather than letting it run across the map', () => {
+ const long = 'x'.repeat(80);
+ layer.render([{ kind: 'dot', at: { lat: 1, lon: 2 }, fill: '#fff', label: long }], flat);
+ const [, text] = named('fillText')[0];
+ expect(text).toHaveLength(ext.LABEL_MAX);
+ expect(text.endsWith('…')).toBe(true);
+ });
+
+ it('draws the moon as its lit fraction', () => {
+ layer.render(
+ [{ kind: 'body', at: { lat: 1, lon: 2 }, bodyKind: 'moon', colour: '#4a93cc', illuminated: 0.5, waxing: true }],
+ flat
+ );
+ expect(named('ellipse')).toHaveLength(1);
+ // a waxing moon is drawn lit-side-right, so nothing is turned
+ expect(named('rotate')).toEqual([]);
+ });
+
+ it('turns the lit side over for a waning moon', () => {
+ layer.render(
+ [{ kind: 'body', at: { lat: 1, lon: 2 }, bodyKind: 'moon', colour: '#4a93cc', illuminated: 0.5, waxing: false }],
+ flat
+ );
+ expect(named('rotate')).toEqual([['rotate', Math.PI]]);
+ });
+
+ it('draws the sun as a disc, with no terminator', () => {
+ layer.render(
+ [{ kind: 'body', at: { lat: 1, lon: 2 }, bodyKind: 'sun', colour: '#bd8721' }],
+ flat
+ );
+ expect(named('ellipse')).toEqual([]);
+ expect(named('arc').length).toBeGreaterThan(1);
+ });
+
+ it('says nothing when there is nothing to say', () => {
+ layer.render([{ kind: 'dot', at: { lat: 1, lon: 2 }, fill: '#fff' }], flat);
+ expect(named('fillText')).toEqual([]);
+ });
+
+ it('clears before each pass, at the device’s pixel ratio', () => {
+ layer.render([], flat);
+ expect(named('clearRect')).toHaveLength(1);
+ const ratio = window.devicePixelRatio || 1;
+ expect(layer.canvas.width).toBe(Math.round(window.innerWidth * ratio));
+ });
+
+ it('takes itself off the page when the panel closes', () => {
+ layer.destroy();
+ expect(document.body.querySelector('canvas')).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/extensionMapEngine.test.js b/frontend/src/lib/extensionMapEngine.test.js
new file mode 100644
index 0000000..16906e7
--- /dev/null
+++ b/frontend/src/lib/extensionMapEngine.test.js
@@ -0,0 +1,1035 @@
+// @vitest-environment happy-dom
+/**
+ * The map tools' view engine (extension/mapoverlay.js), driven end to end.
+ *
+ * `extensionMapFrame.test.js` replays the recordings through the arithmetic.
+ * This replays them through the *panel*: the address bar changes, the wheel
+ * turns, the window is resized, and what is asserted is what the analyst would
+ * see — where the drawing is placed, what the status line says, and what the
+ * app is asked for.
+ *
+ * It exists because everything that makes this tool portable lives here rather
+ * than in the maths. The arithmetic is a pure function of CSS pixels and
+ * coordinates and cannot tell one machine from another; the engine is what
+ * decides *which* pixels it gets — the window's or the map's, this window's or
+ * the one the offset was measured in, the browser's own or the device's.
+ *
+ * Two stand-ins, and no more. The app's parse (`engine/mapsites.py`) answers
+ * from the recording, which `tests/test_mapsites.py` pins to the real parser
+ * URL by URL; and the canvas records the calls made on it, because happy-dom
+ * has no 2D context. Everything else is the file itself.
+ */
+import { describe, expect, it, vi, beforeAll, beforeEach, afterEach } 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 root = join(here, '../../..');
+const read = (name) => readFileSync(join(root, `extension/${name}`), 'utf8');
+const fixture = JSON.parse(readFileSync(join(root, 'tests/fixtures/map-sites.json'), 'utf8'));
+
+/** The files the panel is injected with, in the order the worker injects them. */
+const PARTS = ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapdraw.js', 'mapref.js'];
+
+/** How often the panel re-reads the address bar, how long it waits for a
+ * gesture to land, and how long an offset is held before it counts — all three
+ * stated in `mapoverlay.js`, and what the clock below is wound past. */
+const POLL_MS = 300;
+const SETTLE_MS = 200;
+const FRAME_QUIET_MS = 400;
+
+beforeAll(() => {
+ globalThis.Path2D = class {
+ constructor(d) {
+ this.d = d;
+ }
+ };
+ window.HTMLCanvasElement.prototype.getContext = () => {
+ const noop = () => {};
+ return new Proxy(
+ { measureText: () => ({ width: 20 }) },
+ { get: (target, name) => target[name] ?? noop }
+ );
+ };
+});
+
+// --- the app, and the browser around it ---------------------------------------
+
+/**
+ * The app's reading of one recorded URL.
+ *
+ * The views are the recording's own, so nothing here re-implements a parser.
+ * What it does implement is the one thing a different window really changes: a
+ * scale stated as a *size* — Apple's span, Google satellite's metres — is a
+ * different zoom when the map is drawn in fewer pixels. That is the property
+ * the resize tests below are about, so it has to be in the stand-in rather than
+ * assumed away.
+ */
+function parseOf(step, height, drawnIn, extra = {}) {
+ const view = step.view;
+ const sized = step.scale_source === 'span' || step.scale_source === 'height_m';
+ const metres = /,(\d+(?:\.\d+)?)m(?:$|[,/?])/.exec(step.url);
+ return {
+ site: step.site,
+ label: step.site,
+ lat: view.lat,
+ lon: view.lon,
+ zoom: sized ? view.zoom + Math.log2(height / drawnIn) : view.zoom,
+ bearing: view.bearing,
+ projection: view.projection,
+ view_kind: 'map',
+ geometry: true,
+ far: false,
+ globe_below: null,
+ scale_source: step.scale_source,
+ camera_m: metres ? Number(metres[1]) : null,
+ camera_kind: metres ? 'height_m' : null,
+ imagery_mode: null,
+ title: null,
+ imagery_date: null,
+ ...extra,
+ };
+}
+
+/**
+ * A panel, loaded the way the worker loads it: five classic scripts sharing one
+ * window, then the overlay itself.
+ *
+ * `location` is handed in rather than navigated to, because the whole engine
+ * turns on an address bar that the site rewrites under it — which is a string
+ * changing, and never a page load.
+ */
+function open({ recording, size, ratio = 1, parse, storage = {}, firefox = false } = {}) {
+ const win = size ?? recording?.window ?? { w: 1600, h: 1000 };
+ window.happyDOM.setViewport({ width: win.w, height: win.h });
+ window.devicePixelRatio = ratio;
+
+ const location = { href: 'https://example.invalid/', host: 'example.invalid' };
+ const sent = [];
+ const saved = { ...storage };
+ const api = {
+ storage: {
+ local: {
+ get: vi.fn(async (defaults) => ({ ...defaults, ...saved })),
+ set: vi.fn(async (patch) => Object.assign(saved, patch)),
+ },
+ },
+ runtime: {
+ onMessage: { addListener: vi.fn(), removeListener: vi.fn() },
+ sendMessage: vi.fn(async (message) => {
+ sent.push(message);
+ if (message.type !== 'map-api') return { ok: true, data: {} };
+ if (message.path === '/api/ingest/parse') {
+ return { ok: true, data: parse(message.query) };
+ }
+ if (message.path === '/api/ingest/ping') return { ok: true, data: { units: 'metric' } };
+ if (message.path === '/api/ingest/cases') {
+ return { ok: true, data: [{ id: 'case-1', name: 'Case' }] };
+ }
+ return { ok: true, data: [] };
+ }),
+ },
+ };
+
+ for (const part of PARTS) new Function('window', read(part))(window);
+ new Function('window', 'document', 'location', 'chrome', 'browser', read('mapoverlay.js'))(
+ window,
+ document,
+ location,
+ firefox ? undefined : api,
+ firefox ? api : undefined
+ );
+ const panel = window.__AZIMUT_MAP_TOOLS__;
+ return {
+ ...panel,
+ location,
+ api,
+ saved,
+ /** What the app was asked, in order. */
+ asks: (path) => sent.filter((m) => m.path === path).map((m) => m.query),
+ /** The status line the analyst reads, stripped of its markup. */
+ status: () =>
+ panel.state.collapsed
+ ? ''
+ : document
+ .getElementById('azimut-map-tools')
+ .shadowRoot.querySelector('.status span').textContent,
+ canvas: () => document.getElementById('azimut-map-tools').shadowRoot.querySelector('canvas'),
+ /** The offset the panel settled on, where the analyst can read it. */
+ statusTitle: () =>
+ document
+ .getElementById('azimut-map-tools')
+ .shadowRoot.querySelector('.status span')
+ .getAttribute('title') ?? '',
+ /** Pick a tool up, the way the analyst does — nothing is drawn until one
+ * is open, so nothing about the drawing can be asserted until one is. */
+ pick: (id) =>
+ document
+ .getElementById('azimut-map-tools')
+ .shadowRoot.querySelector(`[data-tab="${id}"]`)
+ .click(),
+ };
+}
+
+/** Let the panel's own clock run: the URL poll, the settle wait, and every
+ * promise they are waiting on. */
+const tick = (ms = POLL_MS + SETTLE_MS + FRAME_QUIET_MS) => vi.advanceTimersByTimeAsync(ms);
+
+const at = (type, x, y, init = {}) =>
+ window.dispatchEvent(
+ new window.MouseEvent(type, { clientX: x, clientY: y, bubbles: true, button: 0, ...init })
+ );
+
+/** One wheel notch over a pixel, which every one of these maps zooms about.
+ * happy-dom's `WheelEvent` drops the pointer position out of its init, and the
+ * pixel the notch was over is the whole measurement — so it is put back. */
+const wheel = (x, y, init = { deltaY: -120 }) => {
+ const event = new window.WheelEvent('wheel', { bubbles: true, ...init });
+ Object.defineProperty(event, 'clientX', { value: x });
+ Object.defineProperty(event, 'clientY', { value: y });
+ return window.dispatchEvent(event);
+};
+
+let panel = null;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ panel?.close();
+ panel = null;
+ vi.useRealTimers();
+ document.documentElement.querySelectorAll('#azimut-map-tools').forEach((node) => node.remove());
+});
+
+/**
+ * Walk a recording: each zoom is the address bar before it, a notch over the
+ * pixel the browser was driven at, and the address bar after.
+ *
+ * This is the panel's whole loop — poll, parse, anchor, solve — with nothing
+ * standing in for it but the app's answer.
+ */
+async function replay(recording, options = {}) {
+ // the height the recording's own views were read at, which is the map's and
+ // not the window's wherever the site keeps a header
+ const drawnIn = recording.map_height ?? recording.window.h;
+ const step = (index) => recording.steps[index];
+ panel = open({
+ recording,
+ parse: (query) => {
+ const found = recording.steps.find((s) => s.url === query.url);
+ // the panel opens on a page that is not a map, as it does in life
+ return found ? parseOf(found, Number(query.height), drawnIn, options.extra) : null;
+ },
+ ...options,
+ });
+ panel.location.href = step(0).url;
+ await tick();
+ for (const zoom of recording.zooms) {
+ panel.location.href = step(zoom.from).url;
+ await tick();
+ wheel(zoom.at.x, zoom.at.y);
+ panel.location.href = step(zoom.to).url;
+ await tick();
+ }
+ return panel;
+}
+
+const offset = (recording) => ({
+ x: recording.centre.x - recording.window.w / 2,
+ y: recording.centre.y - recording.window.h / 2,
+});
+
+const withZooms = fixture.recordings.filter((r) => r.zooms.length >= 1);
+
+// --- what the engine is for ----------------------------------------------------
+
+describe('measuring where a site draws its centre', () => {
+ it.each(withZooms.map((r) => [r.label, r]))(
+ 'lands on the pixel the browser drew it at, on %s',
+ async (_label, recording) => {
+ const live = await replay(recording);
+ const want = offset(recording);
+ expect(live.state.framed).toBe(true);
+ expect(Math.abs(live.state.frame.x - want.x)).toBeLessThan(1.5);
+ expect(Math.abs(live.state.frame.y - want.y)).toBeLessThan(1.5);
+ }
+ );
+
+ it('says so until it knows, and stops saying so once it does', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ expect(live.status()).not.toContain('zoom once to place it');
+ expect(live.state.frame.x).toBeGreaterThan(200);
+ });
+
+ it('remembers it for the next visit, so the first mark is placed', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ const [key] = Object.keys(live.saved);
+ const [kept] = live.saved[key].frames;
+ expect(kept.x).toBeCloseTo(live.state.frame.x, 6);
+ // filed under the window it was measured in, which is what makes it an
+ // answer rather than a number
+ expect(kept.w).toBe(recording.window.w);
+ expect(kept.h).toBe(recording.window.h);
+ });
+});
+
+/**
+ * A zoom is one gesture and, on these sites, two or three readings: the level is
+ * written as soon as the wheel turns and the centre catches up when the camera
+ * stops moving. Solved from the first of them, the site's centre comes out
+ * wherever the camera happened to be passing.
+ *
+ * Nothing downstream catches it. The reading that corrects the centre carries
+ * the same level, so it reads as a pan — and a pan cannot see the frame, which
+ * slides with the map and cancels. So the wrong offset used to be adopted whole,
+ * saved for the next visit, and drawn from with no dimming and nothing said.
+ */
+describe('a zoom the address bar is still writing', () => {
+ const yandex = () => fixture.recordings.find((r) => r.site === 'yandex-maps');
+
+ /** Long enough for the panel to read the address bar again, and short enough
+ * that the reading lands inside the same easing zoom rather than after it. */
+ const DURING = POLL_MS;
+
+ /**
+ * The recording's own zoom, published in instalments.
+ *
+ * `between` is the centre the address bar carries on the way — the recording's
+ * own coordinates in every case, so nothing here invents a position. The level
+ * is the one the zoom lands on, because that is the half the site writes first.
+ */
+ async function easedZoom(between) {
+ const recording = yandex();
+ const drawnIn = recording.map_height ?? recording.window.h;
+ const [gesture] = recording.zooms;
+ const from = recording.steps[gesture.from];
+ const to = recording.steps[gesture.to];
+ const midway = {
+ site: to.site,
+ scale_source: to.scale_source,
+ url: `${to.url}&mid`,
+ view: { ...to.view, ...between(from.view, to.view) },
+ };
+ const table = [from, to, midway];
+ panel = open({
+ recording,
+ parse: (query) => {
+ const found = table.find((s) => s.url === query.url);
+ return found ? parseOf(found, Number(query.height), drawnIn) : null;
+ },
+ });
+ panel.location.href = from.url;
+ await tick();
+ wheel(gesture.at.x, gesture.at.y);
+ panel.location.href = midway.url;
+ await tick(DURING);
+ panel.location.href = to.url;
+ await tick();
+ return panel;
+ }
+
+ const want = () => offset(yandex());
+
+ it('takes the offset from the reading the address bar stopped on', async () => {
+ // the level arrives first and the centre has not moved at all yet
+ const live = await easedZoom((from) => ({ lat: from.lat, lon: from.lon }));
+ expect(live.state.framed).toBe(true);
+ expect(Math.abs(live.state.frame.x - want().x)).toBeLessThan(1.5);
+ expect(Math.abs(live.state.frame.y - want().y)).toBeLessThan(1.5);
+ });
+
+ it('and from the last one, not the first, half way through the ease', async () => {
+ const live = await easedZoom((from, to) => ({
+ lat: (from.lat + to.lat) / 2,
+ lon: (from.lon + to.lon) / 2,
+ }));
+ expect(Math.abs(live.state.frame.x - want().x)).toBeLessThan(1.5);
+ expect(Math.abs(live.state.frame.y - want().y)).toBeLessThan(1.5);
+ });
+
+ it('never remembers one it has not finished solving', async () => {
+ const live = await easedZoom((from) => ({ lat: from.lat, lon: from.lon }));
+ const [key] = Object.keys(live.saved);
+ for (const kept of live.saved[key].frames) {
+ expect(Math.abs(kept.x - want().x)).toBeLessThan(1.5);
+ }
+ });
+});
+
+describe('a gesture the address bar has not caught up with', () => {
+ /**
+ * A pan moves the map by exactly the pixels the pointer travelled, so the
+ * canvas is moved by those pixels rather than redrawn. Nothing is projected
+ * again while the map is under a finger, which is what stops a drawing from
+ * sliding against the ground it was placed on — on any screen, at any size,
+ * because a translation in CSS pixels is the one thing every browser agrees
+ * about.
+ */
+ const pan = async (from, to) => {
+ at('pointerdown', from.x, from.y);
+ at('pointermove', to.x, to.y);
+ };
+
+ it('moves the drawing by the pixels the pointer moved', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording);
+ await pan({ x: 800, y: 500 }, { x: 700, y: 620 });
+ expect(live.canvas().style.transform).toBe('translate(-100px, 120px) scale(1)');
+ });
+
+ it('hands it back to the map the moment the address bar says where it landed', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording);
+ await pan({ x: 800, y: 500 }, { x: 700, y: 620 });
+ at('pointerup', 700, 620);
+ // dimmed while the map glides on and says nothing about it
+ expect(live.canvas().style.opacity).toBe('0.25');
+ live.location.href = recording.steps[recording.pan.to].url;
+ await tick();
+ expect(live.canvas().style.transform).toBe('');
+ expect(live.canvas().style.opacity).toBe('');
+ });
+});
+
+// --- the window, and how much of it the map is --------------------------------
+
+describe('how tall the map is, which is not how tall the window is', () => {
+ /**
+ * Two of these views state their scale as a *size* rather than as a level —
+ * Apple's span in degrees, Google satellite's viewport height in metres — and
+ * a size is only a scale next to the number of pixels it was drawn in. Hand
+ * the app the window's height where the site drew the map in less of it and
+ * every distance comes back out by the ratio: Bing's header is 81 px of a
+ * 1000 px window, which is eight percent.
+ *
+ * Nothing is looked up to avoid that. The same measurement that says where
+ * the centre is says how much of the window the map got: a map centred in
+ * what its chrome leaves is centred by exactly half of what the chrome took.
+ */
+ it('asks the app for the map’s height once it has measured a header', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'bing-maps');
+ const live = await replay(recording);
+ const header = 2 * Math.abs(live.state.frame.y);
+ expect(header).toBeGreaterThan(75); // Bing's own, measured: 81 px
+ const heights = live.asks('/api/ingest/parse').map((q) => q.height);
+ expect(heights[0]).toBe(recording.window.h); // nothing measured yet
+ // a pixel count, in whole pixels, which is how the site drew it
+ expect(heights.at(-1)).toBe(Math.round(recording.window.h - header));
+ });
+
+ it('leaves the window’s own height alone on a site that fills it', async () => {
+ const recording = fixture.recordings.find((r) => r.label === 'google-maps satellite');
+ const live = await replay(recording);
+ const heights = new Set(live.asks('/api/ingest/parse').map((q) => q.height));
+ expect([...heights]).toEqual([recording.window.h]);
+ });
+
+ it('reads the scale again when the window changes height', async () => {
+ // A shorter window is fewer pixels for the same metres, which is a lower
+ // zoom — and the URL never said so, because the URL did not change. Left
+ // unread, the drawing would go on at the scale of a window that is gone.
+ const recording = fixture.recordings.find((r) => r.label === 'google-maps satellite');
+ const live = await replay(recording);
+ const before = live.state.view.zoom;
+ window.happyDOM.setViewport({ width: recording.window.w, height: 760 });
+ window.dispatchEvent(new window.Event('resize'));
+ await tick();
+ expect(live.asks('/api/ingest/parse').at(-1).height).toBe(760);
+ expect(live.state.view.zoom).toBeCloseTo(before + Math.log2(760 / recording.window.h), 6);
+ });
+
+ it('stops standing behind an offset measured in a window that is gone', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ const measured = { ...live.state.frame };
+ window.happyDOM.setViewport({ width: 1100, height: 800 });
+ window.dispatchEvent(new window.Event('resize'));
+ await tick();
+ // kept, because it is still the best answer there is — and no longer
+ // claimed, because a panel sized in percentages would have moved
+ expect(live.state.frame).toEqual(measured);
+ expect(live.state.framed).toBe(false);
+ expect(live.status()).toContain('zoom once to place it');
+ });
+
+ it('drops a remembered offset that cannot fit the window it opened in', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const store = {
+ 'mapTools:example.invalid': { frames: [{ x: 210, y: 10, w: 380, h: 700 }], panel: null },
+ };
+ // the same 420 px panel, in a window narrower than the offset it implies
+ panel = open({
+ recording,
+ size: { w: 380, h: 700 },
+ storage: store,
+ parse: (query) =>
+ parseOf(recording.steps[0], Number(query.height), recording.window.h),
+ });
+ panel.location.href = recording.steps[0].url;
+ await tick();
+ expect(panel.state.framed).toBe(false);
+ expect(panel.state.frame).toEqual({ x: 0, y: 0 });
+ });
+});
+
+/**
+ * A pan is followed exactly while the pointer is down, because the map goes
+ * where the pointer goes. What the panel cannot follow is a pan the site never
+ * reports: the map has moved and the address bar still describes where it was,
+ * so the canvas goes on carrying the difference with nothing to hand it back to.
+ */
+describe('a pan the address bar never reports', () => {
+ const pan = (from, to) => {
+ at('pointerdown', from.x, from.y);
+ at('pointermove', to.x, to.y);
+ at('pointerup', to.x, to.y);
+ };
+
+ /**
+ * A zoom taken in that state measures nothing, and must not pretend to.
+ *
+ * The pixel the wheel turns about is on the screen; the view it would be
+ * solved against is the one from before the pan. Read together they put the
+ * site's centre out by the whole pan — and that answer would be adopted,
+ * saved, and carried into every drawing afterwards.
+ */
+ it('leaves the offset alone rather than solving a zoom across it', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ const measured = { ...live.state.frame };
+ pan({ x: 800, y: 500 }, { x: 700, y: 620 });
+ await tick(3000); // past the give-up: the site is never going to say
+ wheel(1248, 720);
+ live.location.href = recording.steps[recording.zooms[0].from].url;
+ await tick();
+ expect(live.state.frame).toEqual(measured);
+ });
+});
+
+// --- how sure the drawing looks -----------------------------------------------
+
+/**
+ * Only one thing dims the drawing, and not being placed yet is not it.
+ *
+ * It was, briefly. A wheel notch is a third of a level on some of these sites,
+ * so the wait for the zoom that measures the offset can be several gestures
+ * long — and a drawing that stays translucent through all of them reads as a
+ * broken tool rather than a careful one. The doubt is said in words instead.
+ */
+describe('what the drawing dims for', () => {
+ const unplaced = async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const drawnIn = recording.map_height ?? recording.window.h;
+ panel = open({
+ recording,
+ parse: (query) => parseOf(recording.steps[0], Number(query.height), drawnIn),
+ });
+ panel.location.href = recording.steps[0].url;
+ await tick();
+ panel.pick('measure');
+ return panel;
+ };
+
+ it('draws at full strength before a zoom has placed it', async () => {
+ const live = await unplaced();
+ expect(live.state.framed).toBe(false);
+ expect(live.canvas().style.opacity).toBe('');
+ });
+
+ it('says so in the status line instead', async () => {
+ const live = await unplaced();
+ expect(live.status()).toContain('zoom once to place it');
+ expect(live.statusTitle()).toBe('');
+ });
+
+ it('and puts the offset it settled on in that line’s tooltip', async () => {
+ const live = await replay(fixture.recordings.find((r) => r.site === 'yandex-maps'));
+ expect(live.status()).not.toContain('zoom once to place it');
+ // the number to read out when a drawing lands where the ground is not
+ expect(live.statusTitle()).toMatch(/centre at 210, 10 from the middle of a 1600×1000 window/);
+ });
+
+ it('and stays at full strength once it is placed', async () => {
+ const live = await replay(fixture.recordings.find((r) => r.site === 'yandex-maps'));
+ live.pick('measure');
+ expect(live.state.framed).toBe(true);
+ expect(live.canvas().style.opacity).toBe('');
+ });
+});
+
+// --- one site, more than one window -------------------------------------------
+
+/**
+ * These sites fold a results panel away below a width and open it again above
+ * one, so the same site draws its centre in two or three places depending on how
+ * wide the window is. Keeping only the last of them meant an offset measured in
+ * a wide window was reused, silently and at full confidence, in a narrow one —
+ * Yandex's panel is 420 px, which is a hundred metres of error at zoom 18.
+ */
+describe('an offset belongs to the window it was measured in', () => {
+ const store = (live) => live.saved[Object.keys(live.saved)[0]];
+
+ it('is not claimed as measured in a window of another shape', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ const kept = store(live);
+ live.close();
+ panel = null;
+ document.documentElement.querySelectorAll('#azimut-map-tools').forEach((n) => n.remove());
+
+ const drawnIn = recording.map_height ?? recording.window.h;
+ panel = open({
+ recording,
+ size: { w: 1040, h: 900 },
+ storage: { 'mapTools:example.invalid': kept },
+ parse: (query) => parseOf(recording.steps[0], Number(query.height), drawnIn),
+ });
+ panel.location.href = recording.steps[0].url;
+ await tick();
+ // kept, because it is still the best guess there is — and not claimed
+ expect(panel.state.frame.x).toBeCloseTo(kept.frames[0].x, 6);
+ expect(panel.state.framed).toBe(false);
+ expect(panel.status()).toContain('zoom once to place it');
+ });
+
+ it('is picked up again when the window comes back to that shape', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording);
+ const measured = { ...live.state.frame };
+ window.happyDOM.setViewport({ width: 1040, height: 900 });
+ window.dispatchEvent(new window.Event('resize'));
+ await tick();
+ expect(live.state.framed).toBe(false);
+ window.happyDOM.setViewport({ width: recording.window.w, height: recording.window.h });
+ window.dispatchEvent(new window.Event('resize'));
+ await tick();
+ // no second zoom asked for: this window has been measured before
+ expect(live.state.framed).toBe(true);
+ expect(live.state.frame).toEqual(measured);
+ });
+});
+
+// --- the same map on another machine ------------------------------------------
+
+describe('what a pixel is, and what it is not', () => {
+ /**
+ * Every number the geometry touches is a CSS pixel: the window's own size,
+ * the pointer's position, the offset a site's chrome imposes. A device's
+ * pixel ratio changes none of them — it changes how many dots the canvas is
+ * rasterised into, and that is the drawing layer's business alone.
+ *
+ * Which is also what makes the browser's own zoom free: at 125% the layout
+ * viewport is simply smaller in CSS pixels, so it is a resize, and the panel
+ * already knows what to do with one.
+ */
+ it('measures the same site the same way on a screen with three dots to the pixel', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const plain = await replay(recording);
+ const flat = { ...plain.state.frame };
+ plain.close();
+ panel = null;
+ const dense = await replay(recording, { ratio: 3 });
+ expect(dense.state.frame.x).toBeCloseTo(flat.x, 9);
+ expect(dense.state.frame.y).toBeCloseTo(flat.y, 9);
+ expect(dense.asks('/api/ingest/parse').at(-1).height).toBe(
+ plain.asks('/api/ingest/parse').at(-1).height
+ );
+ });
+
+ it('rasterises into the dots the screen has, and lays out in the pixels CSS has', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording, { ratio: 3 });
+ const canvas = live.canvas();
+ expect(canvas.width).toBe(recording.window.w * 3);
+ expect(canvas.style.width).toBe('100%');
+ });
+
+ it('keeps the ratio out of every file that decides where a mark lands', () => {
+ // The guard for the version of this that would pass the tests above and
+ // still be wrong: a ratio multiplied in somewhere along the geometry path
+ // is invisible on a screen with one dot to the pixel, which is the screen
+ // most of these tests run on.
+ for (const file of ['mapmath.js', 'maptools.js']) {
+ expect(read(file)).not.toMatch(/devicePixelRatio|screen\.(width|height)/);
+ }
+ // …and the one that reads it uses it for the backing store, never for a
+ // coordinate: what it scales is the context, at the point of drawing.
+ expect(read('mapdraw.js')).toMatch(/ctx\.setTransform\(ratio/);
+ });
+
+ it('reads a trackpad’s own idea of a notch, and leaves a sideways scroll alone', async () => {
+ // A wheel on Windows steps ±120 and a trackpad on macOS sends whatever the
+ // finger did, fractions included. Both are the same gesture to a map, and
+ // both have to dim the drawing: what follows is a zoom nobody can predict.
+ // A sideways scroll is not a zoom on any of them.
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording);
+ wheel(1200, 300, { deltaY: -3.4, ctrlKey: true }); // a pinch on a trackpad
+ expect(live.canvas().style.opacity).toBe('0.25');
+ live.location.href = recording.steps[1].url; // the map reports where it landed
+ await tick();
+ expect(live.canvas().style.opacity).toBe('');
+ wheel(1200, 300, { deltaY: 0, deltaX: -80 });
+ expect(live.canvas().style.opacity).toBe('');
+ });
+
+ it('runs on a browser that calls the extension API by its other name', async () => {
+ // Firefox hands a content script `browser`; Chrome hands it `chrome`. The
+ // panel takes whichever is there, and the map tools are the one part of the
+ // extension an analyst runs on someone else's page.
+ const recording = fixture.recordings.find((r) => r.site === 'openstreetmap');
+ const live = await replay(recording, { firefox: true });
+ expect(live.state.framed).toBe(true);
+ expect(Math.abs(live.state.frame.y - offset(recording).y)).toBeLessThan(1.5);
+ });
+});
+
+// --- out where the map stops being flat ---------------------------------------
+
+describe('zoomed out', () => {
+ const far = { extra: { far: true } };
+
+ it('keeps drawing, dimmed, and says the edges drift', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording, far);
+ expect(live.canvas().style.opacity).toBe('0.55');
+ expect(live.status()).toContain('drifts at the edges');
+ });
+
+ it('never measures the site’s layout from out there', async () => {
+ // A globe and a Mercator part company away from the point they are anchored
+ // on, so a zoom taken out there would solve for a centre that is not this
+ // site's — and then keep it, for every visit after.
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording, far);
+ expect(live.state.framed).toBe(false);
+ expect(live.state.frame).toEqual({ x: 0, y: 0 });
+ });
+});
+
+// --- the compass ---------------------------------------------------------------
+
+/**
+ * A free camera that has been turned.
+ *
+ * Google Earth is the one view whose address bar states no scale at all, so its
+ * drawing rests entirely on a pan this panel measured — and it is also the one
+ * whose compass can be dragged. Turning it threw that measurement away and the
+ * panel went back to asking for a pan it had already been given, on every nudge
+ * of the compass. Which reads as a tool that does not work on Earth.
+ *
+ * The measurement is handed over rather than performed: what is under test here
+ * is what a *turn* does to one, and `extensionMapMath.test.js` is where a turned
+ * drag is measured.
+ */
+describe('a map that has been turned', () => {
+ const HOME = { lat: 48.8584, lon: 2.2945 };
+ const PX_PER_LON = 1000;
+ const PX_PER_LAT = 1500;
+
+ const url = ({ h = 0, lat = HOME.lat, lon = HOME.lon } = {}) =>
+ `https://earth.google.com/web/@${lat},${lon},146a,666d,35y,${h}h,0t,0r`;
+
+ /** Earth's own reading: a position, a heading, and no scale of any kind. */
+ function earthParse(query) {
+ const at = /@([\d.-]+),([\d.-]+),[^/]*?([\d.-]+)h/.exec(query.url);
+ if (!at) return { site: null };
+ return {
+ site: 'google-earth',
+ label: 'Google Earth',
+ lat: Number(at[1]),
+ lon: Number(at[2]),
+ zoom: null,
+ bearing: Number(at[3]),
+ projection: null,
+ view_kind: 'map',
+ geometry: false,
+ scale_source: null,
+ far: false,
+ };
+ }
+
+ /** Two drags on a map held at `bearing`, as the calibration would have read
+ * them: the world moves along its own axes, so the pointer's travel is turned
+ * into them to work out where the centre went. */
+ function survey(live, bearing) {
+ const from = { ...HOME, bearing, zoom: 15, projection: 'webmercator' };
+ for (const [dx, dy] of [[200, 0], [0, -150]]) {
+ const world = window.AzimutMapMath.unturn(dx, dy, from);
+ const after = {
+ ...from,
+ lon: from.lon - world.dx / PX_PER_LON,
+ lat: from.lat - world.dy / PX_PER_LAT,
+ };
+ live.state.calibration.observe(from, after, dx, dy);
+ }
+ }
+
+ async function onEarth({ h = 0 } = {}) {
+ const live = open({ parse: earthParse });
+ live.location.href = url({ h });
+ await tick();
+ return live;
+ }
+
+ it('asks for a pan before it will draw, like any view with no scale in its URL', async () => {
+ const live = await onEarth();
+ panel = live;
+ expect(live.status()).toContain('Drag the map across and down');
+ });
+
+ it('keeps the scale it measured when the compass moves', async () => {
+ const live = await onEarth();
+ panel = live;
+ survey(live, 0);
+ expect(live.state.calibration.scale.pxPerLon).toBeCloseTo(PX_PER_LON, 0);
+
+ live.location.href = url({ h: 45 }); // the same view, turned
+ await tick();
+
+ expect(live.state.calibration.scale).not.toBe(null);
+ expect(live.state.calibration.scale.pxPerLon).toBeCloseTo(PX_PER_LON, 0);
+ expect(live.status()).toContain('measured off the map');
+ expect(live.status()).not.toContain('Drag the map across and down');
+ });
+
+ it('draws through it on the turned view', async () => {
+ const live = await onEarth({ h: 90 });
+ panel = live;
+ survey(live, 90);
+ live.pick('measure');
+ // A bearing is the direction the map has *up*, so with east up a point east
+ // of the centre is straight above it — 0.01° at 1000 px per degree is ten
+ // pixels, and none of them sideways.
+ const east = { lat: HOME.lat, lon: HOME.lon + 0.01 };
+ const at = window.AzimutMapMath.toScreenMeasured(
+ east,
+ { ...HOME, bearing: 90, projection: 'webmercator' },
+ { x: 0, y: 0, w: window.innerWidth, h: window.innerHeight },
+ live.state.calibration.scale
+ );
+ expect(at.y).toBeCloseTo(window.innerHeight / 2 - 10, 6);
+ expect(at.x).toBeCloseTo(window.innerWidth / 2, 6);
+ });
+
+ it('still throws it away when the turn came with a zoom', async () => {
+ // Two things moved at once and only one of them is a rotation, so nothing
+ // here can say what the other did to the scale. Asking for a pan is the
+ // honest answer to that, and it is the answer this used to give to a turn.
+ const live = await onEarth();
+ panel = live;
+ survey(live, 0);
+ live.api.runtime.sendMessage.mockImplementation(async (message) => {
+ if (message.type !== 'map-api') return { ok: true, data: {} };
+ if (message.path === '/api/ingest/parse') {
+ return { ok: true, data: { ...earthParse(message.query), zoom: 9 } };
+ }
+ if (message.path === '/api/ingest/ping') return { ok: true, data: { units: 'metric' } };
+ return { ok: true, data: [] };
+ });
+ live.location.href = url({ h: 45 });
+ await tick();
+ expect(live.state.calibration.scale).toBe(null);
+ });
+});
+
+// --- the panel's own width -----------------------------------------------------
+
+/**
+ * A name the case chose, in a panel 284 px wide.
+ *
+ * The reference rows carry whatever a video or an image is called, and a case
+ * calls things what the source called them — which is sometimes a sentence. Long
+ * enough, it used to size the panel's grid: the tab strip and the buttons were
+ * pushed out past the panel's own width and whatever sat beyond it was clipped
+ * away, so two tools became unreachable because of a file's name.
+ *
+ * The layout itself cannot be asserted here — happy-dom measures nothing — so
+ * what is pinned is the two things that hold it: the rule that lets every box
+ * shrink, and the name being readable somewhere other than the row it no longer
+ * fits in.
+ */
+describe('a reference whose name does not fit', () => {
+ const LONG = 'Long clip - 10. Mykhailivka railway bridge battles, 05 September, drone footage';
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+
+ it('keeps the name reachable, and lets every box round it shrink', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording);
+ live.tools.refs.add({ path: 'media/clip.mp4', kind: 'video', title: LONG });
+ live.pick('refs');
+
+ const row = root().querySelector('.ref-name');
+ // the row shows what it can and the tooltip carries the rest, rather than
+ // naming an action the analyst can see for themselves
+ expect(row.getAttribute('title')).toBe(LONG);
+ expect(row.querySelector('span').textContent).toBe(LONG);
+
+ const css = root().querySelector('style').textContent;
+ // the tab strip and the body column, each told it may go narrower than what
+ // is in it — `1fr` alone will not
+ const tabs = root().querySelectorAll('.tabs button').length;
+ expect(css).toContain(`repeat(${tabs}, minmax(0, 1fr))`);
+ expect(css).toContain('grid-template-columns: minmax(0, 1fr)');
+ });
+});
+
+/**
+ * Sun & moon out where the map is a globe.
+ *
+ * It is the tool with the least to lose there: what it answers is which way the
+ * light came from, and a bearing off the anchor is right in the middle of the
+ * screen whatever the edges are doing. So it stays available — dimmed and
+ * labelled, like everything else drawn out there, but never switched off.
+ */
+describe('the sky tool, zoomed out', () => {
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+
+ it('stays available on a globe, where only the distances are doubtful', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording, { extra: { far: true } });
+ live.pick('sky');
+ const plant = root().querySelector('[data-act="sky-place"]');
+ expect(plant.disabled).toBe(false);
+ expect(live.status()).toContain('drifts at the edges');
+ plant.click();
+ expect(live.tools.sky.placing).toBe(true);
+ });
+
+ it('draws at full strength out there, unlike the tools that place marks', async () => {
+ // Dimming says "this is somewhere the ground is not", which is true of a
+ // mark and not of a bearing read at its own anchor. Said of the sun path, it
+ // only had the analyst zooming in until the picture looked solid — for an
+ // answer that was already right. The status line still says where this is.
+ const recording = fixture.recordings.find((r) => r.site === 'google-maps');
+ const live = await replay(recording, { extra: { far: true } });
+ live.pick('sky');
+ expect(live.canvas().style.opacity).toBe('');
+ live.pick('measure');
+ expect(live.canvas().style.opacity).toBe('0.55');
+ });
+});
+
+/**
+ * The first measurement on Google Earth, over ground that is not flat.
+ *
+ * Earth is the one view with no scale in its address bar, so a drag is the only
+ * way to learn one — and the one view whose camera distance moves on its own,
+ * because `d` is measured to the ground and the ground has hills in it. Pan over
+ * one and `d` changes by more than the threshold that means "this zoomed".
+ *
+ * The panel then looked for a scale to carry through that zoom, had none — it
+ * was trying to take its first — reset, and threw away the drag that had just
+ * measured it. Every time. Which is a tool that asks for a pan it has already
+ * been given, on the only site where a pan is the whole answer.
+ */
+describe('measuring a view whose camera moves with the ground', () => {
+ const HOME = { lat: 48.8584, lon: 2.2945 };
+ const PX_PER_LON = 1000;
+ const PX_PER_LAT = 1500;
+
+ const url = ({ lat = HOME.lat, lon = HOME.lon, d = 666 } = {}) =>
+ `https://earth.google.com/web/@${lat},${lon},146a,${d}d,35y,0h,0t,0r`;
+
+ /** Earth's reading: a position, a camera distance, and no scale of any kind. */
+ function earthParse(query) {
+ const at = /@([\d.-]+),([\d.-]+),[\d.-]+a,([\d.-]+)d/.exec(query.url);
+ if (!at) return { site: null };
+ return {
+ site: 'google-earth',
+ label: 'Google Earth',
+ lat: Number(at[1]),
+ lon: Number(at[2]),
+ zoom: null,
+ bearing: 0,
+ projection: null,
+ view_kind: 'map',
+ geometry: false,
+ scale_source: null,
+ camera_m: Number(at[3]),
+ camera_kind: 'camera_d',
+ far: false,
+ };
+ }
+
+ /**
+ * A drag the panel will accept as a measurement: far enough on both axes, and
+ * let go of after the map has stopped. The timestamps are set by hand because
+ * that pause is the whole difference between a pan and a fling, and happy-dom
+ * hands out no clock of its own.
+ */
+ function drag(from, to, pause = 200) {
+ const send = (type, x, y, stamp) => {
+ const event = new window.MouseEvent(type, {
+ clientX: x,
+ clientY: y,
+ bubbles: true,
+ button: 0,
+ });
+ Object.defineProperty(event, 'timeStamp', { value: stamp });
+ window.dispatchEvent(event);
+ };
+ send('pointerdown', from.x, from.y, 0);
+ send('pointermove', to.x, to.y, 10);
+ send('pointerup', to.x, to.y, 10 + pause);
+ }
+
+ /** Where that drag leaves the centre, on a map drawn at the scale above. */
+ const landed = (dx, dy, d) =>
+ url({ lon: HOME.lon - dx / PX_PER_LON, lat: HOME.lat - dy / PX_PER_LAT, d });
+
+ async function onEarth() {
+ const live = open({ parse: earthParse });
+ live.location.href = url();
+ await tick();
+ return live;
+ }
+
+ it('takes the measurement even when the pan moved the camera distance', async () => {
+ const live = await onEarth();
+ panel = live;
+ expect(live.status()).toContain('Drag the map across and down');
+
+ drag({ x: 800, y: 500 }, { x: 1000, y: 350 });
+ // the drag crossed a hill: Earth re-writes `d` as well as the centre
+ live.location.href = landed(200, -150, 720);
+ await tick();
+
+ expect(live.state.calibration.scale).not.toBe(null);
+ expect(live.state.calibration.scale.pxPerLon).toBeCloseTo(PX_PER_LON, 0);
+ expect(live.state.calibration.scale.pxPerLat).toBeCloseTo(PX_PER_LAT, 0);
+ expect(live.status()).toContain('measured off the map');
+ });
+
+ it('still carries a scale it already had through a real change of distance', async () => {
+ // The other half of the rule: once something is known, a camera that moved
+ // out is a view drawn smaller, and the ratio of the two distances says by
+ // how much — that is the reading, and the drag is not asked for again.
+ const live = await onEarth();
+ panel = live;
+ drag({ x: 800, y: 500 }, { x: 1000, y: 350 });
+ live.location.href = landed(200, -150, 666);
+ await tick();
+ const measured = live.state.calibration.scale.pxPerLon;
+
+ live.location.href = url({ d: 1332 }); // twice as far out, nothing else moved
+ await tick();
+ expect(live.state.calibration.scale.pxPerLon).toBeCloseTo(measured / 2, 0);
+ expect(live.status()).toContain('measured off the map');
+ });
+
+ it('says what makes a drag count, since a fling looks the same', async () => {
+ const live = await onEarth();
+ panel = live;
+ drag({ x: 800, y: 500 }, { x: 1000, y: 350 }, 10); // let go mid-flight
+ live.location.href = landed(200, -150, 666);
+ await tick();
+ expect(live.state.calibration.scale).toBe(null);
+ expect(live.status()).toContain('pausing before you let go');
+ });
+});
diff --git a/frontend/src/lib/extensionMapFrame.test.js b/frontend/src/lib/extensionMapFrame.test.js
new file mode 100644
index 0000000..e88b424
--- /dev/null
+++ b/frontend/src/lib/extensionMapFrame.test.js
@@ -0,0 +1,356 @@
+// @vitest-environment happy-dom
+/**
+ * The map tools' arithmetic, replayed against real browsers.
+ *
+ * `tests/fixtures/map-sites.json` is a recording: nine map sites opened at a
+ * known level, dragged a known number of pixels and zoomed about a known pixel,
+ * with every URL they wrote about themselves kept. Nothing here is a table
+ * written to suit the code — the numbers came out of Chromium.
+ *
+ * Two properties are checked, and between them they pin the whole drawing model:
+ *
+ * 1. **The centre solve is self-consistent.** Each site was zoomed twice, about
+ * two different pixels. Solving for the camera centre from each zoom
+ * separately must give the same answer — and it only can if the projection,
+ * the zoom the URL stated and the conversion that produced it are all right.
+ * A scale off by a percent shows up here as two centres tens of pixels apart.
+ * 2. **It lands where the browser had it.** The solved centre must match the
+ * offset the site's own layout puts it at, which is the number recorded.
+ *
+ * The views are the ones `engine/mapsites.py` returns; the Python suite asserts
+ * that separately against the same file, so a parser that drifts is caught on
+ * that side rather than quietly moving the geometry here.
+ */
+import { describe, expect, it, beforeAll } 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 root = join(here, '../../..');
+const source = readFileSync(join(root, 'extension/mapmath.js'), 'utf8');
+const { recordings, rounding } = JSON.parse(
+ readFileSync(join(root, 'tests/fixtures/map-sites.json'), 'utf8')
+);
+
+let ext;
+beforeAll(() => {
+ const scope = { window: {} };
+ new Function('window', source)(scope.window);
+ ext = scope.window.AzimutMapMath;
+});
+
+const withZooms = recordings.filter((r) => r.zooms.length >= 1);
+const twoZooms = recordings.filter((r) => r.zooms.length >= 2);
+
+describe('where each site draws its own centre', () => {
+ it('has a recording for every site the app sends people to', () => {
+ const sites = new Set(recordings.map((r) => r.site));
+ expect([...sites].sort()).toEqual([
+ 'apple-maps',
+ 'bing-maps',
+ 'copernicus-browser',
+ 'google-maps',
+ 'openstreetmap',
+ 'satellites-pro',
+ 'yandex-maps',
+ 'zoom-earth',
+ ]);
+ });
+
+ it.each(twoZooms.map((r) => [r.label, r]))(
+ 'solves the same centre from either zoom on %s',
+ (_label, recording) => {
+ const solved = recording.zooms.map((z) =>
+ ext.centreFromZoom(
+ recording.steps[z.from].view,
+ recording.steps[z.to].view,
+ z.at
+ )
+ );
+ for (const centre of solved) expect(centre).not.toBeNull();
+ // …and the two zooms were made far enough apart for that to mean
+ // something. Two notches over the same pixel would agree for the same
+ // reason a ruler agrees with itself. Stated as a share of the window, so
+ // a recording taken in a smaller one is held to the same standard rather
+ // than to the same number of pixels.
+ const [first, second] = recording.zooms;
+ const apart = Math.hypot(first.at.x - second.at.x, first.at.y - second.at.y);
+ expect(apart).toBeGreaterThan(0.2 * Math.hypot(recording.window.w, recording.window.h));
+ // Two pixels of slack, and only Google's satellite view needs any of it:
+ // it states its scale as a whole number of metres, and half a metre in
+ // 3231 comes out of the division below as about a pixel.
+ expect(Math.abs(solved[0].x - solved[1].x)).toBeLessThan(2);
+ expect(Math.abs(solved[0].y - solved[1].y)).toBeLessThan(2);
+ }
+ );
+
+ it.each(withZooms.map((r) => [r.label, r]))(
+ 'puts the camera where the browser had it on %s',
+ (_label, recording) => {
+ const z = recording.zooms[0];
+ const centre = ext.centreFromZoom(
+ recording.steps[z.from].view,
+ recording.steps[z.to].view,
+ z.at
+ );
+ expect(Math.abs(centre.x - recording.centre.x)).toBeLessThan(1.5);
+ expect(Math.abs(centre.y - recording.centre.y)).toBeLessThan(1.5);
+ }
+ );
+
+ /**
+ * The same answers, read as ground rather than as pixels — which is the
+ * question an analyst actually asks.
+ *
+ * A pixel is worth 0.6 m at level 17 and 0.3 m at 18, the range this tool is
+ * used in to pin a building down, so the budget is stated there. What sets
+ * the floor is not the arithmetic but how finely each site writes its own
+ * coordinates: Google writes seven decimals (a centimetre), Copernicus and
+ * OpenStreetMap five (about a metre), and no measurement can be better than
+ * the number it was taken from.
+ */
+ const METRES_PER_PIXEL = (lat, zoom) =>
+ (156543.03392804097 * Math.cos((lat * Math.PI) / 180)) / 2 ** zoom;
+
+ it.each(withZooms.map((r) => [r.label, r]))('is inside a metre of ground on %s', (_label, recording) => {
+ const z = recording.zooms[0];
+ const centre = ext.centreFromZoom(
+ recording.steps[z.from].view,
+ recording.steps[z.to].view,
+ z.at
+ );
+ const off = Math.hypot(centre.x - recording.centre.x, centre.y - recording.centre.y);
+ const { lat } = recording.steps[z.from].view;
+ expect(off * METRES_PER_PIXEL(lat, 18)).toBeLessThan(1);
+ expect(off * METRES_PER_PIXEL(lat, 17)).toBeLessThan(2);
+ });
+
+ it('is not the middle of the window on five of the eight', () => {
+ // The whole point of measuring it. Drawn on the window's centre instead,
+ // Yandex is out by 210 px at every zoom — 90 m of ground at level 15 — and
+ // no pan can ever see it, because the offset slides with the map.
+ const off = recordings.filter(
+ (r) =>
+ Math.abs(r.centre.x - r.window.w / 2) > 5 ||
+ Math.abs(r.centre.y - r.window.h / 2) > 5
+ );
+ expect([...new Set(off.map((r) => r.site))].sort()).toEqual([
+ 'apple-maps',
+ 'bing-maps',
+ 'copernicus-browser',
+ 'openstreetmap',
+ 'yandex-maps',
+ ]);
+ });
+
+ /**
+ * The same site, driven again in a window of another size.
+ *
+ * This is the question a table cannot answer and a measurement can. Some of
+ * this chrome is a fixed number of pixels and keeps its offset whatever the
+ * window does; some of it is a layout that answers the window, and moves.
+ * Nothing in the address bar says which, and the site is free to change its
+ * mind between two releases.
+ *
+ * It is also what makes the browser's own zoom a non-question: at 125% the
+ * layout viewport is simply fewer CSS pixels, so a zoomed browser is a
+ * smaller window, and these are the two answers a smaller window gets.
+ */
+ const offset = (r) => ({ x: r.centre.x - r.window.w / 2, y: r.centre.y - r.window.h / 2 });
+ const twice = [...new Set(recordings.map((r) => r.site))]
+ .map((site) => [site, recordings.filter((r) => r.site === site)])
+ .filter(([, group]) => new Set(group.map((r) => `${r.window.w}x${r.window.h}`)).size > 1);
+
+ it('was driven at more than one window size on three of the sites', () => {
+ expect(twice.map(([site]) => site).sort()).toEqual([
+ 'apple-maps',
+ 'openstreetmap',
+ 'yandex-maps',
+ ]);
+ });
+
+ it.each(twice)('measures %s in each window rather than carrying one answer over', (_site, group) => {
+ for (const recording of group) {
+ const z = recording.zooms[0];
+ const solved = ext.centreFromZoom(
+ recording.steps[z.from].view,
+ recording.steps[z.to].view,
+ z.at
+ );
+ const want = offset(recording);
+ expect(Math.abs(solved.x - recording.window.w / 2 - want.x)).toBeLessThan(1.5);
+ expect(Math.abs(solved.y - recording.window.h / 2 - want.y)).toBeLessThan(1.5);
+ }
+ });
+
+ it('says which browser and which browser zoom each answer came from', () => {
+ // Provenance the recorder writes and the build carries (`protocol.mjs`,
+ // `scripts/build_map_fixture.py`). The second half is the claim it is there
+ // for: two runs of one site in the same CSS window have to agree about where
+ // its camera is, whatever engine drew it and whatever the screen was made
+ // of. It has nothing to compare until the matrix is filled in, and then it
+ // has everything.
+ const window = (r) => `${r.window.w}x${r.window.h}`;
+ for (const recording of recordings) {
+ expect(['chromium', 'firefox']).toContain(recording.browser);
+ expect(recording.page_zoom).toBeGreaterThan(0);
+ }
+ for (const recording of recordings) {
+ for (const other of recordings) {
+ if (other === recording) continue;
+ if (other.site !== recording.site || window(other) !== window(recording)) continue;
+ expect(Math.abs(other.centre.x - recording.centre.x)).toBeLessThan(1.5);
+ expect(Math.abs(other.centre.y - recording.centre.y)).toBeLessThan(1.5);
+ }
+ }
+ });
+
+ it('separates the chrome that keeps its pixels from the chrome that answers the window', () => {
+ // Yandex's results panel is 420 px wide whatever the window is, so its
+ // offset does not move. Apple's sidebar collapses on the way down, and its
+ // offset moves by 70 px — which is 21 m of ground at level 18, on a tool
+ // whose whole job is putting a mark on a building.
+ const moved = Object.fromEntries(
+ twice.map(([site, group]) => {
+ const [a, b] = group.map(offset);
+ return [site, Math.round(Math.hypot(a.x - b.x, a.y - b.y))];
+ })
+ );
+ expect(moved).toEqual({ 'apple-maps': 70, openstreetmap: 0, 'yandex-maps': 0 });
+ });
+
+ it('refuses to answer from a zoom too small to divide by', () => {
+ const [first] = twoZooms;
+ const before = first.steps[first.zooms[0].from].view;
+ const nudged = { ...before, zoom: before.zoom + 0.2, lon: before.lon + 0.001 };
+ expect(ext.centreFromZoom(before, nudged, first.zooms[0].at)).toBeNull();
+ });
+
+ it('refuses a gesture that turned as it zoomed, where one offset had two bearings', () => {
+ const [first] = twoZooms;
+ const z = first.zooms[0];
+ const before = { ...first.steps[z.from].view, bearing: 30 };
+ expect(ext.centreFromZoom(before, first.steps[z.to].view, z.at)).toBeNull();
+ });
+
+ it('answers on a map held at a bearing, the offset turned back first', () => {
+ // Being turned is a state, not a gesture: the same zoom on the same site
+ // says the same thing about where its centre is, whichever way the compass
+ // was pointing while it happened.
+ const [first] = twoZooms;
+ const z = first.zooms[0];
+ const level = ext.centreFromZoom(first.steps[z.from].view, first.steps[z.to].view, z.at);
+ const turn = (view) => ({ ...view, bearing: 30 });
+ const turned = ext.centreFromZoom(turn(first.steps[z.from].view), turn(first.steps[z.to].view), z.at);
+ expect(turned).not.toBeNull();
+ // the held pixel is the same one, so the centre solved from it is too —
+ // rotated, about that pixel, by the bearing the view was held at
+ const spun = ext.turn(level.x - z.at.x, level.y - z.at.y, { bearing: 30 });
+ expect(turned.x).toBeCloseTo(z.at.x + spun.dx, 6);
+ expect(turned.y).toBeCloseTo(z.at.y + spun.dy, 6);
+ });
+});
+
+describe('the drawing follows a drag', () => {
+ /**
+ * The recorded drags are the softer half of the recording: a synthetic
+ * pointer loses a few pixels to each site's own drag threshold, and Apple
+ * eases the map on after the button comes up — measured, it reported a tenth
+ * more movement than the pointer made. So this asks the question those
+ * artefacts cannot swallow: the point that was centred before the drag has to
+ * land nearer where the pointer actually went than to any flip of it.
+ *
+ * That is what a wrong drawing looks like in practice. Yandex writes
+ * longitude first; read as latitude, a pan lands at the mirrored offset and
+ * fails here. So does a sign error, an axis swap, and a scale off by more
+ * than the drag itself.
+ */
+ it.each(recordings.filter((r) => r.pan).map((r) => [r.label, r]))(
+ 'lands nearer the pointer than any flip of it on %s',
+ (_label, recording) => {
+ const { pan } = recording;
+ const before = recording.steps[pan.from].view;
+ const after = recording.steps[pan.to].view;
+ // Copernicus rewrites its URL on a zoom but not on a pan, so it has
+ // nothing to say here — the overlay carries that pan on the canvas
+ // instead, which is `mapoverlay.js`'s business rather than this file's.
+ if (before.lat === after.lat && before.lon === after.lon) return;
+ const area = {
+ x: recording.centre.x - recording.window.w / 2,
+ y: recording.centre.y - recording.window.h / 2,
+ w: recording.window.w,
+ h: recording.window.h,
+ };
+ const landed = ext.toScreen(before, after, area);
+ const middle = { x: area.x + area.w / 2, y: area.y + area.h / 2 };
+ const away = ({ x, y }) =>
+ Math.hypot(landed.x - (middle.x + x), landed.y - (middle.y + y));
+ const right = away({ x: pan.dx, y: pan.dy });
+ for (const flip of [
+ { x: -pan.dx, y: pan.dy },
+ { x: pan.dx, y: -pan.dy },
+ { x: -pan.dx, y: -pan.dy },
+ { x: pan.dy, y: pan.dx },
+ ]) {
+ expect(right).toBeLessThan(away(flip));
+ }
+ // …and within a quarter of the drag, which no flip is
+ expect(right).toBeLessThan(0.25 * Math.hypot(pan.dx, pan.dy));
+ }
+ );
+});
+
+describe('the one site that rounds the zoom it writes', () => {
+ /**
+ * Bing's wheel moves a third of a level and its URL carries one decimal, so
+ * "15.3" is really 15.334. Read as stated, the drawing is scaled two and a
+ * third percent wrong — nothing at the middle of the screen, five metres at
+ * the edge of it at level 18, which is the difference between a building and
+ * the one next door.
+ *
+ * The recording is six notches about one pixel, from a whole level. Each one
+ * is solved from the one before it, the way the panel does it.
+ */
+ const middle = { x: rounding.centre.x, y: rounding.centre.y };
+
+ it('recovers the third of a level the address bar rounded away', () => {
+ let before = rounding.steps[0].view;
+ const solved = [];
+ for (const step of rounding.steps.slice(1)) {
+ const zoom = ext.zoomFromAnchor(before, step.view, rounding.at, middle);
+ solved.push({ stated: step.view.zoom, zoom });
+ before = { ...step.view, zoom };
+ }
+ for (const [i, { zoom }] of solved.entries()) {
+ expect(zoom).not.toBeNull();
+ // the true level is the whole one it started from, plus a third a notch
+ expect(zoom).toBeCloseTo(rounding.steps[0].view.zoom + (i + 1) * rounding.step, 1);
+ }
+ // …and the first of them is a full third of a level from what was written
+ expect(solved[0].zoom - solved[0].stated).toBeGreaterThan(0.02);
+ });
+
+ it('refuses to correct from a view whose own zoom is a guess', () => {
+ // the same pair read straight off the address bar: the answer is inside
+ // half a level of what the site said, so it is a correction, not a rescue
+ const [first, second, third] = rounding.steps;
+ const straight = ext.zoomFromAnchor(second.view, third.view, rounding.at, middle);
+ expect(Math.abs(straight - third.view.zoom)).toBeLessThan(0.5);
+ expect(ext.zoomFromAnchor(first.view, second.view, { x: middle.x + 4, y: middle.y }, middle))
+ .toBeNull(); // an anchor on top of the centre divides by nothing
+ });
+
+ it('still puts the camera where the browser had it, from the whole levels', () => {
+ // 15 → 16 and 16 → 17: the two pairs the address bar states exactly
+ for (const [from, to] of [[0, 3], [3, 6]]) {
+ const centre = ext.centreFromZoom(
+ rounding.steps[from].view,
+ rounding.steps[to].view,
+ rounding.at
+ );
+ expect(Math.abs(centre.x - rounding.centre.x)).toBeLessThan(1);
+ expect(Math.abs(centre.y - rounding.centre.y)).toBeLessThan(1);
+ }
+ });
+});
diff --git a/frontend/src/lib/extensionMapMath.test.js b/frontend/src/lib/extensionMapMath.test.js
new file mode 100644
index 0000000..b1bd166
--- /dev/null
+++ b/frontend/src/lib/extensionMapMath.test.js
@@ -0,0 +1,560 @@
+// @vitest-environment happy-dom
+/**
+ * The map tools' arithmetic, on both sides of a boundary it cannot be imported
+ * across (extension/mapmath.js).
+ *
+ * The extension ships as plain classic scripts with no build step, so the
+ * geodesic measures the app states in `lib/measure.js` are written a second
+ * time over there. That is normally how two copies start disagreeing — so this
+ * file is the module system's replacement: it runs both over the same points
+ * and fails on the first digit they differ about.
+ *
+ * The projections have no counterpart in the app (the app owns its own map, and
+ * never has to guess someone else's), so they are pinned against the property
+ * that actually matters: a round trip, and the two flattenings not being
+ * interchangeable.
+ */
+import { describe, expect, it, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import * as app from './measure.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const source = readFileSync(join(here, '../../../extension/mapmath.js'), 'utf8');
+
+let ext;
+
+beforeAll(() => {
+ const scope = { window: {} };
+ new Function('window', source)(scope.window);
+ ext = scope.window.AzimutMapMath;
+});
+
+/** Points spread over latitude, the antimeridian and both hemispheres — the
+ * places a formula that is nearly right stops being right. */
+const POINTS = [
+ { lat: 0, lon: 0 },
+ { lat: 48.8584, lon: 2.2945 },
+ { lat: -33.8568, lon: 151.2153 },
+ { lat: 68.9585, lon: 33.0827 },
+ { lat: -54.8019, lon: -68.302 },
+ { lat: 1.3521, lon: 103.8198 },
+ { lat: 64.1466, lon: -21.9426 },
+];
+
+const view = (over, projection = 'webmercator', zoom = 15) => ({
+ lat: over.lat,
+ lon: over.lon,
+ zoom,
+ bearing: 0,
+ projection,
+});
+
+const AREA = { x: 0, y: 0, w: 1400, h: 900 };
+
+describe('the two copies of the measures agree', () => {
+ it('on every distance between the sample points', () => {
+ for (const a of POINTS) {
+ for (const b of POINTS) {
+ expect(ext.haversine(a, b)).toBeCloseTo(app.haversine(a, b), 6);
+ }
+ }
+ });
+
+ it('on the length of a path through all of them', () => {
+ expect(ext.pathLength(POINTS)).toBeCloseTo(app.pathLength(POINTS), 6);
+ });
+
+ it('on the area of a polygon, at the equator and up north', () => {
+ const equator = [
+ { lat: 0, lon: 0 },
+ { lat: 0, lon: 1 },
+ { lat: 1, lon: 1 },
+ { lat: 1, lon: 0 },
+ ];
+ const arctic = equator.map((p) => ({ lat: p.lat + 70, lon: p.lon }));
+ expect(ext.polygonArea(equator)).toBeCloseTo(app.polygonArea(equator), 3);
+ expect(ext.polygonArea(arctic)).toBeCloseTo(app.polygonArea(arctic), 3);
+ });
+
+ it('on how a distance is written, in both unit systems', () => {
+ for (const m of [0, 1, 42, 999, 1000, 1609.344, 25000, 1e6]) {
+ expect(ext.formatDistance(m)).toBe(app.formatDistance(m));
+ expect(ext.formatDistance(m, 'imperial')).toBe(app.formatDistance(m, 'imperial'));
+ }
+ });
+
+ it('on how an area is written, in both unit systems', () => {
+ for (const m2 of [0, 500, 9999, 10000, 4046.86, 1e6, 1e7, 2.59e6]) {
+ expect(ext.formatArea(m2)).toBe(app.formatArea(m2));
+ expect(ext.formatArea(m2, 'imperial')).toBe(app.formatArea(m2, 'imperial'));
+ }
+ });
+});
+
+describe('projecting a point onto someone else’s map', () => {
+ it('puts the view’s own centre in the middle of the map area', () => {
+ for (const point of POINTS) {
+ const at = ext.toScreen(point, view(point), AREA);
+ expect(at.x).toBeCloseTo(AREA.x + AREA.w / 2, 6);
+ expect(at.y).toBeCloseTo(AREA.y + AREA.h / 2, 6);
+ }
+ });
+
+ it('round-trips a pixel back to the coordinate it came from', () => {
+ for (const projection of ['webmercator', 'ellipsoidal']) {
+ for (const centre of POINTS) {
+ for (const at of [
+ { x: 10, y: 10 },
+ { x: 700, y: 450 },
+ { x: 1390, y: 890 },
+ ]) {
+ const back = ext.toScreen(ext.toLatLon(at, view(centre, projection), AREA), view(centre, projection), AREA);
+ expect(back.x).toBeCloseTo(at.x, 6);
+ expect(back.y).toBeCloseTo(at.y, 6);
+ }
+ }
+ }
+ });
+
+ it('does not fling a point across the screen at the antimeridian', () => {
+ // a kilometre either side of the line is a kilometre, not most of a world
+ const centre = { lat: 0, lon: 179.99 };
+ const across = { lat: 0, lon: -179.99 };
+ const at = ext.toScreen(across, view(centre, 'webmercator', 10), AREA);
+ expect(Math.abs(at.x - AREA.w / 2)).toBeLessThan(50);
+ });
+
+ it('turns the drawing with a rotated view', () => {
+ const centre = { lat: 48.8584, lon: 2.2945 };
+ const north = { lat: 48.8684, lon: 2.2945 };
+ const up = ext.toScreen(north, { ...view(centre), bearing: 0 }, AREA);
+ const turned = ext.toScreen(north, { ...view(centre), bearing: 90 }, AREA);
+ expect(up.y).toBeLessThan(AREA.h / 2); // north is up…
+ expect(turned.x).toBeLessThan(AREA.w / 2); // …and to the left once turned
+ });
+
+ it('refuses a view whose flattening nobody named', () => {
+ // guessing here is the failure mode the whole field exists to prevent
+ expect(() => ext.toScreen(POINTS[1], view(POINTS[1], null), AREA)).toThrow(/projection/);
+ expect(() => ext.toScreen(POINTS[1], view(POINTS[1], 'guess'), AREA)).toThrow(/projection/);
+ });
+});
+
+describe('the two flattenings are not interchangeable', () => {
+ it('agree at the anchor and drift apart across the viewport', () => {
+ const centre = { lat: 55.7558, lon: 37.6173 }; // Yandex country
+ const middle = { x: AREA.w / 2, y: AREA.h / 2 };
+ const edge = { x: AREA.w / 2, y: 0 };
+ const sphere = view(centre, 'webmercator', 12);
+ const ellipse = view(centre, 'ellipsoidal', 12);
+
+ const atAnchor = ext.haversine(
+ ext.toLatLon(middle, sphere, AREA),
+ ext.toLatLon(middle, ellipse, AREA)
+ );
+ const atEdge = ext.haversine(
+ ext.toLatLon(edge, sphere, AREA),
+ ext.toLatLon(edge, ellipse, AREA)
+ );
+ expect(atAnchor).toBeLessThan(0.01); // the anchor is shared, so no offset
+ expect(atEdge).toBeGreaterThan(1); // …and the scale error shows at the edge
+ });
+
+ it('shrinks the disagreement as the view zooms in, since the edge comes closer', () => {
+ const centre = { lat: 55.7558, lon: 37.6173 };
+ const edge = { x: AREA.w / 2, y: 0 };
+ const gap = (zoom) =>
+ ext.haversine(
+ ext.toLatLon(edge, view(centre, 'webmercator', zoom), AREA),
+ ext.toLatLon(edge, view(centre, 'ellipsoidal', zoom), AREA)
+ );
+ expect(gap(12)).toBeGreaterThan(gap(15));
+ expect(gap(15)).toBeGreaterThan(gap(17));
+ expect(gap(17)).toBeLessThan(2); // where the tools are actually used
+ });
+});
+
+/**
+ * The map itself: dragging the content by dx/dy moves the centre the other way,
+ * in the flattening the site really draws in.
+ *
+ * The extension never does this — it moves the canvas and waits for the address
+ * bar to say where the map landed — so the simulator lives here, where being
+ * the ground truth is the whole job.
+ */
+function dragged(view, dx, dy) {
+ const centre = ext.project(view.lat, view.lon, view.zoom, view.projection);
+ const moved = ext.unproject(centre.x - dx, centre.y - dy, view.zoom, view.projection);
+ return { ...view, ...moved };
+}
+
+describe('the zoom a measured scale names', () => {
+ it('reads back the zoom the map was drawn at', () => {
+ // what makes a measurement able to correct a *scale* without replacing the
+ // *shape*: pxPerLon names the zoom, and both Mercators agree about it
+ for (const zoom of [3, 12.37, 17, 21.5]) {
+ for (const how of ['webmercator', 'ellipsoidal']) {
+ const step = 0.0005;
+ const at = { lat: 48.8584, lon: 2.2945 };
+ const east = ext.project(at.lat, at.lon + step, zoom, how).x;
+ const west = ext.project(at.lat, at.lon - step, zoom, how).x;
+ expect(ext.zoomFromScale((east - west) / (2 * step))).toBeCloseTo(zoom, 9);
+ }
+ }
+ });
+
+ it('has nothing to say without a scale', () => {
+ expect(ext.zoomFromScale(0)).toBe(null);
+ expect(ext.zoomFromScale(null)).toBe(null);
+ });
+});
+
+describe('reading the new scale off the point a zoom held still', () => {
+ /** A map at `zoom`, and the view that results from zooming about `at` by
+ * `factor` while keeping whatever is under that pixel where it is. */
+ function zoomAbout(view, factor, at) {
+ const held = ext.toLatLon(at, view, AREA);
+ const centre = ext.project(view.lat, view.lon, view.zoom, view.projection);
+ const point = ext.project(held.lat, held.lon, view.zoom, view.projection);
+ // The held point keeps its pixel offset from the centre while the scale
+ // grows by `factor`, so in the fixed world of the old zoom the centre closes
+ // in on it by the same factor.
+ const after = {
+ x: point.x + (centre.x - point.x) / factor,
+ y: point.y + (centre.y - point.y) / factor,
+ };
+ const moved = ext.unproject(after.x, after.y, view.zoom, view.projection);
+ return { view: { ...view, ...moved }, held };
+ }
+
+ const START = { lat: 48.8584, lon: 2.2945, zoom: 14, bearing: 0, projection: 'webmercator' };
+
+ function scaleAt(view) {
+ const step = 0.0005;
+ const east = ext.project(view.lat, view.lon + step, view.zoom, view.projection).x;
+ const west = ext.project(view.lat, view.lon - step, view.zoom, view.projection).x;
+ const north = ext.project(view.lat + step, view.lon, view.zoom, view.projection).y;
+ const south = ext.project(view.lat - step, view.lon, view.zoom, view.projection).y;
+ return { pxPerLon: (east - west) / (2 * step), pxPerLat: (north - south) / (2 * step) };
+ }
+
+ it('recovers the factor exactly off the longitude axis', () => {
+ // Longitude is where Mercator is linear, so the answer is the factor itself
+ // — no projection, no zoom level, no tile size anywhere in the arithmetic.
+ const scale = scaleAt(START);
+ for (const at of [{ x: 1100, y: 300 }, { x: 200, y: 700 }]) {
+ for (const factor of [2, 0.5, 1.37]) {
+ const { view, held } = zoomAbout(START, factor, at);
+ expect(ext.rescaleFromAnchor({ x: at.x, y: at.y, ...held }, view, AREA, scale))
+ .toBeCloseTo(factor, 6);
+ }
+ }
+ });
+
+ it('is within a thousandth off the latitude axis, where Mercator bends', () => {
+ // An anchor straight above the centre leaves only the northing to divide by,
+ // and the northing is not linear in latitude. Over a few hundred pixels that
+ // is a fraction of a percent — small enough to draw with, and the residual
+ // is watching it either way.
+ const at = { x: AREA.x + AREA.w / 2, y: 160 };
+ const { view, held } = zoomAbout(START, 2, at);
+ const factor = ext.rescaleFromAnchor({ x: at.x, y: at.y, ...held }, view, AREA, scaleAt(START));
+ expect(factor).toBeCloseTo(2, 2);
+ });
+
+ it('refuses an anchor too close to the centre to divide by', () => {
+ // there the difference in coordinate is smaller than the address bar's own
+ // rounding, and the division turns that into any number at all
+ const at = { x: AREA.x + AREA.w / 2 + 5, y: AREA.y + AREA.h / 2 + 5 };
+ const { view, held } = zoomAbout(START, 2, at);
+ expect(ext.rescaleFromAnchor({ x: at.x, y: at.y, ...held }, view, AREA, scaleAt(START))).toBe(null);
+ });
+
+ it('reads a rotated map, the anchor turned back into the world’s axes', () => {
+ // Turning a view changes which way the screen looks at the ground and
+ // nothing about how big the ground is drawn, so the factor is the same one.
+ // This used to be a refusal, and on Google Earth — the one view with no
+ // scale in its URL — a refusal here meant the tools stopped at the first
+ // nudge of the compass.
+ const turned = { ...START, bearing: 30 };
+ const scale = scaleAt(turned);
+ for (const at of [{ x: 1100, y: 300 }, { x: 200, y: 700 }]) {
+ const { view, held } = zoomAbout(turned, 2, at);
+ expect(ext.rescaleFromAnchor({ x: at.x, y: at.y, ...held }, view, AREA, scale))
+ .toBeCloseTo(2, 2);
+ }
+ });
+
+ it('refuses when there is nothing to rescale from', () => {
+ expect(ext.rescaleFromAnchor(null, START, AREA, scaleAt(START))).toBe(null);
+ expect(ext.rescaleFromAnchor({ x: 900, y: 300, lat: 1, lon: 1 }, START, AREA, null)).toBe(null);
+ });
+
+ it('refuses a factor no zoom could have produced', () => {
+ // a stale anchor, or a jump to somewhere else entirely: a hundredfold is
+ // not a zoom step, it is a different map
+ const anchor = { x: 900, y: 300, lat: 48.8584, lon: 2.2945 + 1e-6 };
+ expect(ext.rescaleFromAnchor(anchor, START, AREA, scaleAt(START))).toBe(null);
+ });
+});
+
+describe('carrying a measured scale through a zoom nobody named', () => {
+ it('rescales by the ratio of two camera spans', () => {
+ const cal = ext.createCalibration();
+ const real = { lat: 10, lon: -66, zoom: 14, bearing: 0, projection: 'webmercator' };
+ for (const [dx, dy] of [[200, 0], [0, -150]]) cal.observe(real, dragged(real, dx, dy), dx, dy);
+ const before = { ...cal.scale };
+ // the address bar went from 4378 m across to 2189: twice as close, twice
+ // the pixels per degree
+ expect(cal.rescale(4378 / 2189)).toBe(true);
+ expect(cal.scale.pxPerLon).toBeCloseTo(before.pxPerLon * 2, 9);
+ expect(cal.scale.pxPerLat).toBeCloseTo(before.pxPerLat * 2, 9);
+ // and it claims nothing about a prediction it has not made yet
+ expect(cal.residual).toBe(null);
+ });
+
+ it('refuses to carry what it never measured, or by a factor that is not one', () => {
+ const cal = ext.createCalibration();
+ expect(cal.rescale(2)).toBe(false); // nothing measured yet
+ const real = { lat: 10, lon: -66, zoom: 14, bearing: 0, projection: 'webmercator' };
+ for (const [dx, dy] of [[200, 0], [0, -150]]) cal.observe(real, dragged(real, dx, dy), dx, dy);
+ expect(cal.rescale(0)).toBe(false);
+ expect(cal.rescale(-1)).toBe(false);
+ expect(cal.rescale(Number.NaN)).toBe(false);
+ });
+});
+
+describe('measuring the map instead of assuming it', () => {
+ const AT = { lat: 55.7558, lon: 37.6173 }; // Moscow, where the two differ most
+
+ /** Pan a simulated map drawn in `truth`, and hand the calibration what the
+ * address bar would have said afterwards — never which projection it was. */
+ function survey(truth, pans = [[200, 0], [0, -150]], zoom = 14) {
+ const real = { ...AT, zoom, bearing: 0, projection: truth };
+ const cal = ext.createCalibration();
+ for (const [dx, dy] of pans) cal.observe(real, dragged(real, dx, dy), dx, dy);
+ return { cal, real };
+ }
+
+ it('puts a name to the flattening it just measured', () => {
+ for (const truth of ['webmercator', 'ellipsoidal']) {
+ const { cal, real } = survey(truth);
+ expect(ext.identify(cal.scale, real)).toBe(truth);
+ }
+ });
+
+ it('says nothing rather than the nearest thing, for a map drawn in neither', () => {
+ // an equal-area map stretches latitude the other way; nothing in the table
+ // matches, and the honest answer is that we cannot name it
+ const { cal, real } = survey('webmercator');
+ const foreign = { ...cal.scale, pxPerLat: cal.scale.pxPerLat * 0.6 };
+ expect(ext.identify(foreign, real)).toBe(null);
+ });
+
+ it('draws through the measurement without consulting any projection', () => {
+ const { cal, real } = survey('ellipsoidal');
+ const point = { lat: AT.lat + 0.004, lon: AT.lon + 0.006 };
+ const truth = ext.toScreen(point, real, AREA);
+ const measured = ext.toScreenMeasured(point, real, AREA, cal.scale);
+ // within a pixel of the projection it never saw
+ expect(measured.x).toBeCloseTo(truth.x, 0);
+ expect(measured.y).toBeCloseTo(truth.y, 0);
+ });
+
+ it('round-trips a pixel through the measured scale', () => {
+ const { cal, real } = survey('webmercator');
+ for (const at of [{ x: 100, y: 120 }, { x: 900, y: 700 }]) {
+ const back = ext.toScreenMeasured(
+ ext.toLatLonMeasured(at, real, AREA, cal.scale),
+ real,
+ AREA,
+ cal.scale
+ );
+ expect(back.x).toBeCloseTo(at.x, 6);
+ expect(back.y).toBeCloseTo(at.y, 6);
+ }
+ });
+
+ it('ignores a nudge too small to divide into a rounded coordinate', () => {
+ const { cal } = survey('webmercator', [[3, 0], [0, -4]]);
+ expect(cal.samples).toBe(0);
+ expect(cal.scale).toBe(null);
+ });
+
+ it('needs a pan on each axis before it can draw anything', () => {
+ const { cal } = survey('webmercator', [[200, 0]]);
+ expect(cal.samples).toBe(1);
+ expect(cal.scale).toBe(null); // one axis is not a scale
+ });
+
+ it('reports a small residual while the map keeps behaving', () => {
+ const { cal, real } = survey('ellipsoidal', [[200, 0], [0, -150]]);
+ cal.observe(real, dragged(real, 120, -90), 120, -90);
+ expect(cal.residual).toBeLessThan(1);
+ });
+
+ it('reports a large one the moment the map stops matching', () => {
+ // the site switched flattening under us, or drew a globe, or opened a panel
+ const { cal, real } = survey('webmercator');
+ const elsewhere = { ...real, projection: 'ellipsoidal', zoom: real.zoom - 3 };
+ cal.observe(real, dragged(elsewhere, 300, -200), 300, -200);
+ expect(cal.residual).toBeGreaterThan(10);
+ });
+
+ /**
+ * A map that is turned, which on Google Earth is one drag of the compass away
+ * and used to stop the tools dead.
+ *
+ * What is measured is pixels per degree, and degrees run along the world's
+ * axes however the screen is oriented — so the pointer's travel is turned back
+ * into them first. Read raw, a drag on a map turned 30° divides an x-travel by
+ * a difference of longitude the drag only partly made: the scale came out
+ * wrong, the next pan missed its prediction, and the panel refused to draw.
+ */
+ describe('a map held at a bearing', () => {
+ /** The same drag on a turned map. The coordinate that sat under the pixel
+ * the pointer started from is the one centred afterwards, which is what a
+ * pan *is* — stated through the projection rather than through the turn
+ * the code under test does itself. */
+ function draggedTurned(view, dx, dy) {
+ const mid = { x: AREA.x + AREA.w / 2, y: AREA.y + AREA.h / 2 };
+ const moved = ext.toLatLon({ x: mid.x - dx, y: mid.y - dy }, view, AREA);
+ return { ...view, ...moved };
+ }
+
+ const PANS = [[200, 0], [0, -150], [140, 90]];
+
+ function measure(bearing) {
+ const real = { ...AT, zoom: 14, bearing, projection: 'webmercator' };
+ const cal = ext.createCalibration();
+ for (const [dx, dy] of PANS) cal.observe(real, draggedTurned(real, dx, dy), dx, dy);
+ return { cal, real };
+ }
+
+ it('measures the same scale as the same map facing north', () => {
+ // To a thousandth, and the rest is Mercator: a turned drag covers a
+ // different span of latitude for the same pixels, and the northing is not
+ // linear in it. That is the same error a level pan carries.
+ const level = measure(0).cal.scale;
+ for (const bearing of [30, 90, 187.5, 315]) {
+ const { cal } = measure(bearing);
+ expect(cal.scale.pxPerLon / level.pxPerLon).toBeCloseTo(1, 3);
+ expect(cal.scale.pxPerLat / level.pxPerLat).toBeCloseTo(1, 3);
+ }
+ });
+
+ it('predicts the next pan on it, so nothing reads as drift', () => {
+ // The residual is what makes the panel stop drawing. Measured raw on a
+ // turned map it ran to hundreds of pixels and the tools switched off.
+ const { cal, real } = measure(30);
+ cal.observe(real, draggedTurned(real, 120, -90), 120, -90);
+ expect(cal.residual).toBeLessThan(1);
+ });
+
+ it('still reports the drift that is real', () => {
+ const { cal, real } = measure(30);
+ const elsewhere = { ...real, zoom: real.zoom - 3 };
+ cal.observe(real, draggedTurned(elsewhere, 300, -200), 300, -200);
+ expect(cal.residual).toBeGreaterThan(10);
+ });
+
+ it('draws through that measurement as accurately as a level map', () => {
+ const { cal, real } = measure(30);
+ const point = { lat: AT.lat + 0.004, lon: AT.lon + 0.006 };
+ const truth = ext.toScreen(point, real, AREA);
+ const measured = ext.toScreenMeasured(point, real, AREA, cal.scale);
+ expect(measured.x).toBeCloseTo(truth.x, 0);
+ expect(measured.y).toBeCloseTo(truth.y, 0);
+ });
+ });
+
+ it('forgets everything when the zoom changes, since scale is a function of it', () => {
+ const { cal } = survey('webmercator');
+ expect(cal.scale).not.toBe(null);
+ cal.reset();
+ expect(cal.scale).toBe(null);
+ expect(cal.residual).toBe(null);
+ });
+});
+
+describe('Equal Earth, carried before anything asks for it', () => {
+ it('round-trips over the whole globe, poles and antimeridian included', () => {
+ for (const lat of [-89, -70, -23.5, 0, 23.5, 45, 70, 89]) {
+ for (const lon of [-180, -120, -1, 0, 55, 179]) {
+ const at = ext.project(lat, lon, 10, 'equalearth');
+ const back = ext.unproject(at.x, at.y, 10, 'equalearth');
+ expect(back.lat).toBeCloseTo(lat, 8);
+ expect(back.lon).toBeCloseTo(lon, 8);
+ }
+ }
+ });
+
+ it('is equal-area, so it does not stretch the poles the way Mercator does', () => {
+ // Mercator's latitude scale runs away towards the pole; an equal-area map's
+ // does the opposite. That is the whole reason anyone wants to switch.
+ const scaleAt = (lat, projection) =>
+ Math.abs(
+ ext.project(lat + 0.001, 0, 12, projection).y - ext.project(lat - 0.001, 0, 12, projection).y
+ );
+ expect(scaleAt(70, 'webmercator')).toBeGreaterThan(scaleAt(0, 'webmercator'));
+ expect(scaleAt(70, 'equalearth')).toBeLessThan(scaleAt(0, 'equalearth'));
+ });
+
+ it('curves its meridians, so longitude narrows towards the poles', () => {
+ const widthAt = (lat) =>
+ ext.project(lat, 1, 12, 'equalearth').x - ext.project(lat, -1, 12, 'equalearth').x;
+ expect(widthAt(70)).toBeLessThan(widthAt(0));
+ // …where Mercator's does not move at all
+ const merc = (lat) =>
+ ext.project(lat, 1, 12, 'webmercator').x - ext.project(lat, -1, 12, 'webmercator').x;
+ expect(merc(70)).toBeCloseTo(merc(0), 6);
+ });
+
+ it('is recognised from a measurement, so a site switching to it keeps working', () => {
+ const { cal, real } = surveyIn('equalearth', 48.85);
+ expect(ext.identify(cal.scale, real, { prefer: 'webmercator' })).toBe('equalearth');
+ });
+
+ it('is told apart from Mercator even where their latitude scales cross', () => {
+ // they cross in the low thirties, where the northing alone says nothing —
+ // the easting is what settles it
+ for (const lat of [30, 32, 34]) {
+ for (const truth of ['webmercator', 'equalearth']) {
+ const { cal, real } = surveyIn(truth, lat);
+ expect(ext.identify(cal.scale, real, { prefer: 'webmercator' }), `${truth} at ${lat}`).toBe(
+ truth
+ );
+ }
+ }
+ });
+});
+
+describe('where measurement cannot decide, the site table does', () => {
+ it('keeps the table’s answer for two Mercators under a percent apart', () => {
+ // no address bar rounds finely enough to separate these, so overruling the
+ // site table here would be noise deciding a fact
+ for (const truth of ['webmercator', 'ellipsoidal']) {
+ const { cal, real } = surveyIn(truth, 55.75);
+ expect(ext.identify(cal.scale, real, { prefer: 'ellipsoidal' })).toBe('ellipsoidal');
+ }
+ });
+
+ it('overrules the table when the measurement is nowhere near it', () => {
+ const { cal, real } = surveyIn('equalearth', 48.85);
+ expect(ext.identify(cal.scale, real, { prefer: 'ellipsoidal' })).toBe('equalearth');
+ });
+});
+
+/** Pan a simulated map drawn in `truth` and hand the calibration only what the
+ * address bar would have said — never which projection produced it. */
+function surveyIn(truth, lat, zoom = 14) {
+ const real = { lat, lon: 10, zoom, bearing: 0, projection: truth };
+ const cal = ext.createCalibration();
+ for (const [dx, dy] of [[220, 0], [0, -170]]) {
+ cal.observe(real, dragged(real, dx, dy), dx, dy);
+ }
+ return { cal, real };
+}
diff --git a/frontend/src/lib/extensionMapRefs.test.js b/frontend/src/lib/extensionMapRefs.test.js
new file mode 100644
index 0000000..3b3b523
--- /dev/null
+++ b/frontend/src/lib/extensionMapRefs.test.js
@@ -0,0 +1,397 @@
+// @vitest-environment happy-dom
+/**
+ * The reference windows over someone else's map (extension/mapref.js).
+ *
+ * The arithmetic — where a pane sits, how far into an image it is zoomed — is
+ * `maptools.js` and is checked against the app's own in
+ * `extensionMapTools.test.js`. What is left here is the glue, and glue is where
+ * this feature can fail quietly: a window that cannot be closed, an image that
+ * never arrives and says nothing, a pane that opens over the panel that opened
+ * it. So the DOM is driven the way a pointer drives it.
+ *
+ * The canvas is faked, as in `extensionMapDraw.test.js` — happy-dom has no 2D
+ * context. What is asserted is what the analyst can see and reach.
+ */
+import { describe, expect, it, beforeEach, beforeAll, 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 read = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+
+const PANE = { w: 320, h: 260 }; // what a window's body measures, since happy-dom measures nothing
+const PICTURE = {
+ path: 'media/roof.jpg',
+ filename: 'roof.jpg',
+ title: 'The roof',
+ kind: 'image',
+ thumbnail: 'media/.thumbs/a.jpg',
+};
+const CLIP = {
+ path: 'media/walk.mp4',
+ filename: 'walk.mp4',
+ title: 'The walk',
+ kind: 'video',
+ thumbnail: 'media/.thumbs/b.jpg',
+};
+
+let tools;
+let refsLib;
+
+beforeAll(() => {
+ const scope = { window: globalThis.window };
+ for (const file of ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapref.js']) {
+ new Function('window', read(file))(scope.window);
+ }
+ tools = scope.window.AzimutMapTools;
+ refsLib = scope.window.AzimutMapRefs;
+ window.HTMLCanvasElement.prototype.getContext = () =>
+ new Proxy({}, { get: (target, key) => (key in target ? target[key] : () => {}) });
+ // neither exists in happy-dom: decoding an image and handing a video a URL
+ globalThis.createImageBitmap = async () => bitmap();
+ globalThis.URL.createObjectURL = vi.fn(() => 'blob:azimut/1');
+ globalThis.URL.revokeObjectURL = vi.fn();
+ // happy-dom measures nothing, and a pane of no size is one the code declines
+ // to paint — so it is given the size a window's body actually has
+ for (const [name, value] of [['clientWidth', PANE.w], ['clientHeight', PANE.h]]) {
+ Object.defineProperty(window.HTMLElement.prototype, name, { get: () => value, configurable: true });
+ }
+});
+
+/** A decoded image, as `createImageBitmap` would hand one over. */
+const bitmap = () => ({ width: 1600, height: 1200, close: vi.fn() });
+
+let refs;
+let layer;
+let asked; // the paths the panel was asked to fetch
+let searches; // the narrowings it asked the case for
+let notes;
+let changes;
+let answer; // what the case says when the picker searches
+
+function mount({ file, search } = {}) {
+ asked = [];
+ searches = [];
+ notes = [];
+ changes = 0;
+ answer = { items: [PICTURE], total: 1 };
+ document.body.innerHTML = '';
+ refs = tools.createRefs();
+ layer = refsLib.create({
+ root: document.body,
+ refs,
+ file:
+ file ??
+ ((path) => {
+ asked.push(path);
+ return Promise.resolve({ type: 'image/jpeg' }); // a blob, as far as this goes
+ }),
+ search:
+ search ??
+ ((params) => {
+ searches.push(params);
+ return Promise.resolve(answer);
+ }),
+ onchange: () => {
+ changes += 1;
+ },
+ onnote: (message) => notes.push(message),
+ });
+}
+
+/** Let the promises behind a file or a search land. */
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+const panes = () => [...document.body.querySelectorAll('.rw')];
+const press = (node) => node.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+const point = (node, type, at = {}) =>
+ node.dispatchEvent(new window.MouseEvent(type, { bubbles: true, clientX: at.x ?? 0, clientY: at.y ?? 0 }));
+
+beforeEach(() => mount());
+
+describe('opening an image over the map', () => {
+ it('mounts one window per reference, named after the file', async () => {
+ refs.add(PICTURE);
+ layer.sync();
+ await settle();
+ expect(panes()).toHaveLength(1);
+ expect(panes()[0].querySelector('.rw-title').textContent).toBe('The roof');
+ expect(asked).toEqual(['media/roof.jpg']);
+ expect(panes()[0].querySelector('.rw-wait')).toBe(null); // the image arrived
+ });
+
+ it('sits above the drawing and below the panel', () => {
+ refs.add(PICTURE);
+ refs.add(PICTURE);
+ layer.sync();
+ // the draw layer is z-index 1 and the panel is above every window; what
+ // matters is that opening windows never climbs
+ expect(panes().map((el) => el.style.zIndex)).toEqual(['2', '3']);
+ });
+
+ it('keeps the window when the file cannot be handed over, and says why', async () => {
+ mount({ file: () => Promise.reject(new Error('that picture is too large to hand over')) });
+ refs.add(PICTURE);
+ layer.sync();
+ await settle();
+ expect(panes()).toHaveLength(1);
+ expect(panes()[0].querySelector('.rw-wait').textContent).toBe('that picture is too large to hand over');
+ expect(notes).toEqual(['that picture is too large to hand over']);
+ });
+});
+
+describe('opening a video over the map', () => {
+ const pane = () => panes()[0];
+
+ beforeEach(async () => {
+ refs.add(CLIP);
+ layer.sync();
+ await settle();
+ });
+
+ it('plays it in a video element, from an object URL', () => {
+ const video = pane().querySelector('video');
+ expect(video.src).toBe('blob:azimut/1');
+ expect(video.controls).toBe(true);
+ expect(URL.createObjectURL).toHaveBeenCalled();
+ // nothing to zoom: a video has no fit-and-scale of its own here
+ expect(pane().querySelector('.rw-foot')).toBe(null);
+ });
+
+ it('says so when the site will not play it, instead of sitting there black', () => {
+ // a blob: URL is the one thing in this panel a page's content policy can
+ // veto, and the veto arrives as an error on the element
+ pane().querySelector('video').dispatchEvent(new window.Event('error'));
+ expect(pane().querySelector('.rw-wait').textContent).toMatch(/will not play a video/);
+ expect(notes.at(-1)).toMatch(/will not play a video/);
+ expect(pane().querySelector('video')).toBe(null);
+ });
+
+ it('leaves the video its own controls, and still keeps the map still', () => {
+ const down = new window.MouseEvent('pointerdown', { bubbles: true, cancelable: true });
+ pane().querySelector('.rw-body').dispatchEvent(down);
+ // cancelling this would kill the scrub bar; the map is held off by the
+ // panel's own guard on anything inside the shadow root
+ expect(down.defaultPrevented).toBe(false);
+ });
+
+ it('gives the URL back when the window closes', () => {
+ press(pane().querySelector('[data-rw="close"]'));
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:azimut/1');
+ });
+});
+
+describe('working one window', () => {
+ const pane = () => panes()[0];
+ const control = (act) => pane().querySelector(`[data-rw="${act}"]`);
+
+ beforeEach(async () => {
+ refs.add(PICTURE);
+ layer.sync();
+ await settle();
+ });
+
+ it('closes from its own header, and tells the panel', () => {
+ press(control('close'));
+ expect(panes()).toHaveLength(0);
+ expect(refs.open).toEqual([]);
+ expect(changes).toBe(1);
+ });
+
+ it('folds away to its header and comes back', () => {
+ press(control('fold'));
+ expect(pane().querySelector('.rw-body').style.display).toBe('none');
+ press(control('fold'));
+ expect(pane().querySelector('.rw-body').style.display).toBe('');
+ });
+
+ it('zooms about the middle of the pane and resets to fit', () => {
+ press(control('in'));
+ expect(refs.open[0].scale).toBeCloseTo(1.25, 6);
+ expect(pane().querySelector('.rw-zoom').textContent).toBe('125%');
+ press(control('out'));
+ expect(refs.open[0].scale).toBeCloseTo(1, 6);
+ press(control('in'));
+ press(control('reset'));
+ expect(refs.open[0]).toMatchObject({ scale: 1, ox: 0, oy: 0 });
+ });
+
+ it('zooms the picture on a wheel and leaves the map alone', () => {
+ const wheel = new window.WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: -120 });
+ pane().querySelector('.rw-body').dispatchEvent(wheel);
+ expect(refs.open[0].scale).toBeCloseTo(1.15, 6);
+ // the map underneath must not zoom with it
+ expect(wheel.defaultPrevented).toBe(true);
+ });
+
+ it('drags by the header, and stops at the edge of the screen', () => {
+ const head = pane().querySelector('header');
+ point(head, 'pointerdown', { x: 100, y: 100 });
+ point(window, 'pointermove', { x: 140, y: 130 });
+ expect(refs.open[0]).toMatchObject({ x: 100, y: 90 });
+ point(window, 'pointermove', { x: 9000, y: 9000 });
+ point(window, 'pointerup');
+ expect(refs.open[0].x).toBe(window.innerWidth - refs.open[0].w);
+ expect(pane().style.left).toBe(`${window.innerWidth - refs.open[0].w}px`);
+ });
+
+ it('keeps the fold chevron under the pointer that pressed it', () => {
+ // Pressing anywhere in a window focuses it, which restacks every window and
+ // re-places them all. Redrawing this glyph there took the node out of the
+ // DOM between the press and the release, and the click never landed: a
+ // chevron that swallowed its own click and folded nothing.
+ const button = pane().querySelector('[data-rw="fold"]');
+ const glyph = button.firstElementChild;
+ point(pane(), 'pointerdown');
+ expect(button.firstElementChild).toBe(glyph);
+
+ press(button);
+ expect(refs.open[0].collapsed).toBe(true);
+ expect(button.firstElementChild).not.toBe(glyph); // it turns over when it folds
+ expect(button.title).toBe('Unfold');
+ });
+
+ it('folds on a double-click on the title bar', () => {
+ pane().querySelector('header').dispatchEvent(new window.MouseEvent('dblclick', { bubbles: true }));
+ expect(refs.open[0].collapsed).toBe(true);
+ expect(pane().querySelector('.rw-body').style.display).toBe('none');
+ // the panel lists the open windows, so it has to hear about it
+ expect(changes).toBe(1);
+ });
+
+ it('raises the window it is pointed at', () => {
+ refs.add(PICTURE);
+ layer.sync();
+ expect(panes().map((el) => el.style.zIndex)).toEqual(['2', '3']);
+ point(panes()[0], 'pointerdown');
+ expect(panes().map((el) => el.style.zIndex)).toEqual(['3', '2']);
+ });
+});
+
+describe('choosing what to open', () => {
+ const picker = () => document.body.querySelector('.pick');
+
+ it('lists what the case answers and opens the one pressed', async () => {
+ layer.openPicker();
+ await settle();
+ expect(picker().querySelectorAll('.pick-item')).toHaveLength(1);
+ expect(picker().querySelector('.pick-name').textContent).toBe('The roof');
+ // the thumbnail is fetched for the grid; the file itself only on a pick
+ expect(asked).toEqual(['media/.thumbs/a.jpg']);
+ expect(picker().querySelector('.pick-thumb canvas')).not.toBe(null);
+
+ press(picker().querySelector('.pick-item'));
+ expect(picker()).toBe(null);
+ expect(refs.open).toHaveLength(1);
+ expect(panes()).toHaveLength(1);
+ });
+
+ it('says how much of a long case it is showing', async () => {
+ mount({ search: () => Promise.resolve({ items: [PICTURE, PICTURE], total: 214 }) });
+ layer.openPicker();
+ await settle();
+ expect(picker().querySelector('.hint').textContent).toBe('2 of 214 — search to narrow it down');
+ });
+
+ it('says when a case has nothing to offer', async () => {
+ mount({ search: () => Promise.resolve({ items: [], total: 0 }) });
+ layer.openPicker();
+ await settle();
+ expect(picker().querySelector('.hint').textContent).toMatch(/no images or videos/i);
+ });
+
+ it('says when the app could not be reached, rather than looking empty', async () => {
+ mount({ search: () => Promise.reject(new Error('Azimut is not answering. Is the app running?')) });
+ layer.openPicker();
+ await settle();
+ expect(picker().querySelector('.hint').textContent).toMatch(/not answering/);
+ });
+
+ it('drops the answer to a search that has already been typed past', async () => {
+ // the first letter's answer landing last would put the whole case back over
+ // the word the analyst is actually looking at
+ const pending = [];
+ mount({
+ search: ({ q }) =>
+ new Promise((resolve) => {
+ pending.push(() => resolve({ items: [{ ...PICTURE, title: q || 'everything' }], total: 1 }));
+ }),
+ });
+ layer.openPicker();
+ const input = picker().querySelector('input');
+ input.value = 'roof';
+ input.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await new Promise((resolve) => setTimeout(resolve, 300)); // past the debounce
+ expect(pending).toHaveLength(2);
+
+ pending[1](); // the search for "roof" answers
+ await settle();
+ pending[0](); // and the one for "" answers after it
+ await settle();
+ expect(picker().querySelector('.pick-name').textContent).toBe('roof');
+ });
+
+ it('asks the case for the narrowing that was chosen', async () => {
+ layer.openPicker();
+ await settle();
+ expect(searches).toEqual([{ q: '', kind: '', sort: 'newest' }]);
+
+ const choose = (which, value) => {
+ const select = picker().querySelector(`[data-pick="${which}"]`);
+ select.value = value;
+ select.dispatchEvent(new window.Event('change', { bubbles: true }));
+ };
+ choose('kind', 'video');
+ await settle();
+ choose('sort', 'name');
+ await settle();
+ // filtering and ordering are the app's: a browser tab holds one page of a
+ // case, never the case
+ expect(searches.at(-1)).toEqual({ q: '', kind: 'video', sort: 'name' });
+ });
+
+ it('marks a video in the grid, and counts both kinds as files', async () => {
+ mount({ search: () => Promise.resolve({ items: [PICTURE, CLIP], total: 2 }) });
+ layer.openPicker();
+ await settle();
+ const tiles = picker().querySelectorAll('.pick-item');
+ expect(tiles[0].querySelector('.pick-kind')).toBe(null);
+ expect(tiles[1].querySelector('.pick-kind')).not.toBe(null);
+ expect(picker().querySelector('.hint').textContent).toBe('2 files');
+ });
+
+ it('closes on Escape and on its own close button', async () => {
+ layer.openPicker();
+ await settle();
+ window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ expect(picker()).toBe(null);
+ expect(layer.picking).toBe(false);
+
+ layer.openPicker();
+ await settle();
+ press(picker().querySelector('[data-pick="close"]'));
+ expect(picker()).toBe(null);
+ });
+});
+
+describe('putting the panel down', () => {
+ it('takes every window and the picker with it', async () => {
+ refs.add(PICTURE);
+ layer.sync();
+ layer.openPicker();
+ await settle();
+ layer.destroy();
+ expect(document.body.querySelectorAll('.rw, .pick')).toHaveLength(0);
+ });
+
+ it('drops the windows the tool no longer holds', async () => {
+ refs.add(PICTURE);
+ refs.add(PICTURE);
+ layer.sync();
+ await settle();
+ refs.clear(); // what changing case does
+ layer.sync();
+ expect(panes()).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/lib/extensionMapSync.test.js b/frontend/src/lib/extensionMapSync.test.js
new file mode 100644
index 0000000..cdd034d
--- /dev/null
+++ b/frontend/src/lib/extensionMapSync.test.js
@@ -0,0 +1,317 @@
+// @vitest-environment happy-dom
+/**
+ * The map tools panel, told about a case it is not the only one working on
+ * (extension/mapoverlay.js, the map-sync port).
+ *
+ * Everything else about this panel is about what it *writes*: a point filed, a
+ * cell marked, a grid saved. This is the other direction, and it is the half
+ * that used to need a page reload — a point saved in the app, a cell swept from
+ * another tab, a sweep discarded by someone who is also the analyst, one screen
+ * over. The nudges are the app's own (`api/events.py`), read by the worker and
+ * handed over a port (`background.js`, `extension.test.js` covers that end).
+ *
+ * What is asserted here is what the panel *asks the app for* after a nudge, and
+ * what it draws once the answer lands. The two rules worth the test are that a
+ * nudge about the case's points is always worth a read, and that a nudge
+ * carrying a revision the panel already holds is not — that one is its own write
+ * coming back, and re-reading the file for it would be a request per marked
+ * cell.
+ */
+import { describe, expect, it, vi, beforeAll, beforeEach, afterEach } 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 read = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+
+/** The files the panel is injected with, in the order the worker injects them. */
+const PARTS = ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapdraw.js', 'mapref.js'];
+
+const CASE = 'case-1';
+const OTHER = 'case-2';
+/** How often the panel re-reads the address bar — the clock the init is wound
+ * past so its opening errands have all landed. */
+const POLL_MS = 300;
+
+/** A saved grid, as the app hands one back. */
+const spec = (statuses = {}, revision = 3) => ({
+ azimut_grid: 1,
+ cell_m: 500,
+ anchor: { lat: 50.44, lon: 30.51 },
+ lat_step: 0.0045,
+ lon_step: 0.007,
+ aoi: { type: 'rect', bounds: { south: 50.44, north: 50.46, west: 30.51, east: 30.54 } },
+ statuses,
+ revision,
+});
+
+const POINT = { id: 'p1', kind: 'place', title: 'The quay', lat: 50.45, lon: 30.52 };
+
+beforeAll(() => {
+ globalThis.Path2D = class {
+ constructor(d) {
+ this.d = d;
+ }
+ };
+ window.HTMLCanvasElement.prototype.getContext = () => {
+ const noop = () => {};
+ return new Proxy(
+ { measureText: () => ({ width: 20 }) },
+ { get: (target, name) => target[name] ?? noop }
+ );
+ };
+});
+
+/**
+ * A panel, loaded the way the worker loads it, with the port it listens on.
+ *
+ * `answers` is the app: one entry per route the panel may ask for, replaced
+ * mid-test to stand for someone else having written the file.
+ */
+function open({ answers } = {}) {
+ window.happyDOM.setViewport({ width: 1400, height: 900 });
+ const location = {
+ href: 'https://www.openstreetmap.org/#map=17/50.45/30.52',
+ host: 'www.openstreetmap.org',
+ };
+ const asked = [];
+ const app = {
+ '/api/ingest/ping': { units: 'metric' },
+ '/api/ingest/cases': [{ id: CASE, name: 'Case one' }, { id: OTHER, name: 'Case two' }],
+ '/api/ingest/parse': {
+ site: 'openstreetmap',
+ label: 'OpenStreetMap',
+ lat: 50.45,
+ lon: 30.52,
+ zoom: 17,
+ bearing: 0,
+ projection: 'webmercator',
+ view_kind: 'map',
+ geometry: true,
+ scale_source: 'zoom',
+ },
+ '/api/ingest/saved': [POINT],
+ '/api/ingest/grids': [{ name: 'sweep', title: 'Quay sweep' }],
+ '/api/ingest/grid': spec(),
+ ...answers,
+ };
+
+ const ports = [];
+ const api = {
+ storage: {
+ local: { get: vi.fn(async (defaults) => ({ ...defaults })), set: vi.fn() },
+ },
+ runtime: {
+ onMessage: { addListener: vi.fn(), removeListener: vi.fn() },
+ sendMessage: vi.fn(async (message) => {
+ if (message.type !== 'map-api') return { ok: true, data: {} };
+ asked.push(message);
+ return { ok: true, data: app[message.path] ?? null };
+ }),
+ connect: vi.fn((info) => {
+ const port = {
+ name: info.name,
+ heard: [],
+ gone: false,
+ messages: [],
+ disconnects: [],
+ onMessage: { addListener: (cb) => port.messages.push(cb) },
+ onDisconnect: { addListener: (cb) => port.disconnects.push(cb) },
+ postMessage: vi.fn((msg) => port.heard.push(msg)),
+ disconnect: vi.fn(() => (port.gone = true)),
+ };
+ ports.push(port);
+ return port;
+ }),
+ },
+ };
+
+ for (const part of PARTS) new Function('window', read(part))(window);
+ new Function('window', 'document', 'location', 'chrome', 'browser', read('mapoverlay.js'))(
+ window,
+ document,
+ location,
+ api,
+ undefined
+ );
+ const panel = window.__AZIMUT_MAP_TOOLS__;
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+ return {
+ ...panel,
+ app,
+ api,
+ ports,
+ /** Which routes the panel has asked for since the last `forget`. */
+ asks: () => asked.map((m) => m.path),
+ queries: (path) => asked.filter((m) => m.path === path).map((m) => m.query),
+ forget: () => (asked.length = 0),
+ /** One nudge, as the worker hands it over. */
+ nudge: (event) => {
+ for (const cb of ports.at(-1).messages) cb({ type: 'app-event', event });
+ },
+ /** The worker went away, taking the port with it. */
+ evict: () => {
+ for (const cb of ports.at(-1).disconnects) cb();
+ },
+ pick: (id) => root().querySelector(`[data-tab="${id}"]`).click(),
+ /** Open a saved sweep the way the picker does. */
+ openSweep: (name = 'sweep') => {
+ const select = root().querySelector('[data-act="grid-open"]');
+ select.value = name;
+ select.dispatchEvent(new window.Event('change', { bubbles: true }));
+ },
+ note: () => root().querySelector('.note')?.textContent ?? '',
+ };
+}
+
+/** Let the panel's opening errands land. */
+const settle = (ms = POLL_MS) => vi.advanceTimersByTimeAsync(ms);
+
+let panel = null;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ panel?.close();
+ panel = null;
+ vi.useRealTimers();
+ document.documentElement.querySelectorAll('#azimut-map-tools').forEach((node) => node.remove());
+});
+
+describe('listening at all', () => {
+ it('opens one port, named so the worker knows what it is', async () => {
+ panel = open();
+ await settle();
+ expect(panel.ports).toHaveLength(1);
+ expect(panel.ports[0].name).toBe('map-sync');
+ });
+
+ it('speaks on it, so the worker is not evicted mid-sweep', async () => {
+ panel = open();
+ await settle();
+ await vi.advanceTimersByTimeAsync(21000);
+ expect(panel.ports[0].postMessage).toHaveBeenCalled();
+ });
+
+ it('opens another when the worker takes the first one with it', async () => {
+ panel = open();
+ await settle();
+ panel.evict();
+ await vi.advanceTimersByTimeAsync(2500);
+ expect(panel.ports).toHaveLength(2);
+ });
+
+ it('lets go of the port when the panel closes', async () => {
+ panel = open();
+ await settle();
+ const port = panel.ports[0];
+ panel.close();
+ panel = null;
+ expect(port.disconnect).toHaveBeenCalled();
+ });
+});
+
+describe('the case’s points', () => {
+ it('re-reads them when one is filed elsewhere', async () => {
+ panel = open();
+ await settle();
+ panel.forget();
+ panel.app['/api/ingest/saved'] = [POINT, { ...POINT, id: 'p2', title: 'The bridge' }];
+ panel.nudge({ type: 'place', case_id: CASE, title: 'The bridge' });
+ await vi.waitFor(() => expect(panel.tools.pins.rows).toHaveLength(2));
+ expect(panel.queries('/api/ingest/saved').at(-1)).toEqual({ case_id: CASE });
+ });
+
+ it('re-reads them when the app moves its own saved work', async () => {
+ panel = open();
+ await settle();
+ panel.forget();
+ panel.app['/api/ingest/saved'] = [];
+ panel.nudge({ type: 'saved', case_id: CASE });
+ await vi.waitFor(() => expect(panel.tools.pins.rows).toHaveLength(0));
+ });
+
+ it('leaves another case’s points where they are', async () => {
+ panel = open();
+ await settle();
+ panel.forget();
+ panel.nudge({ type: 'saved', case_id: OTHER });
+ await settle(50);
+ expect(panel.asks()).not.toContain('/api/ingest/saved');
+ });
+});
+
+describe('an open sweep', () => {
+ /** A panel with the saved sweep open, as the picker opens it. */
+ async function sweeping(options) {
+ const p = open(options);
+ await settle();
+ p.pick('grid');
+ await settle(50);
+ p.openSweep();
+ await settle(50);
+ p.forget();
+ return p;
+ }
+
+ it('takes a cell marked elsewhere', async () => {
+ panel = await sweeping();
+ panel.app['/api/ingest/grid'] = spec({ '0:0': 'flagged' }, 4);
+ panel.nudge({ type: 'grid-marks', case_id: CASE, name: 'sweep', revision: 4 });
+ await vi.waitFor(() => expect(panel.tools.grid.grid.statuses).toEqual({ '0:0': 'flagged' }));
+ });
+
+ it('ignores the revision it is already holding — its own write, heard back', async () => {
+ panel = await sweeping();
+ panel.nudge({ type: 'grid-marks', case_id: CASE, name: 'sweep', revision: 3 });
+ await settle(50);
+ expect(panel.asks()).not.toContain('/api/ingest/grid');
+ });
+
+ it('ignores a nudge about a sweep it does not have open', async () => {
+ panel = await sweeping();
+ panel.nudge({ type: 'grid-marks', case_id: CASE, name: 'another', revision: 9 });
+ await settle(50);
+ expect(panel.asks()).not.toContain('/api/ingest/grid');
+ });
+
+ it('takes an area reshaped elsewhere whole', async () => {
+ panel = await sweeping();
+ const wider = { south: 50.4, north: 50.5, west: 30.5, east: 30.6 };
+ panel.app['/api/ingest/grid'] = { ...spec({}, 5), aoi: { type: 'rect', bounds: wider } };
+ panel.nudge({ type: 'grid', case_id: CASE, name: 'sweep', revision: 5 });
+ await vi.waitFor(() => expect(panel.tools.grid.grid.aoi.bounds.north).toBe(wider.north));
+ });
+
+ it('closes a sweep discarded elsewhere, and says so', async () => {
+ panel = await sweeping();
+ panel.nudge({ type: 'grid-removed', case_id: CASE, name: 'sweep' });
+ await settle(50);
+ expect(panel.tools.grid.grid).toBe(null);
+ expect(panel.note()).toContain('discarded elsewhere');
+ });
+
+ it('adds a grid drawn elsewhere to the picker', async () => {
+ panel = await sweeping();
+ panel.app['/api/ingest/grids'] = [
+ { name: 'sweep', title: 'Quay sweep' },
+ { name: 'hillside', title: 'Hillside sweep' },
+ ];
+ panel.nudge({ type: 'grid', case_id: CASE, name: 'hillside', revision: 1 });
+ await vi.waitFor(() => expect(panel.state.grids).toHaveLength(2));
+ });
+
+ it('does not read a picker it has never opened', async () => {
+ // a panel measuring distances has no grid list to keep current, and a nudge
+ // is not a reason to fetch one
+ panel = open();
+ await settle();
+ panel.forget();
+ panel.nudge({ type: 'grid', case_id: CASE, name: 'hillside', revision: 1 });
+ await settle(50);
+ expect(panel.asks()).not.toContain('/api/ingest/grids');
+ });
+});
diff --git a/frontend/src/lib/extensionMapTheme.test.js b/frontend/src/lib/extensionMapTheme.test.js
new file mode 100644
index 0000000..fee1b16
--- /dev/null
+++ b/frontend/src/lib/extensionMapTheme.test.js
@@ -0,0 +1,118 @@
+// @vitest-environment happy-dom
+/**
+ * The app's look, on both sides of a boundary it cannot be imported across.
+ *
+ * `extension/maptheme.js` is a copy of things the app already states: the design
+ * tokens in `app.css`, the icon paths in `components/Icon.svelte`, the cell and
+ * measure styles the map tools paint with. A copy is normally how two surfaces
+ * start drifting apart, and the drift here is the kind nobody files a bug about
+ * — an amber that is one step off, an icon that is last year's. So both sides
+ * are read here and compared exactly.
+ */
+import { describe, expect, it, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import { paths } from '../components/Icon.svelte';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const read = (rel) => readFileSync(join(here, rel), 'utf8');
+
+let theme;
+
+beforeAll(() => {
+ const scope = { window: {} };
+ new Function('window', read('../../../extension/maptheme.js'))(scope.window);
+ theme = scope.window.AzimutMapTheme;
+});
+
+/** One `--name: value;` out of the app's stylesheet, from the dark theme block
+ * at the top — which is the one the panel is painted in. */
+function token(name) {
+ const css = read('../app.css');
+ const match = new RegExp(`^\\s*--${name}:\\s*([^;]+);`, 'm').exec(css);
+ return match?.[1].trim();
+}
+
+describe('the palette', () => {
+ it('is the app’s, token for token', () => {
+ for (const [key, name] of [
+ ['bg0', 'bg-0'],
+ ['bg1', 'bg-1'],
+ ['bg2', 'bg-2'],
+ ['bg3', 'bg-3'],
+ ['text1', 'text-1'],
+ ['text2', 'text-2'],
+ ['text3', 'text-3'],
+ ['accent', 'accent'],
+ ['accentText', 'accent-text'],
+ ['danger', 'danger'],
+ ['warn', 'warn'],
+ ['skySun', 'sky-sun'],
+ ['skyMoon', 'sky-moon'],
+ ]) {
+ expect(theme.TOKENS[key], name).toBe(token(name));
+ }
+ });
+});
+
+describe('the icons', () => {
+ it('are the app’s own paths', () => {
+ for (const [name, path] of Object.entries(theme.ICONS)) {
+ expect(paths[name], name).toBe(path);
+ }
+ });
+
+ it('covers every glyph the panel and the marks draw', () => {
+ const used = [
+ ...Object.values(theme.SAVED_GLYPH),
+ 'ruler', 'pin', 'sun', 'grid', 'polygon', 'square', 'x', 'check', 'undo',
+ 'save', 'trash', 'eye', 'eyeOff', 'crosshair', 'chevronUp', 'chevronDown', 'alert',
+ 'image', 'video', 'grip', 'minimize',
+ ];
+ for (const name of used) expect(theme.ICONS, name).toHaveProperty(name);
+ });
+
+ it('draws one as an inline svg, and falls back rather than drawing nothing', () => {
+ expect(theme.icon('ruler', 16)).toContain(paths.ruler);
+ expect(theme.icon('ruler', 16)).toContain('width="16"');
+ expect(theme.icon('no-such-icon')).toContain(paths.alert);
+ });
+});
+
+describe('the paint the tools use', () => {
+ /** The app's own style objects, read out of the module that owns them. */
+ function appStyles() {
+ const src = read('../tools/satellite/state/grid.svelte.js');
+ const block = /const CELL_STYLE = \{([\s\S]*?)\n\};/.exec(src)[1];
+ // eslint-disable-next-line no-new-func
+ return new Function(`return {${block}}`)();
+ }
+
+ it('paints a cell exactly as Grid Search paints it', () => {
+ const app = appStyles();
+ for (const status of ['unchecked', 'cleared', 'flagged']) {
+ expect(theme.CELL_STYLE[status], status).toEqual(app[status]);
+ }
+ });
+
+ it('paints the area outline and the measure line as the app does', () => {
+ const grid = read('../tools/satellite/state/grid.svelte.js');
+ const measure = read('../tools/satellite/state/measure.svelte.js');
+ // the app writes its dash as an SVG string; the canvas wants a pair
+ expect(/const AOI_STYLE = \{[\s\S]*?stroke: '(#\w+)'/.exec(grid)[1]).toBe(theme.AOI_STYLE.stroke);
+ expect(/const AOI_STYLE = \{[\s\S]*?dash: '(\d+ \d+)'/.exec(grid)[1]).toBe(theme.AOI_STYLE.dash.join(' '));
+ expect(/const STROKE = \{ stroke: '(#\w+)', strokeWidth: ([\d.]+)/.exec(measure).slice(1)).toEqual([
+ theme.MEASURE_STROKE.stroke,
+ String(theme.MEASURE_STROKE.strokeWidth),
+ ]);
+ });
+
+ it('names the same glyph for a saved row as the Saved layer', () => {
+ const overlay = read('../tools/satellite/SavedOverlay.svelte');
+ const block = /const GLYPH = \{([^}]*)\}/.exec(overlay)[1];
+ // eslint-disable-next-line no-new-func
+ expect(theme.SAVED_GLYPH).toEqual(new Function(`return {${block}}`)());
+ });
+});
diff --git a/frontend/src/lib/extensionMapTools.test.js b/frontend/src/lib/extensionMapTools.test.js
new file mode 100644
index 0000000..c313739
--- /dev/null
+++ b/frontend/src/lib/extensionMapTools.test.js
@@ -0,0 +1,907 @@
+// @vitest-environment happy-dom
+/**
+ * The map tools' state machines, and everything they copy from the app.
+ *
+ * The extension ships as classic scripts with no build step, so five of the
+ * app's modules are written a second time over there: the lattice
+ * (`gridSearch.js`), the measures (`measure.js`), the sky arc
+ * (`skyOverlay.js`), the mark grouping (`savedMarkers.js`) and the reference
+ * windows' geometry (`refViewers.js`). Two copies is
+ * normally how two answers to one question start appearing, so each is run here
+ * against the app's own and compared — a cell addressed differently is a
+ * different patch of ground, and an arc that closes through the hours a body
+ * spends below the horizon is a picture that lies.
+ *
+ * The rest is ordinary state-machine testing: what a click does, what the panel
+ * reads, and the rules that carry a claim — a pin never invents a ground point,
+ * a mark is a patch rather than a copy of the grid, and a tool can always be
+ * put down.
+ */
+import { describe, expect, it, beforeAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import * as app from './gridSearch.js';
+import * as appSky from './skyOverlay.js';
+import * as appMarkers from './savedMarkers.js';
+import * as appRefs from './refViewers.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const load = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+
+let ext;
+
+beforeAll(() => {
+ const scope = { window: {} };
+ // each file reads the globals the ones before it left, as the browser loads them
+ new Function('window', load('mapmath.js'))(scope.window);
+ new Function('window', load('maptheme.js'))(scope.window);
+ new Function('window', load('maptools.js'))(scope.window);
+ ext = scope.window.AzimutMapTools;
+});
+
+const BOUNDS = { south: 48.85, west: 2.29, north: 48.88, east: 2.34 };
+const AOI = { type: 'rect', bounds: BOUNDS };
+const SHAPE = [
+ [48.85, 2.29],
+ [48.88, 2.3],
+ [48.87, 2.34],
+ [48.855, 2.33],
+];
+
+describe('the grid spec, on both sides of the boundary', () => {
+ it('builds the same lattice as the app', () => {
+ for (const cell of [100, 500, 2000]) {
+ expect(ext.createGrid(AOI, cell)).toEqual(app.createGrid(AOI, cell));
+ }
+ });
+
+ it('builds the same lattice over a drawn shape', () => {
+ const aoi = { type: 'polygon', vertices: SHAPE };
+ expect(ext.createGrid(aoi, 500)).toEqual(app.createGrid(aoi, 500));
+ const grid = ext.createGrid(aoi, 500);
+ // the cells a slanted edge keeps are the ones that decide whether water
+ // gets swept, so they are compared cell by cell
+ expect(ext.cellsInAoi(grid)).toEqual(app.cellsInAoi(grid));
+ });
+
+ it('stops at the same ceiling', () => {
+ expect(ext.MAX_CELLS).toBe(app.MAX_CELLS);
+ });
+
+ it('addresses a cell by the same key', () => {
+ expect(ext.cellKey(3, -2)).toBe(app.cellKey(3, -2));
+ const grid = ext.createGrid(AOI, 500);
+ expect(ext.cellRange(grid)).toEqual(app.cellRange(grid));
+ });
+
+ it('agrees about cell size at every latitude that matters', () => {
+ for (const lat of [0, 23.5, 48.8584, -33.8568, 71, 89.9]) {
+ expect(ext.degSteps(lat, 500)).toEqual(app.degSteps(lat, 500));
+ }
+ });
+
+ it('agrees about which points and cells a shape contains', () => {
+ for (const pt of [
+ { lat: 48.86, lon: 2.31 },
+ { lat: 48.9, lon: 2.31 },
+ { lat: 48.85, lon: 2.29 },
+ ]) {
+ expect(ext.pointInPolygon(pt, SHAPE), JSON.stringify(pt)).toBe(app.pointInPolygon(pt, SHAPE));
+ }
+ const grid = ext.createGrid({ type: 'polygon', vertices: SHAPE }, 500);
+ for (const [i, j] of ext.cellRangeCells ?? [[0, 0], [2, 3], [5, 1]]) {
+ const b = ext.cellBounds(grid, i, j);
+ expect(ext.rectIntersectsPolygon(b, SHAPE)).toBe(app.rectIntersectsPolygon(b, SHAPE));
+ }
+ });
+
+ it('closes a ring the same way, and only once it is a shape', () => {
+ const points = SHAPE.map(([lat, lon]) => ({ lat, lon }));
+ expect(ext.closeRing(points.slice(0, 2))).toHaveLength(2);
+ expect(ext.closeRing(points)).toHaveLength(points.length + 1);
+ expect(ext.closeRing(points).at(-1)).toEqual(points[0]);
+ });
+
+ it('addresses the same ground with the same indices', () => {
+ const grid = ext.createGrid(AOI, 500);
+ for (const [i, j] of [[0, 0], [3, 5], [-2, 1]]) {
+ expect(ext.cellBounds(grid, i, j)).toEqual(app.cellBounds(grid, i, j));
+ }
+ expect(ext.cellsInAoi(grid)).toEqual(app.cellsInAoi(grid));
+ expect(ext.estimateCells(grid)).toBe(app.estimateCells(grid));
+ });
+
+ it('tallies coverage the same way', () => {
+ const grid = ext.createGrid(AOI, 500);
+ grid.statuses = { '0:0': 'cleared', '1:1': 'flagged', '2:2': 'cleared' };
+ expect(ext.coverage(grid)).toEqual(app.coverage(grid));
+ });
+
+ it('cycles a cell through the same three states', () => {
+ let status;
+ for (let n = 0; n < 4; n += 1) {
+ const mine = ext.cycleStatus(status);
+ expect(mine).toBe(app.cycleStatus(status));
+ status = mine;
+ }
+ });
+
+ it('pins the lattice to the corner, so resizing cannot shift a mark', () => {
+ const grid = ext.createGrid(AOI, 500);
+ const wider = ext.createGrid({ type: 'rect', bounds: { ...BOUNDS, east: 2.4 } }, 500);
+ expect(wider.anchor).toEqual(grid.anchor);
+ expect(ext.cellBounds(wider, 2, 3)).toEqual(ext.cellBounds(grid, 2, 3));
+ });
+});
+
+describe('the sky arc, on both sides', () => {
+ const ALTITUDES = [-5, -1, 3, 20, 45, 12, -2, -30, 4, 9];
+ const MINUTES = ALTITUDES.map((_, i) => i * 60);
+
+ it('draws the same runs of daylight', () => {
+ expect(ext.upRuns(ALTITUDES)).toEqual(appSky.upRuns(ALTITUDES));
+ });
+
+ it('ticks the same hours', () => {
+ expect(ext.hourTicks(MINUTES, ALTITUDES)).toEqual(appSky.hourTicks(MINUTES, ALTITUDES));
+ });
+
+ it('rides the mark up the ray by the same fraction', () => {
+ for (const altitude of [0, 12.5, 45, 89.9]) {
+ expect(ext.markScale(altitude)).toBe(appSky.markScale(altitude));
+ }
+ });
+});
+
+describe('grouping saved work into marks, on both sides', () => {
+ const ROWS = [
+ { id: 'a', kind: 'place', title: 'Gate', lat: 48.8584, lon: 2.2945 },
+ { id: 'b', kind: 'capture', title: 'Roof', lat: 48.85841, lon: 2.29451 },
+ { id: 'c', kind: 'place', title: 'Far', lat: 48.9, lon: 2.4 },
+ { id: 'd', kind: 'place', title: 'Nowhere', lat: null, lon: null },
+ ];
+
+ it('coarsens the key at the same zooms', () => {
+ for (const zoom of [null, 3, 6, 9, 12, 15, 18]) {
+ expect(ext.markerPrecision(zoom), String(zoom)).toBe(appMarkers.markerPrecision(zoom));
+ }
+ });
+
+ it('merges the same rows into the same marks', () => {
+ for (const precision of [0, 3, 5]) {
+ expect(ext.groupSavedMarkers(ROWS, precision)).toEqual(
+ appMarkers.groupSavedMarkers(ROWS, precision)
+ );
+ }
+ });
+});
+
+describe('the geometry verdict', () => {
+ /** The line a view with no stated scale shows until a drag measures it.
+ * Read from the panel rather than spelled again, so the assertions below say
+ * which branch was taken; what it says is pinned once, on its own. Read
+ * through a function because the panel is loaded in `beforeAll`, after this
+ * block has been walked. */
+ const measureMe = () => ext.MEASURE_ME;
+
+ const MAP = {
+ site: 'google-maps',
+ lat: 48.8584,
+ lon: 2.2945,
+ zoom: 17,
+ view_kind: 'map',
+ projection: 'webmercator',
+ globe_below: 4,
+ scale_source: 'zoom',
+ geometry: true,
+ };
+
+ it('asks for the drag that would measure it, in terms of what makes one count', () => {
+ // "Pan once" was true and useless: a scale is two numbers, so a sideways
+ // drag gives half of one, and a drag let go of mid-flight is a landing the
+ // pointer never made. Neither condition was on screen, so a drag that did
+ // not count looked exactly like one that did.
+ expect(measureMe()).toBe('Drag the map across and down, pausing before you let go');
+ });
+
+ it('lets a straight-down map through', () => {
+ expect(ext.verdict(MAP, null)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('draws on Apple from the span its address bar states', () => {
+ // Apple states no usable zoom, but it does state the span its view covers,
+ // which is a scale next to the height it was drawn in — no pan needed.
+ const apple = { ...MAP, site: 'apple-maps', scale_source: 'span' };
+ expect(ext.verdict(apple, null, false)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('waits for a measurement where the URL states no scale at all', () => {
+ const mute = { ...MAP, scale_source: null };
+ expect(ext.verdict(mute, null, false).why).toBe(measureMe());
+ expect(ext.verdict(mute, null, true)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('refuses a page that is not a map at all', () => {
+ expect(ext.verdict({ site: null }, null).why).toMatch(/not a map Azimut can read/);
+ expect(ext.verdict(null, null).ok).toBe(false);
+ });
+
+ it('waits for the address bar to carry a position', () => {
+ expect(ext.verdict({ ...MAP, lat: null, lon: null }, null).why).toMatch(/move the map once/);
+ });
+
+ it('names the way out of every view it refuses', () => {
+ // each of these is a setting the analyst can change, so the line says which
+ for (const [kind, why] of [
+ ['streetview', 'These tools work on the map, not in Street View'],
+ ['tilted', 'These tools work in 2D only, so turn 3D off'],
+ ]) {
+ expect(ext.verdict({ ...MAP, view_kind: kind, geometry: false }, null).why).toBe(why);
+ }
+ expect(ext.verdict({ ...MAP, view_kind: 'hologram', geometry: false }, null).why)
+ .toBe('This view is not a map to measure on');
+ });
+
+ it('refuses a pitched camera in the viewer\'s own words, not in degrees', () => {
+ // The pitch the URL states is the app's reading of the camera, and an angle
+ // is not something anyone can go and switch off. Whether the view is 40° or
+ // 3° past level, the way out is the same button, so the sentence is too.
+ const tilted = { ...MAP, view_kind: 'tilted', geometry: false, tilt: 39.6 };
+ expect(ext.verdict(tilted, null).why).toBe('These tools work in 2D only, so turn 3D off');
+ expect(ext.verdict({ ...tilted, tilt: null }, null).why)
+ .toBe('These tools work in 2D only, so turn 3D off');
+ });
+
+ it('draws on a satellite view from the height in metres it quotes', () => {
+ // Google drops the zoom in satellite and quotes the viewport's own height
+ // in metres. Next to the number of pixels it was drawn in, that is a zoom,
+ // and the app hands one back (scale_source: height_m).
+ const satellite = { ...MAP, zoom: 15.0015, scale_source: 'height_m' };
+ expect(ext.verdict(satellite, null, false)).toEqual({ ok: true, why: '', far: false });
+
+ // …and without a height to divide by, there is no zoom and no scale
+ const blind = { ...MAP, zoom: null, geometry: false, scale_source: null };
+ expect(ext.verdict(blind, null, false).why).toBe(measureMe());
+ expect(ext.verdict(blind, null, true)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('measures its way onto a level Earth view, which names no projection', () => {
+ // a camera pointed straight down is a uniform scaling of the ground, and a
+ // measured scale needs neither a zoom nor a named flattening
+ const earth = { site: 'google-earth', lat: 48.8, lon: 2.3, zoom: null,
+ view_kind: 'map', projection: null, globe_below: null, scale_source: null,
+ geometry: false };
+ expect(ext.verdict(earth, null, false).why).toBe(measureMe());
+ expect(ext.verdict(earth, null, true)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('keeps drawing when the site has gone to a globe, and says it drifts', () => {
+ // A whole region's worth of marks is worth seeing at a glance. The middle
+ // of the screen is still right out here; the edges are not, and the panel
+ // dims what it draws rather than refusing to draw it.
+ const wide = ext.verdict({ ...MAP, zoom: 3, far: true }, null);
+ expect(wide.ok).toBe(true);
+ expect(wide.far).toBe(true);
+ expect(wide.why).toBe('Zoomed out: marks drift from the middle of the screen');
+
+ // …and in close, nothing is said at all
+ expect(ext.verdict({ ...MAP, far: false }, null)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('still refuses a globe camera whose scale nothing has measured', () => {
+ // Earth far out: no flattening named, no zoom quoted, nothing measured yet
+ const earth = { site: 'google-earth', lat: 48.8, lon: 2.3, zoom: null, view_kind: 'globe',
+ projection: null, globe_below: null, scale_source: null, geometry: false, far: true };
+ expect(ext.verdict(earth, null, false).why).toBe(measureMe());
+ expect(ext.verdict(earth, null, true)).toEqual({
+ ok: true, why: 'Zoomed out: marks drift from the middle of the screen', far: true,
+ });
+ });
+
+ it('falls back to the general refusal when the view names no camera at all', () => {
+ expect(ext.verdict({ ...MAP, view_kind: null, geometry: false, globe_below: null }, null).why)
+ .toBe('This view is not one Azimut can compute on');
+ });
+
+ it('stops drawing when the map stops going where it was predicted', () => {
+ // the overlay only passes a residual once a run of pans has missed — one
+ // overshoot is these maps gliding on after the finger leaves
+ expect(ext.verdict(MAP, ext.RESIDUAL_LIMIT).ok).toBe(true);
+ const drifted = ext.verdict(MAP, ext.RESIDUAL_LIMIT + 40);
+ expect(drifted.ok).toBe(false);
+ expect(drifted.why).toMatch(/^The map landed \d+ px from where it was predicted/);
+ expect(drifted.why).toMatch(/Pan once to measure it again$/);
+ });
+});
+
+describe('measure', () => {
+ it('holds one mode and one path at a time', () => {
+ const tool = ext.createMeasure();
+ expect(tool.armed).toBe(false);
+ tool.setMode('distance');
+ expect(tool.armed).toBe(true);
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.29 });
+ expect(tool.points).toHaveLength(2);
+ tool.setMode('area');
+ expect(tool.points).toHaveLength(0);
+ });
+
+ it('presses the same mode twice to disarm', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('area');
+ expect(tool.setMode('area')).toBe(null);
+ expect(tool.armed).toBe(false);
+ });
+
+ it('lets go of the click when the view stops carrying it', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('distance');
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.29 });
+ tool.disarm();
+ expect(tool.armed).toBe(false);
+ expect(tool.points).toHaveLength(2);
+ });
+
+ it('reads a distance in the units it was asked for', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('distance');
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.29 });
+ expect(tool.readout('metric')).toMatch(/^1\.1\d km$/);
+ expect(tool.readout('imperial')).toMatch(/^\d+ ft$/);
+ tool.click({ lat: 48.95, lon: 2.29 });
+ expect(tool.readout('imperial')).toMatch(/^\d+\.\d+ mi$/);
+ });
+
+ it('undoes one point rather than the path', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('distance');
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.3 });
+ tool.undo();
+ expect(tool.points).toHaveLength(1);
+ });
+
+ it('needs three points before it claims an area', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('area');
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.29 });
+ expect(tool.readout('metric')).toBe('…');
+ tool.click({ lat: 48.86, lon: 2.3 });
+ expect(tool.readout('metric')).toMatch(/(m²|ha|km²)$/);
+ });
+
+ it('paints the line the app paints', () => {
+ const tool = ext.createMeasure();
+ tool.setMode('distance');
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.click({ lat: 48.86, lon: 2.29 });
+ const line = tool.shapes().find((s) => s.kind === 'line');
+ expect(line.stroke).toBe('#f5a623');
+ expect(line.strokeWidth).toBe(2.5);
+ });
+});
+
+describe('saved points', () => {
+ const VIEW = { lat: 48.8, lon: 2.3 };
+ const ROWS = [
+ { id: 'a', key: 'a', kind: 'place', title: 'Gate', lat: 48.8584, lon: 2.2945 },
+ { id: 'b', key: 'b', kind: 'capture', title: 'Roof', lat: 48.8584, lon: 2.2945 },
+ { id: 'c', key: 'c', kind: 'place', title: 'Far', lat: 48.9, lon: 2.4 },
+ ];
+
+ const loaded = (zoom = 18) => {
+ const tool = ext.createPins();
+ tool.load(ROWS);
+ tool.atZoom(zoom);
+ return tool;
+ };
+
+ it('files the clicked pixel when the view can be inverted', () => {
+ const tool = ext.createPins();
+ tool.toggleDrop();
+ tool.click({ lat: 48.9, lon: 2.4 }, VIEW);
+ expect(tool.draft).toEqual({ lat: 48.9, lon: 2.4, anchoredOn: 'pixel' });
+ expect(tool.readout()).toBe('Filing the point you clicked');
+ });
+
+ it('falls back to the point the URL names, and says so', () => {
+ const tool = ext.createPins();
+ tool.toggleDrop();
+ tool.click(null, VIEW);
+ expect(tool.draft).toEqual({ lat: 48.8, lon: 2.3, anchoredOn: 'view' });
+ expect(tool.readout()).toBe('Filing the point this view is centred on');
+ });
+
+ it('ignores a click when it is not dropping', () => {
+ const tool = ext.createPins();
+ expect(tool.click({ lat: 1, lon: 2 }, VIEW)).toBe(false);
+ expect(tool.draft).toBe(null);
+ });
+
+ it('draws nothing but marks — no names until one is pointed at', () => {
+ // fifty saved points drew fifty names across the map, which is a screenshot
+ // of nothing
+ const tool = loaded();
+ const shapes = tool.shapes();
+ expect(shapes.every((s) => s.kind === 'mark')).toBe(true);
+ expect(shapes.every((s) => s.label === '')).toBe(true);
+ });
+
+ it('names the mark under the pointer, and the one held open', () => {
+ const tool = loaded();
+ const stacked = tool.marks.find((m) => m.items.length > 1);
+ tool.hover(stacked.key);
+ expect(tool.shapes().find((s) => s.label)).toMatchObject({ label: '2 saved here', lit: true });
+ tool.hover(null);
+ tool.hold(stacked.key);
+ expect(tool.shapes().find((s) => s.label)).toMatchObject({ label: '2 saved here' });
+ // clicking it again puts it away
+ tool.hold(stacked.key);
+ expect(tool.shapes().some((s) => s.label)).toBe(false);
+ });
+
+ it('merges points at one spot into a counted mark', () => {
+ const tool = loaded();
+ expect(tool.marks).toHaveLength(2);
+ const stacked = tool.shapes().find((s) => s.count === 2);
+ expect(stacked).toBeTruthy();
+ // a stack of two kinds is drawn with the shared place glyph
+ expect(stacked.glyph).toBe('pin');
+ expect(tool.readout()).toBe('3 here, in 2 marks');
+ });
+
+ it('regroups when the zoom coarsens the key, and not otherwise', () => {
+ const tool = loaded(18);
+ expect(tool.atZoom(17)).toBe(false); // same precision
+ expect(tool.atZoom(3)).toBe(true);
+ expect(tool.marks).toHaveLength(1); // whole degrees: a country is one mark
+ });
+
+ it('draws a lone place outlined and a capture filled, like the app', () => {
+ const tool = ext.createPins();
+ tool.load([ROWS[2], { id: 'd', key: 'd', kind: 'capture', title: 'Shot', lat: 40, lon: 3 }]);
+ tool.atZoom(18);
+ const [place, capture] = tool.shapes();
+ expect(place.place).toBe(true);
+ expect(place.glyph).toBe('pin');
+ expect(capture.place).toBe(false);
+ expect(capture.glyph).toBe('satellite');
+ });
+
+ it('finds the mark under a pointer, and nothing when there is none', () => {
+ const tool = loaded();
+ // far enough apart on screen that "nearest" is not a coin toss
+ const project = (point) => ({ x: point.lat * 1000, y: point.lon * 1000 });
+ const target = tool.marks[0];
+ const at = project(target);
+ expect(tool.markAt({ x: at.x + 4, y: at.y + 4 }, project)?.key).toBe(target.key);
+ expect(tool.markAt({ x: at.x + 400, y: at.y }, project)).toBe(null);
+ });
+
+ it('drops the draft it was holding when it is disarmed', () => {
+ const tool = ext.createPins();
+ tool.toggleDrop();
+ tool.click({ lat: 1, lon: 2 }, VIEW);
+ tool.disarm();
+ expect(tool.armed).toBe(false);
+ expect(tool.draft).toBe(null);
+ });
+
+ it('works on a view without geometry', () => {
+ expect(ext.createPins().needsGeometry).toBe(false);
+ });
+});
+
+describe('sun and moon', () => {
+ const DAY = {
+ moment: { local: '2026-09-10T12:00:00+02:00' },
+ moon: { waxing: true },
+ curve: {
+ minutes: [0, 360, 720, 1080],
+ clock: ['00:00', '06:00', '12:00', '18:00'],
+ sun_altitude: [-30, 5, 45, -2],
+ sun_azimuth: [0, 90, 180, 270],
+ moon_altitude: [20, -10, -30, 15],
+ moon_azimuth: [10, 100, 190, 280],
+ moon_illuminated: [0.5, 0.5, 0.5, 0.5],
+ },
+ };
+
+ const planted = () => {
+ const tool = ext.createSky();
+ tool.togglePlacing();
+ tool.click({ lat: 48.85, lon: 2.29 });
+ tool.fit(1000);
+ tool.accept(DAY);
+ return tool;
+ };
+
+ it('opens on the moment the answer was computed for', () => {
+ expect(ext.nowIndex(DAY)).toBe(2);
+ });
+
+ it('opens on the middle of the day when the moment is unreadable', () => {
+ expect(ext.nowIndex({ ...DAY, moment: {} })).toBe(2);
+ });
+
+ it('stays inside the day when the slider is pushed past its end', () => {
+ const tool = planted();
+ tool.index = 99;
+ expect(tool.index).toBe(3);
+ tool.index = -5;
+ expect(tool.index).toBe(0);
+ });
+
+ it('plants the point and stops waiting for a click', () => {
+ const tool = ext.createSky();
+ tool.togglePlacing();
+ expect(tool.armed).toBe(true);
+ tool.click({ lat: 48.85, lon: 2.29 });
+ expect(tool.armed).toBe(false);
+ expect(tool.anchor).toEqual({ lat: 48.85, lon: 2.29 });
+ });
+
+ it('draws the arc each body sweeps, not the whole circle', () => {
+ const tool = planted();
+ const lines = tool.shapes().filter((s) => s.kind === 'line');
+ // one run of daylight for the sun and one for the moon, plus hour ticks and
+ // the two current rays
+ expect(lines.length).toBeGreaterThan(4);
+ expect(lines.some((l) => l.stroke === '#bd8721')).toBe(true);
+ expect(lines.some((l) => l.stroke === '#4a93cc')).toBe(true);
+ });
+
+ it('dashes the ray of a body under the horizon and puts nothing on it', () => {
+ const tool = planted(); // noon: sun up at 45°, moon down at -30°
+ const rays = tool.shapes().filter((s) => s.kind === 'line' && s.strokeWidth === 3.5);
+ expect(rays).toHaveLength(2);
+ expect(rays[0].dash).toBe(null);
+ expect(rays[1].dash).toEqual([6, 6]);
+ const bodies = tool.shapes().filter((s) => s.kind === 'body');
+ expect(bodies).toHaveLength(1);
+ expect(bodies[0].bodyKind).toBe('sun');
+ });
+
+ it('carries the moon’s phase to the drawing', () => {
+ const tool = planted();
+ tool.index = 3; // the moon is up
+ const moon = tool.shapes().find((s) => s.kind === 'body' && s.bodyKind === 'moon');
+ expect(moon.illuminated).toBe(0.5);
+ expect(moon.waxing).toBe(true);
+ });
+
+ it('reads the clock of the sample it is showing', () => {
+ const tool = ext.createSky();
+ expect(tool.readout()).toBe('Plant a point to read its sky');
+ tool.togglePlacing();
+ tool.click({ lat: 48.85, lon: 2.29 });
+ expect(tool.readout()).toBe('Reading…');
+ tool.accept(DAY);
+ expect(tool.readout()).toBe('12:00');
+ });
+
+ it('keeps the arc inside the window', () => {
+ const tool = ext.createSky();
+ tool.togglePlacing();
+ tool.click({ lat: 0, lon: 0 });
+ tool.fit(1000);
+ tool.accept(DAY);
+ const ray = tool.shapes().find((s) => s.strokeWidth === 3.5);
+ const reach = ext.destination({ lat: 0, lon: 0 }, 180, 220);
+ expect(ray.points[1].lat).toBeCloseTo(reach.lat, 6);
+ });
+});
+
+describe('search grid', () => {
+ const SMALL = { south: 48.85, west: 2.29, north: 48.86, east: 2.3 };
+
+ const drawn = (bounds = SMALL, cell = 500) => {
+ const tool = ext.createGridTool();
+ tool.cellM = cell;
+ tool.draw('rect');
+ const answer = tool.finishBox(bounds);
+ return { tool, answer };
+ };
+
+ it('closes a dragged box into a grid the app can open', () => {
+ const { tool, answer } = drawn();
+ expect(answer.error).toBeUndefined();
+ expect(tool.grid.azimut_grid).toBe(1);
+ expect(tool.grid.aoi.type).toBe('rect');
+ expect(tool.drawing).toBe(null);
+ });
+
+ it('shows the ring only while the shape is being drawn', () => {
+ const tool = ext.createGridTool();
+ tool.draw('polygon');
+ for (const [lat, lon] of SHAPE) tool.addVertex({ lat, lon });
+ expect(tool.shapes().some((s) => s.kind === 'line' && s.dash)).toBe(true);
+ tool.finishPolygon();
+ expect(tool.shapes().some((s) => s.dash)).toBe(false);
+ });
+
+ it('closes a clicked shape into one too', () => {
+ const tool = ext.createGridTool();
+ tool.draw('polygon');
+ for (const [lat, lon] of SHAPE) tool.addVertex({ lat, lon });
+ expect(tool.readout()).toMatch(/4 corners/);
+ const { grid } = tool.finishPolygon();
+ expect(grid.aoi).toEqual({ type: 'polygon', vertices: SHAPE });
+ // and the app reads that spec as its own
+ expect(app.coverage(grid)).toEqual(ext.coverage(grid));
+ });
+
+ it('refuses a shape that encloses nothing', () => {
+ const tool = ext.createGridTool();
+ tool.draw('polygon');
+ tool.addVertex({ lat: 48.85, lon: 2.29 });
+ tool.addVertex({ lat: 48.86, lon: 2.3 });
+ expect(tool.finishPolygon().error).toMatch(/three corners/);
+ });
+
+ it('undoes one corner rather than the shape', () => {
+ const tool = ext.createGridTool();
+ tool.draw('polygon');
+ for (const [lat, lon] of SHAPE) tool.addVertex({ lat, lon });
+ tool.undoVertex();
+ expect(tool.vertices).toHaveLength(SHAPE.length - 1);
+ });
+
+ it('reads a box dragged in any direction', () => {
+ const { tool } = drawn({ south: 48.86, west: 2.3, north: 48.85, east: 2.29 });
+ expect(tool.grid.aoi.bounds).toEqual(SMALL);
+ });
+
+ it('refuses an area nobody would sweep, with the count', () => {
+ const { tool, answer } = drawn({ south: 0, west: 0, north: 10, east: 10 }, 100);
+ expect(answer.error).toMatch(/past the 20,000 limit/);
+ expect(tool.grid).toBe(null);
+ });
+
+ it('covers a box smaller than one cell with one cell', () => {
+ const { tool, answer } = drawn({ south: 48.85, west: 2.29, north: 48.8501, east: 2.2901 }, 500);
+ expect(answer.error).toBeUndefined();
+ expect(ext.estimateCells(tool.grid)).toBe(1);
+ });
+
+ it('marks the cell a coordinate falls in, and only inside the area', () => {
+ const { tool } = drawn();
+ expect(tool.click({ lat: 48.855, lon: 2.295 })).toBe(true);
+ expect(Object.values(tool.grid.statuses)).toEqual(['cleared']);
+ expect(tool.click({ lat: 10, lon: 10 })).toBe(false);
+ });
+
+ it('will not mark a cell the drawn shape does not reach', () => {
+ const tool = ext.createGridTool();
+ tool.draw('polygon');
+ for (const [lat, lon] of SHAPE) tool.addVertex({ lat, lon });
+ tool.finishPolygon();
+ // the bounding box holds this corner; the shape does not
+ expect(tool.cellAt({ lat: 48.8505, lon: 2.3395 })).toBe(null);
+ });
+
+ it('hands over the marks it made, once', () => {
+ const { tool } = drawn();
+ tool.click({ lat: 48.855, lon: 2.295 });
+ expect(Object.values(tool.takeMarks())).toEqual(['cleared']);
+ expect(tool.takeMarks()).toEqual({});
+ expect(tool.dirty).toBe(false);
+ });
+
+ it('records an unmark as a null rather than as an absence', () => {
+ const { tool } = drawn();
+ const at = { lat: 48.855, lon: 2.295 };
+ tool.click(at);
+ tool.takeMarks();
+ tool.click(at);
+ tool.click(at);
+ expect(Object.values(tool.takeMarks())).toEqual([null]);
+ });
+
+ it('puts unsent marks back without stepping on newer ones', () => {
+ const { tool } = drawn();
+ tool.click({ lat: 48.855, lon: 2.295 });
+ const failed = tool.takeMarks();
+ const key = Object.keys(failed)[0];
+ tool.click({ lat: 48.855, lon: 2.295 });
+ tool.restoreMarks(failed);
+ expect(tool.takeMarks()[key]).toBe('flagged');
+ });
+
+ it('is armed while drawing or marking, and never both at once', () => {
+ const tool = ext.createGridTool();
+ tool.draw('rect');
+ expect(tool.armed).toBe(true);
+ tool.toggleMark();
+ expect(tool.drawing).toBe(null);
+ expect(tool.marking).toBe(true);
+ tool.toggleMark();
+ expect(tool.armed).toBe(false);
+ });
+
+ it('puts a shape down when its own button is pressed again', () => {
+ const tool = ext.createGridTool();
+ expect(tool.draw('polygon')).toBe('polygon');
+ expect(tool.draw('polygon')).toBe(null);
+ expect(tool.armed).toBe(false);
+ });
+
+ it('paints its cells the way Grid Search paints them', () => {
+ const { tool } = drawn();
+ tool.click({ lat: 48.855, lon: 2.295 });
+ const cells = tool.shapes().filter((s) => s.kind === 'cell');
+ expect(cells).toHaveLength(ext.estimateCells(tool.grid));
+ expect(cells.some((c) => c.fill === '#2b3040' && c.fillOpacity === 0.62)).toBe(true);
+ expect(cells.some((c) => c.stroke === '#ffffff' && c.fillOpacity === 0)).toBe(true);
+ // nothing else: the lattice is the area, and a dashed ring around it is a
+ // second line saying so over imagery that has to stay readable
+ expect(tool.shapes().every((s) => s.kind === 'cell')).toBe(true);
+ });
+
+ it('draws nothing while hidden', () => {
+ const { tool } = drawn();
+ tool.toggleHidden();
+ expect(tool.shapes()).toEqual([]);
+ });
+
+ it('reports coverage as the panel states it', () => {
+ const { tool } = drawn();
+ tool.click({ lat: 48.855, lon: 2.295 });
+ expect(tool.readout()).toMatch(/^\d+% swept · 1 cleared · 0 flagged$/);
+ });
+
+ it('takes the case’s copy back, keeping what it has not sent', () => {
+ // the same sweep is worked from the app at the same time: its marks are the
+ // truth, and the ones made here that never left are the only copy of
+ // themselves
+ const { tool } = drawn();
+ tool.open({ ...ext.createGrid({ type: 'rect', bounds: SMALL }, 500), statuses: {} }, 'Sweep');
+ tool.click({ lat: 48.855, lon: 2.295 }); // marked here, not sent yet
+ const mine = Object.keys(tool.takeMarks())[0];
+ tool.restoreMarks({ [mine]: 'cleared' });
+
+ tool.sync({
+ ...ext.createGrid({ type: 'rect', bounds: SMALL }, 500),
+ statuses: { '3:7': 'flagged' },
+ });
+ expect(tool.grid.statuses['3:7']).toBe('flagged'); // the app's mark arrived
+ expect(tool.grid.statuses[mine]).toBe('cleared'); // and ours survived it
+ });
+
+ it('drops a cell the case says is unchecked once ours has been sent', () => {
+ const { tool } = drawn();
+ tool.open({ ...ext.createGrid({ type: 'rect', bounds: SMALL }, 500), statuses: { '0:0': 'cleared' } }, 'Sweep');
+ tool.sync({ ...ext.createGrid({ type: 'rect', bounds: SMALL }, 500), statuses: {} });
+ expect(tool.grid.statuses).toEqual({});
+ });
+
+ it('has nothing to sync when no grid is open', () => {
+ const tool = ext.createGridTool();
+ expect(tool.sync({ statuses: { '0:0': 'cleared' } })).toBe(false);
+ });
+
+ it('opening a saved grid starts with nothing unsent', () => {
+ const { tool } = drawn();
+ tool.click({ lat: 48.855, lon: 2.295 });
+ tool.open(app.createGrid(AOI, 500), 'North sweep');
+ expect(tool.dirty).toBe(false);
+ expect(tool.name).toBe('North sweep');
+ });
+});
+
+describe('the reference windows', () => {
+ const SCREEN = { w: 1200, h: 800 };
+ const PICTURE = { path: 'media/roof.jpg', filename: 'roof.jpg', title: 'The roof', kind: 'image' };
+ const CLIP = { path: 'media/walk.mp4', filename: 'walk.mp4', kind: 'video' };
+
+ it('places and resizes a window exactly as the app does', () => {
+ const cases = [
+ [10, 10, 320, 260],
+ [-40, -40, 320, 260], // dragged off the top-left corner
+ [1150, 780, 320, 260], // and off the bottom-right one
+ ];
+ for (const [x, y, w, h] of cases) {
+ expect(ext.clampWindow(x, y, w, h, SCREEN)).toEqual(appRefs.clampWindow(x, y, w, h, SCREEN));
+ }
+ for (const [w, h] of [[400, 300], [40, 40], [4000, 4000]]) {
+ expect(ext.clampSize(w, h, 900, 600, SCREEN)).toEqual(appRefs.clampSize(w, h, 900, 600, SCREEN));
+ }
+ });
+
+ it('zooms and pans the picture exactly as the app does', () => {
+ const pane = { w: 320, h: 260 };
+ let ours = ext.createViewer('ref-1', PICTURE);
+ let theirs = appRefs.createViewer('ref-1', PICTURE);
+ // in on the cursor, in again, then all the way back out past the fit
+ for (const [factor, cursor] of [
+ [1.15, { x: 40, y: 30 }],
+ [2, { x: 300, y: 240 }],
+ [1 / 64, { x: 10, y: 10 }],
+ ]) {
+ ours = { ...ours, ...ext.zoomAt(ours, factor, cursor, pane) };
+ theirs = { ...theirs, ...appRefs.zoomAt(theirs, factor, cursor, pane) };
+ expect(ours.scale).toBe(theirs.scale);
+ expect([ours.ox, ours.oy]).toEqual([theirs.ox, theirs.oy]);
+ }
+ // and the pan that follows one cannot open a gap at an edge
+ for (const [ox, oy] of [[200, 200], [-9000, -9000]]) {
+ expect(ext.clampPan(ox, oy, 4, pane.w, pane.h)).toEqual(appRefs.clampPan(ox, oy, 4, pane.w, pane.h));
+ }
+ });
+
+ it('opens a window on the same state the app would', () => {
+ const spawn = { x: 86, y: 86, z: 3 };
+ for (const item of [PICTURE, CLIP]) {
+ expect(ext.createViewer('ref-2', item, spawn)).toEqual(appRefs.createViewer('ref-2', item, spawn));
+ }
+ // the kind decides how the window shows it: a picture is decoded and
+ // painted, a clip is handed to a <video> (mapref.js)
+ expect(ext.createViewer('ref-3', CLIP).kind).toBe('video');
+ });
+
+ it('keeps the stack small and gap-free, so nothing climbs over the panel', () => {
+ const refs = ext.createRefs();
+ for (let i = 0; i < 4; i += 1) refs.add(PICTURE);
+ expect(refs.open.map((v) => v.z)).toEqual([1, 2, 3, 4]);
+ refs.focus(refs.open[0].id);
+ expect(refs.open.map((v) => v.z)).toEqual([4, 1, 2, 3]);
+ expect(ext.nextZ(refs.open)).toBe(appRefs.nextZ(refs.open));
+ expect([...ext.restack(refs.open, 'ref-2')]).toEqual([...appRefs.restack(refs.open, 'ref-2')]);
+ });
+
+ it('staggers new windows and wraps before they walk off the screen', () => {
+ const refs = ext.createRefs();
+ for (let i = 0; i < 7; i += 1) refs.add(PICTURE);
+ expect(refs.open.map((v) => v.x)).toEqual([60, 86, 112, 138, 164, 190, 60]);
+ // two windows on one picture are two windows, not one reopened
+ expect(new Set(refs.open.map((v) => v.id)).size).toBe(7);
+ });
+
+ it('is a tool that never takes the map', () => {
+ const refs = ext.createRefs();
+ refs.add(PICTURE);
+ // nothing is projected, nothing is armed, and no view is refused: a
+ // photograph is worth holding over Street View and a globe too
+ expect(refs.needsGeometry).toBe(false);
+ expect(refs.armed).toBe(false);
+ expect(refs.shapes()).toEqual([]);
+ refs.disarm();
+ expect(refs.open).toHaveLength(1);
+ });
+
+ it('folds one window away without touching the others', () => {
+ const refs = ext.createRefs();
+ const first = refs.add(PICTURE);
+ refs.add(CLIP);
+ refs.fold(first.id);
+ expect(refs.open.map((v) => v.collapsed)).toEqual([true, false]);
+ refs.fold(first.id);
+ expect(refs.open.map((v) => v.collapsed)).toEqual([false, false]);
+ expect(refs.fold('ref-nope')).toBe(undefined); // a window that has gone
+ });
+
+ it('says what is held over the map', () => {
+ const refs = ext.createRefs();
+ expect(refs.readout()).toBe('Nothing held over the map');
+ refs.add(PICTURE);
+ expect(refs.readout()).toBe('1 reference open');
+ refs.add(PICTURE);
+ expect(refs.readout()).toBe('2 references open');
+ });
+
+ it('closes one window, and every window when the case changes', () => {
+ const refs = ext.createRefs();
+ const first = refs.add(PICTURE);
+ refs.add(PICTURE);
+ refs.close(first.id);
+ expect(refs.open.map((v) => v.id)).toEqual(['ref-2']);
+ refs.clear();
+ expect(refs.open).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/extensionOptions.test.js b/frontend/src/lib/extensionOptions.test.js
new file mode 100644
index 0000000..6cdcb6d
--- /dev/null
+++ b/frontend/src/lib/extensionOptions.test.js
@@ -0,0 +1,83 @@
+// @vitest-environment happy-dom
+/**
+ * Tests for the capture extension's options page (extension/options.js).
+ *
+ * Like extension.test.js and extensionPopup.test.js next door, the page has no
+ * exports: the suite loads options.html into the document, stubs `chrome` and
+ * `fetch`, evaluates the source and reads the resulting DOM.
+ *
+ * What is worth pinning here is the state only the signed Firefox add-on can
+ * reach. Everywhere else the extension is handed out of the app and cannot lead
+ * it; Firefox updates a signed add-on from the release manifest without knowing
+ * which Azimut sits beside it, so an old app can end up paired with a newer
+ * add-on. Nothing in a browser can refuse that update, which is exactly why it
+ * has to be named where both numbers are already on screen.
+ */
+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 ext = join(here, '../../../extension');
+const source = readFileSync(join(ext, 'options.js'), 'utf8');
+const html = readFileSync(join(ext, 'options.html'), 'utf8');
+
+const settle = () => new Promise((r) => setTimeout(r, 0));
+
+/** Evaluate the page, press Save & test, and hand back the status line. */
+async function pair({ appVersion, addonVersion }) {
+ document.body.innerHTML = html
+ .replace(/[\s\S]*<body[^>]*>/, '')
+ .replace(/<\/body>[\s\S]*/, '')
+ .replace(/<script[\s\S]*?<\/script>/g, '');
+
+ const chrome = {
+ storage: {
+ local: { get: vi.fn(async (defaults) => ({ ...defaults })), set: vi.fn() },
+ },
+ runtime: { getManifest: () => ({ version: addonVersion }) },
+ };
+ const fetchImpl = vi.fn(async () => ({
+ status: 200,
+ json: async () => ({ app: 'azimut', version: appVersion }),
+ }));
+
+ new Function('chrome', 'browser', 'fetch', source)(chrome, undefined, fetchImpl);
+ await settle(); // init() awaits storage before it wires the button
+ document.getElementById('save').click();
+ await settle();
+ return document.getElementById('status');
+}
+
+describe('options: pairing', () => {
+ it('reports a plain pairing when the app is current', async () => {
+ const status = await pair({ appVersion: '0.4.0', addonVersion: '0.4.0' });
+ expect(status.className).toContain('ok');
+ expect(status.textContent).toBe('Paired with Azimut 0.4.0.');
+ });
+
+ it('says nothing special when the app leads the add-on', async () => {
+ // The ordinary case everywhere but Firefox: the extension comes out of the
+ // app, so it trails whenever a release left it alone.
+ const status = await pair({ appVersion: '0.4.0', addonVersion: '0.3.0' });
+ expect(status.className).toContain('ok');
+ });
+
+ it('warns when the add-on has been updated past the app', async () => {
+ const status = await pair({ appVersion: '0.3.0', addonVersion: '0.4.0' });
+ expect(status.className).toContain('warn');
+ expect(status.textContent).toContain('0.3.0');
+ expect(status.textContent).toContain('0.4.0');
+ expect(status.textContent).toContain('Update Azimut');
+ });
+
+ it('compares versions numerically rather than as text', async () => {
+ // 0.10.0 is above 0.9.0, and a lexical compare reads it the other way — which
+ // would stay silent on the one release where the warning matters most.
+ const ahead = await pair({ appVersion: '0.9.0', addonVersion: '0.10.0' });
+ expect(ahead.className).toContain('warn');
+ const behind = await pair({ appVersion: '0.10.0', addonVersion: '0.9.0' });
+ expect(behind.className).toContain('ok');
+ });
+});
diff --git a/frontend/src/lib/extensionPopup.test.js b/frontend/src/lib/extensionPopup.test.js
index 2c55209..014f598 100644
--- a/frontend/src/lib/extensionPopup.test.js
+++ b/frontend/src/lib/extensionPopup.test.js
@@ -24,7 +24,7 @@ const html = readFileSync(join(ext, 'popup.html'), 'utf8');
const $ = (id) => document.getElementById(id);
/** Run the popup against a tab, with `fetch` answering per URL fragment. */
-async function runPopup({ tabUrl, answers }) {
+async function runPopup({ tabUrl, answers, height = 940 }) {
// Body only, without the <script src> happy-dom refuses to fetch: the source is
// evaluated below by hand, with the globals a popup really has.
document.body.innerHTML = html
@@ -53,6 +53,11 @@ async function runPopup({ tabUrl, answers }) {
},
},
runtime: { getManifest: () => ({ version: '0.2.9' }), sendMessage: vi.fn(async () => ({ ok: true })) },
+ scripting: {
+ executeScript: vi.fn(async () =>
+ height === null ? Promise.reject(new Error('cannot access')) : [{ result: height }]
+ ),
+ },
};
globalThis.fetch = vi.fn(async (url) => {
@@ -130,3 +135,40 @@ describe('a map page with the app answering', () => {
expect($('save-place').disabled).toBe(false);
});
});
+
+describe('how tall the map is drawn', () => {
+ /**
+ * Apple states the span its view covers and Google's satellite mode the metres
+ * its viewport is high. Either is a scale only next to the number of pixels it
+ * was drawn in, and that number is the one thing the app cannot see — so the
+ * popup reads it off the tab and sends it with the URL.
+ */
+ const asked = () => globalThis.fetch.mock.calls.map(([url]) => String(url));
+
+ it('goes with the URL to the app', async () => {
+ await runPopup({
+ tabUrl: 'https://maps.apple.com/frame?center=48.85,2.29&span=0.02,0.03',
+ answers: {
+ '/parse': ok({ site: 'apple-maps', label: 'Apple Maps', lat: 48.85, lon: 2.29, zoom: 17 }),
+ '/cases': ok([{ id: 'c1', name: 'Case one' }]),
+ },
+ });
+
+ expect(asked().some((url) => url.includes('/parse') && url.includes('height=940'))).toBe(true);
+ });
+
+ it('is left out rather than guessed when the tab refuses to be read', async () => {
+ await runPopup({
+ tabUrl: 'https://maps.apple.com/frame?center=48.85,2.29&span=0.02,0.03',
+ height: null,
+ answers: {
+ '/parse': ok({ site: 'apple-maps', label: 'Apple Maps', lat: 48.85, lon: 2.29, zoom: null }),
+ '/cases': ok([{ id: 'c1', name: 'Case one' }]),
+ },
+ });
+
+ const parse = asked().find((url) => url.includes('/parse'));
+ expect(parse).toBeTruthy();
+ expect(parse).not.toContain('height=');
+ });
+});
diff --git a/frontend/src/lib/extensionReverse.test.js b/frontend/src/lib/extensionReverse.test.js
new file mode 100644
index 0000000..c948982
--- /dev/null
+++ b/frontend/src/lib/extensionReverse.test.js
@@ -0,0 +1,258 @@
+// @vitest-environment happy-dom
+/**
+ * Tests for the script that hands an image to a reverse-image engine
+ * (extension/reverse.js).
+ *
+ * Like the composer's next door, what is pinned here is not the markup — that
+ * will change — but the rules around it: the file goes to the engine's **own**
+ * input and to the one the engine names, nothing is ever pressed (on these
+ * pages the upload button *is* the file dialog), a page that never builds an
+ * uploader is dropped on or reported, and nothing throws into the page.
+ *
+ * The source is evaluated with stubs rather than run in a second npm project
+ * inside extension/. It runs in the page's world, so there is no extension API
+ * to stub: the image goes in on a global and the report is the 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/reverse.js'), 'utf8');
+
+class FakeDataTransfer {
+ constructor() {
+ this.files = [];
+ this.items = { add: (file) => this.files.push(file) };
+ }
+}
+
+class FakeDragEvent extends Event {
+ constructor(type, init = {}) {
+ super(type, init);
+ this.dataTransfer = init.dataTransfer;
+ }
+}
+
+/** Chromium's: the paste carries the object it was built with. */
+class FakeClipboardEvent extends Event {
+ constructor(type, init = {}) {
+ super(type, init);
+ this.clipboardData = init.clipboardData;
+ }
+}
+
+/** Gecko's, which builds its own out of text and so can carry no file. */
+class GeckoClipboardEvent extends Event {
+ constructor(type, init = {}) {
+ super(type, init);
+ this.clipboardData = new FakeDataTransfer();
+ }
+}
+
+class FakeFile {
+ constructor(parts, name, opts) {
+ this.parts = parts;
+ this.name = name;
+ this.type = opts?.type;
+ }
+}
+
+// PNG magic, the way it travels: base64, decoded on the other side.
+const IMAGE = { name: 'reverse-bridge.png', type: 'image/png', data: btoa('\x89PNG') };
+
+// Each engine's uploader as the fetched page draws it.
+// Google's page: the two inputs the search box carries for its own "add files",
+// both marked with a `jsname` and neither belonging to Lens, and the one Lens
+// appends to the body afterwards — inline, in no dialog, named `encoded_image`.
+const GOOGLE_BOX =
+ '<input jsname="vhfHxd" accept="*/*" hidden type="file" />' +
+ '<input jsname="wcaWdc" accept="image/avif,image/png" hidden type="file" />';
+const LENS =
+ `${GOOGLE_BOX}<input type="file" name="encoded_image" accept="image/png,image/webp" style="display:none" />`;
+const BING =
+ '<button class="sb_sbi">Browse</button>' +
+ '<input id="sb_fileinput" class="fileinput" type="file" accept="image/gif, image/png" multiple />';
+// Yandex's home page: the camera, and the picker it presses. Both are there
+// from the first paint, which is why nothing has to be pressed.
+const YANDEX =
+ '<button aria-label="Image search" class="image-search__button"></button>' +
+ '<input type="file" id="image-search" class="image-search__picker" />';
+
+/**
+ * Run reverse.js against a page, and resolve with what it reported plus what it
+ * did: the inputs it wrote to, the buttons it pressed, and anything dropped.
+ */
+function run({ hostname, html, image = IMAGE, onReady }) {
+ document.body.innerHTML = html;
+ const inputs = [];
+ const clicked = [];
+ const dropped = [];
+ for (const input of document.querySelectorAll('input[type="file"]')) {
+ input.addEventListener('change', () =>
+ inputs.push({
+ input: input.getAttribute('name') ?? input.getAttribute('jsname') ?? input.className ?? '',
+ files: input.files,
+ })
+ );
+ }
+ document.body.addEventListener('click', (e) => {
+ const node = e.target.closest('button, [role="button"]');
+ if (node) clicked.push(node.getAttribute('aria-label') ?? node.className);
+ });
+ document.body.addEventListener('drop', (e) => dropped.push(e.dataTransfer.files), true);
+ onReady?.(document);
+ if (image) window.__AZIMUT_REVERSE__ = { image };
+ // Time is stubbed, and both halves of it: the script polls for what a page has
+ // not drawn yet, and a page that never draws it is exactly what the last tests
+ // here are about. `Date` walks forward a poll at a time so those waits run out
+ // at once, and `setTimeout` stops them costing the wall clock. Both are plain
+ // globals shadowed as parameters — nothing in the file knows it is in a test.
+ let clock = 0;
+ const FastDate = { now: () => (clock += 250) };
+ const fastTimeout = (fn) => globalThis.setTimeout(fn, 0);
+ // No `fetch` in scope on purpose — see the CSP test at the bottom.
+ return new Function(
+ 'location',
+ 'DataTransfer',
+ 'DragEvent',
+ 'File',
+ 'Date',
+ 'setTimeout',
+ // 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, FakeDragEvent, FakeFile, FastDate, fastTimeout).then((report) => ({
+ ...report,
+ inputs,
+ clicked,
+ dropped,
+ left: window.__AZIMUT_REVERSE__,
+ }));
+}
+
+describe('handing an image to an engine', () => {
+ it('gives Lens the input it names, not the search box\'s add-files', async () => {
+ // On the hostname Lens redirects to: `lens.google.com` answers with
+ // `www.google.com/?olud`, and the uploader is drawn on that page — inline,
+ // in no dialog. Handing the picture to either `jsname` input above it plays
+ // an upload animation and searches nothing at all.
+ const report = await run({ hostname: 'www.google.com', html: LENS });
+
+ expect(report.inputs).toEqual([
+ {
+ input: 'encoded_image',
+ files: [expect.objectContaining({ name: 'reverse-bridge.png', type: 'image/png' })],
+ },
+ ]);
+ expect(report).toMatchObject({ handed: true });
+ expect(report.error).toBeUndefined();
+ });
+
+ it('still steps around those add-files inputs when Lens renames its own', async () => {
+ // The fallback, which is the whole reason it carries `:not([jsname])`.
+ const report = await run({
+ hostname: 'www.google.com',
+ html: `${GOOGLE_BOX}<input type="file" class="late" accept="image/png" />`,
+ });
+
+ expect(report.inputs).toEqual([{ input: 'late', files: [expect.anything()] }]);
+ });
+
+ it('answers to both of Lens\'s hostnames, since the redirect is the site\'s to change', async () => {
+ for (const hostname of ['lens.google.com', 'www.google.com']) {
+ const report = await run({ hostname, html: LENS });
+ expect(report).toMatchObject({ handed: true });
+ }
+ });
+
+ it('finds the input Bing hides behind its Browse button, and leaves the button alone', async () => {
+ const report = await run({ hostname: 'www.bing.com', html: BING });
+
+ expect(report.inputs).toEqual([{ input: 'fileinput', files: [expect.anything()] }]);
+ // Pressing Browse is opening a native file dialog over the analyst's work.
+ expect(report.clicked).toEqual([]);
+ });
+
+ it('takes the picker Yandex keeps in the page, and leaves its camera alone', async () => {
+ // Pressing that camera is what opens the native file dialog, which is the
+ // one thing worse here than doing nothing.
+ const report = await run({ hostname: 'yandex.com', html: YANDEX });
+
+ expect(report.inputs).toEqual([{ input: 'image-search__picker', files: [expect.anything()] }]);
+ expect(report.clicked).toEqual([]);
+ });
+
+ it('drops the image on a page that never builds an uploader', async () => {
+ const report = await run({ hostname: 'tineye.com', html: '<main><div class="dropzone"></div></main>' });
+
+ expect(report.dropped).toEqual([[expect.objectContaining({ name: 'reverse-bridge.png' })]]);
+ expect(report.inputs).toEqual([]);
+ });
+
+ it('says so rather than guessing when there is neither an input nor a drop road', async () => {
+ // Bing, whose entry declares no drop: an upload view that drew no uploader
+ // leaves nothing to try, and that is reported rather than dressed up.
+ const report = await run({ hostname: 'www.bing.com', html: '<div></div>' });
+
+ expect(report).toMatchObject({ handed: false, error: expect.stringMatching(/Could not give the image/) });
+ expect(report.inputs).toEqual([]);
+ });
+
+ it('refuses an engine it does not know, since its markup was never read', async () => {
+ const report = await run({ hostname: 'example.com', html: '<input type="file" />' });
+
+ expect(report).toMatchObject({ handed: false, error: expect.stringMatching(/does not know this engine/) });
+ expect(report.inputs).toEqual([]);
+ });
+
+ it('keeps nothing of the case in the page', async () => {
+ const report = await run({ hostname: 'lens.google.com', html: LENS });
+
+ expect(report.left).toBeUndefined();
+ });
+
+ it('does nothing at all when the worker handed over no image', async () => {
+ const report = await run({ hostname: 'lens.google.com', html: LENS, image: null });
+
+ expect(report).toMatchObject({ handed: false });
+ expect(report.inputs).toEqual([]);
+ expect(report.error).toBeUndefined();
+ });
+
+ it('skips an input the page is holding back', async () => {
+ const report = await run({
+ hostname: 'www.bing.com',
+ html: '<input type="file" accept="image/*" disabled /><input type="file" accept="image/*" class="live" />',
+ });
+
+ expect(report.inputs).toEqual([{ input: 'live', files: [expect.anything()] }]);
+ });
+
+ it('builds the file from base64, because a fetch here answers to the engine', async () => {
+ // It runs in the page's world, so `fetch('data:…')` is a connection the site
+ // decides on, and these are exactly the sites that allow none.
+ expect(source).not.toMatch(/\bfetch\s*\(/);
+
+ const report = await run({ hostname: 'lens.google.com', html: LENS });
+
+ expect([...report.inputs[0].files[0].parts[0]]).toEqual([0x89, 0x50, 0x4e, 0x47]);
+ });
+
+ it('reports a page that blows up instead of throwing into it', async () => {
+ const report = await run({
+ hostname: 'lens.google.com',
+ html: LENS,
+ onReady: (doc) => {
+ Object.defineProperty(doc.querySelector('input[name="encoded_image"]'), 'files', {
+ set() {
+ throw new Error('the uploader is gone');
+ },
+ });
+ },
+ });
+
+ expect(report).toMatchObject({ handed: false, error: 'the uploader is gone' });
+ });
+});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
new file mode 100644
index 0000000..531946c
--- /dev/null
+++ b/frontend/src/lib/guide.js
@@ -0,0 +1,422 @@
+/**
+ * The guide, as data.
+ *
+ * One section per rail workspace plus the case, between two that set up — what a case
+ * is, and the capture extension that feeds it, then three worked examples — and two
+ * that close: every keystroke the app listens for, and what to do when something does
+ * not work. Data rather than markup for two reasons: `guide.test.js` can then fail the
+ * moment a tool joins a workspace and nobody wrote it down, and the per-tool `?` mark
+ * in the topbar addresses a section by the tool it covers instead of the guide growing
+ * a second copy of the same text.
+ *
+ * What belongs in a point: the controls whose icon does not say what they do, and the
+ * promises a screen makes that are not visible on it. Not a feature list — the tool
+ * itself is the feature list, and a guide that repeats it teaches nothing.
+ *
+ * What belongs in a recipe: the order the tabs are visited in. The sections describe
+ * tools and somebody arriving has a goal, so three goals are walked end to end before
+ * the reference starts. Each step names the tool it happens in, and the guide opens it.
+ *
+ * Static text rather than a tour, and no screenshots: a tour breaks silently on the
+ * first layout change, a screenshot is stale the release after it was taken, and both
+ * fail in a way nobody notices. A page of words is wrong in a way that can be read.
+ */
+
+/**
+ * @typedef {{
+ * id: string, // a workspace id, or a section of its own ('start', 'extension')
+ * title: string,
+ * icon?: string, // only where the id names no workspace to read one off
+ * lead: string, // one sentence
+ * tools: string[], // the tool ids this section covers
+ * points?: Array<{ label: string, text: string }>,
+ * recipes?: Array<{ title: string, lead: string, steps: Array<{ tool: string, text: string }> }>,
+ * keymap?: Array<{ where: string, keys: Array<{ combo: string, does: string }> }>,
+ * fixes?: Array<{ symptom: string, fix: string }>,
+ * keys?: Array<{ combo: string, does: string }>,
+ * }} GuideSection
+ */
+
+/** @type {GuideSection[]} */
+export const GUIDE = [
+ {
+ id: 'start',
+ title: 'Start here',
+ icon: 'compass',
+ lead: 'A case is one folder on your disk, and everything in this app files into it.',
+ tools: [],
+ points: [
+ {
+ label: 'Install the capture extension first',
+ text: 'The one setup step worth doing before any work. Without it, a map open in another tab has to be screenshotted and imported by hand. Settings, then Capture extension.',
+ },
+ {
+ label: 'The folder is half yours',
+ text: 'Azimut owns the azimut/ directory inside a case and leaves the rest of the folder alone. A closed case can be copied as it is.',
+ },
+ {
+ label: 'Nothing leaves this machine',
+ text: 'Network access follows an action that needs it, such as a map tile or a download. The one call made on its own is an optional check for a new release, and Settings turns it off.',
+ },
+ {
+ label: 'The rail is a sequence',
+ text: 'Sources, Examine, Map and Compose read top to bottom in the order an investigation runs. Tools are tabs inside a workspace.',
+ },
+ {
+ label: 'The case is in the topbar, not the rail',
+ text: 'It is not a stage. It is what every stage files into, so it hangs off the case name beside the Board button.',
+ },
+ {
+ label: 'You do not need a case to start',
+ text: 'The first tool that saves something opens a scratch session, and Keep as case names it once the work is worth keeping.',
+ },
+ ],
+ },
+ {
+ id: 'extension',
+ title: 'Extension',
+ icon: 'crop',
+ lead: 'A browser add-on that files what you are looking at in another tab straight into the open case.',
+ tools: [],
+ points: [
+ {
+ label: 'Azimut writes the folder for you',
+ text: 'Settings, then Capture extension: press Install, copy the path it gives you, and load it unpacked in your browser. The pairing token on the same tab is what ties it to this workspace.',
+ },
+ {
+ label: 'It files three things',
+ text: 'A screenshot of the map you are on with the coordinates read off its URL, the point itself as a saved place, and any other page as a bookmark. Each arrives with where it came from already written.',
+ },
+ {
+ label: 'It draws tools over maps Azimut does not provide',
+ text: 'Measure, media pins, sun and moon, a search grid and windows holding the case images, on the map sites you were going to use anyway. A pitched or panoramic view switches the geometry off rather than guessing at it.',
+ },
+ {
+ label: 'It reaches past this machine in exactly one place',
+ text: 'Filling the composer on X or Bluesky with a thread Geo Report prepared. It types what the app handed it and reads nothing back. Everything else it does talks to Azimut on localhost.',
+ },
+ {
+ label: 'Updating it is one click',
+ text: 'The app owns the folder, so a new release rewrites the files in place and the extension restarts. Settings says when two copies are loaded and which one to remove.',
+ },
+ ],
+ },
+ {
+ id: 'recipes',
+ title: 'Worked examples',
+ icon: 'layers',
+ lead: 'Three whole jobs, tab by tab, in the order the tabs are visited.',
+ tools: [],
+ recipes: [
+ {
+ title: 'Geolocate a photo',
+ lead: 'From a picture with no caption to a proof that states where it was taken.',
+ steps: [
+ { tool: 'media', text: 'Import the photo, or paste the URL of the post it came from to pull it down with its origin already written.' },
+ { tool: 'inspect', text: 'Crop and adjust what is hard to read, and run the error-level view over anything that looks composited.' },
+ { tool: 'reverse', text: 'Prepare the image and press an engine. Nothing is sent until you do.' },
+ { tool: 'satellite', text: 'Search the area, switch providers and dates until the ground matches, and capture the view.' },
+ { tool: 'proof', text: 'Put the photo beside the capture, mark what agrees, and name the point. It is filed as a place.' },
+ ],
+ },
+ {
+ title: 'Source a video from a post',
+ lead: 'From a URL to a dated claim the case can argue with.',
+ steps: [
+ { tool: 'media', text: 'Paste the post URL. The first attempt is made without cookies, and only an "unavailable" answer offers your saved browser session.' },
+ { tool: 'inspect', text: 'Step the video frame by frame and pull the stills the argument rests on. Each is filed as media made here.' },
+ { tool: 'board', text: 'Confirm what the import proposed, then link the frames to the place, the account and the people.' },
+ { tool: 'timeline', text: 'Date the claim, and read it in UTC, in your own clock, or in local time at the place itself.' },
+ ],
+ },
+ {
+ title: 'Publish a finding',
+ lead: 'From work in the case to something somebody else can check.',
+ steps: [
+ { tool: 'proof', text: 'Export the panels as a PNG. The spec is saved beside it, so next week the same proof reopens and edits.' },
+ { tool: 'post', text: 'Build the sourced thread. With the extension it fills the composer on X or Bluesky box by box, and stops before Post.' },
+ { tool: 'notebook', text: 'Write the note around it, embed the case media and a diagram, and export the PDF.' },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'collect',
+ title: 'Sources',
+ lead: 'Everything the case is built from lands here, hashed, deduplicated and carrying where it came from.',
+ tools: ['media', 'files', 'reverse'],
+ points: [
+ {
+ label: 'Import or download',
+ text: 'The Media Library takes files off your disk and pulls posts from a URL. The first attempt is always made without cookies, and only a download that answers "unavailable" is retried with the browser session you saved.',
+ },
+ {
+ label: 'State the origin once',
+ text: 'A batch that landed without one is offered the origin for the whole import, and any single file can be corrected later from its Details.',
+ },
+ {
+ label: 'Files searches what the sidebar cannot',
+ text: 'The sidebar matches labels. Note contents are searched in the Files tab, which is also the tiled view of the same folder tree.',
+ },
+ {
+ label: 'Reverse Search picks no engine for you',
+ text: 'It prepares an image or a frame, and nothing moves until you press an engine. With the capture extension that press opens the engine with the picture already in its uploader.',
+ },
+ ],
+ },
+ {
+ id: 'examine',
+ title: 'Examine',
+ lead: 'Inspect reads one image or one video closely, and saves the reading as a session you can reopen.',
+ tools: ['inspect'],
+ points: [
+ {
+ label: 'Four modes on one file',
+ text: 'Selection crops and adjusts, Frame pulls stills out of a video, Collage stitches, and Analyze runs the error-level view.',
+ },
+ {
+ label: 'What you make is case material',
+ text: 'A frame or a collage is filed as ordinary media and marked as made here, so the graph can say what it came out of.',
+ },
+ {
+ label: 'The session is the artifact',
+ text: 'Reopening one puts every adjustment back where it was. The file on disk is never overwritten.',
+ },
+ ],
+ },
+ {
+ id: 'map',
+ title: 'Map',
+ lead: 'Where a finding gets a coordinate, and where a coordinate gets a picture.',
+ tools: ['satellite', 'coordinates'],
+ points: [
+ {
+ label: 'Four providers need no key',
+ text: 'Esri, OSM, OpenTopoMap and Sentinel-2 are built in, dated passes included. A keyed provider uses your own key, and a custom XYZ template is accepted.',
+ },
+ {
+ label: 'The search bar answers before it asks',
+ text: 'Saved places, a pasted coordinate and a bundled gazetteer answer while you type. The geocoder is only asked once you stop.',
+ },
+ {
+ label: 'A capture is evidence',
+ text: 'It records its provider, coordinates, zoom and bearing, so the view can be reproduced and the attribution is already written.',
+ },
+ {
+ label: 'Coords & Sky is the other tab',
+ text: 'It converts between coordinate formats and reads sun, moon, twilight and local time for one point on a date.',
+ },
+ {
+ label: 'The sidebar starts closed here',
+ text: 'The map wants the width. The toggle in the topbar brings it back, and this workspace remembers your choice for the session.',
+ },
+ ],
+ },
+ {
+ id: 'compose',
+ title: 'Compose',
+ lead: 'The three ways work leaves a case: a proof, a thread, a note.',
+ tools: ['proof', 'post', 'notebook'],
+ points: [
+ {
+ label: 'Geo Proof stays editable',
+ text: 'Panels, marks and boxes are saved as a spec beside the exported PNG, so a proof exported last week can be reopened and changed.',
+ },
+ {
+ label: 'A proof can argue several points',
+ text: 'Each place is optionally named and one of them can be the camera. They are filed as places and carried into the thread and onto the picture.',
+ },
+ {
+ label: 'Geo Report stops before posting',
+ text: 'It prepares a sourced thread and, with the extension, fills the composer on X or Bluesky box by box. Pressing Post is left to you.',
+ },
+ {
+ label: 'Notebook is Markdown with case material',
+ text: 'Local media, Mermaid diagrams and a PDF export. Remote images in a note contact their host every time the preview opens, and the editor says so.',
+ },
+ ],
+ },
+ {
+ id: 'case',
+ title: 'Case',
+ lead: 'Four readings of one case, and the first three share the same question.',
+ tools: ['board', 'graph', 'timeline', 'sheet'],
+ points: [
+ {
+ label: 'The filter is a sentence you can edit',
+ text: 'The + Filter menu opens on four standing questions. Picking one drops its terms into the bar as ordinary chips, which is also how the filter language is learned.',
+ },
+ {
+ label: 'The count is a proportion',
+ text: '23 of 1204 means the whole case is the denominator. It never shrinks with the answer, because that is the information a count carries.',
+ },
+ {
+ label: 'Draw these N hands over the question',
+ text: 'The Graph receives the filter rather than the rows it matched, so the drawing answers at any case size and stays live as the case changes.',
+ },
+ {
+ label: 'The Graph never writes to the case',
+ text: 'Expanding, hiding, folding and dragging are your picture. Undo reaches all of them and reaches nothing the case holds.',
+ },
+ {
+ label: 'Timeline reads in a clock you choose',
+ text: 'UTC, this computer, any zone in the world, or local time at a place the case saved. Undated work is counted apart rather than hidden.',
+ },
+ {
+ label: 'Sheet works on real CSV files',
+ text: 'The sheets the case holds, in a grid. A declared sheet can be promoted into entities, places and dated statements, read as a plan first.',
+ },
+ ],
+ },
+ {
+ id: 'shortcuts',
+ title: 'Shortcuts',
+ icon: 'keyboard',
+ lead: 'Every key the app listens for, by where it is pressed.',
+ tools: [],
+ keymap: [
+ {
+ where: 'Anywhere',
+ keys: [
+ { combo: 'Ctrl+V', does: 'files a screenshot or a copied address, on Media, Files, Board and Graph' },
+ { combo: 'Escape', does: 'closes whatever is open, shallowest first' },
+ ],
+ },
+ {
+ where: 'Graph',
+ keys: [
+ { combo: '0', does: 'fits the whole drawing' },
+ { combo: '+ / -', does: 'zooms in and out' },
+ { combo: '1 / 2 / 3', does: 'how many hops around the selected node stay lit' },
+ { combo: 'Arrows', does: 'nudges the selected node, Shift for a longer step' },
+ { combo: 'Ctrl+Z', does: 'takes back a change to the drawing' },
+ { combo: 'Ctrl+Shift+Z', does: 'puts it back' },
+ { combo: 'Escape', does: 'lets go of a menu, a search, a narrowing, then the selected node' },
+ ],
+ },
+ {
+ where: 'Timeline',
+ keys: [
+ { combo: 'Arrows', does: 'pans the window' },
+ { combo: 'Page Up / Down', does: 'pans most of a screen' },
+ { combo: '+ / -', does: 'narrows and widens the window' },
+ { combo: 'Home', does: 'shows the whole filtered extent' },
+ { combo: 'Shift-wheel', does: 'pans, as does a horizontal trackpad gesture' },
+ ],
+ },
+ {
+ where: 'Sheet',
+ keys: [
+ { combo: '?', does: 'opens the full list of grid gestures' },
+ { combo: 'Ctrl+F', does: 'jumps to the search box' },
+ { combo: 'Ctrl+S', does: 'saves the sheet' },
+ { combo: 'Ctrl+Enter', does: 'appends a row' },
+ { combo: 'Tab / Enter', does: 'commits the cell and moves right, or down' },
+ { combo: 'Ctrl+Z', does: 'undoes the last change' },
+ { combo: 'Ctrl+Shift+Z', does: 'redoes it' },
+ ],
+ },
+ {
+ where: 'Geo Proof',
+ keys: [
+ { combo: 'V R E A L C D T S', does: 'picks select, rectangle, ellipse, arrow, line, curve, freehand, text and icon' },
+ { combo: 'F', does: 'fits the document' },
+ { combo: 'Space (held)', does: 'pans, whatever tool is in hand' },
+ { combo: 'Delete', does: 'removes what is selected' },
+ { combo: 'Ctrl+Z', does: 'undoes the last change' },
+ { combo: 'Ctrl+Shift+Z', does: 'redoes it' },
+ { combo: 'Escape', does: 'drops the shape being drawn, then the selection, then the pen' },
+ ],
+ },
+ {
+ where: 'Inspect',
+ keys: [
+ { combo: '← / →', does: 'steps one video frame, Shift for a second' },
+ { combo: ', / .', does: 'the same step, on the keys mpv uses' },
+ { combo: 'Space', does: 'plays and pauses' },
+ { combo: 'Enter / Escape', does: 'applies the crop, or leaves it' },
+ ],
+ },
+ {
+ where: 'Media',
+ keys: [
+ { combo: 'Enter', does: 'opens the image under the cursor' },
+ { combo: '← / →', does: 'walks the preview through the folder' },
+ ],
+ },
+ ],
+ },
+ {
+ id: 'trouble',
+ title: 'When something does not work',
+ icon: 'alert',
+ lead: 'The frictions worth knowing about before you hit them, and where each is fixed.',
+ tools: [],
+ fixes: [
+ {
+ symptom: 'A download answers "unavailable"',
+ fix: 'The site wants a session. The Media Library offers your browser cookies at that point, and only at that point: the first attempt is always made without them.',
+ },
+ {
+ symptom: 'A video has no thumbnail, and frames will not export',
+ fix: 'That is ffmpeg. The downloadable builds carry their own; a pip install uses the one on your PATH. Settings, System says which was found.',
+ },
+ {
+ symptom: 'The extension is installed and its buttons do nothing',
+ fix: 'A tab opened before the install has no content script in it, so reload it. If two copies are loaded they fight, and Settings, Capture extension says which one to remove.',
+ },
+ {
+ symptom: 'A map provider draws nothing',
+ fix: 'Four providers need no key. The rest use yours, entered in Settings, Imagery, and the tab says which ones are missing one.',
+ },
+ {
+ symptom: 'The app opens on "this workspace is in use"',
+ fix: 'Another Azimut holds the folder. Close it, or take the lock from the screen offering it. Two copies writing one workspace is the one thing the app refuses.',
+ },
+ {
+ symptom: 'The tab is closed and the app seems gone',
+ fix: 'Azimut is a local server plus a browser tab. Closing the tab stops nothing: open the address the launcher printed again, and the work is where you left it.',
+ },
+ ],
+ },
+];
+
+/** One section by its id, or null. */
+export function guideSection(id) {
+ return GUIDE.find((section) => section.id === id) ?? null;
+}
+
+/**
+ * Which section the reader is in, from where each heading sits against a line near the
+ * top of the column.
+ *
+ * A line rather than the top edge: a heading that has just scrolled past the edge is
+ * the one being read, not the one above it. `marks` arrives in document order with each
+ * heading's offset from the column's own top, so the last one at or above the line
+ * wins and everything below it is still ahead of the reader.
+ *
+ * `atBottom` is not a detail. The final section is usually shorter than the column, so
+ * its heading can never reach the line however far down you scroll, and without this
+ * the list would stick on the second to last entry at the end of the page.
+ *
+ * Pure so it can be tested at all: the component reads the rectangles, this decides.
+ */
+export function readingSection(marks, { line = 0, atBottom = false } = {}) {
+ if (!marks?.length) return null;
+ if (atBottom) return marks[marks.length - 1].id;
+ let current = marks[0].id;
+ for (const mark of marks) {
+ if (mark.top <= line) current = mark.id;
+ }
+ return current;
+}
+
+/**
+ * The section covering one tool, for the per-tool mark that opens the guide on it.
+ *
+ * By tool rather than by workspace: the mark lives in a toolbar, and the analyst
+ * pressing it is asking about the tab they are standing in.
+ */
+export function guideFor(tool) {
+ return GUIDE.find((section) => section.tools.includes(tool)) ?? null;
+}
diff --git a/frontend/src/lib/guide.test.js b/frontend/src/lib/guide.test.js
new file mode 100644
index 0000000..4db3e03
--- /dev/null
+++ b/frontend/src/lib/guide.test.js
@@ -0,0 +1,216 @@
+import { describe, expect, it } from 'vitest';
+import { GUIDE, guideFor, guideSection, readingSection } from './guide.js';
+import { CASE_WORKSPACE, TOOL_LABELS, WORKSPACES } from './workspaces.js';
+
+const RAIL_AND_CASE = [...WORKSPACES, CASE_WORKSPACE];
+
+/** Every sentence the guide puts on screen, whichever shape holds it. */
+const prose = () =>
+ GUIDE.flatMap((section) => [
+ section.lead,
+ ...(section.points ?? []).flatMap((point) => [point.label, point.text]),
+ ...(section.recipes ?? []).flatMap((recipe) => [
+ recipe.title,
+ recipe.lead,
+ ...recipe.steps.map((step) => step.text),
+ ]),
+ ...(section.keymap ?? []).flatMap((group) => group.keys.map((key) => key.does)),
+ ...(section.fixes ?? []).flatMap((fix) => [fix.symptom, fix.fix]),
+ ]);
+
+describe('the guide tracks the app rather than falling behind it', () => {
+ it('has a section for every workspace an analyst can stand in', () => {
+ for (const ws of RAIL_AND_CASE) {
+ expect(guideSection(ws.id), `no guide section for the ${ws.id} workspace`).toBeTruthy();
+ }
+ });
+
+ it('names every tool of those workspaces', () => {
+ // the gate that matters: adding a tab to a workspace fails here until somebody
+ // writes down what it is for, which is the only thing keeping this page true
+ const documented = new Set(GUIDE.flatMap((section) => section.tools));
+ for (const ws of RAIL_AND_CASE) {
+ for (const tool of ws.tools) {
+ expect(documented.has(tool), `${tool} is in the rail and not in the guide`).toBe(true);
+ }
+ }
+ });
+
+ it('claims no tool that is not in a workspace', () => {
+ const real = new Set(RAIL_AND_CASE.flatMap((ws) => ws.tools));
+ for (const section of GUIDE) {
+ for (const tool of section.tools) {
+ expect(real.has(tool), `the guide covers ${tool}, which no workspace holds`).toBe(true);
+ }
+ }
+ });
+
+ it('files each tool under one section, so the per-tool mark has one answer', () => {
+ const seen = new Set();
+ for (const section of GUIDE) {
+ for (const tool of section.tools) {
+ expect(seen.has(tool), `${tool} is covered twice`).toBe(false);
+ seen.add(tool);
+ }
+ }
+ });
+
+ it('opens on the two sections that set up, before any workspace', () => {
+ // orient, then install the one thing worth installing, then the pipeline
+ expect(GUIDE.map((section) => section.id).slice(0, 2)).toEqual(['start', 'extension']);
+ expect(GUIDE[0].tools).toEqual([]);
+ expect(GUIDE[1].tools).toEqual([]);
+ });
+
+ it('carries its own mark where its id names no workspace', () => {
+ // the contents list reads a workspace icon where there is one, so the two cannot
+ // drift; a section standing alone has to bring one
+ const ids = new Set(RAIL_AND_CASE.map((ws) => ws.id));
+ for (const section of GUIDE.filter((entry) => !ids.has(entry.id))) {
+ expect(section.icon, `${section.id} has no mark`).toBeTruthy();
+ }
+ });
+
+ it('says to install the extension in the section somebody reads first', () => {
+ // it is the one setup step that changes what the app can do, so it leads
+ expect(GUIDE[0].points[0].label).toContain('extension');
+ });
+
+ it('reaches a section from a tool, which is how a toolbar mark will ask', () => {
+ expect(guideFor('satellite')?.id).toBe('map');
+ expect(guideFor('graph')?.id).toBe('case');
+ expect(guideFor('settings')).toBe(null);
+ });
+
+ it('is a labelled tool everywhere it is named', () => {
+ for (const section of GUIDE) {
+ for (const tool of section.tools) {
+ expect(TOOL_LABELS[tool], `${tool} has no label`).toBeTruthy();
+ }
+ }
+ });
+});
+
+describe('the register the guide is written in', () => {
+ it('leads every section with one sentence', () => {
+ for (const section of GUIDE) {
+ expect(section.lead.split('. ').length, `${section.id} leads with a paragraph`).toBeLessThan(3);
+ expect(section.lead.endsWith('.')).toBe(true);
+ }
+ });
+
+ it('gives every point a label and a body', () => {
+ for (const section of GUIDE) {
+ for (const point of section.points ?? []) {
+ expect(point.label.trim()).toBeTruthy();
+ expect(point.text.trim().endsWith('.')).toBe(true);
+ }
+ }
+ });
+
+ it('says something in every section, in one form or another', () => {
+ // a section is points, or recipes, or keys, or fixes — never a heading and a lead
+ for (const section of GUIDE) {
+ const body =
+ (section.points?.length ?? 0) +
+ (section.recipes?.length ?? 0) +
+ (section.keymap?.length ?? 0) +
+ (section.fixes?.length ?? 0);
+ expect(body, `${section.id} says nothing`).toBeGreaterThan(2);
+ }
+ });
+
+ it('uses no em-dash appositive, which the house copy rules refuse', () => {
+ for (const line of prose()) {
+ expect(line, 'em-dash in UI copy').not.toMatch(/—/);
+ }
+ });
+
+ it('says what a key does wherever it lists one', () => {
+ for (const section of GUIDE) {
+ for (const group of section.keymap ?? []) {
+ expect(group.where.trim()).toBeTruthy();
+ expect(group.keys.length).toBeGreaterThan(0);
+ for (const key of group.keys) {
+ expect(key.combo.trim()).toBeTruthy();
+ expect(key.does.trim()).toBeTruthy();
+ }
+ }
+ }
+ });
+
+ it('lists keys under a tool the app actually has, or under everywhere', () => {
+ // the one gate that keeps this page from naming a tab that was renamed or removed
+ const labels = new Set(Object.values(TOOL_LABELS));
+ for (const section of GUIDE) {
+ for (const group of section.keymap ?? []) {
+ expect(group.where === 'Anywhere' || labels.has(group.where), group.where).toBe(true);
+ }
+ }
+ });
+
+ it('walks a recipe through tools that exist, in the words the tabs use', () => {
+ const real = new Set([...RAIL_AND_CASE.flatMap((ws) => ws.tools)]);
+ for (const section of GUIDE) {
+ for (const recipe of section.recipes ?? []) {
+ expect(recipe.steps.length, `${recipe.title} is not a walk`).toBeGreaterThan(2);
+ for (const step of recipe.steps) {
+ expect(real.has(step.tool), `${recipe.title} sends the reader to ${step.tool}`).toBe(true);
+ expect(TOOL_LABELS[step.tool], `${step.tool} has no label`).toBeTruthy();
+ expect(step.text.trim().endsWith('.')).toBe(true);
+ }
+ }
+ }
+ });
+
+ it('answers every symptom it raises', () => {
+ for (const section of GUIDE) {
+ for (const fix of section.fixes ?? []) {
+ expect(fix.symptom.trim()).toBeTruthy();
+ expect(fix.fix.trim().endsWith('.')).toBe(true);
+ }
+ }
+ });
+});
+
+describe('which section the reader is in', () => {
+ // one column, four headings, the line 120px below the top of it
+ const marks = [
+ { id: 'start', top: -900 },
+ { id: 'extension', top: -40 },
+ { id: 'collect', top: 620 },
+ { id: 'map', top: 1400 },
+ ];
+ const line = 120;
+
+ it('is the last heading at or above the line, not the first one on screen', () => {
+ // `collect` is visible and `extension` is the one being read
+ expect(readingSection(marks, { line })).toBe('extension');
+ });
+
+ it('counts a heading exactly on the line as reached', () => {
+ expect(readingSection([{ id: 'a', top: 0 }, { id: 'b', top: 120 }], { line })).toBe('b');
+ });
+
+ it('holds the first section while the column is still at the top', () => {
+ expect(readingSection([{ id: 'a', top: 0 }, { id: 'b', top: 900 }], { line })).toBe('a');
+ });
+
+ it('gives the last section the bottom of the page', () => {
+ // a short final section can never reach the line however far down you scroll, so
+ // without this the list sticks one entry short at the end
+ expect(readingSection(marks, { line, atBottom: true })).toBe('map');
+ });
+
+ it('answers nothing when there is nothing to measure', () => {
+ expect(readingSection([], { line })).toBe(null);
+ expect(readingSection(undefined)).toBe(null);
+ });
+
+ it('never answers with a section it was not given', () => {
+ const ids = new Set(marks.map((mark) => mark.id));
+ for (const spot of [-5000, -100, 0, 120, 5000]) {
+ expect(ids.has(readingSection(marks, { line: spot }))).toBe(true);
+ }
+ });
+});
diff --git a/frontend/src/lib/map/engine.css b/frontend/src/lib/map/engine.css
index 1456672..e28c1b6 100644
--- a/frontend/src/lib/map/engine.css
+++ b/frontend/src/lib/map/engine.css
@@ -50,9 +50,12 @@
}
/* 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 */
+ engine's default corner margin, which used to land it on top of that cluster.
+ How far down is the tool's own business — a map with no cluster over it says
+ so with `--map-controls-top` — but that it is stacked rather than cornered is
+ the engine's. */
.maplibregl-ctrl-top-left .maplibregl-ctrl {
- margin: 58px 0 8px 12px;
+ margin: var(--map-controls-top, 58px) 0 8px 12px;
}
.maplibregl-ctrl-group {
background: var(--bg-2);
diff --git a/frontend/src/lib/map/surface.js b/frontend/src/lib/map/surface.js
index c91278c..a11baf4 100644
--- a/frontend/src/lib/map/surface.js
+++ b/frontend/src/lib/map/surface.js
@@ -385,6 +385,10 @@ export function createSurface(engine, { onPopupOpen, onPopupClose } = {}) {
maxWidth: shape.popup.maxWidth == null ? 'none' : `${shape.popup.maxWidth}px`,
closeOnClick: true,
focusAfterOpen: false,
+ // How far off the point the card sits, whichever side it opens on. A mark
+ // anchored on its tip stands above the point, so a card at the point
+ // itself would open over the mark that was clicked.
+ offset: shape.popup.offset ?? 0,
});
popup.setLngLat(marker.getLngLat());
popup.setDOMContent(shape.popup.content());
diff --git a/frontend/src/lib/mapMarkers.js b/frontend/src/lib/mapMarkers.js
index 05cd17f..b45361c 100644
--- a/frontend/src/lib/mapMarkers.js
+++ b/frontend/src/lib/mapMarkers.js
@@ -45,3 +45,28 @@ export function markerSvg(style) {
export function markerGeometry(style) {
return style === 'pin' ? MARKER_GEOMETRY.pin : MARKER_GEOMETRY.crosshair;
}
+
+/**
+ * The teardrop the map draws on a saved point, in every overlay that draws one.
+ *
+ * It is a 24 px box with one sharp corner, turned 45° so that corner hangs
+ * straight down — and the corner is the claim, the same way the pin's tip is.
+ * A rotation moves it half a diagonal below the middle of the box, so that is
+ * where the anchor goes; anchored on the middle, as it used to be, every mark
+ * sat 17 px above what it pointed at, which is ten metres at zoom 18 and five
+ * at zoom 19.
+ *
+ * `extension/mapdraw.js` draws the same shape on other people's maps and
+ * repeats these numbers, because a classic script cannot import this one.
+ */
+const TEARDROP_BOX = 24;
+const TEARDROP_TIP = (TEARDROP_BOX / 2) * Math.SQRT2;
+
+export const TEARDROP = {
+ size: [TEARDROP_BOX, TEARDROP_BOX],
+ anchor: [TEARDROP_BOX / 2, TEARDROP_BOX / 2 + TEARDROP_TIP],
+};
+
+/** How far a mark's card hangs off the point, now that the body is all above
+ * it: the whole diagonal, or the card opens over the mark it belongs to. */
+export const TEARDROP_CARD_OFFSET = Math.round(2 * TEARDROP_TIP);
diff --git a/frontend/src/lib/mapMarkers.test.js b/frontend/src/lib/mapMarkers.test.js
index ec3fb82..8d7dda6 100644
--- a/frontend/src/lib/mapMarkers.test.js
+++ b/frontend/src/lib/mapMarkers.test.js
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { markerGeometry, markerSvg, MARKER_GEOMETRY } from './mapMarkers.js';
+import { readFileSync } from 'node:fs';
+import {
+ markerGeometry,
+ markerSvg,
+ MARKER_GEOMETRY,
+ TEARDROP,
+ TEARDROP_CARD_OFFSET,
+} from './mapMarkers.js';
describe('markerSvg', () => {
it('draws the pin as a teardrop with an eye in it', () => {
@@ -51,3 +58,38 @@ describe('markerGeometry', () => {
}
});
});
+
+/**
+ * The mark the overlays put on a saved point. It is CSS rather than an SVG — a
+ * 24 px box with one sharp corner, turned 45° — so what is pinned here is the
+ * arithmetic that turns that rotation into an anchor, and the agreement with
+ * `extension/mapdraw.js`, which draws the same shape on other people's maps
+ * and cannot import this file.
+ */
+describe('the teardrop on a saved point', () => {
+ it('anchors on the sharp corner, half a diagonal below the middle', () => {
+ const [, height] = TEARDROP.size;
+ expect(TEARDROP.anchor[0]).toBe(TEARDROP.size[0] / 2);
+ expect(TEARDROP.anchor[1]).toBeCloseTo(height / 2 + (height / 2) * Math.SQRT2, 6);
+ });
+
+ it('stands the body clear of the point rather than around it', () => {
+ // What `surface.js` turns the anchor into: the element's centre, relative
+ // to the coordinate. Negative is upward, which is where the body goes.
+ const offsetY = TEARDROP.size[1] / 2 - TEARDROP.anchor[1];
+ expect(offsetY).toBeCloseTo(-16.97, 2);
+ });
+
+ it('hangs a card off the point far enough to clear that body', () => {
+ expect(TEARDROP_CARD_OFFSET).toBeGreaterThanOrEqual(
+ TEARDROP.anchor[1] - TEARDROP.size[1] / 2
+ );
+ });
+
+ it('states the same geometry the extension draws with', () => {
+ const source = readFileSync(new URL('../../../extension/mapdraw.js', import.meta.url), 'utf8');
+ const box = Number(/const MARK = (\d+);/.exec(source)[1]);
+ expect(box).toBe(TEARDROP.size[1]);
+ expect(source).toContain('const MARK_TIP = (MARK / 2) * Math.SQRT2;');
+ });
+});
diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.js
index dd9d289..aa54fcd 100644
--- a/frontend/src/lib/maplinks.js
+++ b/frontend/src/lib/maplinks.js
@@ -2,6 +2,20 @@
// Used by the Satellite "Open in…" panel: the point is to reach the maps that
// aren't reachable from inside Azimut (Esri/OSM are already in-tool tile
// providers, so they're deliberately left out). Pure URL construction.
+//
+// Every form here was opened in a real browser at a known zoom and read back
+// out of the address bar, and `docs/MAP_SITES.md` records what came back. Two
+// rules came out of that and are worth stating where the URLs are written:
+//
+// * **The zoom is the same number on all of them.** Google's `z`, Bing's `lvl`,
+// Yandex's `z`, Copernicus's `zoom`, Zoom Earth's `z`, Satellites.pro's third
+// field and Apple's `z` are all the tile level of a 256-pixel Web Mercator —
+// measured, not assumed, including Apple's, whose documentation declines to
+// say so.
+// * **Order and layer are not.** Yandex writes longitude first. Zoom Earth
+// opens its weather layer unless the path says otherwise. Google needs a
+// `data=` code for satellite, and passing it a distance in metres instead of
+// a zoom lands somewhere else entirely.
export function mapLinks(lat, lon, zoom = 17) {
const z = Math.round(zoom);
return [
@@ -9,12 +23,20 @@ export function mapLinks(lat, lon, zoom = 17) {
{
id: 'google_sat',
label: 'Google Satellite',
- url: `https://www.google.com/maps/@${lat},${lon},2000m/data=!3m1!1e3`,
+ // the zoom is kept and `!3m1!1e3` picks the imagery: Google rewrites it
+ // into its own `,3231m` viewport height on arrival, at this same level
+ url: `https://www.google.com/maps/@${lat},${lon},${z}z/data=!3m1!1e3`,
},
{
id: 'google_earth',
label: 'Google Earth',
- url: `https://earth.google.com/web/@${lat},${lon},0a,1000d,35y,0h,0t,0r`,
+ // Earth takes a camera distance, not a zoom. Measured, `d` halves for
+ // every level zoomed in, so the shape is a constant over 2^z; the
+ // constant itself is nominal, since turning a distance into a ground
+ // scale needs a field of view and a window height that no link can know.
+ // It lands z17 about 600 m out, and the old fixed 1000 m at every zoom
+ // is what it replaces.
+ url: `https://earth.google.com/web/@${lat},${lon},0a,${earthDistance(z)}d,1y,0h,0t,0r`,
},
{
id: 'apple',
@@ -33,7 +55,12 @@ export function mapLinks(lat, lon, zoom = 17) {
label: 'Copernicus Browser',
url: `https://browser.dataspace.copernicus.eu/?zoom=${z}&lat=${lat}&lng=${lon}`,
},
- { id: 'zoom_earth', label: 'Zoom Earth', url: `https://zoom.earth/#view=${lat},${lon},${z}z` },
+ {
+ id: 'zoom_earth',
+ label: 'Zoom Earth',
+ // /maps/satellite/ or it opens on the live weather layer instead
+ url: `https://zoom.earth/maps/satellite/#view=${lat},${lon},${z}z`,
+ },
{
id: 'satellites_pro',
label: 'Satellites.pro',
@@ -41,3 +68,17 @@ export function mapLinks(lat, lon, zoom = 17) {
},
];
}
+
+/**
+ * How far Google Earth's camera sits from the ground for a tile zoom, in metres.
+ *
+ * Earth states no zoom at all — it states `d`, the camera's distance from what
+ * it is looking at. Measured in a browser, that number halves for every level
+ * zoomed in, exactly, which fixes the shape of this: a constant over 2^z. What
+ * the measurement cannot fix is the constant, which is a field of view and a
+ * window height Earth never writes down — so it is chosen, not derived, and
+ * lands a level-17 link about 600 m out.
+ */
+function earthDistance(zoom) {
+ return Math.round(78_600_000 / 2 ** Math.max(0, zoom));
+}
diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.js
index 0335de9..75f89bc 100644
--- a/frontend/src/lib/maplinks.test.js
+++ b/frontend/src/lib/maplinks.test.js
@@ -1,6 +1,13 @@
import { describe, it, expect } from 'vitest';
import { mapLinks } from './maplinks.js';
+/**
+ * The forms asserted here are the ones a browser was actually driven through
+ * (`docs/MAP_SITES.md`): opened at a known level, panned a known number of
+ * pixels, and read back out of the address bar. What the test guards is the
+ * three ways an "Open in…" link lands somewhere else than the view it came
+ * from — the wrong axis order, the wrong layer, or a scale that is not a zoom.
+ */
describe('mapLinks', () => {
const links = mapLinks(48.8584, 2.2945, 16);
const byId = Object.fromEntries(links.map((l) => [l.id, l]));
@@ -33,10 +40,46 @@ describe('mapLinks', () => {
}
});
- it('rounds zoom and uses lon,lat order for Yandex', () => {
+ it('carries the view zoom to every site that takes one', () => {
expect(byId.google.url).toContain(',16z');
+ expect(byId.google_sat.url).toContain(',16z');
+ expect(byId.apple.url).toContain('z=16');
+ expect(byId.bing.url).toContain('lvl=16');
+ expect(byId.yandex.url).toContain('z=16');
+ expect(byId.sentinel.url).toContain('zoom=16');
+ expect(byId.zoom_earth.url).toContain(',16z');
+ expect(byId.satellites_pro.url).toMatch(/,16$/);
+ });
+
+ it('writes longitude first for Yandex, and only for Yandex', () => {
expect(byId.yandex.url).toContain('ll=2.2945,48.8584');
+ expect(byId.apple.url).toContain('ll=48.8584,2.2945');
+ });
+
+ it('asks for the satellite layer rather than the site default', () => {
+ // Google needs the data code; Zoom Earth opens on live weather without the
+ // path; Apple needs map=satellite
+ expect(byId.google_sat.url).toContain('/data=!3m1!1e3');
+ expect(byId.zoom_earth.url).toContain('/maps/satellite/');
expect(byId.apple.url).toContain('map=satellite');
+ expect(byId.yandex.url).toContain('l=sat');
+ expect(byId.bing.url).toContain('style=h');
+ });
+
+ it('gives Earth a camera distance that follows the zoom', () => {
+ // Earth states no zoom: `d` is a distance, and it halves per level
+ const near = mapLinks(48.8584, 2.2945, 17).find((l) => l.id === 'google_earth');
+ const far = mapLinks(48.8584, 2.2945, 16).find((l) => l.id === 'google_earth');
+ const distance = (link) => Number(/,(\d+)d,/.exec(link.url)[1]);
+ expect(distance(far) / distance(near)).toBeCloseTo(2, 2);
+ expect(distance(near)).toBeGreaterThan(100);
+ expect(distance(near)).toBeLessThan(2000);
+ });
+
+ it('never sends Google a viewport height where a zoom belongs', () => {
+ // `,2000m` is a span in metres, not a level: it used to pin every satellite
+ // link to the same 2 km view whatever the map was showing
+ for (const { url } of links) expect(url).not.toMatch(/,\d+m\//);
});
it('every entry has a label and an https url', () => {
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 424881c..e889353 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -6,6 +6,7 @@
*/
import { caseState, toast, uiState } from './state.svelte.js';
import { mediaKindOf } from './entityIcon.js';
+import { GUIDE, guideFor } from './guide.js';
import { revealMediaFolder } from './reveal.js';
/**
@@ -172,6 +173,19 @@ export function gotoPoint(lat, lon) {
uiState.tool = 'satellite';
}
+/**
+ * Open the Guide on whatever covers a tool.
+ *
+ * The press means "what is this tab", so it lands on the section written about that
+ * tab. A tool no section covers — Settings, and the two home tabs themselves — opens
+ * the guide at the top, which is where somebody with a general question belongs
+ * anyway.
+ */
+export function openGuide(tool) {
+ uiState.guideSection = guideFor(tool)?.id ?? GUIDE[0].id;
+ uiState.tool = 'guide';
+}
+
/** Fly the Satellite map to a capture's recorded coordinates (its marker). */
export function gotoCapture(entity) {
const lat = Number(entity.attrs?.lat);
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index 2f1854a..c617e5e 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -4,7 +4,9 @@ const post = vi.fn().mockResolvedValue({ path: '/cases/c1/azimut/media' });
vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: vi.fn() } }));
const { caseState, uiState } = await import('./state.svelte.js');
-const { gotoCapture, gotoPoint, openEntity, opensInFileManager } = await import('./navigate.js');
+const { gotoCapture, gotoPoint, openEntity, openGuide, opensInFileManager } = await import(
+ './navigate.js'
+);
beforeEach(() => {
uiState.tool = 'media';
@@ -16,6 +18,21 @@ beforeEach(() => {
vi.stubGlobal('window', { open: vi.fn() });
});
+describe('openGuide', () => {
+ it('lands on the section written about the tab the mark was pressed from', () => {
+ openGuide('satellite');
+ expect(uiState.tool).toBe('guide');
+ expect(uiState.guideSection).toBe('map');
+ });
+
+ it('opens at the top for a tool no section covers', () => {
+ // Settings is app plumbing rather than a stage, so nothing is written about it;
+ // somebody pressing there has a general question
+ openGuide('settings');
+ expect(uiState.guideSection).toBe('start');
+ });
+});
+
describe('openEntity', () => {
it('opens bookmarks and external captures in a new browser tab', () => {
openEntity({ type: 'bookmark', attrs: { url: 'https://example.test/bookmark' } });
diff --git a/frontend/src/lib/overview.js b/frontend/src/lib/overview.js
new file mode 100644
index 0000000..9c159cf
--- /dev/null
+++ b/frontend/src/lib/overview.js
@@ -0,0 +1,197 @@
+/**
+ * What the home surface reads off the open case, as values.
+ *
+ * Pure on purpose: the numbers arrive as the bounded payloads the case already
+ * serves — one catalog summary and one timeline page — and what comes out is the
+ * rows the page draws. No request and no Svelte, which is the half worth testing
+ * without a browser.
+ *
+ * **The waiting rows are the Board's own standing questions, priced.** Three of the
+ * four come straight out of `entityFilter.js` QUESTIONS, wording and terms included,
+ * and pressing one hands that exact question to the Board. So the number on this page
+ * and the count on that table are one predicate asked twice, and cannot drift into
+ * saying two different things about the same case. Nothing here writes its own
+ * sentence for a question the Board already words.
+ */
+import { QUESTIONS } from './entityFilter.js';
+
+/**
+ * How many entities sit in none of the analyst's folders.
+ *
+ * Derived rather than asked for: `by_folder` counts the rows that *have* a folder, so
+ * the rest of the case is the remainder. Clamped at zero, since a summary read while a
+ * write lands can briefly count more folders than it counts rows.
+ */
+export function unfiledCount(summary) {
+ const total = Number(summary?.total ?? 0);
+ const filed = Object.values(summary?.by_folder ?? {}).reduce(
+ (sum, n) => sum + Number(n || 0),
+ 0
+ );
+ return Math.max(0, total - filed);
+}
+
+/** A Board question by id, carrying its own label, hint and terms. */
+function asked(id) {
+ return QUESTIONS.find((entry) => entry.id === id) ?? { id, label: id, hint: '', terms: {} };
+}
+
+/**
+ * What the case is waiting on, in the order it is worth answering.
+ *
+ * `read` takes the two payloads and returns a count; `surface` is where the row lands
+ * when it is pressed. A row with a `terms` object hands that question over on the way,
+ * which is what makes the landing table show exactly the rows this number counted.
+ *
+ * Deliberately four. *Added this week* is the Board's fourth standing question and is
+ * not one of these: it says what happened, not what is outstanding, so it leads the
+ * recent work instead of sitting in a list of things to do.
+ */
+export const WAITING = [
+ {
+ ...asked('review'),
+ icon: 'check',
+ surface: 'board',
+ read: ({ summary }) => summary?.by_status?.suggested ?? 0,
+ },
+ {
+ ...asked('loose'),
+ icon: 'link',
+ surface: 'board',
+ read: ({ summary }) => summary?.unlinked ?? 0,
+ },
+ {
+ ...asked('unfiled'),
+ icon: 'folderMinus',
+ surface: 'board',
+ read: ({ summary }) => unfiledCount(summary),
+ },
+ {
+ id: 'undated',
+ label: 'No date yet',
+ hint: 'a statement the timeline has nowhere to put',
+ icon: 'clock',
+ surface: 'timeline',
+ read: ({ timeline }) => timeline?.undated ?? 0,
+ },
+];
+
+/** The waiting rows with their counts read off the payloads. */
+export function waitingRows(sources = {}) {
+ return WAITING.map((row) => ({ ...row, count: Math.max(0, Number(row.read(sources) || 0)) }));
+}
+
+/**
+ * Whether the case has nothing outstanding.
+ *
+ * A clear case is an answer rather than four zeros: read as a list it says the page
+ * failed to load, read as one line it says the work is done.
+ */
+export function nothingWaiting(rows) {
+ return rows.every((row) => row.count === 0);
+}
+
+/**
+ * The case by family, biggest first, summed off the per-type counts the summary
+ * already holds.
+ *
+ * Families rather than types, because eight readings is a sentence and twenty type
+ * slugs is a list. `familyOf` is handed in rather than imported so this stays pure of
+ * the registry; a type the vocabulary has never heard of is counted under `other`
+ * instead of being dropped, since a free type is still something the case holds.
+ */
+export function familyCounts(summary, familyOf = () => null) {
+ const totals = new Map();
+ for (const [type, n] of Object.entries(summary?.by_type ?? {})) {
+ const family = familyOf(type) ?? 'other';
+ totals.set(family, (totals.get(family) ?? 0) + Number(n || 0));
+ }
+ return [...totals]
+ .map(([family, count]) => ({ family, count }))
+ .filter((entry) => entry.count > 0)
+ .sort((a, b) => b.count - a.count || a.family.localeCompare(b.family));
+}
+
+/**
+ * The same families, each carrying its share of the biggest one.
+ *
+ * A share of the largest rather than of the total: the bars are read against each
+ * other, and a case where one family holds four fifths of the rows would otherwise
+ * draw seven bars of nothing. The colour is not decided here — the page reads
+ * `--graph-<family>`, the hues the Graph already gives the same eight families, so
+ * one reading of a case cannot be two palettes.
+ */
+export function familyBars(summary, familyOf = () => null) {
+ const rows = familyCounts(summary, familyOf);
+ const top = rows[0]?.count ?? 0;
+ return rows.map((row) => ({ ...row, share: top ? row.count / top : 0 }));
+}
+
+/** How many points the home map draws before it stops. Higher than the plate that
+ * drew them without a map could take: a dense patch there was one smear, and here
+ * it is something to zoom into. The cap is what keeps a case with thousands of
+ * saved points from paying for all of them on a page nobody came to read them on. */
+export const MAP_PINS = 200;
+
+/**
+ * A coordinate a row actually recorded, or NaN where it recorded none.
+ *
+ * `Number(null)` is 0 and zero is a real place, so a row with no position would be
+ * drawn off West Africa and would stretch the plate of every case that holds one.
+ */
+function coordinate(value) {
+ return value === null || value === undefined || value === '' ? NaN : Number(value);
+}
+
+/**
+ * The case's saved points, as the home map takes them.
+ *
+ * Coordinates and nothing else: the map projects, frames and draws them
+ * (`tools/overview/PlaceMap.svelte`), so this only decides which rows can be drawn
+ * at all and how many of them are. A second projection written here is a second
+ * thing that can disagree with the map about where the case is.
+ *
+ * `total` counts every row that holds a position, drawn or not, so the foot can say
+ * how much of the case the map is showing.
+ *
+ * Pure, and the half worth testing: the component only turns these into dots.
+ */
+export function mapPins(rows, { limit = MAP_PINS } = {}) {
+ const points = [];
+ for (const row of rows ?? []) {
+ const lat = coordinate(row?.lat);
+ const lon = coordinate(row?.lon);
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
+ points.push({
+ id: String(row.key ?? row.id ?? `${lat},${lon}`),
+ kind: row.kind ?? 'place',
+ title: row.title ?? '',
+ lat,
+ lon,
+ });
+ }
+ return { pins: points.slice(0, limit), total: points.length };
+}
+
+/** The `YYYY-MM-DD` a week back, as the catalog's own `since` bound. */
+export function weekAgo(now = Date.now()) {
+ const at = new Date(now);
+ at.setDate(at.getDate() - 7);
+ return at.toISOString().slice(0, 10);
+}
+
+/**
+ * The case's own last-written stamp, preferring the freshest of the two the app holds.
+ *
+ * The open case carries the manifest's `updated_at`, which only moves when the
+ * manifest itself is rewritten; the case list carries one recomputed off the database,
+ * so a case worked on all afternoon reads as touched this afternoon rather than as
+ * touched the day it was renamed.
+ */
+export function lastTouched(current, list = []) {
+ const listed = list.find((entry) => entry?.id === current?.id)?.updated_at;
+ const own = current?.updated_at;
+ if (!listed) return own ?? '';
+ if (!own) return listed;
+ return listed > own ? listed : own;
+}
diff --git a/frontend/src/lib/overview.test.js b/frontend/src/lib/overview.test.js
new file mode 100644
index 0000000..23c50cf
--- /dev/null
+++ b/frontend/src/lib/overview.test.js
@@ -0,0 +1,229 @@
+import { describe, expect, it } from 'vitest';
+import { QUESTIONS } from './entityFilter.js';
+import {
+ MAP_PINS,
+ WAITING,
+ familyBars,
+ familyCounts,
+ lastTouched,
+ mapPins,
+ nothingWaiting,
+ unfiledCount,
+ waitingRows,
+ weekAgo,
+} from './overview.js';
+
+const summary = (over = {}) => ({
+ total: 0,
+ by_type: {},
+ by_status: {},
+ by_folder: {},
+ by_source: {},
+ linked_to: {},
+ unlinked: 0,
+ countable: 0,
+ ...over,
+});
+
+describe('what the case is waiting on', () => {
+ it('prices the Board standing questions rather than wording its own', () => {
+ // the number here and the count on that table have to be one predicate asked
+ // twice, or the home page quietly says something the Board contradicts
+ for (const row of WAITING.filter((entry) => entry.surface === 'board')) {
+ const question = QUESTIONS.find((entry) => entry.id === row.id);
+ expect(question, `${row.id} is not a Board question`).toBeTruthy();
+ expect(row.label).toBe(question.label);
+ expect(row.hint).toBe(question.hint);
+ expect(row.terms).toEqual(question.terms);
+ }
+ });
+
+ it('leaves "added this week" out: it says what happened, not what is outstanding', () => {
+ expect(WAITING.map((row) => row.id)).not.toContain('week');
+ });
+
+ it('reads each count off the payload that already holds it', () => {
+ const rows = waitingRows({
+ summary: summary({ total: 30, by_status: { suggested: 4 }, unlinked: 7, by_folder: { a: 10, b: 8 } }),
+ timeline: { undated: 2 },
+ });
+ expect(Object.fromEntries(rows.map((row) => [row.id, row.count]))).toEqual({
+ review: 4,
+ loose: 7,
+ unfiled: 12,
+ undated: 2,
+ });
+ });
+
+ it('answers zero rather than NaN before the reads land', () => {
+ const rows = waitingRows({});
+ expect(rows.map((row) => row.count)).toEqual([0, 0, 0, 0]);
+ expect(nothingWaiting(rows)).toBe(true);
+ });
+
+ it('tells a clear case from a case with one thing left', () => {
+ const rows = waitingRows({ summary: summary({ total: 3, by_folder: { a: 3 } }), timeline: { undated: 1 } });
+ expect(nothingWaiting(rows)).toBe(false);
+ });
+});
+
+describe('what sits in none of the folders', () => {
+ it('is the case less what the folders hold', () => {
+ expect(unfiledCount(summary({ total: 12, by_folder: { work: 5, old: 2 } }))).toBe(5);
+ });
+
+ it('is the whole case when no folder exists yet', () => {
+ expect(unfiledCount(summary({ total: 12 }))).toBe(12);
+ });
+
+ it('never goes negative on a summary read mid-write', () => {
+ // the two counts are separate scans; a folder count can briefly outrun the total
+ expect(unfiledCount(summary({ total: 2, by_folder: { a: 5 } }))).toBe(0);
+ });
+
+ it('is zero on nothing at all', () => {
+ expect(unfiledCount(null)).toBe(0);
+ });
+});
+
+describe('the case in figures', () => {
+ const familyOf = (type) => ({ person: 'actor', account: 'identifier', media: 'collected' })[type] ?? null;
+
+ it('sums types into their family, biggest first', () => {
+ const counts = familyCounts(
+ summary({ by_type: { person: 3, account: 9, media: 40 } }),
+ familyOf
+ );
+ expect(counts).toEqual([
+ { family: 'collected', count: 40 },
+ { family: 'identifier', count: 9 },
+ { family: 'actor', count: 3 },
+ ]);
+ });
+
+ it('counts a free type the vocabulary never heard of rather than dropping it', () => {
+ // a free-typed entity is still something the case holds, and a total that skips
+ // it disagrees with the total beside it
+ const counts = familyCounts(summary({ by_type: { widget: 2 } }), familyOf);
+ expect(counts).toEqual([{ family: 'other', count: 2 }]);
+ });
+
+ it('breaks a tie by name, so the same case draws the same line twice', () => {
+ const counts = familyCounts(summary({ by_type: { account: 1, person: 1 } }), familyOf);
+ expect(counts.map((entry) => entry.family)).toEqual(['actor', 'identifier']);
+ });
+
+ it('leaves out a family the case holds none of', () => {
+ expect(familyCounts(summary({ by_type: { person: 0 } }), familyOf)).toEqual([]);
+ });
+});
+
+describe('the bars the figures are drawn as', () => {
+ const familyOf = (type) => ({ person: 'actor', media: 'collected' })[type] ?? null;
+
+ it('measures every family against the biggest, not against the total', () => {
+ // against the total, a case four fifths of which is media draws six bars of
+ // nothing beside one full one, and says less than the numbers it replaced
+ const bars = familyBars(summary({ by_type: { media: 40, person: 10 } }), familyOf);
+ expect(bars.map((bar) => [bar.family, bar.count, bar.share])).toEqual([
+ ['collected', 40, 1],
+ ['actor', 10, 0.25],
+ ]);
+ });
+
+ it('draws nothing rather than dividing by nothing', () => {
+ expect(familyBars(summary(), familyOf)).toEqual([]);
+ });
+});
+
+describe('the case as points on the map', () => {
+ const row = (over) => ({ key: 'k', kind: 'place', title: 'Quai sud', ...over });
+
+ it('hands the map the position, the kind and the title it draws them with', () => {
+ const { pins, total } = mapPins([row({ lat: 49.98, lon: 36.25 })]);
+ expect(total).toBe(1);
+ expect(pins[0]).toEqual({
+ id: 'k',
+ kind: 'place',
+ title: 'Quai sud',
+ lat: 49.98,
+ lon: 36.25,
+ });
+ });
+
+ it('keeps the rows in the order they arrived, newest first as the index served them', () => {
+ const { pins } = mapPins([row({ key: 'n', lat: 51, lon: 4 }), row({ key: 's', lat: 48, lon: 4 })]);
+ expect(pins.map((pin) => pin.id)).toEqual(['n', 's']);
+ });
+
+ it('names a row that carries no key of its own, since a dot is drawn by id', () => {
+ const { pins } = mapPins([{ id: 'e7', lat: 50, lon: 4 }, { lat: 12, lon: 77 }]);
+ expect(pins.map((pin) => pin.id)).toEqual(['e7', '12,77']);
+ // and a row that says nothing about what it is is still a place
+ expect(pins[1].kind).toBe('place');
+ });
+
+ it('leaves out what has nowhere to be drawn', () => {
+ const { pins, total } = mapPins([
+ row({ key: 'a', lat: 50, lon: 4 }),
+ row({ key: 'b', lat: null, lon: null }),
+ row({ key: 'c' }),
+ ]);
+ expect(pins).toHaveLength(1);
+ expect(total).toBe(1);
+ });
+
+ it('stops drawing past the cap, and says how many there were', () => {
+ const many = Array.from({ length: MAP_PINS + 20 }, (_, i) =>
+ row({ key: `k${i}`, lat: 50 + i * 0.01, lon: 4 })
+ );
+ const { pins, total } = mapPins(many);
+ expect(pins).toHaveLength(MAP_PINS);
+ expect(total).toBe(MAP_PINS + 20);
+ });
+
+ it('is empty on a case that saved nothing', () => {
+ expect(mapPins([])).toEqual({ pins: [], total: 0 });
+ expect(mapPins(null)).toEqual({ pins: [], total: 0 });
+ });
+});
+
+describe('the week the recent band counts', () => {
+ it('is seven days back, as the bare date the catalog compares against', () => {
+ expect(weekAgo(Date.UTC(2026, 2, 15, 12))).toBe('2026-03-08');
+ });
+
+ it('crosses a month boundary', () => {
+ expect(weekAgo(Date.UTC(2026, 2, 3, 12))).toBe('2026-02-24');
+ });
+});
+
+describe('when the case was last touched', () => {
+ const current = { id: 'c1', updated_at: '2026-01-02T00:00:00Z' };
+
+ it('prefers the list stamp, which is recomputed off the database', () => {
+ // the manifest's own stamp only moves when the manifest is rewritten, so a case
+ // worked on all afternoon would read as touched the day it was renamed
+ const list = [{ id: 'c1', updated_at: '2026-03-04T00:00:00Z' }];
+ expect(lastTouched(current, list)).toBe('2026-03-04T00:00:00Z');
+ });
+
+ it('keeps the manifest stamp when it is the fresher of the two', () => {
+ const list = [{ id: 'c1', updated_at: '2025-12-01T00:00:00Z' }];
+ expect(lastTouched(current, list)).toBe('2026-01-02T00:00:00Z');
+ });
+
+ it('falls back to the open case when the list has not landed', () => {
+ expect(lastTouched(current, [])).toBe('2026-01-02T00:00:00Z');
+ });
+
+ it('never reads another case row', () => {
+ expect(lastTouched(current, [{ id: 'other', updated_at: '2030-01-01T00:00:00Z' }])).toBe(
+ '2026-01-02T00:00:00Z'
+ );
+ });
+
+ it('says nothing rather than guessing with no case open', () => {
+ expect(lastTouched(null, [])).toBe('');
+ });
+});
diff --git a/frontend/src/lib/reverseSearch.js b/frontend/src/lib/reverseSearch.js
index a579433..f899819 100644
--- a/frontend/src/lib/reverseSearch.js
+++ b/frontend/src/lib/reverseSearch.js
@@ -7,23 +7,52 @@
//
// `paste: true` marks the engines whose search page accepts a pasted image
// (Ctrl+V); the rest are drag-and-drop only.
+//
+// `fill: true` marks the ones the capture extension can give the image to
+// directly (extension/reverse.js), which is the same hand-off Publish makes to a
+// composer and turns the two gestures above into none. It is what the engine's
+// own uploader can be reached by, not a promise about how the search goes: the
+// extension has to be installed, the switch in Settings on, and every refusal
+// lands back on the clipboard road below.
const ENGINES = [
- { id: 'google', label: 'Google Lens', page: 'https://lens.google.com/', paste: true },
- // Yandex's page has no paste target in practice — it wants a file, so it sits
- // with the drag engines.
- { id: 'yandex', label: 'Yandex', page: 'https://yandex.com/images/', paste: false },
- { id: 'bing', label: 'Bing', page: 'https://www.bing.com/visualsearch', paste: false },
- { id: 'tineye', label: 'TinEye', page: 'https://tineye.com/', paste: false },
+ { id: 'google', label: 'Google Lens', page: 'https://lens.google.com/', paste: true, fill: true },
+ // Yandex has no paste target in practice — it wants a file, so it sits with
+ // the drag engines.
+ // Its home page, not its image search: the camera on `/images/` opens nothing
+ // when pressed, while the home page keeps the picker that takes a file.
+ { id: 'yandex', label: 'Yandex', page: 'https://yandex.com/', paste: false, fill: true },
+ // Not `/visualsearch`: that one redirects to a Microsoft marketing page with
+ // nothing to drop a file on. This is Bing's own search-by-image upload view.
+ {
+ id: 'bing',
+ label: 'Bing',
+ page: 'https://www.bing.com/images/search?view=detailv2&iss=sbiupload',
+ paste: false,
+ fill: true,
+ },
+ { id: 'tineye', label: 'TinEye', page: 'https://tineye.com/', paste: false, fill: true },
];
+/**
+ * The largest image the extension will carry into an engine's page, in bytes.
+ *
+ * Not a guess at what the engines take: it is the point where pushing the file
+ * through the page, the worker and a second page costs more than the two
+ * gestures it saves. Over it, the buttons do what they always did — copy, or
+ * save and drag.
+ */
+export const MAX_HANDOFF_BYTES = 20 * 1024 * 1024;
+
/**
* Each engine's search page. `paste` flags the ones that take a clipboard image
* (Ctrl+V), so the tool can split the copy-and-open hand-off from the
- * save-and-drag one.
+ * save-and-drag one; `fill` flags the ones the extension can hand the image to
+ * itself.
*/
export const UPLOAD_PAGES = ENGINES.map((e) => ({
id: e.id,
label: e.label,
url: e.page,
paste: e.paste,
+ fill: e.fill,
}));
diff --git a/frontend/src/lib/reverseSearch.test.js b/frontend/src/lib/reverseSearch.test.js
index 99fc8f5..ee0945b 100644
--- a/frontend/src/lib/reverseSearch.test.js
+++ b/frontend/src/lib/reverseSearch.test.js
@@ -15,6 +15,19 @@ describe('UPLOAD_PAGES', () => {
}
});
+ it("opens Bing's upload view, not the page that redirects to marketing", () => {
+ // /visualsearch answers with explore.microsoft.com, which has nothing to
+ // drop a file on and no uploader to hand one to.
+ expect(byId.bing.url).toContain('iss=sbiupload');
+ expect(byId.bing.url).not.toContain('visualsearch');
+ });
+
+ it('lets the extension reach every one of them', () => {
+ // Each is declared in the manifest and answered for in extension/reverse.js;
+ // an engine flagged here that neither knows would open and do nothing.
+ expect(UPLOAD_PAGES.every((e) => e.fill)).toBe(true);
+ });
+
it('flags Google Lens as the only paste engine; the rest are drag-only', () => {
expect(byId.google.paste).toBe(true);
expect(byId.yandex.paste).toBe(false);
diff --git a/frontend/src/lib/staleness.js b/frontend/src/lib/staleness.js
index 338e25a..0972c35 100644
--- a/frontend/src/lib/staleness.js
+++ b/frontend/src/lib/staleness.js
@@ -9,12 +9,36 @@
import { shouldShowUpdate } from './appUpdate.js';
import { extensionOutdated } from './extBridge.js';
+/**
+ * Is the extension this browser runs behind what the app ships?
+ *
+ * For a copy the app owns, the digest in its install stamp answers it — and it is
+ * the only thing that can: a release that leaves the extension alone keeps its
+ * version, and within a development cycle the bundled version is already the
+ * app's own, so "behind" and "identical" are indistinguishable from a version.
+ *
+ * For a copy loaded from somebody else's folder there is no stamp to read, so the
+ * version is all there is. It is also all the button can act on there, since the
+ * app can only rewrite the folder it owns.
+ *
+ * Same road for Firefox's signed copy, and it is the one place the answer is
+ * worth more than a button: nothing here can update it, but the app ships the
+ * extension and therefore knows its version offline — so it can say "behind"
+ * on the spot rather than wait out the browser's own daily check.
+ */
+function behindWhatWeShip(verdict, bundled) {
+ if (verdict.status === 'absent') return false;
+ if (verdict.installed) return verdict.updateAvailable;
+ return extensionOutdated(verdict.detectedVersion, bundled);
+}
+
/**
* @param {{
* app?: object|null,
* scrapers?: Array<{dist: string, outdated?: boolean}>|null,
* extensionInstalled?: string|null,
* extensionBundled?: string,
+ * extension?: object|null,
* }|null} state What the startup checks found (state.svelte.js updatesState).
* @param {string} dismissedVersion The release tag muted with "don't show again".
*/
@@ -25,8 +49,15 @@ export function updateBadges(state, dismissedVersion = '') {
// A build that ships no extension has nothing to offer, so it says nothing.
const bundled = state?.extensionBundled ?? '';
const installed = state?.extensionInstalled ?? null;
- const extensionMissing = Boolean(bundled) && !installed;
- const extensionOld = extensionOutdated(installed, bundled);
+ // The probes' verdict once it has come back. Until then — and if it fails —
+ // the synchronous <html> marker and a version comparison, which is where this
+ // badge lived before the app owned the extension's folder.
+ const verdict = state?.extension ?? null;
+ const extensionMissing =
+ Boolean(bundled) && (verdict ? verdict.status === 'absent' : !installed);
+ const extensionOld = verdict
+ ? behindWhatWeShip(verdict, bundled)
+ : extensionOutdated(installed, bundled);
const scrapers = (state?.scrapers ?? []).filter((s) => s?.outdated).map((s) => s.dist);
return {
app,
diff --git a/frontend/src/lib/staleness.test.js b/frontend/src/lib/staleness.test.js
index e23e83c..a4b2e03 100644
--- a/frontend/src/lib/staleness.test.js
+++ b/frontend/src/lib/staleness.test.js
@@ -100,3 +100,96 @@ describe('carryLatest', () => {
expect(entry.outdated).toBe(false);
});
});
+
+describe('updateBadges: the extension verdict', () => {
+ // Once the bridge probes answer, the digest is what decides. The version
+ // cannot: a release that leaves the extension alone keeps its version, and
+ // within a development cycle the bundled version is already the app's own.
+ const verdict = (over = {}) => ({
+ status: 'owned',
+ installed: { version: '0.3.0', extensionId: 'ext-a', loaded: { payload: 'old' } },
+ detectedVersion: '0.3.0',
+ updateAvailable: false,
+ ...over,
+ });
+
+ it('lights the dot on a digest that moved, with both versions identical', () => {
+ const badges = updateBadges({
+ extensionInstalled: '0.3.0',
+ extensionBundled: '0.3.0',
+ extension: verdict({ updateAvailable: true }),
+ });
+ expect(badges.extension).toBe(true);
+ expect(badges.extensionOutdated).toBe(true);
+ expect(badges.tabs.extension).toBe(true);
+ expect(badges.any).toBe(true);
+ });
+
+ it('clears the dot when the running copy carries what the app ships', () => {
+ const badges = updateBadges({
+ extensionInstalled: '0.3.0',
+ extensionBundled: '0.3.0',
+ extension: verdict(),
+ });
+ expect(badges.extension).toBe(false);
+ });
+
+ it('reads the verdict, not the marker, once it has one', () => {
+ // The <html> marker is written by whichever bridge ran last and cannot tell
+ // one copy from another, so a stale version there must not override a
+ // verdict that says the loaded copy is current.
+ const badges = updateBadges({
+ extensionInstalled: '0.2.1',
+ extensionBundled: '0.3.0',
+ extension: verdict(),
+ });
+ expect(badges.extension).toBe(false);
+ });
+
+ it('marks nothing installed from the verdict too', () => {
+ const badges = updateBadges({
+ extensionBundled: '0.3.0',
+ extension: { status: 'absent', installed: null, detectedVersion: null, updateAvailable: false },
+ });
+ expect(badges.extensionMissing).toBe(true);
+ expect(badges.extensionOutdated).toBe(false);
+ });
+
+ it('falls back to versions for a copy the app does not own', () => {
+ // No stamp to compare, and no button that could act on the digest anyway:
+ // the app can only rewrite its own folder.
+ const behind = updateBadges({
+ extensionBundled: '0.3.0',
+ extension: { status: 'foreign', installed: null, detectedVersion: '0.2.1', updateAvailable: false },
+ });
+ expect(behind.extensionOutdated).toBe(true);
+ const current = updateBadges({
+ extensionBundled: '0.3.0',
+ extension: { status: 'foreign', installed: null, detectedVersion: '0.3.0', updateAvailable: false },
+ });
+ expect(current.extensionOutdated).toBe(false);
+ expect(current.extensionMissing).toBe(false);
+ });
+
+ it('says a signed copy is behind without waiting for the browser to notice', () => {
+ // Firefox owns the update and polls once a day. The app cannot act, but it
+ // ships the extension and so knows the version offline — which is the whole
+ // reason to answer here rather than fetch the update manifest ourselves.
+ const behind = updateBadges({
+ extensionBundled: '0.4.0',
+ extension: { status: 'signed', installed: null, detectedVersion: '0.3.0', updateAvailable: false },
+ });
+ expect(behind.extensionOutdated).toBe(true);
+ expect(behind.extensionMissing).toBe(false);
+ const current = updateBadges({
+ extensionBundled: '0.3.0',
+ extension: { status: 'signed', installed: null, detectedVersion: '0.3.0', updateAvailable: false },
+ });
+ expect(current.extensionOutdated).toBe(false);
+ });
+
+ it('keeps the version comparison while the probes have not answered', () => {
+ const badges = updateBadges({ extensionInstalled: '0.2.1', extensionBundled: '0.3.0' });
+ expect(badges.extension).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 266b3b5..67844f8 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -10,7 +10,8 @@ import { formatCoords as renderCoords } from './coords.js';
import { loadWidth, saveWidth, clampWidth } from './sidebar.js';
import { loadTheme, saveTheme, applyTheme } from './theme.js';
import { shouldShowUpdate } from './appUpdate.js';
-import { extensionVersion } from './extBridge.js';
+import { extensionVersion, pingExtensions, extensionState } from './extBridge.js';
+import { classify } from './extInstall.js';
import { loadRelationTypes } from './relations.svelte.js';
/**
@@ -25,6 +26,7 @@ export const prefs = $state({
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
postTarget: 'x', // social composer a fresh post draft starts with
postPrefill: true, // let the capture extension fill that composer on Publish
+ reversePrefill: true, // let it hand the image to the engine on Reverse Search
signatureHandle: '', // account handle stamped onto proofs that opt into it
updateCheckOnStart: true, // ask GitHub for a newer release when the page loads
updateDismissedVersion: '', // the release tag muted with "don't show again"
@@ -54,6 +56,11 @@ export const updatesState = $state({
scrapers: null, // checked downloader entries, or null while never checked
extensionInstalled: null, // version stamped on <html> by the installed extension
extensionBundled: '', // version this build ships (GET /api/settings)
+ // The full extension verdict once the probes answer (lib/extInstall.js): which
+ // copy is loaded, whether the app owns it, whether its digest is behind. The
+ // two fields above are the synchronous half, and stay the fallback until this
+ // arrives — a marker read costs nothing, a probe costs a timeout.
+ extension: null,
});
/** Render a lat/lon the way the user asked for it. The tools' one entry point. */
@@ -87,6 +94,7 @@ export function applyPrefs(s) {
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
if (s.post_target !== undefined) prefs.postTarget = s.post_target;
if (s.post_prefill !== undefined) prefs.postPrefill = s.post_prefill;
+ if (s.reverse_prefill !== undefined) prefs.reversePrefill = s.reverse_prefill;
if (s.signature_handle !== undefined) prefs.signatureHandle = s.signature_handle; // '' = none
if (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;
if (s.update_dismissed_version !== undefined)
@@ -107,6 +115,10 @@ export function applyPrefs(s) {
*/
export async function checkForUpdatesOnStart() {
updatesState.extensionInstalled = extensionVersion();
+ // Deliberately before the gate and deliberately not awaited: reading the app's
+ // own folder and asking the bridges who they are touches no network, so it runs
+ // even with the release check switched off, and nothing else waits on it.
+ checkExtension();
if (!prefs.updateCheckOnStart) return;
const [app, scrapers] = await Promise.allSettled([
api.get('/api/settings/update?check=true'),
@@ -124,6 +136,32 @@ export async function checkForUpdatesOnStart() {
if (scrapers.status === 'fulfilled') updatesState.scrapers = scrapers.value.scrapers ?? [];
}
+/**
+ * What this browser runs against what the app ships: one local read and the two
+ * bridge probes, reconciled by `classify`.
+ *
+ * This is what lets the badge see a digest move. The version comparison it falls
+ * back on cannot: a release that leaves the extension alone keeps its version,
+ * and within a development cycle the bundled version is already the app's own —
+ * so "behind" and "identical" look the same from a version alone.
+ *
+ * Never throws. A failure leaves `extension` null and the version fallback in
+ * charge, which is where the badge was before this existed.
+ */
+export async function checkExtension() {
+ try {
+ const [server, bridges, managed] = await Promise.all([
+ api.get('/api/settings/extension'),
+ pingExtensions(),
+ extensionState(),
+ ]);
+ updatesState.extension = classify(server, { bridges, managed });
+ } catch {
+ /* the fallback is the badge's previous behaviour, which is a fine answer */
+ }
+ return updatesState.extension;
+}
+
/** Close the update pop-up. `mute` remembers the tag so it won't show again. */
export async function dismissUpdate(mute = false) {
updateState.show = false;
@@ -176,12 +214,18 @@ export async function deleteTemplate(kind, id) {
}
export const uiState = $state({
- tool: 'media', // 'media' | 'inspect' | 'satellite' | 'proof' | 'post' | 'settings'
+ // Where the app opens (lib/workspaces.js). Home rather than a tool, because a
+ // fresh install lands in a workspace with no case, and the Media Library's empty
+ // state cannot say what any of the rail means. A deep link still wins.
+ tool: 'overview',
theme: loadTheme(), // 'dark' | 'light'; index.html stamps it before first paint
sidebarOpen: true,
sidebarW: loadWidth(), // px, drag-resizable and remembered across reloads
toasts: [],
settingsTab: null, // settings section id to open when switching to Settings
+ // Guide section to land on when switching to the Guide, from the `?` in the
+ // topbar. Consumed by that tab, so scrolling away afterwards sticks.
+ guideSection: null,
// cross-tool handoffs (the workbench glue):
composeQueue: [], // media paths queued for the Proof Composer
postProof: null, // proof spec handed to the Post Composer
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index 479a0f0..8bebf0c 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -167,7 +167,11 @@ describe('startup update check', () => {
api.get.mockClear();
applyPrefs({ update_check_on_start: false });
await checkForUpdatesOnStart();
- expect(api.get).not.toHaveBeenCalled();
+ // The switch governs the network, which is what `?check=true` marks. The
+ // local reads that stay behind — what the app's own extension folder holds —
+ // reach the loopback server and nothing else, so they are not what it gates.
+ expect(api.get.mock.calls.flat().filter((path) => String(path).includes('check=true')))
+ .toEqual([]);
});
it('records what the downloaders check found', async () => {
@@ -192,12 +196,45 @@ describe('startup update check', () => {
applyPrefs({ update_check_on_start: false, extension_version: '0.2.5' });
await checkForUpdatesOnStart();
- expect(api.get).not.toHaveBeenCalled();
+ // The marker on <html> is a synchronous local read, so the version half of
+ // the answer holds even with every request failing.
+ expect(api.get.mock.calls.flat().filter((path) => String(path).includes('check=true')))
+ .toEqual([]);
expect(updatesState.extensionInstalled).toBe('0.2.1');
expect(updatesState.extensionBundled).toBe('0.2.5');
delete document.documentElement.dataset.azimutCaptureExtension;
});
+ it('reads the extension folder locally, and never on the network switch', async () => {
+ // The digest comparison the badge needs is a disk read on the loopback
+ // server plus two postMessage probes: no third party, nothing to gate.
+ const { api } = await import('./api.js');
+ api.get.mockReset().mockResolvedValue({
+ path: '/w/.azimut/extension',
+ staged: false,
+ bundled: { version: '0.3.0', payload: 'new' },
+ folder: { install_id: 'mine', version: '0.3.0', payload: 'old' },
+ });
+ const { applyPrefs, checkExtension, updatesState } = await freshState();
+ applyPrefs({ update_check_on_start: false });
+
+ await checkExtension();
+
+ expect(api.get).toHaveBeenCalledWith('/api/settings/extension');
+ // Nothing answered the probes here, so the verdict is "nothing loaded" —
+ // and it is a verdict, not a failure.
+ expect(updatesState.extension.status).toBe('absent');
+ });
+
+ it('leaves the version fallback in charge when the folder cannot be read', async () => {
+ const { api } = await import('./api.js');
+ api.get.mockReset().mockRejectedValue(new Error('offline'));
+ const { checkExtension, updatesState } = await freshState();
+
+ await expect(checkExtension()).resolves.toBeFalsy();
+ expect(updatesState.extension).toBe(null);
+ });
+
it('does not surface an offline failure', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('offline'));
diff --git a/frontend/src/lib/usage.js b/frontend/src/lib/usage.js
index 7b917a6..6dd1bee 100644
--- a/frontend/src/lib/usage.js
+++ b/frontend/src/lib/usage.js
@@ -29,6 +29,16 @@
*/
export const FREE_TIER = { mapbox: 200_000, google: 100_000, google_js: 10_000, sentinelhub: 30_000 };
+/**
+ * The imagery that costs nothing and needs no key.
+ *
+ * Named once because two different rules land on it: a billed basemap steps
+ * aside for it when the month is nearly spent or the view is zoomed out
+ * (`displayProviderId`), and any map that is only a reading shows it and
+ * nothing else — the home page's, which has no basemap picker over it.
+ */
+export const FREE_IMAGERY = 'esri-world-imagery';
+
/** This account's allowance for a meter: the served figure, else the default. */
export function freeTier(meter, tiers = null) {
return tiers?.[meter] ?? FREE_TIER[meter];
@@ -124,9 +134,9 @@ export function displayProviderId(
{ eco = true, blocked = false, ecoMaxZoom = ECO_MAX_ZOOM } = {}
) {
if (!provider?.meter) return provider?.id;
- if (blocked) return 'esri-world-imagery';
+ if (blocked) return FREE_IMAGERY;
const threshold = provider.eco_max_zoom ?? ecoMaxZoom;
- if (eco && zoom <= threshold) return 'esri-world-imagery';
+ if (eco && zoom <= threshold) return FREE_IMAGERY;
return provider.id;
}
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 9874ef8..315be5e 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -20,6 +20,24 @@ export const CASE_WORKSPACE = {
tools: ['board', 'graph', 'timeline', 'sheet'],
};
+/**
+ * Where the app opens, and the same argument decides where it sits: the rail is a
+ * sequence of stages and home is not one of them, so it hangs off the wordmark in
+ * the topbar rather than taking a fifth rail seat. Every app puts home on its own
+ * mark, which is the one affordance that needs no label.
+ *
+ * Two tabs. *Overview* answers "what is this case waiting on" for somebody who has
+ * been here before; *Guide* answers "what is this app" for somebody who has not. A
+ * fresh install has no case to summarise, so the overview's empty state is the front
+ * door and the guide is one click from it.
+ */
+export const HOME_WORKSPACE = {
+ id: 'home',
+ label: 'Home',
+ icon: 'compass',
+ tools: ['overview', 'guide'],
+};
+
/** The rail, in investigation order. */
export const WORKSPACES = [
{ id: 'collect', label: 'Sources', icon: 'download', tools: ['media', 'files', 'reverse'] },
@@ -29,9 +47,11 @@ export const WORKSPACES = [
];
/** Every workspace, on the rail or not — what tool lookup and deep links resolve against. */
-export const ALL_WORKSPACES = [CASE_WORKSPACE, ...WORKSPACES];
+export const ALL_WORKSPACES = [HOME_WORKSPACE, CASE_WORKSPACE, ...WORKSPACES];
export const TOOL_LABELS = {
+ overview: 'Overview',
+ guide: 'Guide',
board: 'Board',
graph: 'Graph',
timeline: 'Timeline',
@@ -54,12 +74,15 @@ export function workspaceOf(tool) {
/** Return the session's sidebar state for a workspace, falling back to defaults.
*
- * Closed on `map`, which needs the width, and on `case`, where the board already
- * lists the same entities — two lists of one case side by side is a question about
- * which one is the real one. */
+ * Closed on `map`, which needs the width; on `case`, where the board already lists
+ * the same entities — two lists of one case side by side is a question about which
+ * one is the real one — and on `home`, which is read rather than worked in and whose
+ * whole subject is the case the sidebar would be listing again. */
+const SIDEBAR_CLOSED = new Set(['map', 'case', 'home']);
+
export function sidebarOpenForWorkspace(workspaceId, remembered = {}) {
if (remembered[workspaceId] !== undefined) return remembered[workspaceId];
- return workspaceId !== 'map' && workspaceId !== 'case';
+ return !SIDEBAR_CLOSED.has(workspaceId);
}
/**
diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.js
index 38c85fe..a5474ce 100644
--- a/frontend/src/lib/workspaces.test.js
+++ b/frontend/src/lib/workspaces.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
ALL_WORKSPACES,
CASE_WORKSPACE,
+ HOME_WORKSPACE,
WORKSPACES,
TOOL_LABELS,
sidebarOpenForWorkspace,
@@ -10,13 +11,14 @@ import {
} from './workspaces.js';
const ALL_TOOLS = [
- 'board', 'graph', 'timeline', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook',
+ 'overview', 'guide',
+ 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook',
'settings',
];
describe('workspaceOf', () => {
it('maps every tool to exactly one workspace', () => {
- for (const tool of ['board', 'graph', 'timeline', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook']) {
+ for (const tool of ['overview', 'guide', 'board', 'graph', 'timeline', 'sheet', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook']) {
const owners = ALL_WORKSPACES.filter((w) => w.tools.includes(tool));
expect(owners).toHaveLength(1);
expect(workspaceOf(tool)).toBe(owners[0]);
@@ -30,9 +32,21 @@ describe('workspaceOf', () => {
expect(workspaceOf('timeline')).toBe(CASE_WORKSPACE);
});
- it('resolves the case workspace even though the rail never lists it', () => {
- expect(ALL_WORKSPACES[0]).toBe(CASE_WORKSPACE);
- expect(ALL_WORKSPACES).toHaveLength(WORKSPACES.length + 1);
+ it('resolves the two workspaces the rail never lists', () => {
+ // the rail is a sequence of stages; neither home nor the case is one, so both
+ // hang off the topbar and both still have to resolve as workspaces
+ expect(ALL_WORKSPACES).toContain(HOME_WORKSPACE);
+ expect(ALL_WORKSPACES).toContain(CASE_WORKSPACE);
+ expect(ALL_WORKSPACES).toHaveLength(WORKSPACES.length + 2);
+ });
+
+ it('keeps home off the rail too, on the mark rather than a fifth seat', () => {
+ expect(WORKSPACES.map((w) => w.id)).not.toContain('home');
+ expect(workspaceOf('overview')).toBe(HOME_WORKSPACE);
+ expect(workspaceOf('guide')).toBe(HOME_WORKSPACE);
+ // two tabs, so the strip draws itself: the overview for somebody who has been
+ // here, the guide for somebody who has not
+ expect(HOME_WORKSPACE.tools).toEqual(['overview', 'guide']);
});
it('groups media, files and reverse search under collect', () => {
@@ -63,14 +77,20 @@ describe('product-facing labels', () => {
expect(TOOL_LABELS.proof).toBe('Geo Proof');
expect(TOOL_LABELS.post).toBe('Geo Report');
expect(TOOL_LABELS.timeline).toBe('Timeline');
+ // the tab is the overview; "Home" is the workspace the mark opens
+ expect(TOOL_LABELS.overview).toBe('Overview');
+ expect(TOOL_LABELS.guide).toBe('Guide');
});
});
describe('sidebarOpenForWorkspace', () => {
- it('defaults Map and Case closed, and other workspaces open', () => {
+ it('defaults Map, Case and Home closed, and other workspaces open', () => {
expect(sidebarOpenForWorkspace('map')).toBe(false);
// the board lists the same case: two lists side by side ask which is the real one
expect(sidebarOpenForWorkspace('case')).toBe(false);
+ // home is read rather than worked in, and its whole subject is the case the
+ // sidebar would be listing again
+ expect(sidebarOpenForWorkspace('home')).toBe(false);
expect(sidebarOpenForWorkspace('collect')).toBe(true);
expect(sidebarOpenForWorkspace('examine')).toBe(true);
});
@@ -91,9 +111,11 @@ describe('toolFromHash', () => {
it('accepts a bare workspace id (first tool)', () => {
expect(toolFromHash('#collect', ALL_TOOLS)).toBe('media');
expect(toolFromHash('#compose', ALL_TOOLS)).toBe('proof');
- // off the rail, still a workspace: #case has to keep resolving
+ // off the rail, still a workspace: #case and #home have to keep resolving
expect(toolFromHash('#case', ALL_TOOLS)).toBe('board');
expect(toolFromHash('#case/timeline', ALL_TOOLS)).toBe('timeline');
+ expect(toolFromHash('#home', ALL_TOOLS)).toBe('overview');
+ expect(toolFromHash('#home/guide', ALL_TOOLS)).toBe('guide');
});
it('accepts workspace/tab form', () => {
diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelte
index a368956..e01cf5c 100644
--- a/frontend/src/tools/Board.svelte
+++ b/frontend/src/tools/Board.svelte
@@ -68,6 +68,7 @@
entityLabel,
entityTypes,
familyReads,
+ familyTitle,
loadEntityTypes,
} from '../lib/entityTypes.svelte.js';
import { createBookmark } from '../lib/bookmarks.js';
@@ -795,9 +796,6 @@
}
});
- /** The slug with a capital, not a second vocabulary: the families are code, and
- * inventing readings for them here is how two lists start. */
- const familyTitle = (family) => family.charAt(0).toUpperCase() + family.slice(1);
/** The question as one sentence, which is what the graph writes over the drawing
* so nobody has to remember what they asked two tabs ago. */
diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelte
index 505a240..610c1b1 100644
--- a/frontend/src/tools/Graph.svelte
+++ b/frontend/src/tools/Graph.svelte
@@ -96,6 +96,7 @@
entityLabel,
entityTypes,
familyReads,
+ familyTitle,
loadEntityTypes,
} from '../lib/entityTypes.svelte.js';
import {
@@ -321,7 +322,6 @@
let hiddenFamilies = $state([]);
/** Every type the case actually holds, from the catalog summary. */
let caseTypes = $state([]);
- const familyTitle = (family) => family.charAt(0).toUpperCase() + family.slice(1);
const searchFamilies = $derived(
[...new Set(caseTypes.map((type) => entityFamily(type)).filter(Boolean))].sort()
);
diff --git a/frontend/src/tools/Guide.render.test.js b/frontend/src/tools/Guide.render.test.js
new file mode 100644
index 0000000..01dc300
--- /dev/null
+++ b/frontend/src/tools/Guide.render.test.js
@@ -0,0 +1,176 @@
+// @vitest-environment happy-dom
+/**
+ * The guide, mounted.
+ *
+ * `lib/guide.test.js` holds the text to its own rules, fails when a tool joins a
+ * workspace undocumented, and decides which section a reader is in. This checks what
+ * only a DOM can answer: that every section reaches the page, that a section can be
+ * left at the workspace it just described, and that the contents list follows the
+ * scroll without fighting the press that started it.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const uiState = { tool: 'guide', guideSection: null };
+vi.mock('../lib/state.svelte.js', () => ({ uiState }));
+
+const { default: Guide } = await import('./Guide.svelte');
+const { GUIDE } = await import('../lib/guide.js');
+
+let live = null;
+let target = null;
+
+function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Guide, { target });
+ flushSync();
+ return target;
+}
+
+const jumps = () => [...target.querySelectorAll('.contents .jump')];
+const marked = () => jumps().findIndex((jump) => jump.classList.contains('on'));
+
+/** A scroll of the column the page actually scrolls in. */
+function scroll() {
+ target.querySelector('.tool-body').dispatchEvent(new Event('scroll'));
+ flushSync();
+}
+
+beforeEach(() => {
+ uiState.tool = 'guide';
+ uiState.guideSection = null;
+ vi.useFakeTimers();
+ // run the measurement on the spot: this DOM has no frames and no layout, and what
+ // is under test is the bookkeeping around it rather than the arithmetic
+ vi.stubGlobal('requestAnimationFrame', (cb) => {
+ cb();
+ return 1;
+ });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ target = null;
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('the guide on screen', () => {
+ it('draws every section it holds, and a contents entry for each', () => {
+ open();
+ expect(target.querySelectorAll('section')).toHaveLength(GUIDE.length);
+ expect(target.querySelectorAll('.contents .jump')).toHaveLength(GUIDE.length);
+ for (const section of GUIDE) {
+ expect(target.querySelector(`#guide-${section.id}`), section.id).toBeTruthy();
+ }
+ });
+
+ it('writes every point out, label and body', () => {
+ open();
+ const text = target.textContent;
+ for (const section of GUIDE) {
+ expect(text).toContain(section.lead);
+ for (const point of section.points ?? []) {
+ expect(text).toContain(point.label);
+ expect(text).toContain(point.text);
+ }
+ }
+ });
+
+ it('writes the recipes, the keys and the fixes out too', () => {
+ open();
+ const text = target.textContent;
+ for (const section of GUIDE) {
+ for (const recipe of section.recipes ?? []) {
+ expect(text).toContain(recipe.title);
+ for (const step of recipe.steps) expect(text).toContain(step.text);
+ }
+ for (const group of section.keymap ?? []) {
+ expect(text).toContain(group.where);
+ for (const key of group.keys) expect(text).toContain(key.combo);
+ }
+ for (const fix of section.fixes ?? []) {
+ expect(text).toContain(fix.symptom);
+ expect(text).toContain(fix.fix);
+ }
+ }
+ });
+
+ it('opens the tool a recipe step names, from the step itself', () => {
+ // reading how something is done and then hunting for the tab it is done in is
+ // exactly the work a guide exists to remove
+ open();
+ const first = target.querySelector('.recipe .step-tool');
+ expect(first.textContent.trim()).toBe('Media');
+ first.click();
+ flushSync();
+ expect(uiState.tool).toBe('media');
+ });
+
+ it('lands on the section the topbar mark asked for, and consumes the request', () => {
+ uiState.guideSection = 'map';
+ open();
+ expect(marked()).toBe(GUIDE.findIndex((section) => section.id === 'map'));
+ // consumed, so a reader who scrolls away is not sent back next time this tab shows
+ expect(uiState.guideSection).toBe(null);
+ });
+
+ it('leaves a section at the workspace it describes', () => {
+ // a guide you cannot leave at the thing it just explained is a document, not help
+ open();
+ const map = target.querySelector('#guide-map');
+ const open_it = [...map.querySelectorAll('button')].find((b) => b.textContent.includes('Open it'));
+ open_it.click();
+ flushSync();
+ expect(uiState.tool).toBe('satellite');
+ });
+
+ it('offers no way out of the section that describes no workspace', () => {
+ open();
+ const start = target.querySelector('#guide-start');
+ expect([...start.querySelectorAll('button')].some((b) => b.textContent.includes('Open it'))).toBe(
+ false
+ );
+ });
+
+ it('marks the contents entry the reader jumped to', () => {
+ open();
+ expect(marked()).toBe(0);
+ jumps()[2].click();
+ flushSync();
+ expect(marked()).toBe(2);
+ });
+
+ it('lets the press own the list while the scroll it started travels', () => {
+ // otherwise the one control that says "go here" walks the mark down every section
+ // on the way and answers by pointing somewhere else three times first
+ open();
+ jumps()[2].click();
+ flushSync();
+ scroll();
+ expect(marked()).toBe(2);
+ });
+
+ it('follows the column again once the press has landed', () => {
+ open();
+ jumps()[2].click();
+ flushSync();
+ vi.advanceTimersByTime(800);
+ scroll();
+ // this DOM measures every heading at zero, which is also the foot of the column,
+ // so the answer is the last section: what is asserted is that it moved at all
+ expect(marked()).toBe(jumps().length - 1);
+ });
+
+ it('listens on the column rather than the window', () => {
+ // the page scrolls inside .tool-body, so a window listener would never fire
+ open();
+ window.dispatchEvent(new Event('scroll'));
+ flushSync();
+ expect(marked()).toBe(0);
+ });
+});
diff --git a/frontend/src/tools/Guide.svelte b/frontend/src/tools/Guide.svelte
new file mode 100644
index 0000000..f25507b
--- /dev/null
+++ b/frontend/src/tools/Guide.svelte
@@ -0,0 +1,515 @@
+<script>
+ /**
+ * What the app is, and what each workspace is for.
+ *
+ * One section per rail workspace plus the case, read down a column with a contents
+ * list beside it, between two that set up — what a case is, the capture extension,
+ * then three jobs walked end to end — and two that close: the keys, and what to do
+ * when something breaks. The text is `lib/guide.js` rather than markup here, so the
+ * `?` in the topbar can open this tab on one section instead of the app growing a
+ * second copy of the same sentences.
+ *
+ * Static on purpose: no tour, no overlay, no step that points at a live button.
+ * A guided tour breaks silently on the first layout change and nobody notices for a
+ * release; a page of text is wrong in a way that can be read and fixed.
+ */
+ import { GUIDE, readingSection } from '../lib/guide.js';
+ import { ALL_WORKSPACES, TOOL_LABELS } from '../lib/workspaces.js';
+ import { uiState } from '../lib/state.svelte.js';
+ import Icon from '../components/Icon.svelte';
+
+ /** Where the whole picture lives, for a reader who downloaded a binary and has no
+ * repository in front of them. */
+ const SPEC_URL = 'https://github.com/OsintMeThat/azimut/blob/main/docs/SPEC.md';
+
+ /** How far below the top of the column a heading counts as the one being read. */
+ const LINE = 120;
+ /** How long a press owns the list for, while the smooth scroll travels. */
+ const STEER = 700;
+
+ /** The section the contents list is pointing at. Local to this tab: which paragraph
+ * somebody read last is not state the case or the browser should carry. */
+ let at = $state(GUIDE[0].id);
+ let column = $state(null);
+
+ /** A section's mark: the workspace's own where the id names one, so the contents
+ * list and the rail cannot drift apart, and the section's own where it names none. */
+ const iconOf = (section) =>
+ ALL_WORKSPACES.find((ws) => ws.id === section.id)?.icon ?? section.icon ?? 'compass';
+
+ /**
+ * Follow the reading: the contents list marks whatever section is under the eye.
+ *
+ * Measured on the frame rather than on every scroll event, and off the **column**
+ * rather than the window, since the page scrolls inside `.tool-body` and a heading's
+ * viewport position says nothing about where it sits in there.
+ */
+ let frame = 0;
+ let pending = false;
+ let steering = 0;
+
+ /** The headings, in document order, each measured against the top of the column. */
+ function measure() {
+ pending = false;
+ if (!column) return;
+ const top = column.getBoundingClientRect().top;
+ const marks = GUIDE.map((section) => ({
+ id: section.id,
+ el: column.querySelector(`#guide-${section.id}`),
+ }))
+ .filter((mark) => mark.el)
+ .map((mark) => ({ id: mark.id, top: mark.el.getBoundingClientRect().top - top }));
+ at =
+ readingSection(marks, {
+ line: LINE,
+ atBottom: column.scrollTop + column.clientHeight >= column.scrollHeight - 4,
+ }) ?? at;
+ }
+
+ // The guard is its own flag rather than the frame handle: a handle is only assigned
+ // once `requestAnimationFrame` returns, so anything that runs the callback before
+ // that would leave a number behind and wedge this shut.
+ function follow() {
+ if (steering || pending || !column) return;
+ pending = true;
+ frame = requestAnimationFrame(measure);
+ }
+
+ $effect(() => {
+ const el = column;
+ if (!el) return;
+ el.addEventListener('scroll', follow, { passive: true });
+ return () => {
+ el.removeEventListener('scroll', follow);
+ if (frame) cancelAnimationFrame(frame);
+ clearTimeout(steering);
+ };
+ });
+
+ /**
+ * Jump to a section, and let the press own the list until it lands.
+ *
+ * Without that, the scroll it starts walks the highlight down every section on the
+ * way, so the one control that says *go here* answers by pointing somewhere else
+ * three times first.
+ */
+ function show(id) {
+ at = id;
+ clearTimeout(steering);
+ steering = setTimeout(() => {
+ steering = 0;
+ follow();
+ }, STEER);
+ const target = column?.querySelector(`#guide-${id}`);
+ target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ }
+
+ /** Open the workspace a section describes, from the section itself. A guide that
+ * cannot be left at the thing it just explained is a document, not help. */
+ function go(section) {
+ const first = section.tools[0];
+ if (first) uiState.tool = first;
+ }
+
+ /**
+ * Arrive on a section, because the `?` in the topbar asked for it.
+ *
+ * The request is consumed rather than kept: it says *go there now*, and a reader who
+ * then scrolls somewhere else must not be sent back the next time this tab is shown.
+ * A frame is waited for because the column is laid out after this tab becomes the
+ * visible one, and a heading measured in a hidden panel is at zero.
+ */
+ $effect(() => {
+ const wanted = uiState.guideSection;
+ if (!wanted) return;
+ uiState.guideSection = null;
+ requestAnimationFrame(() => show(wanted));
+ });
+</script>
+
+<div class="tool">
+ <div class="tool-body" bind:this={column}>
+ <div class="sheet">
+ <nav class="contents" aria-label="Guide contents">
+ {#each GUIDE as section (section.id)}
+ <button class="jump" class:on={at === section.id} onclick={() => show(section.id)}>
+ <Icon name={iconOf(section)} size={14} />
+ <span>{section.title}</span>
+ </button>
+ {/each}
+ </nav>
+
+ <div class="body">
+ {#each GUIDE as section (section.id)}
+ <section id="guide-{section.id}">
+ <header>
+ <h2><Icon name={iconOf(section)} size={17} />{section.title}</h2>
+ {#if section.tools.length}
+ <button class="aside" onclick={() => go(section)}>
+ Open it
+ <Icon name="arrowRight" size={13} />
+ </button>
+ {/if}
+ </header>
+ <p class="lead">{section.lead}</p>
+
+ {#if section.tools.length}
+ <p class="tabs">
+ {#each section.tools as tool, i (tool)}
+ {#if i > 0}<span class="dot">·</span>{/if}<span>{TOOL_LABELS[tool] ?? tool}</span>
+ {/each}
+ </p>
+ {/if}
+
+ {#if section.points?.length}
+ <dl>
+ {#each section.points as point (point.label)}
+ <dt>{point.label}</dt>
+ <dd>{point.text}</dd>
+ {/each}
+ </dl>
+ {/if}
+
+ <!-- A job, tab by tab. The tool on each step is the control, not a label:
+ reading how something is done and then hunting for the tab it is done
+ in is the part a guide is supposed to remove. -->
+ {#if section.recipes?.length}
+ <div class="recipes">
+ {#each section.recipes as recipe (recipe.title)}
+ <article class="recipe">
+ <h3>{recipe.title}</h3>
+ <p class="recipe-lead">{recipe.lead}</p>
+ <ol>
+ {#each recipe.steps as step, i (step.tool + i)}
+ <li>
+ <span class="step-n">{i + 1}</span>
+ <button class="step-tool" onclick={() => (uiState.tool = step.tool)}>
+ {TOOL_LABELS[step.tool] ?? step.tool}
+ <Icon name="arrowRight" size={11} />
+ </button>
+ <span class="step-say">{step.text}</span>
+ </li>
+ {/each}
+ </ol>
+ </article>
+ {/each}
+ </div>
+ {/if}
+
+ {#if section.keymap?.length}
+ <div class="keymap">
+ {#each section.keymap as group (group.where)}
+ <div class="keygroup">
+ <h3>{group.where}</h3>
+ <ul class="keys">
+ {#each group.keys as key (key.combo)}
+ <li><kbd>{key.combo}</kbd><span>{key.does}</span></li>
+ {/each}
+ </ul>
+ </div>
+ {/each}
+ </div>
+ {/if}
+
+ {#if section.fixes?.length}
+ <dl class="fixes">
+ {#each section.fixes as fix (fix.symptom)}
+ <dt>{fix.symptom}</dt>
+ <dd>{fix.fix}</dd>
+ {/each}
+ </dl>
+ {/if}
+ </section>
+ {/each}
+
+ <p class="tail">
+ The full picture of what is shipped and what is planned lives in
+ <a href={SPEC_URL} target="_blank" rel="noreferrer">
+ docs/SPEC.md<Icon name="external" size={10} />
+ </a>.
+ </p>
+ </div>
+ </div>
+ </div>
+</div>
+
+<style>
+ .sheet {
+ display: grid;
+ grid-template-columns: 168px minmax(0, 1fr);
+ gap: 40px;
+ max-width: 940px;
+ margin: 0 auto;
+ padding: 36px 28px 72px;
+ }
+
+ /* The contents list stays put while the text moves under it: six sections is more
+ than fits a screen, and a reader who has scrolled has nothing else to navigate by. */
+ .contents {
+ position: sticky;
+ top: 36px;
+ align-self: start;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ }
+ .jump {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 7px 9px;
+ border-left: 2px solid transparent;
+ border-radius: 0 var(--r-sm) var(--r-sm) 0;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ text-align: left;
+ transition: color 0.14s var(--ease), background 0.14s var(--ease);
+ }
+ .jump:hover {
+ color: var(--text-1);
+ background: var(--bg-1);
+ }
+ .jump.on {
+ color: var(--text-1);
+ border-left-color: var(--accent);
+ }
+
+ section {
+ padding-bottom: 34px;
+ margin-bottom: 34px;
+ border-bottom: 1px solid var(--border);
+ scroll-margin-top: 24px;
+ }
+ section:last-of-type {
+ border-bottom: 0;
+ }
+ header {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 14px;
+ }
+ h2 {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ font-size: var(--fs-lg);
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ }
+ .lead {
+ margin-top: 7px;
+ font-size: var(--fs-md);
+ color: var(--text-2);
+ line-height: 1.6;
+ }
+ /* Which tabs the section is about, in the words the tab strip uses. */
+ .tabs {
+ margin-top: 9px;
+ font-size: var(--fs-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-3);
+ }
+
+ dl {
+ margin: 22px 0 0;
+ }
+ dt {
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ dd {
+ margin: 3px 0 16px;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ line-height: 1.62;
+ }
+ dd:last-child {
+ margin-bottom: 0;
+ }
+
+ /* ---- worked examples ------------------------------------------------------ */
+
+ .recipes {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ margin-top: 22px;
+ }
+ .recipe {
+ padding: 16px 18px 18px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ }
+ .recipe h3 {
+ font-size: var(--fs-md);
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .recipe-lead {
+ margin-top: 3px;
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+ .recipe ol {
+ list-style: none;
+ margin: 14px 0 0;
+ padding: 0;
+ counter-reset: step;
+ }
+ /* Number, tab, sentence: three columns rather than a wrapped line, so the steps
+ read down the tabs they happen in instead of starting in a different place each
+ time the tool's name changes length. */
+ .recipe li {
+ display: grid;
+ grid-template-columns: 1.45rem 8rem minmax(0, 1fr);
+ gap: 0 12px;
+ align-items: start;
+ padding-bottom: 12px;
+ }
+ .recipe li:last-child {
+ padding-bottom: 0;
+ }
+ @media (max-width: 820px) {
+ .recipe li {
+ grid-template-columns: 1.45rem minmax(0, 1fr);
+ row-gap: 5px;
+ }
+ .step-tool,
+ .step-say {
+ grid-column: 2;
+ }
+ }
+ .step-n {
+ flex-shrink: 0;
+ width: 1.45rem;
+ height: 1.45rem;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--bg-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ line-height: 1.35rem;
+ text-align: center;
+ color: var(--text-2);
+ }
+ .step-say {
+ padding-top: 1px;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ line-height: 1.6;
+ }
+ .step-tool {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ white-space: nowrap;
+ padding: 1px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-1);
+ transition: border-color 0.14s var(--ease), color 0.14s var(--ease);
+ }
+ .step-tool:hover {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+
+ /* ---- the keys ------------------------------------------------------------- */
+
+ .keymap {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 12px;
+ margin-top: 22px;
+ }
+ .keygroup {
+ padding: 12px 14px 14px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ }
+ .keygroup h3 {
+ margin-bottom: 9px;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--text-3);
+ }
+ /* One grid for the whole card rather than one per row, so every key in a card
+ starts at the same place and its sentence wraps in its own column instead of
+ dropping whole to the next line. */
+ .keys {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: 7px 11px;
+ align-items: baseline;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ }
+ .keys li {
+ display: contents;
+ }
+
+ /* ---- when something does not work ----------------------------------------- */
+
+ .fixes dt {
+ padding-left: 13px;
+ border-left: 2px solid var(--warn);
+ }
+ .fixes dd {
+ padding-left: 15px;
+ }
+ kbd {
+ justify-self: start;
+ white-space: nowrap;
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-1);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
+ text-align: center;
+ }
+
+ .aside {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ flex-shrink: 0;
+ font-size: var(--fs-xs);
+ font-weight: 500;
+ color: var(--text-3);
+ transition: color 0.14s var(--ease);
+ }
+ .aside:hover {
+ color: var(--accent);
+ }
+
+ .dot {
+ margin: 0 7px;
+ opacity: 0.55;
+ }
+ .tail {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .tail a {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ color: var(--accent);
+ }
+</style>
diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.js
new file mode 100644
index 0000000..9d5e3b9
--- /dev/null
+++ b/frontend/src/tools/Overview.render.test.js
@@ -0,0 +1,407 @@
+// @vitest-environment happy-dom
+/**
+ * The page the app opens on, driven the way somebody opening the app drives it.
+ *
+ * `lib/overview.test.js` covers the arithmetic. This covers what is only true in a
+ * browser: that a count of nothing stops being a control, that pressing a tile hands
+ * the Board the same question the number was read from, that a case holding nothing is
+ * offered a way in rather than a reading of nothing, and that a workspace with no case
+ * asks the backend nothing at all.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const SUMMARY = {
+ total: 30,
+ by_type: { place: 6, media: 20, person: 4 },
+ by_status: { confirmed: 26, suggested: 4 },
+ by_folder: { work: 18 },
+ by_source: {},
+ linked_to: {},
+ unlinked: 7,
+ countable: 0,
+};
+
+const RECENT = [
+ {
+ id: 'e1',
+ type: 'media',
+ label: 'Clip',
+ attrs: { kind: 'video' },
+ thumb: 'azimut/media/.thumbs/clip.jpg',
+ provenance: { at: '2026-09-10T09:00:00Z' },
+ },
+ { id: 'e2', type: 'place', label: 'Quai sud', attrs: {}, provenance: { at: '2026-09-09T09:00:00Z' } },
+];
+
+const SAVED = [
+ { id: 'p1', key: 'p1', kind: 'place', title: 'Quai sud', lat: 49.98, lon: 36.25 },
+ { id: 'p2', key: 'p2', kind: 'capture', title: 'Depot', lat: 49.99, lon: 36.3 },
+];
+
+const PROVIDERS = [
+ { id: 'esri-world-imagery', label: 'Esri World Imagery', max_zoom: 19, tile_size: 256, oversample: 1 },
+];
+
+// The map of the case is a map, and a test DOM has no canvas to draw one on. What
+// it asks `lib/map` for is covered next door (`overview/PlaceMap.render.test.js`);
+// here it stands in for itself so the page around it can be driven.
+vi.mock('../lib/map/engine.js', () => ({
+ createMapEngine: async () => ({ fitPoints: () => true, getZoom: () => 3, destroy: () => {}, impl: {} }),
+}));
+vi.mock('../lib/map/basemap.js', () => ({
+ createBasemaps: () => ({ show: () => {}, dispose: () => {}, setLabels: () => {} }),
+}));
+vi.mock('../lib/map/surface.js', () => ({
+ createSurface: () => ({ set: () => {}, destroy: () => {} }),
+}));
+
+/** What the case answers unless a test says otherwise. Re-armed every time, since
+ * clearing a mock leaves the last implementation in place and the next test would
+ * quietly inherit the empty case the one before it asked for. */
+const answers = async (url) => {
+ if (url === '/api/satellite/providers') return PROVIDERS;
+ if (url.includes('/catalog/summary')) return SUMMARY;
+ if (url.includes('/timeline')) return { items: [], undated: 3, unplaced: 0, total: 9 };
+ if (url.includes('/satellite/index')) return SAVED;
+ if (url.includes('since=')) return { items: [], total: 5, next_cursor: null };
+ if (url.includes('/catalog/entities')) return { items: RECENT, total: 30, next_cursor: null };
+ return {};
+};
+const get = vi.fn(answers);
+vi.mock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn(), patch: vi.fn(), put: vi.fn() }, ApiError: Error }));
+
+const createCase = vi.fn(async () => ({ id: 'new' }));
+const openCase = vi.fn(async () => {});
+const toast = vi.fn();
+vi.mock('../lib/state.svelte.js', async () => {
+ const fixture = await import('./overview.fixture.svelte.js');
+ return {
+ caseState: fixture.caseState,
+ uiState: fixture.uiState,
+ prefs: fixture.prefs,
+ updatesState: fixture.updatesState,
+ createCase,
+ openCase,
+ toast,
+ };
+});
+
+const setAnalysisFilter = vi.fn();
+const leaveAnalysisView = vi.fn();
+vi.mock('../lib/analysisSearch.svelte.js', () => ({ setAnalysisFilter, leaveAnalysisView }));
+
+const openEntity = vi.fn();
+vi.mock('../lib/navigate.js', () => ({ openEntity }));
+
+// The registry is served by the backend and never loaded here, so the families it
+// would answer with are stated instead: without them every type falls into "other"
+// and the band under test draws one bar.
+vi.mock('../lib/entityTypes.svelte.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ entityFamily: (type) => ({ place: 'place', media: 'collected', person: 'actor' })[type] ?? null,
+}));
+
+const { default: Overview } = await import('./Overview.svelte');
+const { caseState, prefs, uiState, updatesState, resetOverviewFixture } = await import(
+ './overview.fixture.svelte.js'
+);
+
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 12; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open() {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(Overview, { target });
+ flushSync();
+ await settle();
+ return target;
+}
+
+/** The waiting tiles, as `[label, count, pressable]`. */
+const waiting = () =>
+ [...target.querySelectorAll('.tiles .tile')].map((tile) => [
+ tile.querySelector('.say-label').textContent.trim(),
+ tile.querySelector('.n').textContent.trim(),
+ !tile.disabled,
+ ]);
+
+const pressRow = async (label) => {
+ const row = [...target.querySelectorAll('.tile, .row')].find(
+ (candidate) => candidate.querySelector('.say-label')?.textContent.trim() === label
+ );
+ row.click();
+ flushSync();
+ await settle();
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ get.mockImplementation(answers);
+ resetOverviewFixture();
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ target = null;
+ document.body.innerHTML = '';
+});
+
+describe('with a case open', () => {
+ beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Kharkiv strike', updated_at: '2026-09-10T08:00:00Z' };
+ caseState.list = [{ id: 'case-a', name: 'Kharkiv strike', updated_at: '2026-09-11T08:00:00Z' }];
+ });
+
+ it('prices each waiting row off the payload that holds it', async () => {
+ await open();
+ expect(waiting()).toEqual([
+ ['To review', '4', true],
+ ['Nothing linked yet', '7', true],
+ ['Unfiled', '12', true],
+ ['No date yet', '3', true],
+ ]);
+ });
+
+ it('reads the case with five bounded requests and no more', async () => {
+ await open();
+ const asked = get.mock.calls.map(([url]) => url);
+ const paths = asked.filter((url) => url.startsWith('/api/cases/'));
+ expect(paths).toHaveLength(5);
+ // every one of them capped, counting, or the compact index the map panel already
+ // opens on — never a whole-graph read
+ expect(paths.filter((url) => url.includes('limit=')).length).toBe(3);
+ expect(paths.every((url) => url.startsWith('/api/cases/case-a/'))).toBe(true);
+ // and the one read that is not the case's own: which basemap the map of the
+ // case draws, asked once by the map itself
+ expect(asked.filter((url) => !url.startsWith('/api/cases/'))).toEqual([
+ '/api/satellite/providers',
+ ]);
+ });
+
+ it('stops being a control where the answer is nothing', async () => {
+ // a zero is the answer; offering a press that lands on an empty table asks the
+ // analyst to go and confirm what the page already told them
+ get.mockImplementation(async (url) => {
+ if (url.includes('/catalog/summary')) return { ...SUMMARY, by_status: {} };
+ if (url.includes('/timeline')) return { undated: 3 };
+ if (url.includes('since=')) return { items: [], total: 0 };
+ if (url.includes('/catalog/entities')) return { items: [], total: 0, next_cursor: null };
+ return {};
+ });
+ await open();
+ expect(waiting()[0]).toEqual(['To review', '0', false]);
+ expect(waiting()[3]).toEqual(['No date yet', '3', true]);
+ });
+
+ it('says a clear case in one line rather than four zeros', async () => {
+ get.mockImplementation(async (url) => {
+ if (url.includes('/catalog/summary')) {
+ return { ...SUMMARY, total: 18, by_status: {}, by_folder: { work: 18 }, unlinked: 0 };
+ }
+ if (url.includes('/timeline')) return { undated: 0 };
+ if (url.includes('/satellite/index')) return [];
+ return { items: [], total: 0, next_cursor: null };
+ });
+ await open();
+ expect(target.querySelectorAll('.tiles .tile')).toHaveLength(0);
+ // and it says it about the four questions, not about the case: a case is never
+ // finished, so nothing here may read as a case that is
+ expect(target.textContent).toContain('Nothing waiting on these four right now.');
+ });
+
+ it('offers a way in rather than a reading of nothing, on a case holding nothing', async () => {
+ get.mockImplementation(async (url) => {
+ if (url.includes('/catalog/summary')) return { ...SUMMARY, total: 0, by_type: {}, by_status: {}, by_folder: {}, unlinked: 0 };
+ if (url.includes('/timeline')) return { undated: 0 };
+ if (url.includes('/satellite/index')) return [];
+ return { items: [], total: 0, next_cursor: null };
+ });
+ await open();
+ expect(target.querySelector('.tiles')).toBeNull();
+ expect(target.textContent).toContain('Nothing in this case yet');
+ const steps = [...target.querySelectorAll('.step')];
+ expect(steps).toHaveLength(3);
+ steps[0].click();
+ flushSync();
+ expect(uiState.tool).toBe('media');
+ });
+
+ it('draws the case by family in the hues the Graph gives those families', async () => {
+ await open();
+ const bars = [...target.querySelectorAll('.bars li')];
+ expect(bars.map((bar) => bar.querySelector('strong').textContent)).toEqual(['20', '6', '4']);
+ // the widest bar is the biggest family, and every bar carries its family's token
+ expect(bars[0].getAttribute('style')).toContain('--graph-');
+ expect(bars[0].querySelector('.track i').getAttribute('style')).toContain('100%');
+ });
+
+ it('puts the case on a map, and presses through to the tool that works it', async () => {
+ await open();
+ expect(target.querySelector('.area-places .plate')).not.toBeNull();
+ expect(target.textContent).toContain('2 points on the map');
+ target.querySelector('.plate .foot').click();
+ flushSync();
+ expect(uiState.tool).toBe('satellite');
+ });
+
+ it('leaves the map out, and the shoulder filled, when nothing is placed', async () => {
+ get.mockImplementation(async (url) => {
+ if (url.includes('/satellite/index')) return [];
+ return answers(url);
+ });
+ await open();
+ expect(target.querySelector('.plate')).toBeNull();
+ expect(target.querySelector('.grid').classList.contains('flat')).toBe(true);
+ });
+
+ it('shows the case its own pictures where the catalog attached one', async () => {
+ await open();
+ const shot = target.querySelector('.row.thin .glyph img');
+ expect(shot.getAttribute('src')).toBe('/files/case-a/azimut/media/.thumbs/clip.jpg');
+ });
+
+ it('hands the Board the same question the number was read from', async () => {
+ await open();
+ await pressRow('To review');
+ expect(leaveAnalysisView).toHaveBeenCalledWith('case-a', 'board');
+ const [, filter] = setAnalysisFilter.mock.calls.at(-1);
+ expect(filter.status).toBe('suggested');
+ expect(uiState.tool).toBe('board');
+ });
+
+ it('sends the undated row to the Timeline, which is what answers it', async () => {
+ await open();
+ await pressRow('No date yet');
+ expect(setAnalysisFilter).not.toHaveBeenCalled();
+ expect(uiState.tool).toBe('timeline');
+ });
+
+ it('prefers the list stamp, which is recomputed off the database', async () => {
+ await open();
+ // the manifest says 10 September, the list says the 11th
+ expect(target.querySelector('.meta span').title).toContain('2026-09-11');
+ });
+
+ it('opens a recent row in whatever tool owns it', async () => {
+ await open();
+ const row = [...target.querySelectorAll('.row.thin')][0];
+ row.click();
+ flushSync();
+ expect(openEntity).toHaveBeenCalledWith(expect.objectContaining({ id: 'e1' }));
+ });
+});
+
+describe('what the startup checks left on the page', () => {
+ beforeEach(() => {
+ caseState.current = { id: 'case-a', name: 'Kharkiv strike' };
+ });
+
+ it('says nothing at all when both checks came back happy', async () => {
+ await open();
+ expect(target.querySelector('.notice')).toBeNull();
+ expect(target.querySelector('.notice-line')).toBeNull();
+ });
+
+ it('unfolds the release body the check already brought back', async () => {
+ updatesState.app = {
+ update_available: true,
+ latest: 'v0.3.0',
+ url: 'https://example.invalid/releases',
+ notes: '## Fixed\n- a thing that was broken',
+ };
+ await open();
+ const card = target.querySelector('.notice');
+ expect(card.textContent).toContain('Azimut v0.3.0 is available');
+ // folded until asked for: a landing page is not where somebody else's changelog
+ // sits open
+ expect(target.querySelector('.notes')).toBeNull();
+ card.querySelector('.notice-head').click();
+ flushSync();
+ expect(target.querySelector('.notes').textContent).toContain('a thing that was broken');
+ expect(card.querySelector('a').getAttribute('href')).toBe('https://example.invalid/releases');
+ });
+
+ it('never checks anything itself, so a muted release leaves no card', async () => {
+ updatesState.app = { update_available: true, latest: 'v0.3.0', notes: 'x' };
+ prefs.updateDismissedVersion = 'v0.3.0';
+ await open();
+ expect(target.querySelector('.notice')).toBeNull();
+ });
+
+ it('points an uninstalled extension at the tab that installs it', async () => {
+ updatesState.extensionBundled = '0.2.0';
+ updatesState.extensionInstalled = null;
+ await open();
+ const line = target.querySelector('.notice-line');
+ expect(line.textContent).toContain('capture extension is not installed');
+ line.click();
+ flushSync();
+ expect(uiState.tool).toBe('settings');
+ expect(uiState.settingsTab).toBe('extension');
+ });
+
+ it('says nothing about an extension that is already loaded', async () => {
+ updatesState.extensionBundled = '0.2.0';
+ updatesState.extensionInstalled = '0.2.0';
+ await open();
+ expect(target.querySelector('.notice-line')).toBeNull();
+ });
+});
+
+describe('with no case open', () => {
+ it('asks the backend nothing, because there is nothing to summarise', async () => {
+ await open();
+ expect(get).not.toHaveBeenCalled();
+ });
+
+ it('is the front door instead of an empty reading', async () => {
+ await open();
+ expect(target.querySelector('.door')).toBeTruthy();
+ expect(target.querySelectorAll('.stage')).toHaveLength(4); // the rail, as a sequence
+ expect(target.textContent).toContain('Nothing leaves this machine.');
+ });
+
+ it('names the first case from the door itself', async () => {
+ await open();
+ const field = target.querySelector('#home-case-name');
+ field.value = 'Kharkiv strike';
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ const create = [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Create');
+ expect(create.disabled).toBe(false);
+ create.click();
+ await settle();
+ expect(createCase).toHaveBeenCalledWith('Kharkiv strike');
+ });
+
+ it('refuses to create a case with no name', async () => {
+ await open();
+ const create = [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Create');
+ expect(create.disabled).toBe(true);
+ });
+
+ it('offers the cases the workspace already holds', async () => {
+ caseState.list = [
+ { id: 'case-a', name: 'Kharkiv strike', updated_at: '2026-09-01T00:00:00Z' },
+ { id: 'case-b', name: 'Odesa port', updated_at: '2026-08-01T00:00:00Z' },
+ ];
+ await open();
+ const chips = [...target.querySelectorAll('.chip')];
+ expect(chips.map((chip) => chip.querySelector('span').textContent)).toEqual([
+ 'Kharkiv strike',
+ 'Odesa port',
+ ]);
+ chips[1].click();
+ flushSync();
+ expect(openCase).toHaveBeenCalledWith('case-b');
+ });
+});
diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelte
new file mode 100644
index 0000000..3a50791
--- /dev/null
+++ b/frontend/src/tools/Overview.svelte
@@ -0,0 +1,1029 @@
+<script>
+ /**
+ * Where the app opens: what this case is waiting on, what it looks like, and what
+ * was worked on last.
+ *
+ * Two surfaces in one, chosen by whether a case is open. With a case it is a
+ * reading — four outstanding counts as tiles, the case's points on a map, the last
+ * things filed, and the case by family. Without one it is the front door, because a
+ * fresh install lands in an empty workspace and nothing here could be summarised.
+ *
+ * **It asks the case nothing new.** The waiting counts come from the catalog summary
+ * and one timeline page, both of which the Board and the Timeline already read; the
+ * plate comes from the saved index the Satellite panel opens on. Pressing a row hands
+ * the *question* to the surface that answers it rather than the rows it counted, so
+ * the number here and the count there are one predicate asked twice, and no route,
+ * table or migration was added to put a landing page in front of the app.
+ *
+ * Bounded like every other list (docs/STORAGE_AND_PERFORMANCE.md): five small reads
+ * against the **open** case only. Nothing here opens a second case to count it, and
+ * the only thing that reaches the network is the map of the case, which fetches the
+ * free imagery under its points (`overview/PlaceMap.svelte`). The release card is
+ * not an exception: it shows what the startup check already found, and says nothing
+ * when that check is switched off.
+ */
+ import { api } from '../lib/api.js';
+ import {
+ caseState,
+ createCase,
+ openCase,
+ prefs,
+ toast,
+ uiState,
+ updatesState,
+ } from '../lib/state.svelte.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { leaveAnalysisView, setAnalysisFilter } from '../lib/analysisSearch.svelte.js';
+ import { askQuestion, emptyFilter } from '../lib/entityFilter.js';
+ import { exactStamp, timeAgo } from '../lib/analysisViews.js';
+ import { entityFamily, entityLabel, familyTitle } from '../lib/entityTypes.svelte.js';
+ import { entityIcon, entityKindLabel } from '../lib/entityIcon.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { markdownHtml } from '../lib/markdown.js';
+ import { openEntity } from '../lib/navigate.js';
+ import { updateBadges } from '../lib/staleness.js';
+ import {
+ familyBars,
+ lastTouched,
+ mapPins,
+ nothingWaiting,
+ waitingRows,
+ weekAgo,
+ } from '../lib/overview.js';
+ import { WORKSPACES } from '../lib/workspaces.js';
+ import Icon from '../components/Icon.svelte';
+ import Logo from '../components/Logo.svelte';
+ import PlaceMap from './overview/PlaceMap.svelte';
+
+ const RECENT = 6;
+
+ /** What an empty case is offered instead of a reading of nothing. Three presses,
+ * in the order the pipeline runs, because a case with no material in it has no
+ * question to be asked about it yet. */
+ const FIRST_STEPS = [
+ {
+ tool: 'media',
+ icon: 'download',
+ label: 'Bring in media',
+ hint: 'import from your disk, or pull a post from its URL',
+ },
+ {
+ tool: 'files',
+ icon: 'folder',
+ label: 'Drop in documents',
+ hint: 'anything else the case is built from, filed in folders',
+ },
+ {
+ tool: 'satellite',
+ icon: 'satellite',
+ label: 'Capture a map',
+ hint: 'a view saved with its provider, coordinates and zoom',
+ },
+ ];
+
+ let summary = $state(null); // catalog counts, or null until the first read lands
+ let timeline = $state(null); // one timeline page, read for its undated count
+ let recent = $state([]); // the newest rows the case filed
+ let saved = $state([]); // the case's saved points, for the plate
+ let week = $state(0); // how many landed in the last seven days
+ let naming = $state(''); // the first case being named, on the front door
+ let creating = $state(false);
+ let notesOpen = $state(false); // is the release body unfolded
+
+ const rows = $derived(waitingRows({ summary, timeline }));
+ const clear = $derived(Boolean(summary) && nothingWaiting(rows));
+ /** A case that holds nothing is not a case that is up to date. It has no reading,
+ * so it is offered the three ways material gets in instead. */
+ const empty = $derived(Boolean(summary) && Number(summary.total ?? 0) === 0);
+ const bars = $derived(familyBars(summary, entityFamily));
+ const plate = $derived(mapPins(saved));
+ const touched = $derived(lastTouched(caseState.current, caseState.list));
+ const badges = $derived(updateBadges(updatesState, prefs.updateDismissedVersion));
+ const notes = $derived(markdownHtml(updatesState.app?.notes ?? ''));
+ /** Cases other than the one open, newest first — what the front door offers when
+ * the workspace is not actually empty, only unopened. */
+ const others = $derived(caseState.list.filter((entry) => entry.id !== caseState.current?.id));
+
+ /**
+ * The five reads, settled together so one refusal cannot blank the page.
+ *
+ * Guarded on the case it was asked about: opening a second case while these are in
+ * flight must not paint the first one's counts under the second one's name.
+ */
+ async function load(id) {
+ const [counts, dates, newest, lately, points] = await Promise.allSettled([
+ api.get(`/api/cases/${id}/catalog/summary`),
+ api.get(`/api/cases/${id}/timeline?limit=1`),
+ api.get(buildCatalogQuery(id, { limit: RECENT, order: '-created' })),
+ api.get(buildCatalogQuery(id, { limit: 1, since: weekAgo() })),
+ api.get(`/api/cases/${id}/satellite/index`),
+ ]);
+ if (caseState.current?.id !== id) return;
+ if (counts.status === 'fulfilled') summary = counts.value;
+ if (dates.status === 'fulfilled') timeline = dates.value;
+ if (newest.status === 'fulfilled') recent = newest.value?.items ?? [];
+ if (lately.status === 'fulfilled') week = Number(lately.value?.total ?? 0);
+ if (points.status === 'fulfilled') saved = Array.isArray(points.value) ? points.value : [];
+ }
+
+ // Re-read when the case changes, when a write reloads it, and when the analyst
+ // comes back to this tab. A summary surface that answers with what was true when it
+ // was last looked at is worse than no summary: the counts are the whole point.
+ $effect(() => {
+ const id = caseState.current?.id;
+ const looking = uiState.tool === 'overview';
+ void caseState.rev;
+ if (!id) {
+ summary = null;
+ timeline = null;
+ recent = [];
+ saved = [];
+ week = 0;
+ return;
+ }
+ if (looking) void load(id);
+ });
+
+ /**
+ * Put one of the Board's standing questions on the Board, and go there.
+ *
+ * It travels through the slot Board and Graph already share, so the table lands on
+ * exactly the rows this page counted. The named reading is left first: the question
+ * came from here rather than from a saved view, and writing it into one would
+ * quietly edit somebody else's view.
+ */
+ function askBoard(question) {
+ const id = caseState.current?.id;
+ leaveAnalysisView(id, 'board');
+ setAnalysisFilter(id, askQuestion(emptyFilter(), question));
+ uiState.tool = 'board';
+ }
+
+ /** Hand a waiting row to whichever surface answers it. */
+ function ask(row) {
+ if (row.surface === 'timeline') {
+ uiState.tool = 'timeline';
+ return;
+ }
+ askBoard(row.id);
+ }
+
+ function openSettings(tab = 'system') {
+ uiState.settingsTab = tab;
+ uiState.tool = 'settings';
+ }
+
+ /** The thumbnail the catalog attached to a row, or nothing. Data URLs come back
+ * whole; everything else is a case-relative path served by the file route. */
+ function thumbSrc(item) {
+ const thumb = item?.thumb;
+ if (!thumb || !caseState.current) return '';
+ return thumb.startsWith('data:') ? thumb : fileUrl(caseState.current.id, thumb);
+ }
+
+ async function create() {
+ const name = naming.trim();
+ if (!name || creating) return;
+ creating = true;
+ try {
+ await createCase(name);
+ naming = '';
+ } catch (error) {
+ toast(error.message, 'warn', 5000);
+ } finally {
+ creating = false;
+ }
+ }
+</script>
+
+<div class="tool home">
+ <div class="tool-body">
+ <div class="sheet" class:centred={!caseState.current}>
+ {#if caseState.current}
+ <header class="head">
+ <div class="who">
+ <h1>{caseState.current.name}</h1>
+ <p class="meta">
+ {#if touched}<span title={exactStamp(touched)}>Updated {timeAgo(touched)}</span>{/if}
+ {#if summary}<span>{summary.total} entities</span>{/if}
+ {#if caseState.current.scratch}<span class="scratch">Scratch session</span>{/if}
+ </p>
+ </div>
+ <button class="btn" onclick={() => (uiState.tool = 'board')}>
+ Open the board
+ <Icon name="arrowRight" size={14} />
+ </button>
+ </header>
+
+ {#if badges.app}
+ <!-- What the startup check already found, said once. It never checks
+ anything itself, so with the release check off this never appears, and
+ the body it unfolds came back with that same answer. -->
+ <div class="notice">
+ <button class="notice-head" onclick={() => (notesOpen = !notesOpen)}>
+ <Icon name="download" size={14} />
+ <span>Azimut {updatesState.app?.latest} is available</span>
+ {#if updatesState.app?.notes}
+ <em>{notesOpen ? 'Hide notes' : "What's new"}</em>
+ <Icon name={notesOpen ? 'chevronUp' : 'chevronDown'} size={13} />
+ {/if}
+ </button>
+ {#if notesOpen && updatesState.app?.notes}
+ <!-- Our own release body, through the renderer the Notebook uses, which
+ strips unsafe HTML. -->
+ <div class="notes markdown">{@html notes}</div>
+ {/if}
+ <div class="notice-foot">
+ <a class="btn btn-sm btn-primary" href={updatesState.app?.url} target="_blank" rel="noreferrer">
+ <Icon name="download" size={13} /> Download
+ <Icon name="external" size={11} />
+ </a>
+ <button class="btn btn-ghost btn-sm" onclick={() => openSettings('system')}>
+ Settings
+ </button>
+ </div>
+ </div>
+ {/if}
+
+ {#if badges.extensionMissing}
+ <button class="notice-line" onclick={() => openSettings('extension')}>
+ <Icon name="crop" size={14} />
+ <span>The capture extension is not installed. It files the map you are looking at, in any tab, straight into this case.</span>
+ <em>Install</em>
+ </button>
+ {/if}
+
+ {#if empty}
+ <section>
+ <h2 class="label">Nothing in this case yet</h2>
+ <ul class="steps">
+ {#each FIRST_STEPS as step (step.tool)}
+ <li>
+ <button class="step" onclick={() => (uiState.tool = step.tool)}>
+ <span class="step-mark"><Icon name={step.icon} size={19} /></span>
+ <strong>{step.label}</strong>
+ <span class="step-hint">{step.hint}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ </section>
+ {:else}
+ <div class="grid" class:flat={!plate.pins.length}>
+ <section class="area-waiting">
+ <h2 class="label">What is waiting</h2>
+ {#if !summary}
+ <p class="quiet-line">Reading the case…</p>
+ {:else if clear}
+ <p class="quiet-line">Nothing waiting on these four right now.</p>
+ {:else}
+ <ul class="tiles">
+ {#each rows as row (row.id)}
+ <li>
+ <button
+ class="tile"
+ class:none={row.count === 0}
+ disabled={row.count === 0}
+ title={row.count === 0 ? 'Nothing here' : row.hint}
+ onclick={() => ask(row)}
+ >
+ <span class="tile-mark"><Icon name={row.icon} size={15} /></span>
+ <span class="n">{row.count}</span>
+ <span class="say-label">{row.label}</span>
+ <span class="say-hint">{row.hint}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </section>
+
+ {#if plate.pins.length}
+ <section class="area-places">
+ <h2 class="label">On the ground</h2>
+ <PlaceMap
+ pins={plate.pins}
+ total={plate.total}
+ imperial={prefs.units === 'imperial'}
+ onopen={() => (uiState.tool = 'satellite')}
+ />
+ </section>
+ {/if}
+
+ {#if recent.length}
+ <section class="area-recent">
+ <h2 class="label">
+ <span>Recent work</span>
+ {#if week}
+ <button class="aside" onclick={() => askBoard('week')}>
+ {week} added this week
+ </button>
+ {/if}
+ </h2>
+ <ul class="rows">
+ {#each recent as item (item.id)}
+ {@const src = thumbSrc(item)}
+ <li>
+ <button class="row thin" onclick={() => openEntity(item)}>
+ <span class="glyph" class:shot={Boolean(src)}>
+ {#if src}
+ <img src={src} alt="" loading="lazy" />
+ {:else}
+ <Icon name={entityIcon(item)} size={15} />
+ {/if}
+ </span>
+ <span class="say">
+ <span class="say-label">{item.label}</span>
+ <span class="say-hint">{entityKindLabel(item, entityLabel(item.type))}</span>
+ </span>
+ <span class="when" title={exactStamp(item.provenance?.at)}>
+ {timeAgo(item.provenance?.at)}
+ </span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ </section>
+ {/if}
+
+ {#if bars.length}
+ <section class="area-figures">
+ <h2 class="label">In the case</h2>
+ <ul class="bars">
+ {#each bars as entry (entry.family)}
+ <li style="--tint: var(--graph-{entry.family}, var(--text-3))">
+ <span class="bar-label">{familyTitle(entry.family)}</span>
+ <span class="track"><i style="width: {Math.max(entry.share * 100, 2)}%"></i></span>
+ <strong>{entry.count}</strong>
+ </li>
+ {/each}
+ </ul>
+ </section>
+ {/if}
+ </div>
+ {/if}
+
+ <footer class="foot">
+ <button class="aside" onclick={() => (uiState.tool = 'guide')}>
+ New here? Read the guide
+ <Icon name="arrowRight" size={13} />
+ </button>
+ </footer>
+ {:else}
+ <!-- The front door. A fresh install lands here, with no case to summarise and
+ nothing on screen that says what any of the rail means. -->
+ <div class="door">
+ <Logo size={52} />
+ <h1>Azimut</h1>
+ <p class="pitch">
+ A local OSINT workspace. Source media, geolocation work, proofs and notes live
+ in one case folder you can copy anywhere.
+ </p>
+
+ <ol class="pipeline">
+ {#each WORKSPACES as ws, i (ws.id)}
+ {#if i > 0}<li class="arrow" aria-hidden="true"><Icon name="chevronRight" size={13} /></li>{/if}
+ <li class="stage">
+ <Icon name={ws.icon} size={17} />
+ <span>{ws.label}</span>
+ </li>
+ {/each}
+ </ol>
+
+ <div class="start">
+ <label class="label" for="home-case-name">Name your first case</label>
+ <div class="start-row">
+ <input
+ id="home-case-name"
+ class="input"
+ bind:value={naming}
+ placeholder="Kharkiv strike, 12 March"
+ onkeydown={(e) => e.key === 'Enter' && create()}
+ />
+ <button class="btn btn-primary" disabled={!naming.trim() || creating} onclick={create}>
+ Create
+ </button>
+ </div>
+ </div>
+
+ {#if others.length}
+ <div class="reopen">
+ <span class="label">Or open one you have</span>
+ <ul>
+ {#each others.slice(0, 5) as entry (entry.id)}
+ <li>
+ <button class="chip" onclick={() => openCase(entry.id)}>
+ <span>{entry.name}</span>
+ {#if entry.updated_at}<em>{timeAgo(entry.updated_at)}</em>{/if}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ </div>
+ {/if}
+
+ <div class="door-foot">
+ <button class="btn btn-ghost btn-sm" onclick={() => (uiState.tool = 'guide')}>
+ Read the guide
+ <Icon name="arrowRight" size={13} />
+ </button>
+ <span class="door-note">Nothing leaves this machine.</span>
+ </div>
+ </div>
+ {/if}
+ </div>
+ </div>
+</div>
+
+<style>
+ /* Wider than a reading column and narrower than the tools: this page is scanned
+ rather than read, and four counts hung in a 760px ribbon on a 27-inch screen is
+ the emptiest an app can look. The front door keeps the narrow measure. */
+ .sheet {
+ max-width: 1180px;
+ margin: 0 auto;
+ padding: 40px 28px 56px;
+ }
+ /* The front door is the whole page rather than its first band, so it is centred
+ in the window instead of hanging from the top of it. */
+ .sheet.centred {
+ display: flex;
+ flex-direction: column;
+ min-height: 100%;
+ max-width: 820px;
+ }
+
+ .head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 20px;
+ padding-bottom: 30px;
+ }
+ .head h1 {
+ font-size: var(--fs-xl);
+ font-weight: 600;
+ letter-spacing: -0.015em;
+ line-height: 1.2;
+ }
+ .meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ margin-top: 5px;
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+ /* middots between the facts, drawn rather than typed so no fact has to carry one */
+ .meta span + span::before {
+ content: '·';
+ margin-right: 10px;
+ }
+ .meta .scratch {
+ color: var(--warn);
+ }
+
+ /* ---- the two notices ------------------------------------------------------ */
+
+ .notice {
+ margin-bottom: 16px;
+ border: 1px solid var(--border);
+ border-left: 2px solid var(--accent);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ overflow: hidden;
+ }
+ .notice-head {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ width: 100%;
+ padding: 10px 12px;
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ text-align: left;
+ transition: background 0.15s var(--ease);
+ }
+ .notice-head:hover {
+ background: var(--bg-2);
+ }
+ .notice-head em {
+ margin-left: auto;
+ color: var(--accent);
+ font-style: normal;
+ font-weight: 600;
+ font-size: var(--fs-xs);
+ }
+ /* Capped, because a release body is somebody else's document and this is a corner
+ of a landing page: past a screenful the place to read it is the release page. */
+ .notes {
+ max-height: 260px;
+ overflow: auto;
+ padding: 4px 14px 12px;
+ border-top: 1px solid var(--border);
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ }
+ .notes :global(h1),
+ .notes :global(h2),
+ .notes :global(h3) {
+ margin: 14px 0 6px;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .notes :global(ul) {
+ margin: 0;
+ padding-left: 18px;
+ }
+ .notes :global(li) {
+ margin: 3px 0;
+ }
+ .notice-foot {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ border-top: 1px solid var(--border);
+ }
+
+ /* The extension, said in one line. It disappears the moment one is installed, so
+ it is a setup step rather than a standing message. */
+ .notice-line {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ width: 100%;
+ margin-bottom: 16px;
+ padding: 9px 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ text-align: left;
+ transition: background 0.15s var(--ease), color 0.15s var(--ease);
+ }
+ .notice-line:hover {
+ background: var(--bg-2);
+ color: var(--text-2);
+ }
+ .notice-line em {
+ margin-left: auto;
+ flex-shrink: 0;
+ color: var(--accent);
+ font-style: normal;
+ font-weight: 600;
+ font-size: var(--fs-xs);
+ }
+
+ /* ---- the reading ---------------------------------------------------------- */
+
+ .grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1.05fr) minmax(0, 0.95fr);
+ grid-template-areas:
+ 'waiting places'
+ 'recent figures';
+ gap: 30px 40px;
+ align-items: start;
+ padding-top: 4px;
+ }
+ /* With no point saved there is no plate, and the figures take the shoulder rather
+ than leaving a hole where the map would have been. */
+ .grid.flat {
+ grid-template-areas:
+ 'waiting figures'
+ 'recent recent';
+ }
+ .area-waiting {
+ grid-area: waiting;
+ }
+ .area-places {
+ grid-area: places;
+ }
+ .area-recent {
+ grid-area: recent;
+ }
+ .area-figures {
+ grid-area: figures;
+ }
+ @media (max-width: 980px) {
+ .grid,
+ .grid.flat {
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-areas: 'waiting' 'places' 'recent' 'figures';
+ gap: 30px;
+ }
+ }
+
+ .label {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 10px;
+ }
+
+ /* Four counts as tiles rather than four lines: this is the band somebody opens the
+ app to read, and a number is read at a glance or it is not read. */
+ .tiles {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 10px;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ }
+ .tile {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: start;
+ gap: 0 8px;
+ width: 100%;
+ height: 100%;
+ padding: 13px 14px 14px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ text-align: left;
+ transition: background 0.14s var(--ease), border-color 0.14s var(--ease);
+ }
+ .tile:not(:disabled):hover,
+ .tile:focus-visible {
+ background: var(--bg-2);
+ border-color: var(--accent);
+ outline: none;
+ }
+ .tile-mark {
+ grid-column: 2;
+ grid-row: 1;
+ display: flex;
+ color: var(--text-3);
+ }
+ .tile .n {
+ grid-column: 1;
+ grid-row: 1;
+ font-size: 1.75rem;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.03em;
+ line-height: 1.1;
+ color: var(--text-1);
+ }
+ .tile .say-label {
+ grid-column: 1 / -1;
+ margin-top: 6px;
+ }
+ /* A tile is not a row: the hint has the width to be read, so it wraps to a second
+ line rather than being cut off mid-clause. */
+ .tile .say-hint {
+ grid-column: 1 / -1;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ white-space: normal;
+ line-height: 1.45;
+ }
+ /* A count of nothing is the answer, so the tile states it and stops being a control
+ rather than offering a press that lands on an empty table. */
+ .tile.none {
+ cursor: default;
+ background: transparent;
+ }
+ .tile.none .n,
+ .tile.none .say-label {
+ color: var(--text-3);
+ font-weight: 500;
+ }
+ .tile.none .say-hint {
+ opacity: 0.65;
+ }
+
+ .rows {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ }
+
+ /* Flat rows with a hairline between them, not cards. The active mark is the amber
+ edge bar the rail already uses for "you are here", so the app has one way of
+ saying a row is under the pointer. */
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ padding: 9px 10px 9px 8px;
+ border-bottom: 1px solid var(--border);
+ border-left: 2px solid transparent;
+ text-align: left;
+ transition: background 0.14s var(--ease), border-color 0.14s var(--ease);
+ }
+ .rows li:last-child .row {
+ border-bottom-color: transparent;
+ }
+ .row:not(:disabled):hover {
+ background: var(--bg-1);
+ border-left-color: var(--accent);
+ }
+ .row:focus-visible {
+ outline: none;
+ background: var(--bg-1);
+ border-left-color: var(--accent);
+ }
+
+ .say {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-width: 0;
+ flex: 1;
+ }
+ .say-label {
+ font-size: var(--fs-md);
+ font-weight: 500;
+ color: var(--text-1);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .say-hint {
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .row .say-label {
+ font-size: var(--fs-sm);
+ }
+ .row .say-hint {
+ font-size: var(--fs-xs);
+ }
+
+ /* The case's own pictures, where it has them: a list of six filenames says far less
+ about an afternoon's work than six frames of it. */
+ .glyph {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ width: 34px;
+ height: 26px;
+ color: var(--text-3);
+ }
+ .glyph.shot {
+ border-radius: var(--r-sm);
+ overflow: hidden;
+ background: var(--bg-2);
+ }
+ .glyph img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .row.thin:hover .glyph {
+ color: var(--text-2);
+ }
+ .when {
+ flex-shrink: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ font-variant-numeric: tabular-nums;
+ }
+
+ .quiet-line {
+ padding: 12px 8px;
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ }
+
+ /* The case by family, in the hues the Graph gives those same eight families. One
+ reading of one case cannot be two palettes. */
+ .bars {
+ list-style: none;
+ margin: 0;
+ padding: 12px 14px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ }
+ .bars li {
+ display: grid;
+ grid-template-columns: minmax(0, 5.5rem) minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 10px;
+ }
+ .bars li + li {
+ margin-top: 9px;
+ }
+ .bar-label {
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .track {
+ display: block;
+ height: 6px;
+ border-radius: 3px;
+ background: var(--bg-2);
+ overflow: hidden;
+ }
+ .track i {
+ display: block;
+ height: 100%;
+ border-radius: 3px;
+ background: var(--tint);
+ opacity: 0.85;
+ }
+ .bars strong {
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ color: var(--text-1);
+ }
+
+ /* ---- a case with nothing in it -------------------------------------------- */
+
+ .steps {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 12px;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ }
+ .step {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 3px;
+ width: 100%;
+ height: 100%;
+ padding: 18px 16px 17px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ text-align: left;
+ transition: background 0.14s var(--ease), border-color 0.14s var(--ease);
+ }
+ .step:hover,
+ .step:focus-visible {
+ background: var(--bg-2);
+ border-color: var(--accent);
+ outline: none;
+ }
+ .step-mark {
+ display: flex;
+ margin-bottom: 9px;
+ color: var(--accent);
+ }
+ .step strong {
+ font-size: var(--fs-md);
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .step-hint {
+ font-size: var(--fs-sm);
+ color: var(--text-3);
+ line-height: 1.5;
+ }
+
+ /* A quiet secondary act: the guide link, and the count beside a heading. */
+ .aside {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: var(--fs-xs);
+ font-weight: 500;
+ color: var(--text-3);
+ transition: color 0.14s var(--ease);
+ }
+ .aside:hover {
+ color: var(--accent);
+ }
+ .foot {
+ margin-top: 36px;
+ padding-top: 16px;
+ border-top: 1px solid var(--border);
+ }
+
+ /* ---- the front door ------------------------------------------------------ */
+
+ .door {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ flex: 1;
+ text-align: center;
+ }
+ .door h1 {
+ margin-top: 16px;
+ font-size: var(--fs-xl);
+ font-weight: 600;
+ letter-spacing: -0.015em;
+ }
+ .pitch {
+ max-width: 460px;
+ margin-top: 8px;
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ line-height: 1.6;
+ }
+
+ /* The rail, before anyone has used it. It is a sequence and reads as one. */
+ .pipeline {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ list-style: none;
+ margin: 30px 0 34px;
+ padding: 0;
+ }
+ .stage {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 7px 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ font-size: var(--fs-sm);
+ font-weight: 500;
+ color: var(--text-2);
+ }
+ .arrow {
+ display: flex;
+ color: var(--text-3);
+ opacity: 0.7;
+ }
+
+ .start {
+ width: min(420px, 100%);
+ text-align: left;
+ }
+ .start-row {
+ display: flex;
+ gap: 8px;
+ }
+ .start-row .input {
+ flex: 1;
+ }
+
+ .reopen {
+ margin-top: 28px;
+ width: min(520px, 100%);
+ }
+ .reopen .label {
+ justify-content: center;
+ }
+ .reopen ul {
+ display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ gap: 6px;
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ }
+ .chip {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 7px;
+ padding: 5px 11px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ transition: background 0.14s var(--ease), border-color 0.14s var(--ease);
+ }
+ .chip:hover {
+ background: var(--bg-2);
+ border-color: var(--border-strong);
+ }
+ .chip em {
+ font-style: normal;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+
+ .door-foot {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ margin-top: 40px;
+ }
+ .door-note {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelte
index 4598fb9..da8eec3 100644
--- a/frontend/src/tools/ReverseSearch.svelte
+++ b/frontend/src/tools/ReverseSearch.svelte
@@ -4,6 +4,11 @@
// preps the image (clipboard for paste engines, a saved file for drag ones)
// and each button is a plain link to the engine's page.
//
+ // With the capture extension installed and the switch in Settings on, a button
+ // instead opens the engine with the image already in its uploader, and the
+ // engine searches. That is a press of the same button, and the clipboard road
+ // is still what every refusal falls back to.
+ //
// Pick a case photo, or scrub a case video to a frame. Adjustments
// (brightness, contrast, …) preview live and are baked into the exported
// image via a same-origin canvas — nothing leaves the machine until an
@@ -11,8 +16,9 @@
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { matchesTerms } from '../lib/folderBrowse.js';
- import { caseState, uiState, toast } from '../lib/state.svelte.js';
- import { UPLOAD_PAGES } from '../lib/reverseSearch.js';
+ import { caseState, prefs, uiState, toast } from '../lib/state.svelte.js';
+ import { extensionVersion, handOffReverse } from '../lib/extBridge.js';
+ import { MAX_HANDOFF_BYTES, UPLOAD_PAGES } from '../lib/reverseSearch.js';
import Modal from '../components/Modal.svelte';
import Icon from '../components/Icon.svelte';
import SearchInput from '../components/SearchInput.svelte';
@@ -20,6 +26,10 @@
const PASTE = UPLOAD_PAGES.filter((e) => e.paste);
const DRAG = UPLOAD_PAGES.filter((e) => !e.paste);
+ // The marker the extension stamps on <html> at document_start. Read once:
+ // installing it with the app already open needs a tab reload either way, and
+ // Settings is where that is said.
+ const extInstalled = extensionVersion();
const MEDIA_FILTERS = [
{ id: 'all', label: 'All' },
{ id: 'image', label: 'Images' },
@@ -71,6 +81,15 @@
const srcOf = (item) => fileUrl(caseState.current.id, item.path);
const nameOf = (item) => (item.label || item.path).replace(/^media\//, '');
const frameLabel = $derived(selected?.kind === 'video' ? 'frame' : 'image');
+ const downloadName = () =>
+ `reverse-${nameOf(selected).replace(/^.*\//, '').replace(/\.[^.]+$/, '')}.png`;
+
+ // Which engines this press can be handed to, and which are left on the two
+ // gestures. An engine the extension cannot fill keeps its old group, so the
+ // headings never promise more than the buttons under them do.
+ const filled = $derived(prefs.reversePrefill && extInstalled ? UPLOAD_PAGES.filter((e) => e.fill) : []);
+ const pasteLeft = $derived(PASTE.filter((e) => !filled.includes(e)));
+ const dragLeft = $derived(DRAG.filter((e) => !filled.includes(e)));
// -- picker -----------------------------------------------------------------
async function openPicker() {
@@ -192,30 +211,106 @@
}
// -- hand-off (buttons are real links, so nothing is popup-blocked) ---------
- async function copySelection() {
+ //
+ // Which road a press takes is decided **before** anything is awaited: the
+ // button is a real link, and a preventDefault that comes back after a promise
+ // comes back too late to stop it.
+
+ /** Put the PNG on the clipboard. `note` is the toast when it lands; a refusal
+ * is always reported, since both roads lean on the clipboard. */
+ async function copyPng(pending, note) {
try {
- await navigator.clipboard.write([new ClipboardItem({ 'image/png': pngBlob() })]);
- toast(`Copied the ${frameLabel}. Paste it in the tab with Ctrl+V`, 'ok', 4500);
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': pending })]);
+ if (note) toast(note, 'ok', 4500);
+ return true;
} catch (e) {
toast(e.message || 'Could not copy the image', 'warn');
+ return false;
}
}
+ function savePng(blob, note) {
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = downloadName();
+ a.click();
+ URL.revokeObjectURL(a.href);
+ toast(note, 'ok', 4500);
+ }
+
+ async function copySelection() {
+ await copyPng(pngBlob(), `Copied the ${frameLabel}. Paste it in the tab with Ctrl+V`);
+ }
+
async function saveSelection() {
try {
- const blob = await pngBlob();
- const base = nameOf(selected).replace(/^.*\//, '').replace(/\.[^.]+$/, '');
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = `reverse-${base}.png`;
- a.click();
- URL.revokeObjectURL(a.href);
- toast(`Saved the ${frameLabel}. Drag it into the tab`, 'ok', 4500);
+ savePng(await pngBlob(), `Saved the ${frameLabel}. Drag it into the tab`);
} catch (e) {
toast(e.message || 'Could not save the image', 'warn');
}
}
+ /** Base64 of a blob: a message carries no blob, so the bytes cross as a string
+ * and the extension rebuilds the file inside the engine's page. */
+ async function base64(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 btoa(binary);
+ }
+
+ /**
+ * Press an engine the extension can fill.
+ *
+ * The link was stopped, so the tab is the extension's to open and every
+ * refusal has to open it here instead. The image goes on the clipboard first,
+ * while this tab still has focus: it is what the extension's own notice
+ * promises if the engine's page has moved on, and the encode is shared with
+ * the hand-off rather than run a second time.
+ */
+ async function fillEngine(engine) {
+ let blob;
+ const pending = pngBlob();
+ copyPng(pending);
+ try {
+ blob = await pending;
+ } catch (e) {
+ toast(e.message || 'Could not read the image', 'warn');
+ return;
+ }
+ if (blob.size <= MAX_HANDOFF_BYTES) {
+ try {
+ await handOffReverse({
+ url: engine.url,
+ image: { name: downloadName(), type: 'image/png', data: await base64(blob) },
+ });
+ toast(`${engine.label} is opening with the ${frameLabel}.`, 'info', 4200);
+ return;
+ } catch {
+ // Absent, switched off mid-press, not permitted on that site, silent:
+ // one answer, one fallback. Nothing to explain that the toast below
+ // does not say by doing the old thing.
+ }
+ }
+ window.open(engine.url, '_blank', 'noopener,noreferrer');
+ if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with Ctrl+V`, 'info', 4500);
+ else savePng(blob, `Opened ${engine.label}. Drag the saved ${frameLabel} in`);
+ }
+
+ /** The engine buttons' one handler. */
+ function pressEngine(event, engine) {
+ if (!filled.includes(engine)) {
+ if (engine.paste) copySelection();
+ else saveSelection();
+ return;
+ }
+ event.preventDefault();
+ fillEngine(engine);
+ }
+
function openInInspect() {
uiState.inspectPath = selected.path;
uiState.tool = 'inspect';
@@ -232,7 +327,13 @@
<div class="tool">
<div class="tool-header">
<h2>Reverse Search</h2>
- {#if selected}<span class="sub">Copy or save the {frameLabel}, then hand it to an engine</span>{/if}
+ {#if selected}
+ <span class="sub">
+ {filled.length
+ ? `Send the ${frameLabel} to an engine`
+ : `Copy or save the ${frameLabel}, then hand it to an engine`}
+ </span>
+ {/if}
</div>
<div class="tool-body">
@@ -318,26 +419,60 @@
</div>
<div class="engines">
- <div class="eg-group">
- <span class="eg-head">Copy, then paste (Ctrl+V) in the tab</span>
- <div class="eg-list">
- {#each PASTE as e (e.id)}
- <a href={e.url} target="_blank" rel="noreferrer" class="btn engine-btn" onclick={copySelection}>
- <Icon name="copy" size={14} /> {e.label}
- </a>
- {/each}
+ {#if filled.length}
+ <div class="eg-group">
+ <span class="eg-head">Opens with the {frameLabel} in it</span>
+ <div class="eg-list">
+ {#each filled as e (e.id)}
+ <a
+ href={e.url}
+ target="_blank"
+ rel="noreferrer"
+ class="btn engine-btn"
+ onclick={(event) => pressEngine(event, e)}
+ >
+ <Icon name="search" size={14} /> {e.label}
+ </a>
+ {/each}
+ </div>
</div>
- </div>
- <div class="eg-group">
- <span class="eg-head">Save, then drag the file into the tab</span>
- <div class="eg-list">
- {#each DRAG as e (e.id)}
- <a href={e.url} target="_blank" rel="noreferrer" class="btn engine-btn" onclick={saveSelection}>
- <Icon name="download" size={14} /> {e.label}
- </a>
- {/each}
+ {/if}
+ {#if pasteLeft.length}
+ <div class="eg-group">
+ <span class="eg-head">Copy, then paste (Ctrl+V) in the tab</span>
+ <div class="eg-list">
+ {#each pasteLeft as e (e.id)}
+ <a
+ href={e.url}
+ target="_blank"
+ rel="noreferrer"
+ class="btn engine-btn"
+ onclick={(event) => pressEngine(event, e)}
+ >
+ <Icon name="copy" size={14} /> {e.label}
+ </a>
+ {/each}
+ </div>
</div>
- </div>
+ {/if}
+ {#if dragLeft.length}
+ <div class="eg-group">
+ <span class="eg-head">Save, then drag the file into the tab</span>
+ <div class="eg-list">
+ {#each dragLeft as e (e.id)}
+ <a
+ href={e.url}
+ target="_blank"
+ rel="noreferrer"
+ class="btn engine-btn"
+ onclick={(event) => pressEngine(event, e)}
+ >
+ <Icon name="download" size={14} /> {e.label}
+ </a>
+ {/each}
+ </div>
+ </div>
+ {/if}
</div>
{#if selected.kind === 'video'}
diff --git a/frontend/src/tools/ReverseSearch.test.js b/frontend/src/tools/ReverseSearch.test.js
index a9c38d9..ca9cd01 100644
--- a/frontend/src/tools/ReverseSearch.test.js
+++ b/frontend/src/tools/ReverseSearch.test.js
@@ -26,6 +26,42 @@ describe('Reverse Search case picker', () => {
expect(source).toContain("source.op === 'collage'");
});
+ it('decides the road before it awaits, since the button is a real link', () => {
+ // A preventDefault that comes back after a promise comes back too late: the
+ // tab would already be opening, and the extension would open a second one.
+ expect(source).toContain('function pressEngine(event, engine)');
+ expect(source).toContain('if (!filled.includes(engine))');
+ expect(source).toContain('event.preventDefault();');
+ expect(source).toContain('fillEngine(engine);');
+ });
+
+ it('hands the image over only with the extension there and the switch on', () => {
+ expect(source).toContain(
+ "const filled = $derived(prefs.reversePrefill && extInstalled ? UPLOAD_PAGES.filter((e) => e.fill) : []);"
+ );
+ expect(source).toContain('const extInstalled = extensionVersion();');
+ // An engine the extension cannot fill keeps its old group, so a heading
+ // never promises more than the buttons under it do.
+ expect(source).toContain('const pasteLeft = $derived(PASTE.filter((e) => !filled.includes(e)));');
+ expect(source).toContain('const dragLeft = $derived(DRAG.filter((e) => !filled.includes(e)));');
+ });
+
+ it('falls back to the two gestures whenever the hand-off is refused', () => {
+ // Absent, switched off, silent, or an image too big to carry: one answer,
+ // one fallback, and it is the road that always worked.
+ expect(source).toContain('blob.size <= MAX_HANDOFF_BYTES');
+ expect(source).toContain("window.open(engine.url, '_blank', 'noopener,noreferrer');");
+ expect(source).toContain('if (engine.paste) toast(`Opened ${engine.label}. Paste the ${frameLabel} with Ctrl+V`');
+ expect(source).toContain('else savePng(blob, `Opened ${engine.label}. Drag the saved ${frameLabel} in`);');
+ });
+
+ it('copies the image once, while this tab still has the focus to do it', () => {
+ // The extension's own notice says the image is on the clipboard, so it has
+ // to be — and the encode is shared with the hand-off rather than run twice.
+ expect(source).toContain('const pending = pngBlob();\n copyPng(pending);');
+ expect(source).toContain('blob = await pending;');
+ });
+
it('offers the same read-only folder browser as Inspect', () => {
expect(source).toContain("import FolderBrowser from '../components/FolderBrowser.svelte'");
expect(source).toContain('title="Browse folders"');
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 0cd72a0..dae5dc3 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1,13 +1,23 @@
<script>
import { onMount, tick } from 'svelte';
- import { fileUrl } from '../lib/fileUrl.js';
// 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';
+ // drag gestures. Nothing in this file knows which engine that is — and the
+ // map itself is a surface (satellite/MapSurface.svelte), which is what lets a
+ // second one be mounted beside this one.
import { createSurface } from '../lib/map/surface.js';
+ import MapSurface from './satellite/MapSurface.svelte';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
import { createSavedState } from './satellite/state/saved.svelte.js';
+ import { createImageryState, FALLBACK_PROVIDER } from './satellite/state/imagery.svelte.js';
+ import { createMeasureState, HINTS as MEASURE_HINT } from './satellite/state/measure.svelte.js';
+ import { createSkyState } from './satellite/state/sky.svelte.js';
+ import { createGridState } from './satellite/state/grid.svelte.js';
+ import { createRefsState } from './satellite/state/refs.svelte.js';
+ import {
+ createCaptureState,
+ PRESETS,
+ RATIOS,
+ } from './satellite/state/capture.svelte.js';
import { api } from '../lib/api.js';
import { setAnalysisPeriod } from '../lib/analysisSearch.svelte.js';
import { temporalMapQuery } from '../lib/temporalMap.js';
@@ -17,63 +27,24 @@
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
import { mapLinks } from '../lib/maplinks.js';
- import * as measure from '../lib/measure.js';
import { markerGeometry, markerSvg } from '../lib/mapMarkers.js';
- import {
- bodyReading,
- bodySvg,
- hourTicks,
- isBelow,
- markScale,
- nearestSample,
- upRuns,
- } from '../lib/skyOverlay.js';
- import * as gridSearch from '../lib/gridSearch.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';
import { assignFolder } from '../lib/filing.js';
import { saveRelation } from '../lib/relations.svelte.js';
import { openEntity } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
- import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';
- import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';
- import {
- monthCount,
- tilesShort,
- usageBlocked,
- displayProviderId,
- layerCell,
- } from '../lib/usage.js';
+ import { extensionVersion, onActivated } from '../lib/extBridge.js';
import {
SENTINEL_ID,
- DEFAULT_LAYER,
- DEFAULT_MAXCC,
- variantId,
- validDay,
- validMaxcc,
maxccLabel,
- overCloudCeiling,
- latestAllowedPass,
cloudLabel,
cloudClass,
- isoDay,
- monthOf,
monthLabel,
- monthBounds,
monthGrid,
- addMonths,
- sentinelPlaceKey,
- coverageRequestPath,
- dateAfterCoverage,
} from '../lib/sentinel.js';
- import { createViewer, nextZ, restack } from '../lib/refViewers.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 RefViewer from './RefViewer.svelte';
import MapToolCluster from './satellite/MapToolCluster.svelte';
@@ -92,17 +63,22 @@
import SheetPointsOverlay from './satellite/SheetPointsOverlay.svelte';
import TemporalMapOverlay from './satellite/TemporalMapOverlay.svelte';
- let mapEl;
let toolEl; // Browser fullscreen target.
- // The map, through lib/map's façade: no engine type reaches this file's
- // camera, projection or event code.
+ // The map surface: it owns the engine, the basemap and everything that
+ // describes the pixels, and hands back the façade and its own container for
+ // the acts this tool owns — flying to a saved point, and the drag gestures it
+ // arms over the map.
+ let surface = $state(null);
+ let mapEl = $state(null);
let engine = $state.raw(null);
- let basemaps = null; // lib/map/basemap.js: the imagery layer and the labels over it
- let providers = $state([]);
- let providerId = $state('esri-world-imagery');
+ // The catalogue and the month's tally are the tool's, not one map's: a tile
+ // counted against the month is counted once however many surfaces drew it.
+ const imagery = createImageryState({ api });
+ let providerId = $state(FALLBACK_PROVIDER);
let coordsText = $state('');
- // Start at the saved home view unless case navigation supplies a position.
- // Re-read after preferences load because deep links can mount first.
+ // The map opens on the saved home view, so it is not built until preferences
+ // have landed — a deep link can mount this tool first.
+ let homeReady = $state(false);
let center = $state({ ...prefs.homeView });
let markerStyle = $state('none'); // 'crosshair' | 'pin' | 'none'
let moveMode = $state(false); // pin decoupled from center, draggable
@@ -112,9 +88,7 @@
// Middle-drag rotates the map around the grabbed point.
let rotating = $state(false);
let rotatePivot = $state({ x: 0, y: 0 }); // grabbed point, map-wrap-local px
- 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
// 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 });
@@ -149,14 +123,12 @@
// 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).
- const currentProvider = $derived(providers.find((p) => p.id === providerId));
+ const currentProvider = $derived(imagery.find(providerId));
const baseIsImagery = $derived(currentProvider?.imagery ?? true);
// view-only basemaps (capturable=false) keep the map but not the capture
// button (IMAGERY_PROVIDERS.md). Widget basemaps are also capturable=false —
// there are no tiles to stitch — but they are *not* blocked: they capture the
// same way through the same button, from screen pixels rather than tiles.
- const isWidgetBase = $derived(!!currentProvider?.widget);
- const captureBlocked = $derived(currentProvider?.capturable === false && !isWidgetBase);
// --- Sentinel-2: which layer, and over which window ---
// The one basemap with choices in it. What has been asked, what came back and
@@ -164,195 +136,59 @@
// 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,
+ onBilled: () => imagery.refreshUsage(),
notify: toast,
api,
});
const isSentinel = $derived(currentProvider?.id === SENTINEL_ID);
- // A pinned day *is* the acquisition date — the one provider that can answer
- // "when was this taken?" without being asked.
- 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
- // actually serves — this readout just mirrors settings.json.
- let usageTotals = $state({});
- let usageMonth = $state('');
- // keyed-provider prefs mirrored from Settings: overrides lift the 90% soft
- // block, eco swaps billed basemaps for free imagery when zoomed out
- // `tiers` is this account's real allowance per meter (the user's correction
- // where they made one) — a provider's free tier is not ours to hardcode
- let usagePrefs = $state({ overrides: {}, eco: true, ecoMaxZoom: 15, tiers: null });
- async function refreshUsage() {
- try {
- const s = await api.get('/api/settings');
- usageTotals = s.usage;
- usageMonth = s.month;
- usagePrefs = {
- overrides: s.usage_overrides ?? {},
- eco: s.eco_zoom_fallback !== false,
- ecoMaxZoom: s.eco_max_zoom ?? 15,
- tiers: s.free_tier ?? null,
- };
- } catch {
- /* readout only — never blocks the map */
- }
- }
+ // --- what the map is actually showing (state/imagery.svelte.js) ---
+ // A billed basemap steps aside for free imagery when paused (90% soft block)
+ // or zoomed out (eco). The capture follows the display, so provenance always
+ // matches the pixels.
+ const shown = $derived(imagery.displayed(providerId, center.zoom, s2.variant));
// small readout near the basemap selector, billed providers only
- const usagePill = $derived(
- currentProvider?.meter
- ? tilesShort(monthCount(usageTotals, currentProvider.meter, usageMonth), currentProvider.meter)
- : null
- );
-
- // What the map actually shows: a billed basemap steps aside for free imagery
- // when paused (90% soft block) or zoomed out (eco). Captures and the imagery
- // date follow the display, so provenance always matches the pixels.
- const meterBlocked = $derived(
- currentProvider?.meter
- ? usageBlocked(
- monthCount(usageTotals, currentProvider.meter, usageMonth),
- currentProvider.meter,
- usagePrefs.overrides,
- usagePrefs.tiers
- )
- : false
- );
- // the basemap on screen, before Sentinel-2's layer/window choices are folded in
- const displayedBaseId = $derived(
- displayProviderId(currentProvider, center.zoom, {
- eco: usagePrefs.eco,
- blocked: meterBlocked,
- ecoMaxZoom: usagePrefs.ecoMaxZoom,
- })
- );
- const displayedProvider = $derived(providers.find((p) => p.id === displayedBaseId));
- // What every downstream consumer asks for: the tile URL, the capture, the
- // disk cache. For Sentinel-2 the layer and window ride *on the id*
- // (lib/sentinel.js), so none of them can be rendered from one window and
- // filed as another.
- const displayedProviderId = $derived(
- 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
- const displayedCell = $derived(
- displayedProvider ? layerCell(displayedProvider, center.zoom) : 256
- );
-
- // Acquisition date of the imagery under the crosshair — Esri only (item 2).
- let imageryDate = $state(null); // { supported, date, source } | null
- let dateReqId = 0;
- let dateTimer;
+ const usagePill = $derived(imagery.pill(currentProvider));
// Fullscreen: the tool covers the whole viewport; SAVED stays collapsible (item 4).
let fullscreen = $state(false);
- // Editable bearing readout (item 3): click the number to type an angle.
- let editingBearing = $state(false);
- let bearingInput = $state('');
-
- // Measure tools (item 5): distance / area / angle drawn on the map.
- let measureMode = $state(null); // null | 'distance' | 'area' | 'angle'
- let measurePoints = $state([]);
- let measureSurface = null; // lib/map/surface.js
- let toolsOpen = $state(false);
+ // Measure tools (item 5): distance / area / angle, in their own store.
+ const measure = createMeasureState({
+ engine: () => engine,
+ units: () => prefs.units,
+ });
// External-maps quick links, in the SAVED panel (item 6).
let linksOpen = $state(false);
// --- Grid Search (spec §5): overlay a metric grid on an area of interest and
- // sweep it cell by cell, marking each cleared or flagged. A case can hold
- // several saved grids (files under search/, working aids, not entities); each
- // action auto-saves. Persists across basemap changes — its own layer group is
- // untouched by setLayer().
- let gridMode = $state(false); // mode armed from the tools bar
- let grid = $state(null); // the open grid spec (lib/gridSearch.js), or null
- let gridName = $state(null); // slug of the open grid's file (drives the picker)
- let gridList = $state([]); // summaries of this case's saved grids (the picker)
- let gridFor = null; // case id the list was loaded for (plain: load-dedup only)
- let gridCollapsed = $state(false); // fold the panel down to its header
- let gridCellM = $state(500); // metric cell size the next area is drawn with
- let gridDraw = $state(null); // null | 'rect' | 'polygon' — drawing an area
- let polyDraft = $state([]); // polygon vertices being placed, [{ lat, lon }]
- let editArea = $state(false); // showing the area box to resize/reshape it
- let gridHidden = $state(false); // eye toggle: keep the grid but hide it on the map
- let renamingGrid = $state(false); // editing the open grid's title inline
- let renameText = $state(''); // the title being typed while renaming
- let reviewKey = $state(null); // 'i:j' of the cell under review, or null
- let gridSaveTimer; // debounce the persist call
- 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 placed
- let dragBounds = null; // live rect bounds while a corner handle is dragged
- let liveVerts = null; // live polygon vertices while a vertex handle is dragged
- const gridCov = $derived(grid ? gridSearch.coverage(grid) : null);
- const savedOthers = $derived(gridList.filter((g) => g.name !== gridName));
- const GRID_MAX_CELLS = gridSearch.MAX_CELLS;
- // status → cell paint. Unchecked is a bright thin outline so the lattice reads
- // 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: { 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 CORNERS = ['sw', 'se', 'nw', 'ne']; // rect resize handles
-
-
- // --- reference viewers: floating scratch windows over the map that hold a
- // media image (the shot to geolocate) so you can eyeball it against the
- // imagery while panning. Session-only (uiState.refViewers) — never captured,
- // never saved, dropped when the case changes (see openCase).
- let refPicker = $state(false); // the "pick an image" modal
- let refMedia = $state([]); // case images available to reference
- let refLoading = $state(false);
- let refSeq = 0; // id source for spawned windows
-
- async function openRefPicker() {
- refPicker = true;
- refLoading = true;
- try {
- const id = caseState.current?.id;
- const media = id ? await api.get(`/api/cases/${id}/media`) : [];
- refMedia = media.filter((m) => m.kind === 'image' || m.kind === 'video');
- } catch (e) {
- toast(`Could not load media: ${e.message}`, 'danger');
- refMedia = [];
- } finally {
- refLoading = false;
- }
- }
-
- function addRef(item) {
- const vs = uiState.refViewers;
- const n = vs.length;
- vs.push(
- createViewer(`ref-${++refSeq}`, item, {
- x: 60 + (n % 6) * 26,
- y: 60 + (n % 6) * 26,
- z: nextZ(vs),
- })
- );
- refPicker = false;
- }
-
- function focusRef(id) {
- const z = restack(uiState.refViewers, id);
- for (const v of uiState.refViewers) v.z = z.get(v.id);
- }
+ // sweep it cell by cell, marking each cleared or flagged. The grids a case
+ // holds, which one is open and where the sweep is are its own store; it keeps
+ // its layers across basemap changes.
+ const grid = createGridState({
+ engine: () => engine,
+ api,
+ notify: toast,
+ caseId: () => caseState.current?.id,
+ ensureCase,
+ reloadCase,
+ coords: fmtCoords,
+ zoom: () => center.zoom,
+ });
- function closeRef(id) {
- uiState.refViewers = uiState.refViewers.filter((v) => v.id !== id);
- }
+ // --- reference windows: floating scratch panes over the map holding a media
+ // image (the shot to geolocate), to eyeball against the imagery while panning.
+ // Session-only (uiState.refViewers) — never captured, never saved, dropped
+ // when the case changes (see openCase). Their own store: state/refs.svelte.js.
+ const refs = createRefsState({
+ api,
+ notify: toast,
+ caseId: () => caseState.current?.id,
+ viewers: () => uiState.refViewers,
+ setViewers: (windows) => (uiState.refViewers = windows),
+ });
// Svelte only honours a cleanup returned from a *synchronous* onMount, and the
// setup below has to await the providers and the saved home view. So onMount
@@ -373,106 +209,78 @@
});
async function build() {
- refreshUsage(); // prefs drive the eco/soft-block fallbacks from the start
- providers = await api.get('/api/satellite/providers');
+ imagery.refreshUsage(); // prefs drive the eco/soft-block fallbacks from the start
+ await imagery.loadProviders();
await prefsReady; // the home view has to land before the map is built
center = { ...prefs.homeView };
- 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();
- 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 };
- });
- const offRotate = engine.on('rotate', (view) => {
- bearing = Math.round(view.bearing);
- });
- 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 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 armed
- mapEl.addEventListener('mousedown', onGridRectStart, true);
+ homeReady = true; // …and only now is there a view for the surface to open on
window.addEventListener('keydown', onKeydown);
document.addEventListener('fullscreenchange', onFullscreenChange);
// the user clicked the extension after a refused capture — close the loop
const offActivated = onActivated(() =>
toast('Extension ready. Press Capture again', 'ok', 5000)
);
- mapReady = true;
return () => {
window.removeEventListener('keydown', onKeydown);
document.removeEventListener('fullscreenchange', onFullscreenChange);
offActivated();
- offSettled();
- offRotate();
- offClick();
- basemaps.dispose();
- for (const surface of [measureSurface, sunSurface, markerSurface, gridCells, gridAoi, gridDraft]) {
- surface?.destroy();
- }
- engine.destroy();
+ measure.destroy();
+ sky.destroy();
+ grid.destroy();
+ markerSurface?.destroy();
};
}
+ /**
+ * The gestures this tool arms over the map, once the surface has one.
+ *
+ * Capture-phase, all three: the engine's own container drag handler must not
+ * see the event first, or a turn also pans and a marquee also drags the map.
+ */
+ $effect(() => {
+ const element = mapEl;
+ if (!element) return;
+ // middle-mouse or shift drag rotates the view
+ element.addEventListener('mousedown', onMiddleRotateStart, true);
+ // left-drag draws the capture marquee when that mode is armed
+ element.addEventListener('mousedown', onSelectDrag, true);
+ // …and a Grid Search area when the rectangle tool is armed
+ element.addEventListener('mousedown', onGridRectStart, true);
+ return () => {
+ element.removeEventListener('mousedown', onMiddleRotateStart, true);
+ element.removeEventListener('mousedown', onSelectDrag, true);
+ element.removeEventListener('mousedown', onGridRectStart, true);
+ };
+ });
+
function onKeydown(e) {
if (uiState.tool !== 'satellite') return;
// a dialog on top owns the keyboard — it closes itself, the map keeps state
- if (notesItem || placeModal || refPicker || deleteTarget) return;
+ if (notesItem || placeModal || refs.picking || deleteTarget) return;
const tag = e.target?.tagName;
const typing = tag === 'INPUT' || tag === 'TEXTAREA' || e.target?.isContentEditable;
// Enter confirms a polygon area, same as the Confirm button
- if (gridMode && gridDraw === 'polygon' && !typing && e.key === 'Enter' && polyDraft.length >= 3) {
+ if (grid.on && grid.drawMode === 'polygon' && !typing && e.key === 'Enter') {
e.preventDefault();
- confirmPolygon();
+ grid.confirmPolygon();
return;
}
// Grid Search sweep: single-key marks while a cell is under review
- if (gridMode && reviewKey && !typing) {
+ if (grid.on && grid.reviewKey && !typing) {
const k = e.key.toLowerCase();
- if (k === ' ' || k === 'c') return void (e.preventDefault(), markReview('cleared'));
- if (k === 'f') return void (e.preventDefault(), markReview('flagged'));
- if (k === 's') return void (e.preventDefault(), reviewAdvance());
- if (k === 'p') return void (e.preventDefault(), reviewToPlace());
+ if (k === ' ' || k === 'c') return void (e.preventDefault(), grid.markReview('cleared'));
+ if (k === 'f') return void (e.preventDefault(), grid.markReview('flagged'));
+ if (k === 's') return void (e.preventDefault(), grid.advance());
+ if (k === 'p') return void (e.preventDefault(), grid.reviewToPlace());
}
if (e.key !== 'Escape') return;
- if (gridDraw) return cancelGridDraw();
- if (reviewKey) return stopReview();
- if (selectArmed) toggleSelect();
- else if (sizeMenuOpen) sizeMenuOpen = false;
- else if (sunPlacing) sunPlacing = false;
- else if (sunMode) toggleSunMode();
- else if (measureMode) setMeasureMode(null);
+ if (grid.drawMode) return grid.cancelDraw();
+ if (grid.reviewKey) return grid.stopReview();
+ if (capture.armed) toggleSelect();
+ else if (capture.menuOpen) capture.menuOpen = false;
+ else if (sky.placing) sky.togglePlacing();
+ else if (sky.on) toggleSunMode();
+ else if (measure.mode) setMeasureMode(null);
// native fullscreen already exits on Esc (handled by onFullscreenChange);
// only the CSS fallback needs an explicit toggle here
else if (fullscreen && !document.fullscreenElement) toggleFullscreen();
@@ -483,13 +291,6 @@
if (!baseIsImagery && osmOverlay) osmOverlay = false;
});
- $effect(() => {
- 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);
- });
-
// 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(() => {
@@ -507,7 +308,7 @@
// one metadata request, on the user's own action (choosing the basemap), and
// only once per place. Not on mount: no tab may phone out by being opened.
$effect(() => {
- if (!mapReady || displayedBaseId !== SENTINEL_ID) return;
+ if (!mapReady || shown.provider?.id !== SENTINEL_ID) return;
center.lat;
center.lon;
s2.maxcc; // a new ceiling can make a different pass the most recent one
@@ -517,31 +318,6 @@
});
let s2LatestTimer;
- // --- imagery date under the crosshair (item 2) ---
- async function refreshImageryDate() {
- const id = ++dateReqId;
- try {
- const r = await api.get(
- `/api/satellite/imagery-date?lat=${center.lat}&lon=${center.lon}` +
- `&zoom=${center.zoom}&provider=${displayedProviderId}`
- );
- if (id === dateReqId) imageryDate = r;
- } catch {
- if (id === dateReqId) imageryDate = { supported: true, date: null, source: null };
- }
- }
-
- // debounce: the target moves a lot while panning — only query once it settles
- $effect(() => {
- center.lat;
- center.lon;
- center.zoom;
- displayedProviderId;
- if (!mapReady) return;
- clearTimeout(dateTimer);
- dateTimer = setTimeout(refreshImageryDate, 500);
- });
-
// --- middle-drag rotate (item 3), Google-Earth style ---
// Grab a point → the map turns around *that* point (not the centre) as the
// cursor sweeps, with a sober target marking the pivot. A map only rotates
@@ -552,7 +328,8 @@
// 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';
+ const shiftDrag =
+ e.button === 0 && e.shiftKey && !capture.armed && grid.drawMode !== 'rect';
if (e.button !== 1 && !shiftDrag) return;
startRotateDrag(engine, e, {
onPivot: (pivot) => {
@@ -563,17 +340,6 @@
});
}
- function startEditBearing() {
- bearingInput = String(bearing);
- editingBearing = true;
- }
-
- function commitBearing() {
- const v = parseFloat(bearingInput);
- if (Number.isFinite(v)) setBearing(v);
- editingBearing = false;
- }
-
// Actions that leave the tool — switching to another tool, opening a browser
// tab — can't do anything visible while the map owns the whole screen, so
// they're greyed out rather than silently dropping the user out of it.
@@ -617,92 +383,23 @@
tick().then(() => engine?.resize());
}
- // --- measure tools (item 5) ---
+ // --- what a click on the map means -------------------------------------
+ //
+ // One router, asked in the order the modes exclude each other: a polygon
+ // being placed owns the click, then a sky anchor waiting to be planted, then
+ // the measure tools. Each mode answers whether it took it.
/** Where the analyst clicked, `{ lat, lon }` from the façade. */
function onMapClick(at) {
- // Grid Search polygon: each click drops a vertex
- if (gridDraw === 'polygon') {
- polyDraft = [...polyDraft, at];
- renderDraft();
- return;
- }
- // Sun & moon: one click plants the anchor the day's path is drawn from
- if (sunPlacing) {
- sunAnchor = at;
- sunSky = null;
- sunPlacing = false;
- return;
- }
- if (!measureMode) return;
- // an angle is exactly three points; a fourth click starts a fresh angle
- if (measureMode === 'angle' && measurePoints.length >= 3) measurePoints = [];
- measurePoints = [...measurePoints, at];
- redrawMeasure();
- }
-
- function setMeasureMode(m) {
- measureMode = measureMode === m ? null : m;
- if (measureMode) selectArmed = false; // measuring and marquee can't both be armed
- measurePoints = [];
- measureSurface?.clear();
- }
-
- // toggling the panel shut also drops any active measure tool — otherwise the
- // ruler button stays lit (and the tool stays armed) with the panel gone
- function toggleTools() {
- toolsOpen = !toolsOpen;
- if (!toolsOpen && measureMode) setMeasureMode(null);
+ if (grid.addVertex(at)) return;
+ if (sky.place(at)) return;
+ measure.addPoint(at);
}
- function clearMeasure() {
- measurePoints = [];
- measureSurface?.clear();
+ function setMeasureMode(mode) {
+ // measuring and the capture marquee can't both be armed
+ if (measure.setMode(mode)) capture.disarm();
}
- 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 (!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(() => {
- if (!measureMode || measurePoints.length < 2) return null;
- if (measureMode === 'distance')
- return measure.formatDistance(measure.pathLength(measurePoints), prefs.units);
- if (measureMode === 'area')
- return measurePoints.length >= 3
- ? measure.formatArea(measure.polygonArea(measurePoints), prefs.units)
- : '…';
- // angle needs a middle vertex
- return measurePoints.length >= 3
- ? measure.formatAngle(measure.angleAt(measurePoints[0], measurePoints[1], measurePoints[2]))
- : '…';
- });
-
- const MEASURE_HINT = {
- distance: 'Click points along the path',
- area: 'Click the polygon corners',
- angle: 'Click three points (vertex second)',
- };
-
// --- external map links (item 6) ---
const externalLinks = $derived(mapLinks(displayCoords.lat, displayCoords.lon, center.zoom));
@@ -719,13 +416,6 @@
setBearing(row.bearing);
}
- // 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);
- }
-
// 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.
@@ -737,19 +427,17 @@
});
} 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 imagery.loadProviders();
}
- $effect(() => {
- displayedProviderId; // track provider changes (incl. eco/block fallbacks,
- // and Sentinel-2's layer/window — a new window is a new set of tiles)
- displayedCell; // and the z17 detail-boost bracket
- setLayer();
- });
+ function onWidgetFailed(provider, error) {
+ toast(`Google Maps failed to load: ${error.message}`, 'danger', 6000);
+ providerId = FALLBACK_PROVIDER;
+ }
// a basemap disabled in Settings can leave a stale selection — fall back
$effect(() => {
- if (providers.length && !currentProvider) providerId = 'esri-world-imagery';
+ if (imagery.providers.length && !currentProvider) providerId = FALLBACK_PROVIDER;
});
// re-sync providers + prefs when returning to this tab: Settings may have
@@ -757,8 +445,8 @@
// eco / override prefs meanwhile (tools stay mounted, so no fresh onMount)
$effect(() => {
if (uiState.tool !== 'satellite' || !mapReady) return;
- refreshUsage();
- api.get('/api/satellite/providers').then((r) => (providers = r));
+ imagery.refreshUsage();
+ imagery.loadProviders();
});
// A different case drops everything this one was holding: both indexes, the
@@ -817,9 +505,9 @@
$effect(() => {
const target = uiState.gotoCoords;
if (mapReady && target && Number.isFinite(target.lat) && Number.isFinite(target.lon)) {
- if (target.provider && !providers.length) return;
+ if (target.provider && !imagery.providers.length) return;
uiState.gotoCoords = null;
- if (target.provider && providers.some((provider) => provider.id === target.provider)) {
+ if (target.provider && imagery.find(target.provider)) {
providerId = target.provider;
}
const zoom = Number.isFinite(target.zoom) ? target.zoom : Math.max(engine.getZoom(), 16);
@@ -926,199 +614,54 @@
temporalMapError = '';
}
- // --- sun and moon mode ---
+ // --- sun and moon ---
//
- // One anchored point, one date, and an hour you drag: the day's path drawn as
- // the arc the body sweeps while it is up, hour ticks along it, and the bearing
- // at the chosen moment. Everything drawn is an azimuth, which is the only
- // celestial quantity a plan view can state honestly; altitude stays in the
- // panel. Map Measures will absorb this as its general bearing layer.
- let sunMode = $state(false);
- let sunAnchor = $state.raw(null); // { lat, lon } — fixed, never the moving view
- let sunDay = $state(''); // empty: the backend's today at that point
- let sunIndex = $state(0); // sample of the day the slider is on
- let sunSky = $state(null);
- let sunLoading = $state(false);
- let sunPlacing = $state(false);
- let sunSurface = null; // lib/map/surface.js
- let sunTicket = 0;
+ // One anchored point, one date, and an hour you drag, in its own store
+ // (state/sky.svelte.js). The tool keeps only what the mode means *here*:
+ // which other modes it turns off, and where it opens when nothing is planted.
+ const sky = createSkyState({ engine: () => engine, api, notify: toast });
function toggleSunMode() {
- sunMode = !sunMode;
- if (sunMode) {
- if (selectArmed) toggleSelect(); // exclusive with the capture marquee…
- if (measureMode) setMeasureMode(null); // …the measure tools…
- if (gridMode) toggleGridMode(); // …and Grid Search
- if (!sunAnchor) sunAnchor = markerLatLng ?? { lat: center.lat, lon: center.lon };
- } else {
- sunPlacing = false;
- sunSurface?.clear();
+ if (sky.on) {
+ sky.close();
+ return;
}
+ if (capture.armed) toggleSelect(); // exclusive with the capture marquee…
+ setMeasureMode(null); // …the measure tools…
+ if (grid.on) toggleGridMode(); // …and Grid Search
+ sky.open(markerLatLng ?? { lat: center.lat, lon: center.lon });
}
- // Wall clock to land the slider on, once the day's samples are in.
- let handedClock = null;
-
- // Coords & Sky hands over a point, a date and a time: same mode, second way in,
- // so there is only ever one rendering of this to keep right.
+ // Coords & Sky hands over a point, a date and a time: same mode, second way
+ // in, so there is only ever one rendering of this to keep right.
$effect(() => {
const handed = uiState.skyAt;
if (!mapReady || !handed) return;
uiState.skyAt = null;
- sunAnchor = { lat: handed.lat, lon: handed.lon };
- sunDay = handed.date ?? '';
- sunSky = null;
- sunIndex = 0;
- handedClock = handed.time ?? null;
- if (!sunMode) toggleSunMode();
+ if (!sky.on) toggleSunMode();
+ sky.handOff(handed);
});
$effect(() => {
- if (!sunMode || !sunAnchor) return;
- const params = new URLSearchParams({ lat: sunAnchor.lat, lon: sunAnchor.lon });
- if (sunDay) params.set('date', sunDay);
- const ticket = ++sunTicket;
- sunLoading = true;
- api
- .get(`/api/geo/sky?${params}`)
- .then((result) => {
- if (ticket !== sunTicket) return;
- sunSky = result;
- sunDay = result.date;
- sunIndex = nearestSample(result.curve.clock, handedClock ?? result.moment.local.slice(11, 16));
- handedClock = null;
- })
- .catch(() => {
- if (ticket === sunTicket) toast('Could not read the sky for that point', 'danger');
- })
- .finally(() => {
- if (ticket === sunTicket) sunLoading = false;
- });
+ sky.on;
+ sky.anchor;
+ sky.day;
+ sky.load();
});
- function themeColour(name, fallback) {
- const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
- return value || fallback;
- }
-
- const SKY_BODY_SIZE = 20;
-
- function drawSun() {
- if (!engine) return;
- sunSurface ??= createSurface(engine);
- if (!sunMode || !sunSky || !sunAnchor) {
- sunSurface.clear();
- return;
- }
- const origin = sunAnchor;
- // 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, down } = engine.viewSpanMeters();
- const reach = Math.min(across, down) * 0.22;
- const at = (azimuth, scale = 1) => measure.destination(origin, azimuth, reach * scale);
- const curve = sunSky.curve;
- const shapes = [];
-
- for (const body of [
- {
- key: 'sun',
- label: 'Sun',
- colour: themeColour('--sky-sun', '#bd8721'),
- azimuth: curve.sun_azimuth,
- altitude: curve.sun_altitude,
- },
- {
- key: 'moon',
- label: 'Moon',
- colour: themeColour('--sky-moon', '#4a93cc'),
- azimuth: curve.moon_azimuth,
- altitude: curve.moon_altitude,
- },
- ]) {
- // 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)) {
- 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)) {
- 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
- );
- 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) {
- 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,
- SKY_BODY_SIZE
- ),
- size: [SKY_BODY_SIZE, SKY_BODY_SIZE],
- anchor: [SKY_BODY_SIZE / 2, SKY_BODY_SIZE / 2],
- keyboard: false,
- tip: body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading,
- });
- }
- }
-
- 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.
$effect(() => {
- sunMode;
- sunSky;
- sunIndex;
- sunAnchor;
- if (mapReady) drawSun();
+ sky.on;
+ sky.sky;
+ sky.index;
+ sky.anchor;
+ if (mapReady) sky.draw();
});
// The arc is drawn in metres, so a zoom or a pan has to restretch it.
$effect(() => {
- if (!mapReady || !sunMode) return;
- return engine.on('view-settled', () => drawSun());
+ if (!mapReady || !sky.on) return;
+ return engine.on('view-settled', () => sky.draw());
});
let searching = $state(false);
@@ -1161,10 +704,6 @@
engine?.setBearing(deg); // the façade normalises whatever it is handed
}
- function resetNorth() {
- setBearing(0);
- }
-
// --- marker (crosshair / pin), optionally decoupled from center ---
// the coordinates shown & recorded: the moved pin, else the crop center
@@ -1172,48 +711,32 @@
moveMode && markerLatLng ? markerLatLng : { lat: center.lat, lon: center.lon }
);
- // --- capture sizing (backend validates 256–4096 px per side; see lib/captureSize.js) ---
-
- // Standard output sizes for the centred Capture button, named by intent.
- const PRESETS = [
- { id: '1200x675', label: 'Tweet 16:9', w: 1200, h: 675 },
- { id: '1080x1080', label: 'Square', w: 1080, h: 1080 },
- { id: '1200x630', label: 'OG card', w: 1200, h: 630 },
- { id: '1280x800', label: 'Wide', w: 1280, h: 800 },
- { id: 'custom', label: 'Custom', w: 0, h: 0 },
- ];
- let preset = $state('1200x675');
- let customW = $state(1200);
- let customH = $state(675);
- // preset dimensions in px — the centred Capture frame + its hover preview
- const presetSize = $derived.by(() => {
- if (preset === 'custom') return [clampSize(customW), clampSize(customH)];
- const p = PRESETS.find((x) => x.id === preset);
- return [p.w, p.h];
+ // --- capture: what shape the crop is, and filing what is inside it ---
+ // The output size, the marquee's ratio lock, the resolution, which mode the
+ // button re-runs and both roads to a filed crop are its own store
+ // (state/capture.svelte.js). The pixels' provenance is asked of the surface
+ // that drew them, never of the provider that was chosen.
+ const capture = createCaptureState({
+ api,
+ notify: toast,
+ ensureCase,
+ reloadCase,
+ engine: () => engine,
+ element: () => mapEl,
+ view: () => center,
+ bearing: () => bearing,
+ marker: () => ({ style: markerStyle, at: moveMode ? markerLatLng : null }),
+ basemap: () => currentProvider,
+ maxZoom: () => shown.provider?.max_zoom ?? 19,
+ provenance: () => surface.provenance(),
+ onRect: (rect) => (selRect = rect),
+ onArm: () => setMeasureMode(null),
});
-
- // Marquee ratio lock (width/height); null = free-form drag.
- const RATIOS = [
- { id: 'free', label: 'Free', r: null },
- { id: '16:9', label: '16:9', r: 16 / 9 },
- { id: '4:3', label: '4:3', r: 4 / 3 },
- { id: '1:1', label: '1:1', r: 1 },
- ];
- let ratio = $state('free');
- const ratioValue = $derived(RATIOS.find((x) => x.id === ratio)?.r ?? null);
-
- // Output resolution: 1 = view zoom, 2 = one zoom deeper (2×), 'max' = provider max.
- let resolution = $state(1);
- const providerMaxZoom = $derived(displayedProvider?.max_zoom ?? 19);
-
- // Single capture button, split-style: the main part re-runs whichever mode
- // was used last (remembered here); the arrow opens mode + size/ratio/
- // resolution settings.
- let captureMode = $state('center'); // 'center' | 'select'
- let sizeMenuOpen = $state(false); // the mode/size/ratio/resolution popover
- let sizeMenuEl = $state(); // bound to the popover's wrapper — used to detect outside clicks
- let selectArmed = $state(false); // marquee mode: drag a box on the map to capture
- let selRect = $state(null); // live marquee { x0, y0, x1, y1 } in map-container px
+ let sizeMenuEl = $state(); // bound to the popover wrapper — outside-click detection
+ // The live drag outline, in map-container px. Shared chrome: the capture
+ // marquee and the Grid Search rectangle are the same gesture and cannot both
+ // be armed, so one outline serves both.
+ let selRect = $state(null);
const PIN = 'pin'; // the one shape on the move-mode surface
@@ -1261,261 +784,14 @@
}
});
- // 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(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 = 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 = 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: framedOn.lat,
- lon: framedOn.lon,
- zoom,
- width,
- height,
- // capture what's on screen: the eco/soft-block fallback, if active
- provider: displayedProviderId,
- bearing,
- marker_style: markerStyle,
- marker_x,
- marker_y,
- marker_lat,
- marker_lon,
- // second date on the capture: the imagery's acquisition date, if known
- // a pinned Sentinel-2 window is the acquisition date outright; every
- // other provider's is Esri's best-effort estimate or nothing
- imagery_date: s2PinnedDate ?? imageryDate?.date ?? null,
- });
- await reloadCase();
- toast(
- result.tiles_missing
- ? `Captured with ${result.tiles_missing} missing tile(s). No imagery was available there`
- : result.tiles_upscaled
- ? `Captured. ${result.tiles_upscaled} tile(s) were upscaled from a lower zoom and recorded in provenance`
- : 'Satellite crop captured & filed',
- result.tiles_missing || result.tiles_upscaled ? 'warn' : 'ok'
- );
- } catch (e) {
- toast(`Capture failed: ${e.message}`, 'danger', 6000);
- } finally {
- capturing = false;
- }
- }
-
- // Centred Capture button: the standard preset size, framed on the map centre.
- function captureCentered() {
- const [w, h] = presetSize;
- const r = mapEl.getBoundingClientRect();
- doCapture(engine.camera(), w, h, {
- x: (r.width - w) / 2,
- y: (r.height - h) / 2,
- w,
- h,
- });
- }
-
- // The main capture button runs whichever mode is currently selected —
- // captureMode itself *is* the "last used mode" memory, so nothing else
- // needs to track it.
- async function runCapture() {
- if (captureBlocked || capturing) return; // view-only basemap
- // The widget basemap captures from screen pixels via the browser extension
- // (extBridge.js). Without it there is nothing legitimate to capture with —
- // gate here, before any frame is drawn, and explain instead of half-working.
- if (isWidgetBase && !extensionVersion()) {
- extGateOpen = true;
- return;
- }
- if (captureMode === 'select') toggleSelect();
- else captureCentered();
- }
-
- // --- widget capture: the same crop frame, filled with screen pixels ---
- //
- // Google's terms allow a user-taken screenshot with attribution and nothing
- // programmatic out of the widget: the cloned tiles in the DOM are off-limits,
- // so the pixels come from the capture extension — one tabs.captureVisibleTab
- // behind the user's click, the browser-blessed way to screenshot the tab.
- // No share prompt, no sharing bar, fullscreen stays. That's the only
- // difference from a tile capture: the frame, the modes (centred preset /
- // free marquee) and the filing are identical, so the widget goes through
- // doCapture() like every other basemap.
- let extGateOpen = $state(false); // "you need the extension" explainer
-
- // One frame of this tab as a drawable image, via the extension. The frame is
- // exactly the viewport, so registration is the viewport aspect check — a
- // mismatch means browser zoom mid-flight or a foreign frame, both refusals.
- async function extFrame() {
- const dataUrl = await captureTab();
- const img = new window.Image();
- await new Promise((resolve, reject) => {
- img.onload = resolve;
- img.onerror = () => reject(new Error('unreadable frame from the extension'));
- img.src = dataUrl;
- });
- if (!isRegistered(img.naturalWidth, img.naturalHeight, window.innerWidth, window.innerHeight)) {
- throw new Error('the captured frame does not match this view. Try again');
- }
- return img;
- }
-
- // Map a rect in map-container CSS px onto the captured frame, and render it
- // at exactly outW × outH (default: the native source pixels). Source pixels
- // are usually denser than CSS px (devicePixelRatio, Region Capture), so a
- // requested size is a supersampled downscale rather than a blur-up.
- async function shotCropCanvas(img, rect, outW, outH) {
- const src = sourceRect(rect, {
- mapRect: mapEl.getBoundingClientRect(),
- viewportWidth: window.innerWidth,
- videoWidth: img.naturalWidth,
- videoHeight: img.naturalHeight,
- });
- if (!src) {
- throw new Error('the frame runs past the captured area. Resize the window or pick a smaller size');
- }
- const { sx, sy, sw, sh } = src;
- const canvas = document.createElement('canvas');
- canvas.width = Math.round(outW ?? sw);
- canvas.height = Math.round(outH ?? sh);
- const ctx = canvas.getContext('2d');
- ctx.imageSmoothingQuality = 'high';
- ctx.drawImage(img, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
- return canvas;
- }
-
- // The widget arm of doCapture: grab the tab via the extension, crop, file.
- async function doWidgetCapture(framedOn, rect) {
- if (!extensionVersion()) {
- extGateOpen = true;
- return;
- }
- const mapRect = mapEl.getBoundingClientRect();
- if (!frameFitsView(rect, mapRect)) {
- toast(
- `The ${Math.round(rect.w)}×${Math.round(rect.h)} frame is bigger than the map view. Pick a smaller size or enlarge the window`,
- 'warn', 7000
- );
- return;
- }
- capturing = true;
- // The tab frame is the whole viewport, so our own chrome painted over the
- // map (HUD, controls, reference windows, the frame outline itself) would
- // land inside the crop. Hide it for the grab — a capture must show the
- // map, not the app. Only the marker stays: the tile path burns one into
- // its crop, so dropping it here would be the odd one out.
- hideOverlays = true;
- try {
- // let the hidden chrome actually leave the composited frame
- await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
- await new Promise((r) => setTimeout(r, 60));
- 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, framedOn, true);
- } catch (e) {
- if (e.needsActivation) {
- // one-time per tab: the browser only lets the extension screenshot a
- // tab it has been invoked on (activeTab) — not an error, a step
- toast(
- 'One-time step: click the Azimut Capture icon in the toolbar (or press Alt+Shift+A), then press Capture again',
- 'warn',
- 10000
- );
- } else {
- // Never fall back to the import dialog: a capture that couldn't be
- // taken must stay untaken. Quietly offering to file some other image
- // instead is how an unregistered picture ends up wearing a capture's
- // provenance.
- toast(`Capture failed: ${e.message}`, 'danger', 7000);
- }
- } finally {
- hideOverlays = false;
- capturing = false;
- }
- }
-
- // File a screenshot blob as a capture. `framed` records whether the
- // 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, framedOn, framed) {
- const c = await ensureCase();
- const form = new FormData();
- form.append('image', blob, 'screenshot.png');
- 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);
- form.append('framed', String(!!framed));
- const result = await api.post(`/api/cases/${c.id}/satellite/screenshot`, form);
- await reloadCase();
- toast(
- framed
- ? 'Screen crop captured & filed (attribution burned in)'
- : 'Screenshot filed as a capture (attribution burned in)',
- 'ok'
- );
- return result;
- }
-
- // --- 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);
-
- /** The whole map view as a PNG blob, through the extension. Null if refused. */
- async function grabView() {
- try {
- const img = await extFrame();
- 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 works
- toast(`Screen capture unavailable (${e.message}). Paste a screenshot instead`, 'warn', 6000);
- return null;
- }
- }
-
- /** File what the dialog holds, at the map view rather than a registered frame. */
- async function fileScreenshotBlob(blob) {
- try {
- await fileScreenshot(blob, null, false);
- return true;
- } catch (e) {
- toast(`Could not file the screenshot: ${e.message}`, 'danger', 6000);
- return false;
- }
- }
+ // Both roads to a filed crop — the backend stitching tiles, and the extension
+ // grabbing screen pixels for a widget basemap — are state/capture.svelte.js.
// clicking outside the open size/ratio/resolution popover closes it
$effect(() => {
- if (!sizeMenuOpen) return;
+ if (!capture.menuOpen) return;
const onDocMousedown = (e) => {
- if (sizeMenuEl && !sizeMenuEl.contains(e.target)) sizeMenuOpen = false;
+ if (sizeMenuEl && !sizeMenuEl.contains(e.target)) capture.menuOpen = false;
};
document.addEventListener('mousedown', onDocMousedown, true);
return () => document.removeEventListener('mousedown', onDocMousedown, true);
@@ -1532,316 +808,38 @@
});
// --- marquee: drag a rectangle on the map to capture exactly that area ---
+ // The frame, the ratio lock and the filing are the store's. What stays here
+ // is the wiring only this file can do: the mode exclusivity, and handing the
+ // store a left-drag off the map element it does not own.
function toggleSelect() {
- selectArmed = !selectArmed;
- if (selectArmed) {
- sizeMenuOpen = false;
- if (measureMode) setMeasureMode(null);
- } else {
- selRect = null;
- }
+ capture.toggleSelect();
}
- function onSelectStart(e) {
- if (!selectArmed || e.button !== 0 || !engine) return;
- startRectDrag(engine, e, {
- ratio: ratioValue,
- onChange: (rect) => (selRect = rect),
- onDone: finishSelect,
- });
+ function onSelectDrag(e) {
+ capture.startSelect(e);
}
- 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 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(framedOn, Math.round(w), Math.round(h), {
- x: Math.min(r.x0, r.x1),
- y: Math.min(r.y0, r.y1),
- w,
- h,
- });
- }
-
- // --- Grid Search: layers, drawing, sweeping, persistence -------------------
+ // --- Grid Search: the mode, and the gesture that draws a rectangle --------
+ //
+ // The lattice, the sweep and the case's saved grids are the store's
+ // (state/grid.svelte.js). What stays here is what Grid Search means *in this
+ // tool*: which other modes it turns off, and the left-drag that draws an area
+ // — the same gesture as the capture marquee, sharing its live outline.
function toggleGridMode() {
- gridMode = !gridMode;
- if (gridMode) {
- if (selectArmed) toggleSelect(); // exclusive with the capture marquee…
- if (measureMode) setMeasureMode(null); // …and the measure tools
- gridHidden = false;
- ensureGridLayers();
- refreshGridList();
- if (grid) {
- renderGrid();
- renderAoi();
- }
- } else {
- cancelGridDraw();
- stopReview();
- editArea = false;
- clearGridLayers();
- }
- }
-
- function ensureGridLayers() {
- 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 back
- function syncGridVisibility() {
- for (const surface of [gridCells, gridAoi, gridDraft]) surface?.visible(!gridHidden);
- }
-
- function toggleGridHidden() {
- gridHidden = !gridHidden;
- syncGridVisibility();
- }
-
- function startRename() {
- if (!grid) return;
- renameText = grid.title || '';
- renamingGrid = true;
- }
-
- function commitRename() {
- renamingGrid = false;
- if (!grid) return;
- const t = renameText.trim();
- if (t && t !== grid.title) {
- grid.title = t;
- scheduleGridSave();
- }
- }
-
- function clearGridLayers() {
- gridCells?.clear();
- gridAoi?.clear();
- gridDraft?.clear();
- }
-
- // 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, stroke: '#33c9ff', strokeWidth: 2.5, strokeOpacity: 1 }
- : base;
- }
-
- function renderGrid() {
- ensureGridLayers();
- 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) {
- gridCells?.patch(key, { style: cellStyle(key) });
- }
-
- function setReview(key) {
- const prev = reviewKey;
- reviewKey = key;
- if (prev) restyleCell(prev);
- if (key) restyleCell(key);
- }
-
- function cycleCell(i, j) {
- const key = gridSearch.cellKey(i, j);
- // during a sweep, clicking the cell you're reviewing clears it and moves on
- // (same as the Clear button) — you're looking right at it
- if (reviewKey && key === reviewKey) {
- markReview('cleared');
- return;
- }
- const next = gridSearch.cycleStatus(grid.statuses[key]);
- if (next) grid.statuses[key] = next;
- else delete grid.statuses[key];
- restyleCell(key);
- scheduleGridSave();
- }
-
- function flagCell(i, j) {
- const key = gridSearch.cellKey(i, j);
- if (grid.statuses[key] === 'flagged') delete grid.statuses[key];
- else grid.statuses[key] = 'flagged';
- restyleCell(key);
- scheduleGridSave();
- }
-
- // --- 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();
- 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') {
- 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, at) {
- if (!dragBounds) return;
- 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() {
- if (!dragBounds || !grid) return;
- const b = gridSearch.normalizeBounds(dragBounds);
- dragBounds = null;
- const resized = gridSearch.resizeRect(grid, b);
- if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {
- toast(`That area is too fine for ${grid.cell_m} m cells. Keeping the previous size`, 'warn', 5000);
- renderAoi(); // snap the handles back
+ if (grid.on) {
+ grid.exit();
return;
}
- grid = resized;
- renderGrid();
- renderAoi();
- scheduleGridSave();
- }
-
- function commitVertEdit() {
- if (!liveVerts || !grid) return;
- const verts = liveVerts;
- liveVerts = null;
- const resized = gridSearch.resizePolygon(grid, verts);
- if (gridSearch.estimateCells(resized) > GRID_MAX_CELLS) {
- toast(`That shape is too fine for ${grid.cell_m} m cells. Keeping the previous one`, 'warn', 5000);
- renderAoi();
- return;
- }
- grid = resized;
- renderGrid();
- renderAoi();
- scheduleGridSave();
- }
-
- // show the area box to resize (rect corners) or reshape (polygon vertices)
- function toggleEditArea() {
- if (!grid) return;
- stopReview();
- cancelGridDraw();
- editArea = !editArea;
- renderAoi();
- }
-
- function startDraw(type) {
- cancelGridDraw();
- stopReview();
- editArea = false;
- gridHidden = false;
- gridDraw = type;
- // hide the current cells while drawing so map clicks reach the canvas
- // (polygon vertices) instead of being swallowed by a cell underneath
- gridCells?.clear();
- if (type === 'polygon') {
- polyDraft = [];
- renderDraft();
- }
+ if (capture.armed) toggleSelect(); // exclusive with the capture marquee…
+ setMeasureMode(null); // …and the measure tools
+ grid.open();
}
- function cancelGridDraw() {
- const wasDrawing = gridDraw;
- gridDraw = null;
- polyDraft = [];
- selRect = null;
- 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'.
+ // rectangle area: drag a box, mirroring the capture marquee and reusing
+ // selRect for the live outline. Armed while the rectangle tool is chosen.
function onGridRectStart(e) {
- if (gridDraw !== 'rect' || e.button !== 0 || !engine) return;
+ if (grid.drawMode !== 'rect' || e.button !== 0 || !engine) return;
startRectDrag(engine, e, {
onChange: (rect) => (selRect = rect),
onDone: finishGridRect,
@@ -1850,264 +848,22 @@
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 draw
- return;
- }
- 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.lon, east: p2.lon }),
- });
- }
-
- // polygon area: click to drop vertices (handled in onMapClick), drag the
- // handles to adjust, Confirm to build.
- const DRAFT_RING = 'ring';
-
- function draftRing() {
- return gridSearch.closeRing(polyDraft.map((point) => [point.lat, point.lon]))
- .map(([lat, lon]) => ({ lat, lon }));
- }
-
- function renderDraft() {
- ensureGridLayers();
- 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,
- zIndex: 1200,
- onDrag: (at) => {
- polyDraft[k] = at;
- gridDraft.patch(DRAFT_RING, { points: draftRing() });
- },
- onDragEnd: renderDraft,
- })),
- ]);
- }
-
- function confirmPolygon() {
- if (polyDraft.length < 3) return;
- const vertices = polyDraft.map((p) => [p.lat, p.lon]);
- gridDraw = null;
- polyDraft = [];
- gridDraft?.clear();
- doApplyArea({ type: 'polygon', vertices });
- }
-
- // Drawing an area always makes a *new* grid (the case can hold several); the
- // one you were on stays saved. Resizing the current grid is the handles.
- async function doApplyArea(aoi) {
- const cellM = Math.max(10, Number(gridCellM) || 500); // never a NaN lattice
- const g = gridSearch.createGrid(aoi, cellM);
- if (gridSearch.estimateCells(g) > GRID_MAX_CELLS) {
- toast(`That area exceeds the ${GRID_MAX_CELLS}-cell limit. Use a larger cell size.`, 'warn', 6000);
- renderGrid(); // restore the previous grid we hid to draw
- return;
- }
- await ensureCase(); // a grid is case state; make sure there is one to hold it
- await flushGridSave(); // persist the grid we're leaving before switching
- g.title = gridTitleFor(aoi);
- grid = g;
- gridName = `grid-${Date.now().toString(36)}`;
- gridFor = caseState.current?.id;
- reviewKey = null;
- editArea = false;
- gridHidden = false;
- renderGrid();
- renderAoi();
- await saveGrid(); // create it on disk now, then refresh the picker
- refreshGridList();
- }
-
- function gridTitleFor(aoi) {
- const c = gridSearch.aoiCenter(aoi);
- return fmtCoords(c.lat, c.lon);
- }
-
- // --- sweep loop: fly to a cell, mark it, advance ---
- function flyToCell([i, j]) {
- setReview(gridSearch.cellKey(i, j));
- const b = gridSearch.cellBounds(grid, i, j);
- engine.fitBounds(b, { padding: [80, 80], maxZoom: 20, animate: true });
- }
-
- function startReview() {
- if (!grid) return;
- editArea = false;
- const cell = gridSearch.nextUnchecked(grid, null);
- if (!cell) {
- toast('Every cell is marked. Sweep complete', 'ok');
- return;
- }
- flyToCell(cell);
- }
-
- function reviewAdvance() {
- const next = gridSearch.nextUnchecked(grid, reviewKey);
- if (!next) {
- setReview(null);
- toast('Sweep complete', 'ok');
- return;
- }
- flyToCell(next);
- }
-
- function markReview(status) {
- if (!reviewKey) return;
- if (status) grid.statuses[reviewKey] = status;
- else delete grid.statuses[reviewKey];
- restyleCell(reviewKey);
- scheduleGridSave();
- reviewAdvance();
- }
-
- function stopReview() {
- if (reviewKey) setReview(null);
- }
-
- // flag the cell under review and file its centre as a place (spec §5 — a hit
- // the analyst promotes into the case graph)
- async function reviewToPlace() {
- if (!reviewKey || !grid) return;
- const [i, j] = gridSearch.parseKey(reviewKey);
- const c = gridSearch.cellCenter(grid, i, j);
- grid.statuses[reviewKey] = 'flagged';
- restyleCell(reviewKey);
- scheduleGridSave();
- try {
- const cs = await ensureCase();
- await api.post(`/api/cases/${cs.id}/satellite/place`, {
- lat: c.lat,
- lon: c.lon,
- zoom: Math.max(center.zoom, 16),
- bearing: 0,
- });
- await reloadCase();
- toast('Cell flagged and saved as a place', 'ok');
- } catch (e) {
- toast(`Could not save place: ${e.message}`, 'danger', 6000);
- }
- }
-
- // --- the case's saved grids: list, load, new, delete, persist ---
- function scheduleGridSave() {
- clearTimeout(gridSaveTimer);
- gridSaveTimer = setTimeout(saveGrid, 600);
- }
-
- // persist any pending change to the *current* grid before we switch away
- async function flushGridSave() {
- clearTimeout(gridSaveTimer);
- await saveGrid();
- }
-
- async function saveGrid() {
- const id = caseState.current?.id;
- if (!id || !grid || !gridName) return;
- try {
- const spec = JSON.parse(JSON.stringify(grid)); // strip the $state proxy
- await api.put(`/api/cases/${id}/search-grids/${gridName}`, { spec, title: grid.title });
- } catch (e) {
- toast(`Could not save the grid: ${e.message}`, 'danger', 5000);
- }
- }
-
- async function refreshGridList() {
- const id = caseState.current?.id;
- if (!id) {
- gridList = [];
- return;
- }
- try {
- gridList = await api.get(`/api/cases/${id}/search-grids`);
- } catch {
- gridList = [];
- }
- }
-
- async function loadGrid(name) {
- const id = caseState.current?.id;
- if (!id) return;
- cancelGridDraw();
- stopReview();
- editArea = false;
- gridHidden = false;
- await flushGridSave(); // persist the grid we're leaving
- try {
- const spec = await api.get(`/api/cases/${id}/search-grids/${name}`);
- grid = spec;
- gridName = name;
- reviewKey = null;
- ensureGridLayers();
- renderGrid();
- renderAoi();
- refreshGridList(); // the grid we left becomes a picker entry
- } catch (e) {
- toast(`Could not load grid: ${e.message}`, 'danger', 6000);
- }
- }
-
- // close the open grid (it stays saved) — the draw buttons then start a fresh one
- function closeGrid() {
- grid = null;
- gridName = null;
- reviewKey = null;
- editArea = false;
- cancelGridDraw();
- clearGridLayers();
- }
-
- // the Discard button: persist any pending rename/marks first, then close, then
- // refresh the picker so the just-closed grid shows its latest title
- async function discardOpenGrid() {
- await flushGridSave();
- closeGrid();
- refreshGridList();
- }
-
- async function deleteGrid(name) {
- const id = caseState.current?.id;
- if (id) {
- try {
- await api.del(`/api/cases/${id}/search-grids/${name}`);
- } catch {
- /* the file may already be gone — nothing left to do */
+ grid.finishRect(
+ r && {
+ p1: engine.containerPointToLatLng({ x: r.x0, y: r.y0 }),
+ p2: engine.containerPointToLatLng({ x: r.x1, y: r.y1 }),
+ widthPx: Math.abs(r.x1 - r.x0),
+ heightPx: Math.abs(r.y1 - r.y0),
}
- }
- if (gridName === name) closeGrid();
- refreshGridList();
+ );
}
- // on case change: refresh the picker and close whatever grid was open
+ // A different case: the grids on disk are its own, and whatever was open
+ // belonged to the last one.
$effect(() => {
const id = caseState.current?.id;
caseState.rev; // re-read after a reload elsewhere
- if (!mapReady) return;
- if (gridFor === id) return;
- gridFor = id;
- grid = null;
- gridName = null;
- reviewKey = null;
- editArea = false;
- clearGridLayers();
- refreshGridList();
+ if (mapReady) grid.forCase(id);
});
// save just the point (pin if moved, else center) as a navigable place — no image
@@ -2407,19 +1163,35 @@
</div>
<div class="body">
- <div
- class="map-wrap dark-surface"
- class:measuring={measureMode}
- class:selecting={selectArmed}
- class:grid-drawing={!!gridDraw}
- class:grabbing={hideOverlays}
- >
- <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}
-
+ {#if homeReady}
+ <MapSurface
+ bind:this={surface}
+ bind:engine
+ bind:element={mapEl}
+ bind:view={center}
+ bind:bearing
+ bind:ready={mapReady}
+ bind:refused={mapRefused}
+ {imagery}
+ {providerId}
+ {s2}
+ home={prefs.homeView}
+ labels={osmOverlay}
+ imperial={prefs.units === 'imperial'}
+ armed={measure.mode
+ ? 'measuring'
+ : capture.armed
+ ? 'selecting'
+ : grid.drawMode
+ ? 'grid-drawing'
+ : null}
+ grabbing={capture.hiding}
+ onclick={onMapClick}
+ onusage={() => imagery.refreshUsage()}
+ onwidgetload={(meter) => imagery.countLoad(meter)}
+ onwidgetauthfailure={onWidgetAuthFailure}
+ onwidgetfailed={onWidgetFailed}
+ >
<!-- 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}
@@ -2494,70 +1266,67 @@
{toggleFullscreen}
bind:osmOverlay
{baseIsImagery}
- {toolsOpen}
- {measureMode}
- {toggleTools}
- {gridMode}
+ toolsOpen={measure.panelOpen}
+ measureMode={measure.mode}
+ toggleTools={() => measure.togglePanel()}
+ gridMode={grid.on}
{toggleGridMode}
bind:savedOverlay
savedCount={savedWork.rows.length}
- referenceCount={uiState.refViewers.length}
- {openRefPicker}
+ referenceCount={refs.open.length}
+ openRefPicker={() => refs.openPicker()}
{setMeasureMode}
- {measureReadout}
+ measureReadout={measure.readout}
measureHint={MEASURE_HINT}
- {clearMeasure}
- {sunMode}
+ clearMeasure={() => measure.clear()}
+ sunMode={sky.on}
{toggleSunMode}
/>
- {#if sunMode}
+ {#if sky.on}
<SunPanel
- sky={sunSky}
- loading={sunLoading}
- day={sunDay}
- index={sunIndex}
- anchor={sunAnchor}
- placing={sunPlacing}
- ondate={(value) => {
- sunDay = value;
- sunSky = null;
- }}
- onindex={(value) => (sunIndex = value)}
- onplace={() => (sunPlacing = !sunPlacing)}
+ sky={sky.sky}
+ loading={sky.loading}
+ day={sky.day}
+ index={sky.index}
+ anchor={sky.anchor}
+ placing={sky.placing}
+ ondate={(value) => sky.setDay(value)}
+ onindex={(value) => sky.setIndex(value)}
+ onplace={() => sky.togglePlacing()}
onclose={toggleSunMode}
/>
{/if}
- {#if gridMode}
+ {#if grid.on}
<GridSearchPanel
- bind:collapsed={gridCollapsed}
- bind:renaming={renamingGrid}
- bind:renameText
- {commitRename}
- {startRename}
- {grid}
- toggleHidden={toggleGridHidden}
- hidden={gridHidden}
- coverage={gridCov}
- {reviewKey}
- {markReview}
- {reviewToPlace}
- {stopReview}
- {startReview}
- {editArea}
- {toggleEditArea}
- discard={discardOpenGrid}
- {deleteGrid}
- {gridName}
- bind:cellMetres={gridCellM}
- drawMode={gridDraw}
- {startDraw}
- polygonDraft={polyDraft}
- {confirmPolygon}
- cancelDraw={cancelGridDraw}
- savedGrids={savedOthers}
- {loadGrid}
+ bind:collapsed={grid.collapsed}
+ bind:renaming={grid.renaming}
+ bind:renameText={grid.renameText}
+ commitRename={() => grid.commitRename()}
+ startRename={() => grid.startRename()}
+ grid={grid.grid}
+ toggleHidden={() => grid.toggleHidden()}
+ hidden={grid.hidden}
+ coverage={grid.coverage}
+ reviewKey={grid.reviewKey}
+ markReview={grid.markReview}
+ reviewToPlace={grid.reviewToPlace}
+ stopReview={grid.stopReview}
+ startReview={() => grid.startReview()}
+ editArea={grid.editArea}
+ toggleEditArea={() => grid.toggleEditArea()}
+ discard={() => grid.discard()}
+ deleteGrid={(slug) => grid.remove(slug)}
+ gridName={grid.name}
+ bind:cellMetres={grid.cellMetres}
+ drawMode={grid.drawMode}
+ startDraw={(type) => grid.startDraw(type)}
+ polygonDraft={grid.draft}
+ confirmPolygon={() => grid.confirmPolygon()}
+ cancelDraw={() => grid.cancelDraw()}
+ savedGrids={grid.others}
+ loadGrid={(slug) => grid.load(slug)}
/>
{/if}
</div>
@@ -2565,10 +1334,10 @@
<!-- capture-frame outline: what the centred Capture will cover — only when
a centred capture is the intent (hovering the capture button, or
mid-capture) and not while drawing a marquee -->
- {#if captureMode === 'center' && (captureHover || capturing) && !selectArmed && !selRect}
+ {#if capture.mode === 'center' && (captureHover || capture.busy) && !capture.armed && !selRect}
<div
class="frame-overlay"
- style="width:{presetSize[0]}px;height:{presetSize[1]}px"
+ style="width:{capture.size[0]}px;height:{capture.size[1]}px"
aria-hidden="true"
></div>
{/if}
@@ -2634,88 +1403,9 @@
</button>
</div>
- <!-- imagery acquisition date: a compact, unobtrusive pill in the corner so
- it doesn't crowd the coordinates readout (item 2) -->
- {#if isSentinel && displayedBaseId === SENTINEL_ID}
- <!-- Sentinel-2 says what it is showing: a pinned day is the window the
- tiles were rendered from; otherwise the layer's default renders the
- most recent pass, which the calendar lookup has already named. -->
- <span
- class="date-pill mono"
- class:exact={!!s2PinnedDate}
- title={s2PinnedDate
- ? `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 ?? s2.latest ?? ''}
- {#if !s2PinnedDate}
- <span class="tag">{s2.latest ? 'latest' : 'most recent'}</span>
- {/if}
- {#if s2.layer !== DEFAULT_LAYER}
- <span class="tag layer">{s2.layerShort}</span>
- {/if}
- {#if s2.maxcc !== DEFAULT_MAXCC}
- <span class="tag" title="Passes over this cloud cover are not rendered"
- >≤{s2.maxcc}% cloud</span
- >
- {/if}
- </span>
- {:else if imageryDate?.supported}
- <span
- class="date-pill mono"
- title={imageryDate.source
- ? `Imagery acquired around this date (source: ${imageryDate.source})`
- : 'Approximate acquisition date of the imagery here'}
- >
- <Icon name="clock" size={11} />
- {imageryDate.date ?? '—'}
- </span>
- {/if}
-
- <!-- lightweight compass: click the rose to reset north; middle-drag the map
- to rotate; click the number to type an exact bearing (item 3) -->
- <div class="rotate-ctl">
- <button
- class="compass"
- onclick={resetNorth}
- 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)">
- <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>
- <span class="n">N</span>
- </button>
- {#if editingBearing}
- <!-- svelte-ignore a11y_autofocus -->
- <input
- class="input deg-input mono"
- type="number"
- min="0"
- max="359"
- bind:value={bearingInput}
- autofocus
- onblur={commitBearing}
- onkeydown={(e) => {
- if (e.key === 'Enter') commitBearing();
- else if (e.key === 'Escape') editingBearing = false;
- }}
- aria-label="Set bearing in degrees"
- />
- {:else}
- <button class="deg mono" onclick={startEditBearing} title="Click to type an exact angle">
- {bearing}°
- </button>
- {/if}
- </div>
-
<div class="capture-bar card">
<select class="select" bind:value={providerId} title="Imagery provider">
- {#each providers as p (p.id)}
+ {#each imagery.providers as p (p.id)}
<option value={p.id} disabled={p.needs_key}>
{p.label}{p.needs_key ? ' (needs API key)' : ''}
</option>
@@ -2738,16 +1428,16 @@
title="Requests to this billed provider this month"
>{usagePill}</span>
{/if}
- {#if currentProvider?.meter && displayedBaseId !== providerId}
+ {#if shown.fallenBack}
<span
class="fallback-pill"
- class:paused={meterBlocked}
- title={meterBlocked
+ class:paused={shown.blocked}
+ title={shown.blocked
? `${currentProvider.label} passed 90% of its monthly free tier. Free imagery is shown instead. Override in Settings to keep using it (billed).`
: `Eco mode shows free imagery at low zoom. Zoom in for ${currentProvider.label} detail. Toggle in Settings.`}
>
- <Icon name={meterBlocked ? 'alert' : 'leaf'} size={11} />
- {meterBlocked ? `${currentProvider.label} paused · free imagery` : 'eco · free imagery'}
+ <Icon name={shown.blocked ? 'alert' : 'leaf'} size={11} />
+ {shown.blocked ? `${currentProvider.label} paused · free imagery` : 'eco · free imagery'}
</span>
{/if}
<select class="select" bind:value={markerStyle} title="Marker style">
@@ -2791,35 +1481,36 @@
active mode. -->
<CaptureOptions
bind:menuEl={sizeMenuEl}
- bind:menuOpen={sizeMenuOpen}
- bind:mode={captureMode}
+ bind:menuOpen={capture.menuOpen}
+ bind:mode={capture.mode}
bind:hover={captureHover}
- {selectArmed}
- {capturing}
- blocked={captureBlocked}
- widgetBase={isWidgetBase}
- {runCapture}
+ selectArmed={capture.armed}
+ capturing={capture.busy}
+ blocked={capture.blocked}
+ widgetBase={capture.widget}
+ runCapture={() => capture.run()}
ratios={RATIOS}
- bind:ratio
+ bind:ratio={capture.ratio}
presets={PRESETS}
- bind:preset
- bind:customWidth={customW}
- bind:customHeight={customH}
- bind:resolution
- openScreenshot={() => (shotOpen = true)}
- openExtensionGate={() => (extGateOpen = true)}
+ bind:preset={capture.preset}
+ bind:customWidth={capture.customW}
+ bind:customHeight={capture.customH}
+ bind:resolution={capture.resolution}
+ openScreenshot={() => (capture.shotOpen = true)}
+ openExtensionGate={() => (capture.extGate = true)}
/>
</div>
<!-- floating reference-image windows (scratch aids over the map) -->
- {#each uiState.refViewers as v (v.id)}
+ {#each refs.open as pane (pane.id)}
<RefViewer
- viewer={v}
+ viewer={pane}
caseId={caseState.current?.id}
- onfocus={focusRef}
- onclose={closeRef}
+ onfocus={(id) => refs.focus(id)}
+ onclose={(id) => refs.close(id)}
/>
{/each}
- </div>
+ </MapSurface>
+ {/if}
<aside
class="captures"
@@ -2974,21 +1665,21 @@
/>
{/if}
-{#if shotOpen}
+{#if capture.shotOpen}
<ScreenshotDialog
view={center}
{fmtCoords}
- grab={grabView}
- file={fileScreenshotBlob}
- onclose={() => (shotOpen = false)}
+ grab={() => capture.grabView()}
+ file={(blob) => capture.fileBlob(blob)}
+ onclose={() => (capture.shotOpen = false)}
/>
{/if}
-{#if extGateOpen}
+{#if capture.extGate}
<ExtensionGate
- onclose={() => (extGateOpen = false)}
+ onclose={() => (capture.extGate = false)}
onsettings={() => {
- extGateOpen = false;
+ capture.extGate = false;
uiState.settingsTab = 'extension';
uiState.tool = 'settings';
}}
@@ -3015,13 +1706,13 @@
/>
{/if}
-{#if refPicker}
+{#if refs.picking}
<RefPicker
- media={refMedia}
- loading={refLoading}
+ media={refs.media}
+ loading={refs.loading}
caseId={caseState.current?.id}
- onpick={addRef}
- onclose={() => (refPicker = false)}
+ onpick={(item) => refs.add(item)}
+ onclose={() => (refs.picking = false)}
/>
{/if}
@@ -3034,31 +1725,6 @@
display: flex;
min-height: 0;
}
- .map-wrap {
- position: relative;
- flex: 1;
- min-width: 0;
- overflow: hidden;
- /* 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 {
- position: absolute;
- 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;
@@ -3098,18 +1764,6 @@
}
.temporal-layer-card button:hover { text-decoration: underline; }
.temporal-layer-card .quiet { margin-left: auto; color: var(--text-3); }
- /* Mid screen-grab: a widget capture crops the map element's *rectangle*, so
- everything we paint over the map (HUD, control clusters, capture bar,
- reference windows, the frame outline itself) would land in the capture.
- Hide our chrome for the grab and leave the map — Google's own credits live
- inside it and must ride along. The marker is the deliberate exception: the
- tile path burns one into its crop, so a screen crop keeps its own.
- :global is load-bearing — the reference windows are a child component, so
- a scoped selector would skip exactly the overlay the spec says must never
- be captured. */
- .map-wrap.grabbing > :global(:not(.map):not(.marker-overlay)) {
- visibility: hidden;
- }
.frame-overlay {
position: absolute;
top: 50%;
@@ -3196,23 +1850,6 @@
color: var(--text-3);
font-size: var(--fs-xs);
}
- /* imagery date: small, low-contrast pill tucked into the bottom-left corner */
- .date-pill {
- position: absolute;
- bottom: 12px;
- left: 12px;
- z-index: 600;
- display: flex;
- align-items: center;
- gap: 5px;
- padding: 3px 8px;
- border-radius: var(--r-sm);
- font-size: var(--fs-xs);
- color: var(--text-3);
- background: rgba(24, 24, 24, 0.7);
- backdrop-filter: blur(6px);
- pointer-events: none;
- }
/* fullscreen: the whole tool covers the viewport, above the app chrome */
.tool.fullscreen {
@@ -3235,11 +1872,6 @@
gap: 8px;
align-items: flex-start;
}
- .map-wrap.measuring :global(.map-surface),
- .map-wrap.selecting :global(.map-surface),
- .map-wrap.grid-drawing :global(.map-surface) {
- cursor: crosshair;
- }
/* draggable square handle for the area corners / polygon vertices */
:global(.grid-handle) {
@@ -3275,69 +1907,6 @@
white-space: nowrap;
}
- /* lightweight compass — no heavy card, just the rose + an editable readout */
- .rotate-ctl {
- position: absolute;
- top: 12px;
- right: 12px;
- z-index: 600;
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 4px;
- }
- .compass {
- position: relative;
- display: grid;
- place-items: center;
- width: 38px;
- height: 38px;
- color: var(--text-2);
- cursor: pointer;
- /* round translucent backing disc so the rose reads clearly over any
- imagery — same fill as the degree readout below (item 3) */
- border-radius: 50%;
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-1);
- }
- .compass:hover {
- color: var(--accent);
- }
- .compass svg {
- transition: transform 0.1s linear;
- }
- .compass .n {
- position: absolute;
- top: 1px;
- left: 50%;
- transform: translateX(-50%);
- font-size: 9px;
- font-weight: 700;
- color: var(--text-1);
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
- pointer-events: none;
- }
- .deg {
- min-width: 40px;
- text-align: center;
- padding: 2px 6px;
- border-radius: var(--radius-1);
- font-size: var(--fs-xs);
- color: var(--text-1);
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- cursor: text;
- }
- .deg:hover {
- color: var(--accent);
- }
- .deg-input {
- width: 52px;
- padding: 2px 4px;
- text-align: center;
- font-size: var(--fs-xs);
- }
.capture-bar {
position: absolute;
bottom: 34px;
@@ -3402,25 +1971,6 @@
.fallback-pill.paused {
color: var(--danger);
}
- /* a pinned date is a fact about the pixels; "latest" is an inference from the
- pass list — they must not look identical */
- .date-pill.exact {
- border-color: var(--ok, #46a758);
- }
- .date-pill .tag {
- font-family: var(--font-sans);
- font-size: 9px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--text-3);
- border: 1px solid var(--border);
- border-radius: 3px;
- padding: 0 3px;
- }
- .date-pill .tag.layer {
- color: var(--accent);
- border-color: color-mix(in srgb, var(--accent) 45%, transparent);
- }
.prov.dates {
display: flex;
align-items: center;
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 3d6d27f..94319b4 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -10,14 +10,16 @@ const cluster = readFileSync(
// 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');
-/** The tool and everything it is made of, for the checks that must hold of all of it. */
+/** The tool and everything it is made of, keyed by the path a failure names, 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');
+ const key = at.slice(at.indexOf('/satellite/') + 1).replace(/\/{2,}/g, '/');
+ files[key] = readFileSync(at, 'utf8');
}
return files;
}
@@ -136,25 +138,30 @@ describe('filing saved work from its details dialog', () => {
});
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('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;');
+ // When the case is read, where the windows live and how they stack are the
+ // store's (`satellite/state/refs.svelte.test.js`); the picker itself is
+ // `satellite/RefPicker.svelte`. What is this file's business is that the tool
+ // hands one store to all three places the windows are touched.
+ it('hands one store to the cluster, the picker and the windows', () => {
+ expect(source).toContain("import { createRefsState } from './satellite/state/refs.svelte.js'");
+ expect(source).toContain('referenceCount={refs.open.length}');
+ expect(source).toContain('openRefPicker={() => refs.openPicker()}');
+ expect(source).toContain('{#each refs.open as pane (pane.id)}');
+ expect(source).toContain('onpick={(item) => refs.add(item)}');
+ });
+
+ it('keeps the windows in the session, never in the case', () => {
+ // the store holds no list of its own: it reads and writes the tab's, which
+ // is what makes the windows survive a tool switch and die with the tab
+ expect(source).toContain('viewers: () => uiState.refViewers');
+ expect(source).toContain('setViewers: (windows) => (uiState.refViewers = windows)');
+ expect(source).not.toContain('refViewers:');
});
- 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');
+ it('leaves them out of a screen capture, wherever the crop is taken', () => {
+ // the rule is stated once, on the surface that owns the grab
+ const surfaces = satelliteSources();
+ expect(surfaces['satellite/MapSurface.svelte']).toContain('.map-wrap.grabbing');
});
});
@@ -187,7 +194,7 @@ describe('the saved panel is resizable', () => {
// 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'"
+ "e.button === 0 && e.shiftKey && !capture.armed && grid.drawMode !== 'rect'"
);
});
@@ -214,100 +221,83 @@ describe('filing saved work by dragging it in the panel', () => {
});
describe('sun and moon mode', () => {
+ // Where the path is anchored, what is asked of the backend and what reaches
+ // the map are the store's (`satellite/state/sky.svelte.test.js`), and the
+ // geometry under it is `lib/skyOverlay.js`, which has its own. What is left
+ // here is what the mode means *in this tool*: one map mode among the others.
it('is a map mode in the tool cluster, exclusive with the others', () => {
- expect(source).toContain('let sunMode = $state(false)');
+ expect(source).toContain("import { createSkyState } from './satellite/state/sky.svelte.js'");
expect(source).toContain('{toggleSunMode}');
// the same exclusivity the grid mode declares
- expect(source).toContain('if (selectArmed) toggleSelect()');
- expect(source).toContain('if (gridMode) toggleGridMode()');
- expect(source).toContain('else if (sunMode) toggleSunMode()'); // the Esc cascade
- });
-
- it('anchors the path to a fixed point, never to the moving view', () => {
- expect(source).toContain('let sunAnchor = $state.raw(null)');
- expect(source).toContain('sunAnchor = markerLatLng ?? { lat: center.lat, lon: center.lon }');
- // and a click can move it
- expect(source).toContain('if (sunPlacing) {');
- });
-
- it('draws only the arc the body sweeps while it is up', () => {
- expect(sky).toContain('export function upRuns(altitudes)');
- expect(sky).toContain('if (altitude >= 0)');
- expect(source).toContain('for (const run of upRuns(body.altitude))');
- expect(source).toContain('measure.destination(origin, azimuth, reach * scale)');
+ expect(source).toContain('if (capture.armed) toggleSelect()');
+ expect(source).toContain('if (grid.on) toggleGridMode()');
+ expect(source).toContain('else if (sky.on) toggleSunMode()'); // the Esc cascade
});
- it('ticks the arc hourly, longer every three hours', () => {
- expect(sky).toContain('if (minute % 60 || altitudes[i] < 0) return');
- expect(sky).toContain('long: minute % 180 === 0');
- expect(source).toContain('hourTicks(curve.minutes, body.altitude)');
+ it('opens on the moved pin when there is one, else on the view', () => {
+ expect(source).toContain('sky.open(markerLatLng ?? { lat: center.lat, lon: center.lon })');
});
- it('rides the body along its own ray, as close to the anchor as it is high', () => {
- // the anchor stands for the zenith and the arc for the horizon, the same
- // radial convention as the compass rosette
- expect(sky).toContain('return (90 - altitude) / 90;');
- 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('redraws the arc when the view moves, since it is drawn in metres', () => {
+ expect(source).toContain("return engine.on('view-settled', () => sky.draw())");
});
- it('leaves the ray bare while the body is under the horizon', () => {
- // a mark on it would claim the body is visible
- expect(source).toContain('if (!below) {');
- });
-
- it('draws the moon mark at its phase, worked out of the lit fraction', () => {
- expect(sky).toContain('Math.acos(clamped) * 180) / Math.PI');
- expect(sky).toContain('litPath(r, illuminated, phaseAngleOf(illuminated))');
- // a plan view has no vertical, so the bright-limb angle is not used here
- expect(sky).toContain('glyphRotation(waxing)');
- expect(sky).not.toContain('glyphRotation(waxing, ');
- });
-
- 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("tip: body.key === 'moon' ? `${reading} · ${sunSky.moon.phase}` : reading");
+ it('takes the handoff from Coords & Sky into the same mode', () => {
+ expect(source).toContain('const handed = uiState.skyAt');
+ expect(source).toContain('uiState.skyAt = null'); // consumed once, like gotoCoords
+ expect(source).toContain('if (!sky.on) toggleSunMode()');
+ // no computed value travels: the store asks for its own
+ expect(source).not.toContain('handed.sun');
});
- 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("dash: below ? '6 6' : null");
+ it('hands the panel the store, not a copy of its numbers', () => {
+ expect(source).toContain('<SunPanel');
+ expect(source).toContain('sky={sky.sky}');
+ expect(source).toContain('onindex={(value) => sky.setIndex(value)}');
});
+});
- it('scrubs the hour without asking the backend again', () => {
- // the whole day arrived in one response, so the slider reads an array
- expect(sky).toContain('export function nearestSample(clock, wanted)');
- expect(source).toContain('onindex={(value) => (sunIndex = value)}');
- expect(source).toMatch(/if \(sunDay\) params\.set\('date', sunDay\)/);
+describe('the capture button', () => {
+ // The frame, the two roads to a filed crop and every refusal are the store's
+ // (`satellite/state/capture.svelte.test.js`). What is this file's business is
+ // the wiring only it can do: the shared drag outline, the mode exclusivity,
+ // and giving the store the map element it does not own.
+ it('hands one store to the options popover and both dialogs', () => {
+ expect(source).toContain(
+ "import {\n createCaptureState,\n PRESETS,\n RATIOS,\n } from './satellite/state/capture.svelte.js';"
+ );
+ expect(source).toContain('<CaptureOptions');
+ expect(source).toContain('runCapture={() => capture.run()}');
+ expect(source).toContain('capturing={capture.busy}');
+ expect(source).toContain('{#if capture.shotOpen}');
+ expect(source).toContain('{#if capture.extGate}');
});
- it('labels a moment from the payload clock, not from arithmetic on minutes', () => {
- expect(source).toContain('curve.clock[sunIndex]');
- expect(source).not.toContain('Math.floor(minute / 60)');
+ it('asks the surface what drew the pixels, never the provider that was picked', () => {
+ // an eco or soft-block fallback means the two differ, and provenance has to
+ // name the imagery actually on screen
+ expect(source).toContain('provenance: () => surface.provenance()');
});
- 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.
- // 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');
+ it('shares one live outline with the grid rectangle, since one gesture draws both', () => {
+ expect(source).toContain('onRect: (rect) => (selRect = rect)');
+ expect(source).toContain('let selRect = $state(null);');
+ // …and the grid's own drag writes the same outline
+ expect(source).toContain('onChange: (rect) => (selRect = rect)');
});
- it('restretches the arc when the view moves, since it is drawn in metres', () => {
- expect(source).toContain("return engine.on('view-settled', () => drawSun())");
+ it('cannot be armed at the same time as a measure tool', () => {
+ // each direction is stated once: arming the marquee disarms measuring…
+ expect(source).toContain('onArm: () => setMeasureMode(null)');
+ // …and arming a measure tool disarms the marquee
+ expect(source).toContain('if (measure.setMode(mode)) capture.disarm()');
});
- it('takes the handoff from Coords & Sky into the same mode', () => {
- expect(source).toContain('const handed = uiState.skyAt');
- expect(source).toContain('uiState.skyAt = null'); // consumed once, like gotoCoords
- expect(source).toContain('if (!sunMode) toggleSunMode()');
- // no computed value travels: the map asks for its own
- expect(source).not.toContain('handed.sun');
+ it('gives the store the map element rather than reaching for one itself', () => {
+ expect(source).toContain('element: () => mapEl');
+ expect(source).toContain('function onSelectDrag(e)');
+ expect(source).toContain("element.addEventListener('mousedown', onSelectDrag, true)");
+ expect(source).toContain("element.removeEventListener('mousedown', onSelectDrag, true)");
});
});
@@ -328,24 +318,45 @@ describe('Satellite — lifecycle and the date line', () => {
expect(source).toContain('teardown?.();');
});
- it('takes the centre as the façade hands it over, and never rewraps it', () => {
+ it('takes the centre as the surface 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');
+ // in lib/map (facade.test.js). A second place reaching for wrapLon would be
+ // a second place that guarantee could be got wrong — and now that the map
+ // is a component, the tool only ever reads the view it reports.
+ const surfaces = satelliteSources();
+ expect(surfaces['satellite/MapSurface.svelte']).toContain(
+ "engine.on('view-settled', (settled) => {"
+ );
+ expect(surfaces['satellite/MapSurface.svelte']).toContain(
+ 'view = { lat: settled.lat, lon: settled.lon, zoom: settled.zoom };'
+ );
+ for (const [name, text] of Object.entries(surfaces)) {
+ expect(text, name).not.toContain('wrapLon');
+ }
+ });
+
+ it('builds the map in one place, so a second one costs nothing to mount', () => {
+ // The engine, its basemap and everything describing the pixels are the
+ // surface's; the tool mounts one today and several for Compare.
+ const surfaces = satelliteSources();
+ expect(surfaces['satellite/MapSurface.svelte']).toContain(
+ "import { createMapEngine } from '../../lib/map/engine.js';"
+ );
+ expect(source).toContain("import MapSurface from './satellite/MapSurface.svelte';");
+ expect(source).not.toContain('createMapEngine');
+ expect(source).not.toContain('createBasemaps');
});
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');
+ for (const [name, text] of Object.entries(satelliteSources())) {
+ expect(text, name).not.toContain('map.setView');
+ expect(text, name).not.toContain('map.getCenter');
+ expect(text, name).not.toContain('map.containerPointToLatLng');
+ expect(text, name).not.toContain('map.latLngToContainerPoint');
+ }
});
it('names no engine at all, not even in a class or a comment', () => {
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 2c38e27..b5c805b 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -11,7 +11,10 @@
import { formatCoords, parseHomeView } from '../lib/coords.js';
import { USAGE_LINKS, ECO_MAX_ZOOM } from '../lib/usage.js';
import { probeKey, googleMapsLoadedKey } from '../lib/map/gmaps.js';
- import { extensionVersion } from '../lib/extBridge.js';
+ import {
+ extensionVersion, extensionState, pingExtensions, reloadExtension, onBridgeHello,
+ } from '../lib/extBridge.js';
+ import { classify, reloadLanded } from '../lib/extInstall.js';
import { CASE_FOLDER_LABEL, saveDestination } from '../lib/exportDest.js';
import Icon from '../components/Icon.svelte';
import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
@@ -157,6 +160,14 @@
let tokenShown = $state(false);
// Read once per mount because an extension installed mid-session needs a reload.
const extDetected = extensionVersion();
+ // What the app's own extension folder holds, and which copy the browser runs.
+ // The probe is authoritative in this tab: the <html> marker above is written by
+ // whichever bridge ran last, and two can be loaded at once (extInstall.js).
+ // Seeded from the startup verdict so the tab has content on its first frame,
+ // then re-probed on open: the copies loaded can change while the app is up.
+ let extState = $state(updatesState.extension);
+ let extProbed = $state(false);
+ let extBusy = $state('');
// Every dot in this tool comes from the same place as the one on the Settings
// icon, so a tab can never disagree with the rail that led the user to it.
@@ -187,11 +198,120 @@
ingestToken = r.ingest_token;
toast('New token minted. Every extension must pair again', 'ok', 6000);
}
+
+ // Ask the server what its folder holds and the browser which copies are
+ // loaded, then let extInstall.js reconcile the two.
+ async function refreshExtension() {
+ const [server, ...probes] = await Promise.all([
+ api.get('/api/settings/extension'),
+ ...probeExtension(),
+ ]);
+ return adoptExtState(classify(server, { bridges: probes[0], managed: probes[1] }));
+ }
+
+ // One verdict, two readers: this tab and the dots. Writing it back is what
+ // makes a dot clear on the click that fixed it instead of on the next reload —
+ // the rule this tool has for every other badge it owns.
+ function adoptExtState(verdict) {
+ extState = verdict;
+ updatesState.extension = verdict;
+ if (verdict.installed?.version) updatesState.extensionInstalled = verdict.installed.version;
+ return verdict;
+ }
+
+ // Both probes, in parallel. `ping` counts what is loaded — every extension
+ // version ever shipped answers it — and `ext-state` identifies the copies new
+ // enough to be managed. An install older than the update button is loud on the
+ // first and silent on the second, which is how it gets recognised instead of
+ // being reported as absent.
+ const probeExtension = () => [pingExtensions(), extensionState()];
+
+ async function installExtension() {
+ extBusy = 'install';
+ try {
+ const server = await api.post('/api/settings/extension/install');
+ const [bridges, managed] = await Promise.all(probeExtension());
+ adoptExtState(classify(server, { bridges, managed }));
+ if (extState.staged) {
+ toast('Files are staged. Close the browser and press again', 'warn', 8000);
+ } else if (extState.status === 'owned' || extState.status === 'duplicate') {
+ toast('Extension folder written', 'ok');
+ } else {
+ // Written, but this browser is not running it yet — which is the whole
+ // remaining step, so the toast says it rather than reporting success.
+ toast('Folder written. Load it in your browser to finish', 'ok', 8000);
+ }
+ } catch (e) {
+ toast(e.message || 'Could not write the extension folder', 'error');
+ } finally {
+ extBusy = '';
+ }
+ }
+
+ async function updateExtension() {
+ extBusy = 'update';
+ try {
+ const server = await api.post('/api/settings/extension/install');
+ if (server.staged) {
+ const [bridges, managed] = await Promise.all(probeExtension());
+ adoptExtState(classify(server, { bridges, managed }));
+ toast('Files are staged. Close the browser and press again', 'warn', 8000);
+ return;
+ }
+ // The id off the fresh response, not the one the last probe saw: this pass
+ // may have minted it.
+ const installId = server.folder?.install_id ?? extState?.installId;
+ // A refusal here is inconclusive, not fatal: the extension dies mid-reply
+ // by design. Either way the verdict comes from probing afterwards.
+ try {
+ await reloadExtension(installId);
+ } catch {
+ /* verified below */
+ }
+ // The restart is asynchronous and re-injects the bridge when it lands, so
+ // the first probe can still reach the context that is going away.
+ for (let attempt = 0; attempt < 4; attempt++) {
+ await new Promise((r) => setTimeout(r, 400));
+ const [bridges, managed] = await Promise.all(probeExtension());
+ if (reloadLanded(server, { bridges, managed })) {
+ adoptExtState(classify(server, { bridges, managed }));
+ toast(`Extension updated to v${extState.installed?.version ?? server.bundled.version}`, 'ok');
+ return;
+ }
+ }
+ const [bridges, managed] = await Promise.all(probeExtension());
+ adoptExtState(classify(server, { bridges, managed }));
+ toast('Folder updated. Reload the extension in your browser', 'warn', 8000);
+ } catch (e) {
+ toast(e.message || 'Could not update the extension', 'error');
+ } finally {
+ extBusy = '';
+ }
+ }
+
+ async function copyExtensionPath() {
+ const path = extState?.path || '';
+ try {
+ await navigator.clipboard.writeText(path);
+ toast('Path copied', 'ok');
+ } catch {
+ toast('Could not copy. Select the path and copy it', 'warn');
+ }
+ }
+
+ async function revealExtension() {
+ try {
+ await api.post('/api/settings/extension/reveal');
+ } catch (e) {
+ toast(e.message || 'Could not open the folder', 'error');
+ }
+ }
// Keep home-view fields as text until change so partial numbers remain editable.
let home = $state({ lat: '', lon: '', zoom: '' });
let mention = $state('');
let postTarget = $state('x');
let postPrefill = $state(true);
+ let reversePrefill = $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 first
let proofPlaceAuto = $state(true);
@@ -405,6 +525,7 @@
mention = s.post_mention ?? '';
postTarget = s.post_target ?? 'x';
postPrefill = s.post_prefill ?? true;
+ reversePrefill = s.reverse_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
@@ -534,6 +655,22 @@
if (tab === 'system' && !report) loadReport();
});
+ // Same rule for the extension: one local read and one bridge probe, when the
+ // tab that shows them is opened.
+ $effect(() => {
+ if (tab === 'extension' && !extProbed) {
+ extProbed = true;
+ refreshExtension().catch((e) => toast(`Could not read the extension: ${e.message}`, 'warn'));
+ }
+ });
+
+ // A bridge announcing itself means the extension just (re)attached, which is
+ // what an update looks like from here. Re-probe so the tab follows without a
+ // page reload.
+ onMount(() => onBridgeHello(() => {
+ if (tab === 'extension') refreshExtension().catch(() => {});
+ }));
+
$effect(() => {
if (uiState.tool !== 'settings') return;
const aliases = { preferences: 'general', about: 'system' };
@@ -685,6 +822,7 @@
{savePrefs}
{saveHome}
bind:proofPlaceAuto
+ bind:reversePrefill
/>
{/if}
@@ -729,10 +867,15 @@
{#if tab === 'extension'}
<ExtensionTab
- {about}
{badges}
{extDetected}
{extOutdated}
+ {extState}
+ {extBusy}
+ {installExtension}
+ {updateExtension}
+ {copyExtensionPath}
+ {revealExtension}
{ingestToken}
{copyToken}
{ensureToken}
diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.js
index 6c8c89f..45dcdfe 100644
--- a/frontend/src/tools/Settings.test.js
+++ b/frontend/src/tools/Settings.test.js
@@ -116,6 +116,13 @@ describe('Settings sections', () => {
expect(general).toContain('Off, the composer asks each time.');
});
+ it('switches the reverse-search hand-off from General, checked by default', () => {
+ expect(general).toContain('reverse_prefill: reversePrefill');
+ expect(shell).toContain('reversePrefill = s.reverse_prefill ?? true');
+ expect(general).toContain('Let the extension open the engine with the image');
+ expect(general).toContain('so it\n searches straight away');
+ });
+
it('manages all three export folders from Storage', () => {
expect(shell).toContain("{ id: 'notes', label: 'Note PDFs' }");
expect(shell).toContain("{ id: 'media', label: 'Media copies' }");
diff --git a/frontend/src/tools/overview.fixture.svelte.js b/frontend/src/tools/overview.fixture.svelte.js
new file mode 100644
index 0000000..c4d082b
--- /dev/null
+++ b/frontend/src/tools/overview.fixture.svelte.js
@@ -0,0 +1,46 @@
+/**
+ * Reactive stand-in for `Overview.render.test.js`.
+ *
+ * The page re-reads the case out of an effect, so a plain object would never make it
+ * run again when the test opens or closes a case. Runes only work in `.svelte.js` and
+ * a `vi.mock` factory runs inside the `.test.js`, so the state lives here.
+ *
+ * Its own file rather than the views fixture next door: this one carries the case
+ * `list` — the front door offers the cases you have, and the header prefers the
+ * list's stamp over the manifest's.
+ */
+export const caseState = $state({
+ current: null,
+ list: [],
+ folders: [],
+ loading: false,
+ rev: 0,
+});
+
+export const uiState = $state({ tool: 'overview', settingsTab: null, guideSection: null });
+
+export const prefs = $state({ updateDismissedVersion: '', units: 'metric' });
+
+export const updatesState = $state({
+ app: null,
+ scrapers: null,
+ extensionInstalled: null,
+ extensionBundled: '',
+ extension: null,
+});
+
+/** Put the fixture back the way every test starts. */
+export function resetOverviewFixture() {
+ caseState.current = null;
+ caseState.list = [];
+ caseState.rev = 0;
+ uiState.tool = 'overview';
+ uiState.settingsTab = null;
+ uiState.guideSection = null;
+ prefs.updateDismissedVersion = '';
+ prefs.units = 'metric';
+ updatesState.app = null;
+ updatesState.extensionInstalled = null;
+ updatesState.extensionBundled = '';
+ updatesState.extension = null;
+}
diff --git a/frontend/src/tools/overview/PlaceMap.render.test.js b/frontend/src/tools/overview/PlaceMap.render.test.js
new file mode 100644
index 0000000..006190e
--- /dev/null
+++ b/frontend/src/tools/overview/PlaceMap.render.test.js
@@ -0,0 +1,180 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+/**
+ * The home map: what it asks the engine for, and what it never asks for.
+ *
+ * The map itself is drawn in a real browser (`e2e/home-guide.spec.js`); what is
+ * worth pinning here is the contract with `lib/map`, which a canvas cannot show.
+ * Three halves of it: one basemap and no choice of one, the points framed once
+ * rather than on every re-read, and nothing on the layer that writes.
+ */
+
+const fitPoints = vi.fn(() => true);
+const engineDestroy = vi.fn();
+const engine = { fitPoints, getZoom: () => 3, destroy: engineDestroy, impl: {} };
+const createMapEngine = vi.fn(async () => engine);
+vi.mock('../../lib/map/engine.js', () => ({ createMapEngine: (...args) => createMapEngine(...args) }));
+
+const show = vi.fn();
+const dispose = vi.fn();
+vi.mock('../../lib/map/basemap.js', () => ({
+ createBasemaps: () => ({ show, dispose, setLabels: vi.fn() }),
+}));
+
+const set = vi.fn();
+const surfaceDestroy = vi.fn();
+vi.mock('../../lib/map/surface.js', () => ({
+ createSurface: () => ({ set, destroy: surfaceDestroy }),
+}));
+
+const PROVIDERS = [
+ {
+ id: 'esri-world-imagery',
+ label: 'Esri World Imagery',
+ attribution: 'Esri',
+ max_zoom: 19,
+ tile_size: 256,
+ oversample: 1,
+ },
+ { id: 'mapbox', label: 'Mapbox Satellite', max_zoom: 22, tile_size: 512, oversample: 1, meter: 'mapbox' },
+];
+const get = vi.fn(async () => PROVIDERS);
+vi.mock('../../lib/api.js', () => ({ api: { get: (...args) => get(...args) }, ApiError: Error }));
+
+const { default: PlaceMap } = await import('./PlaceMap.svelte');
+const { mapProps, resetMapProps } = await import('./placemap.fixture.svelte.js');
+
+const PINS = [
+ { id: 'p1', kind: 'place', title: 'Quai sud', lat: 49.98, lon: 36.25 },
+ { id: 'p2', kind: 'capture', title: '', lat: 49.99, lon: 36.3 },
+];
+
+const opened = vi.fn();
+let live = null;
+let target = null;
+
+async function settle() {
+ for (let index = 0; index < 8; index += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function open(over = {}) {
+ target = document.createElement('div');
+ document.body.append(target);
+ resetMapProps({ pins: PINS, total: PINS.length, onopen: opened, ...over });
+ live = mount(PlaceMap, { target, props: mapProps });
+ flushSync();
+ await settle();
+ return target;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ fitPoints.mockReturnValue(true);
+ createMapEngine.mockResolvedValue(engine);
+ get.mockResolvedValue(PROVIDERS);
+});
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ target?.remove();
+ target = null;
+ document.body.innerHTML = '';
+});
+
+describe('the case on the home map', () => {
+ it('shows the free imagery, and offers no other', async () => {
+ await open();
+ expect(get).toHaveBeenCalledWith('/api/satellite/providers');
+ const [provider, id, cell] = show.mock.calls.at(-1);
+ expect(provider.id).toBe('esri-world-imagery');
+ expect(id).toBe('esri-world-imagery');
+ expect(cell).toBe(256);
+ expect(show).toHaveBeenCalledTimes(1);
+ // no picker, no labels toggle, nothing that would spend a metered basemap
+ expect(target.querySelector('select')).toBeNull();
+ });
+
+ it('frames the points it was handed, capped short of a rooftop', async () => {
+ await open();
+ const [points, options] = fitPoints.mock.calls.at(-1);
+ expect(points).toEqual(PINS);
+ expect(options.maxZoom).toBe(15);
+ expect(options.padding).toBeGreaterThan(0);
+ });
+
+ it('draws one dot per point, named on hover where the row has a title', async () => {
+ await open();
+ const shapes = set.mock.calls.at(-1)[0];
+ expect(shapes.map((shape) => shape.kind)).toEqual(['dot', 'dot']);
+ expect(shapes[0]).toMatchObject({ id: 'p1', at: { lat: 49.98, lon: 36.25 } });
+ expect(shapes[0].tip.text).toBe('Quai sud');
+ // an untitled capture has nothing to read out, so it says nothing
+ expect(shapes[1].tip).toBeUndefined();
+ });
+
+ it('draws nothing that writes: the map is a reading', async () => {
+ await open();
+ for (const shape of set.mock.calls.at(-1)[0]) {
+ expect(shape.onClick).toBeUndefined();
+ expect(shape.onContextMenu).toBeUndefined();
+ }
+ });
+
+ it('leaves the camera alone when the same case is read again', async () => {
+ await open();
+ expect(fitPoints).toHaveBeenCalledTimes(1);
+ // coming back to this tab re-reads the case and answers the same points: a
+ // refit here would snatch the view back from wherever it was panned to
+ mapProps.pins = PINS.map((pin) => ({ ...pin }));
+ await settle();
+ expect(fitPoints).toHaveBeenCalledTimes(1);
+ });
+
+ it('redraws and reframes when the points themselves change', async () => {
+ await open();
+ mapProps.pins = [{ id: 'p3', kind: 'place', title: 'Depot', lat: 12, lon: 77 }];
+ mapProps.total = 1;
+ await settle();
+ expect(fitPoints).toHaveBeenCalledTimes(2);
+ expect(set.mock.calls.at(-1)[0].map((shape) => shape.id)).toEqual(['p3']);
+ });
+
+ it('presses through to the map tool, and says how much of the case is drawn', async () => {
+ await open({ pins: PINS, total: 9 });
+ expect(target.textContent).toContain('9 points on the map');
+ expect(target.textContent).toContain('2 drawn');
+ target.querySelector('.foot').click();
+ flushSync();
+ expect(opened).toHaveBeenCalled();
+ });
+
+ it('says what it cannot draw when the browser refuses WebGL', async () => {
+ createMapEngine.mockRejectedValue(new Error('no webgl'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await open();
+ expect(target.textContent).toContain('needs WebGL');
+ // the count is still true, and the way through to the map still works
+ expect(target.textContent).toContain('2 points on the map');
+ expect(get).not.toHaveBeenCalled();
+ });
+
+ it('still draws the case when the basemap catalogue cannot be read', async () => {
+ get.mockRejectedValue(new Error('offline'));
+ await open();
+ expect(show).not.toHaveBeenCalled();
+ expect(set.mock.calls.at(-1)[0]).toHaveLength(2);
+ });
+
+ it('takes the map down with it', async () => {
+ await open();
+ unmount(live);
+ live = null;
+ expect(dispose).toHaveBeenCalled();
+ expect(surfaceDestroy).toHaveBeenCalled();
+ expect(engineDestroy).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/tools/overview/PlaceMap.svelte b/frontend/src/tools/overview/PlaceMap.svelte
new file mode 100644
index 0000000..3eccb9e
--- /dev/null
+++ b/frontend/src/tools/overview/PlaceMap.svelte
@@ -0,0 +1,239 @@
+<script>
+ /**
+ * The case's saved points, on the ground they were saved from.
+ *
+ * A reading and nothing else: satellite imagery under the points, the wheel and
+ * the drag to look around them, and no act that writes. Everything a point can be
+ * worked on with — the card, the capture frame, the other basemaps, the hover tie
+ * to the tree — belongs to the Map tool, and the foot of this plate is the way
+ * through to it.
+ *
+ * **One basemap, never chosen.** The free imagery (`lib/usage.js`), which needs no
+ * key and counts against no meter, so a home page cannot spend anybody's quota and
+ * has no picker to explain. It is the same layer stack the Map tool draws
+ * (`lib/map`), through the same façade — the plate that stood here before drew its
+ * own projection, and a second projection is a second thing that can disagree with
+ * the map.
+ *
+ * It costs tiles, which is the one thing arriving on the home page did not use to
+ * do. Deliberate: without a map under them the points said "one street or three
+ * countries" and nothing more.
+ */
+ import { onMount } from 'svelte';
+ import { api } from '../../lib/api.js';
+ import { createMapEngine } from '../../lib/map/engine.js';
+ import { createBasemaps } from '../../lib/map/basemap.js';
+ import { createSurface } from '../../lib/map/surface.js';
+ import { FREE_IMAGERY, layerCell } from '../../lib/usage.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let { pins = [], total = 0, imperial = false, onopen } = $props();
+
+ /** How deep the opening frame goes. A case whose points sit on one corner would
+ * otherwise open on a rooftop, which says nothing about where the case is. */
+ const FRAME_ZOOM = 15;
+ /** Room left around the outermost points, so an edge one is drawn whole. */
+ const FRAME_PAD = 26;
+ /** The dot a saved point is drawn as. Small enough that a street's worth of them
+ * stays countable, ringed so it reads over pale sand and over dark water. */
+ const DOT = { radius: 5, fillOpacity: 1, stroke: '#141414', strokeWidth: 1.5 };
+
+ let mapEl = $state();
+ let refused = $state(false);
+ let engine = null;
+ let layer = null;
+ /** The point set the camera was last framed on, so re-reading the same case on
+ * the way back to this tab does not snatch the view back from the analyst. */
+ let framed = null;
+
+ const signature = $derived(pins.map((pin) => `${pin.id}@${pin.lat},${pin.lon}`).join('|'));
+
+ /** A token's value, since the map is painted rather than styled. */
+ function themeColour(name, fallback) {
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return value || fallback;
+ }
+
+ /**
+ * One colour for every point, whatever was saved there.
+ *
+ * The Map tool tells a place from a capture because it is worked on there; here
+ * the points are one layer saying where the case is, and a legend nobody asked
+ * for would be the only thing to read.
+ */
+ function dots() {
+ const fill = themeColour('--accent', '#e8a33d');
+ return pins.map((pin) => ({
+ id: pin.id,
+ kind: 'dot',
+ at: { lat: pin.lat, lon: pin.lon },
+ // above the cursor, so the reading never covers the dot it names
+ tip: pin.title ? { text: pin.title, direction: 'top', offset: [0, -10] } : undefined,
+ style: { ...DOT, fill },
+ }));
+ }
+
+ function draw() {
+ layer?.set(dots());
+ }
+
+ function frame() {
+ if (!engine?.fitPoints(pins, { padding: FRAME_PAD, maxZoom: FRAME_ZOOM })) return;
+ framed = signature;
+ }
+
+ // Svelte only honours a cleanup returned from a *synchronous* onMount, and the
+ // build below has to await the engine — so the teardown is handed over late.
+ onMount(() => {
+ let teardown = null;
+ let gone = false;
+ build().then((cleanup) => {
+ if (gone) cleanup?.();
+ else teardown = cleanup;
+ });
+ return () => {
+ gone = true;
+ teardown?.();
+ };
+ });
+
+ async function build() {
+ const [first] = pins;
+ try {
+ engine = await createMapEngine(mapEl, {
+ view: { lat: first?.lat ?? 0, lon: first?.lon ?? 0, zoom: 3 },
+ imperial,
+ });
+ } catch (error) {
+ // The map draws through WebGL and a browser can refuse it. The count below
+ // is still true, so the plate says what it cannot draw rather than leaving
+ // an empty panel.
+ console.error(error);
+ refused = true;
+ return null;
+ }
+ layer = createSurface(engine);
+ draw();
+ frame();
+ const basemaps = createBasemaps(engine);
+ await showImagery(basemaps);
+ return () => {
+ basemaps.dispose();
+ layer.destroy();
+ engine.destroy();
+ layer = null;
+ engine = null;
+ };
+ }
+
+ async function showImagery(basemaps) {
+ let provider = null;
+ try {
+ const catalogue = await api.get('/api/satellite/providers');
+ provider = (Array.isArray(catalogue) ? catalogue : []).find(
+ (entry) => entry.id === FREE_IMAGERY
+ );
+ } catch {
+ /* the points still read on the empty plate */
+ }
+ // `engine` is gone when the page was left while this was in flight
+ if (!provider || !engine) return;
+ // This provider does not oversample, so its grid is the same at every zoom
+ // and the cell is read once.
+ basemaps.show(provider, provider.id, layerCell(provider, engine.getZoom()));
+ }
+
+ // A case re-read on the way back to this tab answers with the same points, and
+ // redrawing those must not move a camera the analyst put where they wanted it.
+ $effect(() => {
+ const points = signature;
+ if (!layer) return;
+ draw();
+ if (points !== framed) frame();
+ });
+</script>
+
+<div class="plate">
+ <div class="frame">
+ <div class="map" bind:this={mapEl}></div>
+ {#if refused}
+ <p class="refused">The map needs WebGL, which this browser does not have.</p>
+ {/if}
+ </div>
+
+ <button class="foot" onclick={onopen} title="Open the map">
+ <Icon name="pin" size={13} />
+ <span>{total} {total === 1 ? 'point' : 'points'} on the map</span>
+ {#if total > pins.length}<em>{pins.length} drawn</em>{/if}
+ <span class="go"><Icon name="arrowRight" size={13} /></span>
+ </button>
+</div>
+
+<style>
+ .plate {
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ overflow: hidden;
+ }
+
+ .frame {
+ position: relative;
+ aspect-ratio: 1.7;
+ min-height: 210px;
+ /* the engine's own controls and its credit line stay inside this box, so a
+ dialog opened over the page still lands on top of them */
+ isolation: isolate;
+ /* nothing is stacked over this map, so the zoom buttons take the corner they
+ are built for rather than the room the Map tool's cluster needs */
+ --map-controls-top: 8px;
+ }
+ .map {
+ position: absolute;
+ inset: 0;
+ background: var(--bg-2);
+ }
+
+ .refused {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-content: center;
+ margin: 0;
+ padding: 0 24px;
+ text-align: center;
+ color: var(--text-2);
+ }
+
+ .foot {
+ display: flex;
+ width: 100%;
+ align-items: center;
+ gap: 7px;
+ padding: 8px 11px;
+ border-top: 1px solid var(--border);
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ text-align: left;
+ transition: color 0.14s var(--ease);
+ }
+ .foot:hover,
+ .foot:focus-visible {
+ color: var(--text-1);
+ outline: none;
+ }
+ .foot em {
+ font-style: normal;
+ opacity: 0.75;
+ }
+ .go {
+ display: flex;
+ margin-left: auto;
+ opacity: 0;
+ transition: opacity 0.14s var(--ease);
+ }
+ .foot:hover .go,
+ .foot:focus-visible .go {
+ opacity: 1;
+ }
+</style>
diff --git a/frontend/src/tools/overview/placemap.fixture.svelte.js b/frontend/src/tools/overview/placemap.fixture.svelte.js
new file mode 100644
index 0000000..3f6dbfe
--- /dev/null
+++ b/frontend/src/tools/overview/placemap.fixture.svelte.js
@@ -0,0 +1,17 @@
+/**
+ * Reactive props for `PlaceMap.render.test.js`.
+ *
+ * What the test is about is the second read: the same case answered again must not
+ * move the camera, and a different set of points must. That only happens if the
+ * props are reactive, runes only work in `.svelte.js`, so they live here.
+ */
+export const mapProps = $state({ pins: [], total: 0, imperial: false, onopen: () => {} });
+
+/** Put the props back the way every test starts. */
+export function resetMapProps(over = {}) {
+ mapProps.pins = [];
+ mapProps.total = 0;
+ mapProps.imperial = false;
+ mapProps.onopen = () => {};
+ Object.assign(mapProps, over);
+}
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
new file mode 100644
index 0000000..78118b4
--- /dev/null
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -0,0 +1,463 @@
+<script>
+ /**
+ * One map, complete: the engine, its basemap, and everything that describes
+ * the pixels on it.
+ *
+ * A tool mounts one of these today and several tomorrow (SPEC v3, Compare),
+ * which is the whole reason it exists as a component rather than as the top
+ * of Satellite.svelte. So the line it draws is between *the map* and *the
+ * work being done on it*: which imagery is showing, which way is up, when the
+ * imagery was taken and how far a pixel goes all belong to the surface and
+ * would be wrong shared between two of them. The capture frame, the marks,
+ * the saved pins and the panels are the tool's, and arrive through `children`
+ * — rendered inside this wrapper so they are positioned against this map.
+ *
+ * The camera reports out rather than being driven in: the engine settles a
+ * pan on a whole zoom level and wraps a longitude back inside ±180, and a
+ * parent that assumed otherwise would fight it. `engine` and `element` are
+ * handed back for the acts a tool owns — flying to a saved point, and the
+ * drag gestures it arms over the map.
+ *
+ * The catalogue and the month's tally are shared (state/imagery.svelte.js):
+ * a tile counted against the month is counted once, however many surfaces
+ * drew it. Which provider *this* surface shows is its own.
+ */
+ import { onMount, tick } from 'svelte';
+ import { createMapEngine } from '../../lib/map/engine.js';
+ import { createBasemaps } from '../../lib/map/basemap.js';
+ import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ /** The shared catalogue + meter (state/imagery.svelte.js). */
+ imagery,
+ /** The basemap this surface is asked to show. */
+ providerId,
+ /** This surface's Sentinel-2 choices, when that basemap is on it. */
+ s2 = null,
+ /** Labels laid over the imagery. Only ever meaningful over a satellite base. */
+ labels = false,
+ /** Scale bar in miles rather than metres. */
+ imperial = false,
+ /** The view the map opens on. Read once, at build. */
+ home,
+ /** Where the camera is now. Reported out; the engine is what moves it. */
+ view = $bindable({ lat: 0, lon: 0, zoom: 2 }),
+ bearing = $bindable(0),
+ /** The façade, once the map is up. Null while it is not. */
+ engine = $bindable(null),
+ /** The map container, for the drag gestures a tool arms over it. */
+ element = $bindable(null),
+ ready = $bindable(false),
+ refused = $bindable(false),
+ /** A mode armed above the map, which the cursor says: 'measuring' |
+ * 'selecting' | 'grid-drawing' | null. */
+ armed = null,
+ /** Hide this surface's own chrome for a screen capture. */
+ grabbing = false,
+ /** A click on the map, `{ lat, lon }`. */
+ onclick = () => {},
+ /** Metered tiles went out. The proxy counted them; the tally is just stale. */
+ onusage = () => {},
+ /** A widget basemap was built, which is one billed map load. Nothing but
+ * this page saw it happen, so it has to be counted here or not at all. */
+ onwidgetload = () => {},
+ onwidgetauthfailure = () => {},
+ onwidgetfailed = () => {},
+ children,
+ } = $props();
+
+ let mapEl = $state();
+ let basemaps = null;
+ let editingBearing = $state(false);
+ let bearingInput = $state('');
+ // Acquisition date of the imagery under the crosshair — Esri only.
+ let imageryDate = $state(null); // { supported, date, source } | null
+ let dateRequest = 0;
+ let dateTimer;
+
+ /**
+ * What this surface actually shows, which is not always what it was asked
+ * for: a billed basemap steps aside when the month is nearly spent or the
+ * view is zoomed out. The capture and the imagery date follow the display,
+ * so provenance always matches the pixels.
+ */
+ const shown = $derived(imagery.displayed(providerId, view.zoom, s2?.variant));
+
+ /** A pinned Sentinel-2 day *is* the acquisition date — the one provider that
+ * can answer "when was this taken?" without being asked. */
+ const pinnedDay = $derived(
+ shown.provider?.id === SENTINEL_ID && s2?.window.from ? s2.window.from : null
+ );
+
+ export function resize() {
+ engine?.resize();
+ }
+
+ /** What a capture of this surface must record: the pixels' own provenance. */
+ export function provenance() {
+ return { provider: shown.id, imageryDate: pinnedDay ?? imageryDate?.date ?? null };
+ }
+
+ // Svelte only honours a cleanup returned from a *synchronous* onMount, and the
+ // build below has to await the engine. So onMount stays synchronous and hands
+ // back a teardown that runs whatever the async build registered.
+ onMount(() => {
+ let teardown = null;
+ let gone = false;
+ build().then((cleanup) => {
+ if (gone) cleanup?.();
+ else teardown = cleanup;
+ });
+ return () => {
+ gone = true;
+ teardown?.();
+ };
+ });
+
+ async function build() {
+ view = { ...home };
+ try {
+ engine = await createMapEngine(mapEl, { view, 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 surface says so instead of drawing an empty
+ // panel and leaving the analyst to wonder which part broke.
+ console.error(e);
+ refused = true;
+ return null;
+ }
+ element = mapEl;
+ basemaps = createBasemaps(engine, {
+ onMeteredTiles: onusage,
+ // one billed map load, counted where it happens (the proxy can't see it)
+ onWidgetLoad: (provider) => onwidgetload(provider.meter),
+ onWidgetAuthFailure: onwidgetauthfailure,
+ onWidgetFailed: onwidgetfailed,
+ });
+ showBasemap();
+ basemaps.setLabels(labels);
+ // the façade wraps the centre back inside ±180 for us, which is what every
+ // route a capture reaches enforces
+ const offSettled = engine.on('view-settled', (settled) => {
+ view = { lat: settled.lat, lon: settled.lon, zoom: settled.zoom };
+ });
+ const offRotate = engine.on('rotate', (turned) => {
+ bearing = Math.round(turned.bearing);
+ });
+ const offClick = engine.on('click', (at) => onclick(at));
+ ready = true;
+ return () => {
+ offSettled();
+ offRotate();
+ offClick();
+ basemaps.dispose();
+ engine.destroy();
+ engine = null;
+ element = null;
+ ready = false;
+ };
+ }
+
+ function showBasemap() {
+ if (!shown.provider || !basemaps) return;
+ basemaps.show(shown.provider, shown.id, shown.cell);
+ }
+
+ $effect(() => {
+ shown.id; // a new provider, a new eco/block fallback, a new Sentinel window
+ shown.cell; // …and the z17 detail-boost bracket
+ showBasemap();
+ });
+
+ $effect(() => {
+ const on = labels; // 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);
+ });
+
+ // debounce: the target moves a lot while panning — only ask once it settles
+ $effect(() => {
+ view.lat;
+ view.lon;
+ view.zoom;
+ shown.id;
+ if (!ready) return;
+ clearTimeout(dateTimer);
+ dateTimer = setTimeout(readImageryDate, 500);
+ return () => clearTimeout(dateTimer);
+ });
+
+ async function readImageryDate() {
+ const mine = ++dateRequest;
+ try {
+ const answer = await imagery.imageryDate(view, shown.id);
+ if (mine === dateRequest) imageryDate = answer;
+ } catch {
+ if (mine === dateRequest) imageryDate = { supported: true, date: null, source: null };
+ }
+ }
+
+ function setBearing(deg) {
+ engine?.setBearing(deg); // the façade normalises whatever it is handed
+ }
+
+ function startEditBearing() {
+ bearingInput = String(bearing);
+ editingBearing = true;
+ }
+
+ function commitBearing() {
+ const deg = parseFloat(bearingInput);
+ if (Number.isFinite(deg)) setBearing(deg);
+ editingBearing = false;
+ }
+
+ // the container resizes when a panel opens or the window changes, and
+ // reappears from display:none when the tool tab is re-selected
+ export async function remeasure() {
+ await tick();
+ engine?.resize();
+ }
+</script>
+
+<div
+ class="map-wrap dark-surface"
+ class:measuring={armed === 'measuring'}
+ class:selecting={armed === 'selecting'}
+ class:grid-drawing={armed === 'grid-drawing'}
+ class:grabbing
+>
+ <div class="map" bind:this={mapEl}></div>
+
+ {#if refused}
+ <p class="map-refused">The map needs WebGL, which this browser does not have.</p>
+ {/if}
+
+ {@render children?.()}
+
+ <!-- imagery acquisition date: a compact, unobtrusive pill in the corner so it
+ doesn't crowd the tool's own readouts -->
+ {#if s2 && shown.provider?.id === SENTINEL_ID}
+ <!-- Sentinel-2 says what it is showing: a pinned day is the window the tiles
+ were rendered from; otherwise the layer's default renders the most
+ recent pass, which the calendar lookup has already named. -->
+ <span
+ class="date-pill mono"
+ class:exact={!!pinnedDay}
+ title={pinnedDay
+ ? `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} />
+ {pinnedDay ?? s2.latest ?? ''}
+ {#if !pinnedDay}
+ <span class="tag">{s2.latest ? 'latest' : 'most recent'}</span>
+ {/if}
+ {#if s2.layer !== DEFAULT_LAYER}
+ <span class="tag layer">{s2.layerShort}</span>
+ {/if}
+ {#if s2.maxcc !== DEFAULT_MAXCC}
+ <span class="tag" title="Passes over this cloud cover are not rendered"
+ >≤{s2.maxcc}% cloud</span
+ >
+ {/if}
+ </span>
+ {:else if imageryDate?.supported}
+ <span
+ class="date-pill mono"
+ title={imageryDate.source
+ ? `Imagery acquired around this date (source: ${imageryDate.source})`
+ : 'Approximate acquisition date of the imagery here'}
+ >
+ <Icon name="clock" size={11} />
+ {imageryDate.date ?? '—'}
+ </span>
+ {/if}
+
+ <!-- lightweight compass: click the rose to reset north; middle-drag the map to
+ rotate; click the number to type an exact bearing -->
+ <div class="rotate-ctl">
+ <button
+ class="compass"
+ onclick={() => setBearing(0)}
+ 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)">
+ <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>
+ <span class="n">N</span>
+ </button>
+ {#if editingBearing}
+ <!-- svelte-ignore a11y_autofocus -->
+ <input
+ class="input deg-input mono"
+ type="number"
+ min="0"
+ max="359"
+ bind:value={bearingInput}
+ autofocus
+ onblur={commitBearing}
+ onkeydown={(e) => {
+ if (e.key === 'Enter') commitBearing();
+ else if (e.key === 'Escape') editingBearing = false;
+ }}
+ aria-label="Set bearing in degrees"
+ />
+ {:else}
+ <button class="deg mono" onclick={startEditBearing} title="Click to type an exact angle">
+ {bearing}°
+ </button>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .map-wrap {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ /* 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 {
+ position: absolute;
+ 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);
+ }
+ /* Mid screen-grab: a widget capture crops the map element's *rectangle*, so
+ everything we paint over the map (HUD, control clusters, capture bar,
+ reference windows, the frame outline itself) would land in the capture.
+ Hide our chrome for the grab and leave the map — Google's own credits live
+ inside it and must ride along. The marker is the deliberate exception: the
+ tile path burns one into its crop, so a screen crop keeps its own.
+ :global is load-bearing — the reference windows are a child component, so
+ a scoped selector would skip exactly the overlay the spec says must never
+ be captured. */
+ .map-wrap.grabbing > :global(:not(.map):not(.marker-overlay)) {
+ visibility: hidden;
+ }
+ .map-wrap.measuring :global(.map-surface),
+ .map-wrap.selecting :global(.map-surface),
+ .map-wrap.grid-drawing :global(.map-surface) {
+ cursor: crosshair;
+ }
+ /* imagery date: small, low-contrast pill tucked into the bottom-left corner */
+ .date-pill {
+ position: absolute;
+ bottom: 12px;
+ left: 12px;
+ z-index: 600;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ padding: 3px 8px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ background: rgba(24, 24, 24, 0.7);
+ backdrop-filter: blur(6px);
+ pointer-events: none;
+ }
+ /* a pinned date is a fact about the pixels; "latest" is an inference from the
+ pass list — they must not look identical */
+ .date-pill.exact {
+ border-color: var(--ok, #46a758);
+ }
+ .date-pill .tag {
+ font-family: var(--font-sans);
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ color: var(--text-3);
+ border: 1px solid var(--border);
+ border-radius: 3px;
+ padding: 0 3px;
+ }
+ .date-pill .tag.layer {
+ color: var(--accent);
+ border-color: color-mix(in srgb, var(--accent) 45%, transparent);
+ }
+ /* lightweight compass — no heavy card, just the rose + an editable readout */
+ .rotate-ctl {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ z-index: 600;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ }
+ .compass {
+ position: relative;
+ display: grid;
+ place-items: center;
+ width: 38px;
+ height: 38px;
+ color: var(--text-2);
+ cursor: pointer;
+ /* round translucent backing disc so the rose reads clearly over any
+ imagery — same fill as the degree readout below (item 3) */
+ border-radius: 50%;
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-1);
+ }
+ .compass:hover {
+ color: var(--accent);
+ }
+ .compass svg {
+ transition: transform 0.1s linear;
+ }
+ .compass .n {
+ position: absolute;
+ top: 1px;
+ left: 50%;
+ transform: translateX(-50%);
+ font-size: 9px;
+ font-weight: 700;
+ color: var(--text-1);
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
+ pointer-events: none;
+ }
+ .deg {
+ min-width: 40px;
+ text-align: center;
+ padding: 2px 6px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-xs);
+ color: var(--text-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ cursor: text;
+ }
+ .deg:hover {
+ color: var(--accent);
+ }
+ .deg-input {
+ width: 52px;
+ padding: 2px 4px;
+ text-align: center;
+ font-size: var(--fs-xs);
+ }</style>
diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelte
index e33935d..9a64af9 100644
--- a/frontend/src/tools/satellite/SavedOverlay.svelte
+++ b/frontend/src/tools/satellite/SavedOverlay.svelte
@@ -7,6 +7,7 @@
import { createSurface } from '../../lib/map/surface.js';
import { paths } from '../../components/Icon.svelte';
import { groupSavedMarkers, markerPrecision } from '../../lib/savedMarkers.js';
+ import { TEARDROP, TEARDROP_CARD_OFFSET } from '../../lib/mapMarkers.js';
import { openEntity } from '../../lib/navigate.js';
import SavedPopup from './SavedPopup.svelte';
@@ -52,8 +53,7 @@
return {
className: 'saved-mark-wrap',
html: `<span class="saved-mark saved-mark-${kind}">${glyph(GLYPH[kind] ?? 'pin', 13)}${count}${worked}</span>`,
- size: [24, 24],
- anchor: [12, 12],
+ ...TEARDROP,
};
}
@@ -187,6 +187,7 @@
className: 'saved-popup',
minWidth: 296,
maxWidth: 330,
+ offset: TEARDROP_CARD_OFFSET,
},
},
])
diff --git a/frontend/src/tools/satellite/SheetPointsOverlay.svelte b/frontend/src/tools/satellite/SheetPointsOverlay.svelte
index 3b1a2a8..91fd04c 100644
--- a/frontend/src/tools/satellite/SheetPointsOverlay.svelte
+++ b/frontend/src/tools/satellite/SheetPointsOverlay.svelte
@@ -14,6 +14,7 @@
import { createSurface } from '../../lib/map/surface.js';
import { paths } from '../../components/Icon.svelte';
import { precisionMetres } from '../../lib/sheetRoles.js';
+ import { TEARDROP } from '../../lib/mapMarkers.js';
let { engine = null, points = [] } = $props();
let surface = null;
@@ -36,8 +37,7 @@
return {
className: 'sheet-mark-wrap',
html: `<span class="sheet-mark${coarse ? ' sheet-mark-coarse' : ''}">${glyph(12)}</span>`,
- size: [24, 24],
- anchor: [12, 12],
+ ...TEARDROP,
};
}
diff --git a/frontend/src/tools/satellite/TemporalMapOverlay.svelte b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
index 916d5cd..15e1405 100644
--- a/frontend/src/tools/satellite/TemporalMapOverlay.svelte
+++ b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
@@ -12,6 +12,7 @@
import { createSurface } from '../../lib/map/surface.js';
import { paths } from '../../components/Icon.svelte';
import { groupTemporalMapItems } from '../../lib/temporalMap.js';
+ import { TEARDROP, TEARDROP_CARD_OFFSET } from '../../lib/mapMarkers.js';
import TemporalPopup from './TemporalPopup.svelte';
let { engine = null, items = [], caseId = '', onopen = () => {} } = $props();
@@ -31,8 +32,7 @@
return {
className: 'temporal-mark-wrap',
html: `<span class="temporal-mark">${glyph('clock', 13)}${count}</span>`,
- size: [24, 24],
- anchor: [12, 12],
+ ...TEARDROP,
};
}
@@ -96,6 +96,7 @@
className: 'temporal-popup',
minWidth: 272,
maxWidth: 320,
+ offset: TEARDROP_CARD_OFFSET,
},
},
])
diff --git a/frontend/src/tools/satellite/state/capture.svelte.js b/frontend/src/tools/satellite/state/capture.svelte.js
new file mode 100644
index 0000000..f6b0862
--- /dev/null
+++ b/frontend/src/tools/satellite/state/capture.svelte.js
@@ -0,0 +1,492 @@
+/**
+ * Taking a crop of the map and filing it as a capture.
+ *
+ * Two roads reach the same place. Most basemaps are tiles, so the backend
+ * stitches the frame at whatever zoom the output asks for. A widget basemap has
+ * no tiles anyone may touch — Google's terms allow a user-taken screenshot and
+ * nothing programmatic — so those pixels come from the browser extension
+ * grabbing the tab. Everything either side of that one step is deliberately
+ * identical: the same frame, the same two modes, the same filing.
+ *
+ * What the rules here are actually protecting is *provenance*. A capture is
+ * evidence, and the questions it has to survive are "which imagery is this?"
+ * and "where exactly?":
+ *
+ * - **The pixels name themselves.** Provenance is asked of the surface that
+ * drew them, not of the provider that was chosen — a billed basemap that
+ * stepped aside for the eco fallback must not be filed under the name of the
+ * one the analyst picked.
+ * - **A refused capture stays untaken.** When the extension grab fails, nothing
+ * offers to file some other image instead: that is how an unregistered
+ * picture ends up wearing a capture's provenance.
+ * - **Our own chrome leaves the frame first.** A tab grab sees the whole
+ * viewport, so the HUD, the controls and the reference windows are hidden for
+ * the shot. The marker is the exception, because the tile path burns one into
+ * its crop and a screen crop missing it would be the odd one out.
+ * - **The frame has to fit the view.** A crop bigger than the map on screen has
+ * no pixels to come from, so it is refused with the reason rather than
+ * silently shrunk.
+ *
+ * The sizing arithmetic is `lib/captureSize.js`, the registration and crop maths
+ * `lib/screenCrop.js`, and the extension handshake `lib/extBridge.js`. This
+ * holds what shape the output is, which mode the button runs, and the acts.
+ *
+ * @param {object} deps
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify
+ * @param {() => Promise<object>} deps.ensureCase the case to file into, made if needed
+ * @param {() => Promise<any>} deps.reloadCase
+ * @param {() => object|null} deps.engine the map, through the façade
+ * @param {() => Element|null} deps.element the map container, for its rectangle
+ * @param {() => {lat: number, lon: number, zoom: number}} deps.view where the camera is
+ * @param {() => number} deps.bearing which way is up
+ * @param {() => {style: string, at: object|null}} deps.marker the pin, if one was moved
+ * @param {() => object|undefined} deps.basemap the provider the analyst chose
+ * @param {() => number} deps.maxZoom the deepest zoom the *shown* provider has
+ * @param {() => {provider: string, imageryDate: string|null}} deps.provenance the pixels' own
+ * @param {(rect: object|null) => void} deps.onRect the live marquee outline
+ * @param {() => void} deps.onArm the map modes arming the marquee turns off
+ */
+import { clampSize, scaledCapture } from '../../../lib/captureSize.js';
+import { captureTab, extensionVersion } from '../../../lib/extBridge.js';
+import { frameFitsView, isRegistered, sourceRect } from '../../../lib/screenCrop.js';
+import { startRectDrag } from '../../../lib/map/gestures.js';
+
+/** Standard output sizes for the centred button, named by what they are for. */
+export const PRESETS = [
+ { id: '1200x675', label: 'Tweet 16:9', w: 1200, h: 675 },
+ { id: '1080x1080', label: 'Square', w: 1080, h: 1080 },
+ { id: '1200x630', label: 'OG card', w: 1200, h: 630 },
+ { id: '1280x800', label: 'Wide', w: 1280, h: 800 },
+ { id: 'custom', label: 'Custom', w: 0, h: 0 },
+];
+
+/** Marquee aspect lock (width / height); null drags free-form. */
+export const RATIOS = [
+ { id: 'free', label: 'Free', r: null },
+ { id: '16:9', label: '16:9', r: 16 / 9 },
+ { id: '4:3', label: '4:3', r: 4 / 3 },
+ { id: '1:1', label: '1:1', r: 1 },
+];
+
+/** Below this, a drag is a slipped click rather than a box. */
+const MIN_DRAG_PX = 12;
+
+export function createCaptureState({
+ api,
+ notify,
+ ensureCase,
+ reloadCase,
+ engine,
+ element,
+ view,
+ bearing,
+ marker,
+ basemap,
+ maxZoom,
+ provenance,
+ onRect,
+ onArm,
+}) {
+ let preset = $state('1200x675');
+ let customW = $state(1200);
+ let customH = $state(675);
+ let ratio = $state('free');
+ // 1 = the view's own zoom, 2 = one zoom deeper, 'max' = the provider's deepest.
+ let resolution = $state(1);
+ // The button runs whichever mode was used last, so this *is* that memory.
+ let mode = $state('center'); // 'center' | 'select'
+ let menuOpen = $state(false); // the mode/size/ratio/resolution popover
+ let armed = $state(false); // marquee: drag a box on the map to capture it
+ let busy = $state(false);
+ let hiding = $state(false); // our chrome, out of the way of a tab grab
+ let extGate = $state(false); // the "you need the extension" explainer
+ let shotOpen = $state(false); // the paste/drop fallback dialog
+
+ /** The chosen output size in px. Custom is clamped to what the backend takes. */
+ const size = $derived.by(() => {
+ if (preset === 'custom') return [clampSize(customW), clampSize(customH)];
+ const chosen = PRESETS.find((entry) => entry.id === preset);
+ return [chosen.w, chosen.h];
+ });
+
+ const lock = $derived(RATIOS.find((entry) => entry.id === ratio)?.r ?? null);
+ /** A widget basemap is captured from screen pixels — it has no tiles to stitch. */
+ const widget = $derived(!!basemap()?.widget);
+ /** View-only basemaps keep the map but not the button. A widget is *not* one:
+ * it captures the same way through the same button, from other pixels. */
+ const blocked = $derived(basemap()?.capturable === false && !widget);
+
+ /** One frame of this tab as a drawable image, through the extension. The
+ * frame is exactly the viewport, so registration is the viewport aspect
+ * check — a mismatch means browser zoom mid-flight or a foreign frame, and
+ * both are refusals. */
+ async function tabFrame() {
+ const dataUrl = await captureTab();
+ const img = new window.Image();
+ await new Promise((resolve, reject) => {
+ img.onload = resolve;
+ img.onerror = () => reject(new Error('unreadable frame from the extension'));
+ img.src = dataUrl;
+ });
+ if (!isRegistered(img.naturalWidth, img.naturalHeight, window.innerWidth, window.innerHeight)) {
+ throw new Error('the captured frame does not match this view. Try again');
+ }
+ return img;
+ }
+
+ /** Map a rect in map-container CSS px onto the captured frame and render it at
+ * exactly `outW`×`outH` (default: the native source pixels). Source pixels
+ * are usually denser than CSS px, so a requested size is a supersampled
+ * downscale rather than a blur-up. */
+ async function cropFrame(img, rect, outW, outH) {
+ const src = sourceRect(rect, {
+ mapRect: element().getBoundingClientRect(),
+ viewportWidth: window.innerWidth,
+ videoWidth: img.naturalWidth,
+ videoHeight: img.naturalHeight,
+ });
+ if (!src) {
+ throw new Error(
+ 'the frame runs past the captured area. Resize the window or pick a smaller size'
+ );
+ }
+ const { sx, sy, sw, sh } = src;
+ const canvas = document.createElement('canvas');
+ canvas.width = Math.round(outW ?? sw);
+ canvas.height = Math.round(outH ?? sh);
+ const ctx = canvas.getContext('2d');
+ ctx.imageSmoothingQuality = 'high';
+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
+ return canvas;
+ }
+
+ /** File a screenshot blob as a capture. `framed` records whether the
+ * coordinates are the centre of a registered crop or just the map view at
+ * filing time — the backend keeps that distinction in provenance. */
+ async function fileScreenshot(blob, framedOn, framed) {
+ const here = view();
+ const owner = await ensureCase();
+ const form = new FormData();
+ form.append('image', blob, 'screenshot.png');
+ form.append('lat', String(framedOn ? framedOn.lat : here.lat));
+ form.append('lon', String(framedOn ? framedOn.lon : here.lon));
+ form.append('zoom', String(here.zoom));
+ form.append('bearing', String(bearing()));
+ form.append('provider', basemap().id);
+ form.append('framed', String(!!framed));
+ const result = await api.post(`/api/cases/${owner.id}/satellite/screenshot`, form);
+ await reloadCase();
+ notify(
+ framed
+ ? 'Screen crop captured & filed (attribution burned in)'
+ : 'Screenshot filed as a capture (attribution burned in)',
+ 'ok'
+ );
+ return result;
+ }
+
+ /** The widget arm: grab the tab, crop it to the frame, file it. */
+ async function widgetCapture(framedOn, rect) {
+ if (!extensionVersion()) {
+ extGate = true;
+ return;
+ }
+ if (!frameFitsView(rect, element().getBoundingClientRect())) {
+ notify(
+ `The ${Math.round(rect.w)}×${Math.round(rect.h)} frame is bigger than the map view. ` +
+ 'Pick a smaller size or enlarge the window',
+ 'warn',
+ 7000
+ );
+ return;
+ }
+ busy = true;
+ hiding = true;
+ try {
+ // let the hidden chrome actually leave the composited frame
+ await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
+ await new Promise((r) => setTimeout(r, 60));
+ const img = await tabFrame();
+ const canvas = await cropFrame(img, rect, Math.round(rect.w), Math.round(rect.h));
+ const blob = await new Promise((r) => canvas.toBlob(r, 'image/png'));
+ await fileScreenshot(blob, framedOn, true);
+ } catch (e) {
+ if (e.needsActivation) {
+ // one-time per tab: the browser only lets the extension screenshot a tab
+ // it has been invoked on (activeTab) — not an error, a step
+ notify(
+ 'One-time step: click the Azimut Capture icon in the toolbar ' +
+ '(or press Alt+Shift+A), then press Capture again',
+ 'warn',
+ 10000
+ );
+ } else {
+ notify(`Capture failed: ${e.message}`, 'danger', 7000);
+ }
+ } finally {
+ hiding = false;
+ busy = false;
+ }
+ }
+
+ /**
+ * The single capture path. `framedOn` is the `{ lat, lon }` the crop is framed
+ * on; `baseW`/`baseH` are its 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 road needs it, since it crops screen
+ * pixels rather than stitching tiles.
+ */
+ async function take(framedOn, baseW, baseH, rectCss) {
+ if (busy) return;
+ if (widget) return widgetCapture(framedOn, rectCss);
+ busy = true;
+ const facade = engine();
+ const here = view();
+ const { zoom, width, height, mult } = scaledCapture(
+ baseW,
+ baseH,
+ resolution,
+ here.zoom,
+ maxZoom()
+ );
+ const pin = marker();
+ let markerX = 0;
+ let markerY = 0;
+ let markerLat = framedOn.lat;
+ let markerLon = framedOn.lon;
+ if (pin.at) {
+ markerLat = pin.at.lat;
+ markerLon = pin.at.lon;
+ // offset from the crop centre in container px (rotation already folded
+ // in), scaled up to the output pixel size
+ const middle = facade.latLngToContainerPoint(framedOn);
+ const point = facade.latLngToContainerPoint(pin.at);
+ markerX = Math.round((point.x - middle.x) * mult);
+ markerY = Math.round((point.y - middle.y) * mult);
+ }
+ // The pixels' own provenance, asked of the surface that drew them.
+ const pixels = provenance();
+ try {
+ const owner = await ensureCase();
+ const result = await api.post(`/api/cases/${owner.id}/satellite/capture`, {
+ lat: framedOn.lat,
+ lon: framedOn.lon,
+ zoom,
+ width,
+ height,
+ provider: pixels.provider,
+ bearing: bearing(),
+ marker_style: pin.style,
+ marker_x: markerX,
+ marker_y: markerY,
+ marker_lat: markerLat,
+ marker_lon: markerLon,
+ // the second date on a capture: when the imagery itself was acquired. A
+ // pinned Sentinel-2 window is that date outright; every other provider's
+ // is Esri's best-effort estimate, or nothing.
+ imagery_date: pixels.imageryDate,
+ });
+ await reloadCase();
+ notify(
+ result.tiles_missing
+ ? `Captured with ${result.tiles_missing} missing tile(s). No imagery was available there`
+ : result.tiles_upscaled
+ ? `Captured. ${result.tiles_upscaled} tile(s) were upscaled from a lower zoom and recorded in provenance`
+ : 'Satellite crop captured & filed',
+ result.tiles_missing || result.tiles_upscaled ? 'warn' : 'ok'
+ );
+ } catch (e) {
+ notify(`Capture failed: ${e.message}`, 'danger', 6000);
+ } finally {
+ busy = false;
+ }
+ }
+
+ /** The centred button: the chosen preset, framed on the map centre. */
+ function takeCentered() {
+ const [w, h] = size;
+ const box = element().getBoundingClientRect();
+ return take(engine().camera(), w, h, {
+ x: (box.width - w) / 2,
+ y: (box.height - h) / 2,
+ w,
+ h,
+ });
+ }
+
+ function toggleSelect() {
+ armed = !armed;
+ if (armed) {
+ menuOpen = false;
+ onArm();
+ } else {
+ onRect(null);
+ }
+ return armed;
+ }
+
+ function finishSelect(dragged) {
+ onRect(null);
+ if (!dragged) return;
+ const w = Math.abs(dragged.x1 - dragged.x0);
+ const h = Math.abs(dragged.y1 - dragged.y0);
+ if (w < MIN_DRAG_PX || h < MIN_DRAG_PX) return; // a slipped click, not a box
+ const framedOn = engine().containerPointToLatLng({
+ x: (dragged.x0 + dragged.x1) / 2,
+ y: (dragged.y0 + dragged.y1) / 2,
+ });
+ armed = false; // one box per arm — re-arm to draw another
+ take(framedOn, Math.round(w), Math.round(h), {
+ x: Math.min(dragged.x0, dragged.x1),
+ y: Math.min(dragged.y0, dragged.y1),
+ w,
+ h,
+ });
+ }
+
+ return {
+ get preset() {
+ return preset;
+ },
+ set preset(value) {
+ preset = value;
+ },
+ get customW() {
+ return customW;
+ },
+ set customW(value) {
+ customW = value;
+ },
+ get customH() {
+ return customH;
+ },
+ set customH(value) {
+ customH = value;
+ },
+ get ratio() {
+ return ratio;
+ },
+ set ratio(value) {
+ ratio = value;
+ },
+ get resolution() {
+ return resolution;
+ },
+ set resolution(value) {
+ resolution = value;
+ },
+ get mode() {
+ return mode;
+ },
+ set mode(value) {
+ mode = value;
+ },
+ get menuOpen() {
+ return menuOpen;
+ },
+ set menuOpen(value) {
+ menuOpen = value;
+ },
+ get extGate() {
+ return extGate;
+ },
+ set extGate(value) {
+ extGate = value;
+ },
+ get shotOpen() {
+ return shotOpen;
+ },
+ set shotOpen(value) {
+ shotOpen = value;
+ },
+ get armed() {
+ return armed;
+ },
+ get busy() {
+ return busy;
+ },
+ /** Our chrome is hidden mid-grab, so it cannot land in the crop. */
+ get hiding() {
+ return hiding;
+ },
+ get size() {
+ return size;
+ },
+ get lock() {
+ return lock;
+ },
+ get widget() {
+ return widget;
+ },
+ get blocked() {
+ return blocked;
+ },
+
+ /**
+ * The main button. It runs whichever mode was last used, which is what
+ * `mode` remembers. A widget basemap needs the extension before any frame
+ * is drawn — gate there and explain, rather than half-working.
+ */
+ run() {
+ if (blocked || busy) return;
+ if (widget && !extensionVersion()) {
+ extGate = true;
+ return;
+ }
+ if (mode === 'select') toggleSelect();
+ else takeCentered();
+ },
+
+ toggleSelect,
+
+ /** Put the marquee away because another map mode took the left button.
+ * Unlike `toggleSelect`, this claims nothing back: the mode arming is the
+ * one saying what else it turns off. */
+ disarm() {
+ if (!armed) return;
+ armed = false;
+ onRect(null);
+ },
+
+ /** Left-drag on the map, while the marquee is armed. */
+ startSelect(e) {
+ const facade = engine();
+ if (!armed || e.button !== 0 || !facade) return;
+ startRectDrag(facade, e, {
+ ratio: lock,
+ onChange: (rect) => onRect(rect),
+ onDone: finishSelect,
+ });
+ },
+
+ /** The whole map view as a PNG blob, for the paste/drop dialog's preview.
+ * Null if the extension refused — that path still takes a pasted image. */
+ async grabView() {
+ try {
+ const img = await tabFrame();
+ const box = element().getBoundingClientRect();
+ const canvas = await cropFrame(img, { x: 0, y: 0, w: box.width, h: box.height });
+ return await new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
+ } catch (e) {
+ notify(
+ `Screen capture unavailable (${e.message}). Paste a screenshot instead`,
+ 'warn',
+ 6000
+ );
+ return null;
+ }
+ },
+
+ /** File what the dialog holds, at the map view rather than a registered frame. */
+ async fileBlob(blob) {
+ try {
+ await fileScreenshot(blob, null, false);
+ return true;
+ } catch (e) {
+ notify(`Could not file the screenshot: ${e.message}`, 'danger', 6000);
+ return false;
+ }
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/capture.svelte.test.js b/frontend/src/tools/satellite/state/capture.svelte.test.js
new file mode 100644
index 0000000..647fc54
--- /dev/null
+++ b/frontend/src/tools/satellite/state/capture.svelte.test.js
@@ -0,0 +1,322 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createCaptureState, PRESETS, RATIOS } from './capture.svelte.js';
+
+/**
+ * What a capture records, and what it refuses to record.
+ *
+ * The sizing arithmetic (lib/captureSize.js) and the crop registration
+ * (lib/screenCrop.js) have their own tests. What is asserted here is the part
+ * that makes a capture evidence: which provider the pixels are filed under,
+ * which road they came down, and every case where the answer is "no" rather
+ * than a picture that overstates itself.
+ */
+
+const TILES = { id: 'esri-world-imagery', label: 'Esri', max_zoom: 19 };
+const WIDGET = { id: 'gmaps-satellite', label: 'Google', widget: true, capturable: false };
+const VIEW_ONLY = { id: 'osm', label: 'OSM', capturable: false };
+
+const HERE = { lat: 48.85, lon: 2.35, zoom: 16 };
+
+let api;
+let notify;
+let reloadCase;
+let engine;
+let element;
+let basemap;
+let pin;
+let pixels;
+let rects;
+let armedOff;
+let extension;
+
+vi.mock('../../../lib/extBridge.js', () => ({
+ extensionVersion: () => extension,
+ captureTab: () => Promise.reject(new Error('no extension here')),
+}));
+
+function store(overrides = {}) {
+ return createCaptureState({
+ api,
+ notify,
+ ensureCase: async () => ({ id: 'case-1' }),
+ reloadCase,
+ engine: () => engine,
+ element: () => element,
+ view: () => HERE,
+ bearing: () => 30,
+ marker: () => pin,
+ basemap: () => basemap,
+ maxZoom: () => basemap?.max_zoom ?? 19,
+ provenance: () => pixels,
+ onRect: (rect) => rects.push(rect),
+ onArm: () => (armedOff += 1),
+ ...overrides,
+ });
+}
+
+beforeEach(() => {
+ api = { post: vi.fn(async () => ({})) };
+ notify = vi.fn();
+ reloadCase = vi.fn(async () => {});
+ engine = {
+ camera: () => HERE,
+ latLngToContainerPoint: ({ lat, lon }) => ({ x: lon * 100, y: lat * 100 }),
+ containerPointToLatLng: ({ x, y }) => ({ lat: y / 100, lon: x / 100 }),
+ };
+ element = { getBoundingClientRect: () => ({ x: 0, y: 0, width: 1600, height: 900 }) };
+ basemap = TILES;
+ pin = { style: 'crosshair', at: null };
+ pixels = { provider: 'esri-world-imagery', imageryDate: '2024-05-01' };
+ rects = [];
+ armedOff = 0;
+ extension = '1.0.0';
+});
+
+describe('the output shape', () => {
+ it('starts on a preset, and reads its size off the catalogue', () => {
+ const capture = store();
+ const chosen = PRESETS.find((entry) => entry.id === capture.preset);
+ expect(capture.size).toEqual([chosen.w, chosen.h]);
+ });
+
+ it('clamps a custom size to what the backend will take', () => {
+ const capture = store();
+ capture.preset = 'custom';
+ capture.customW = 99999;
+ capture.customH = 4;
+ const [w, h] = capture.size;
+ expect(w).toBeLessThanOrEqual(4096);
+ expect(h).toBeGreaterThanOrEqual(256);
+ });
+
+ it('drags free-form until a ratio is locked', () => {
+ const capture = store();
+ expect(capture.lock).toBe(null);
+ capture.ratio = '16:9';
+ expect(capture.lock).toBeCloseTo(16 / 9);
+ expect(RATIOS.find((entry) => entry.id === '1:1').r).toBe(1);
+ });
+});
+
+describe('which road the pixels come down', () => {
+ it('stitches tiles for an ordinary basemap', async () => {
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][0]).toBe('/api/cases/case-1/satellite/capture');
+ });
+
+ it('refuses outright on a view-only basemap', () => {
+ basemap = VIEW_ONLY;
+ const capture = store();
+ expect(capture.blocked).toBe(true);
+ capture.run();
+ expect(api.post).not.toHaveBeenCalled();
+ });
+
+ it('treats a widget basemap as capturable, just down the other road', () => {
+ basemap = WIDGET;
+ const capture = store();
+ // capturable=false on the catalogue entry, but the button still works
+ expect(capture.widget).toBe(true);
+ expect(capture.blocked).toBe(false);
+ });
+
+ it('explains the missing extension before drawing any frame', () => {
+ basemap = WIDGET;
+ extension = null;
+ const capture = store();
+ capture.run();
+ expect(capture.extGate).toBe(true);
+ expect(api.post).not.toHaveBeenCalled();
+ });
+
+ it('never files a tile capture for a widget basemap', async () => {
+ basemap = WIDGET;
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());
+ // the grab fails in this harness; what matters is which route it took
+ expect(api.post).not.toHaveBeenCalled();
+ });
+});
+
+describe('what a capture records', () => {
+ it('files the provider that drew the pixels, not the one that was chosen', async () => {
+ // the analyst picked a billed basemap; eco swapped in free imagery
+ basemap = { id: 'bing-aerial', label: 'Bing', max_zoom: 19 };
+ pixels = { provider: 'esri-world-imagery', imageryDate: '2023-01-01' };
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].provider).toBe('esri-world-imagery');
+ });
+
+ it('carries the imagery acquisition date beside the capture date', async () => {
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].imagery_date).toBe('2024-05-01');
+ });
+
+ it('records the frame centre when no pin was moved', async () => {
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ const body = api.post.mock.calls[0][1];
+ expect([body.marker_lat, body.marker_lon]).toEqual([HERE.lat, HERE.lon]);
+ expect([body.marker_x, body.marker_y]).toEqual([0, 0]);
+ });
+
+ it('records the moved pin, and where it sits inside the crop', async () => {
+ pin = { style: 'pin', at: { lat: 48.9, lon: 2.4 } };
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ const body = api.post.mock.calls[0][1];
+ expect(body.marker_lat).toBe(48.9);
+ expect(body.marker_style).toBe('pin');
+ // the pin is north-east of centre, so it is offset from it
+ expect(body.marker_x).not.toBe(0);
+ });
+
+ it('keeps the bearing, so a turned map is filed turned', async () => {
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].bearing).toBe(30);
+ });
+
+ it('re-reads the case, so the panel shows what was just filed', async () => {
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(reloadCase).toHaveBeenCalled());
+ });
+});
+
+describe('when a capture is imperfect', () => {
+ it('says how many tiles were missing rather than filing quietly', async () => {
+ api.post = vi.fn(async () => ({ tiles_missing: 3 }));
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());
+ expect(notify.mock.calls[0][0]).toContain('3 missing tile');
+ expect(notify.mock.calls[0][1]).toBe('warn');
+ });
+
+ it('says when tiles were upscaled, since that is in the provenance too', async () => {
+ api.post = vi.fn(async () => ({ tiles_upscaled: 2 }));
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());
+ expect(notify.mock.calls[0][0]).toContain('upscaled');
+ expect(notify.mock.calls[0][1]).toBe('warn');
+ });
+
+ it('names the failure and files nothing', async () => {
+ api.post = vi.fn(async () => {
+ throw new Error('disk full');
+ });
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());
+ expect(notify.mock.calls[0][0]).toContain('disk full');
+ expect(notify.mock.calls[0][1]).toBe('danger');
+ expect(capture.busy).toBe(false);
+ });
+
+ it('takes one capture at a time, so a double press files one crop', async () => {
+ let release;
+ api.post = vi.fn(() => new Promise((resolve) => (release = () => resolve({}))));
+ const capture = store();
+ capture.run();
+ await vi.waitFor(() => expect(capture.busy).toBe(true));
+ capture.run();
+ expect(api.post).toHaveBeenCalledTimes(1);
+ release();
+ });
+});
+
+describe('the marquee', () => {
+ it('arming it turns off whatever else owns the left button', () => {
+ const capture = store();
+ expect(capture.toggleSelect()).toBe(true);
+ expect(armedOff).toBe(1);
+ });
+
+ it('arming it shuts the settings popover, which would cover the map', () => {
+ const capture = store();
+ capture.menuOpen = true;
+ capture.toggleSelect();
+ expect(capture.menuOpen).toBe(false);
+ });
+
+ it('disarming clears the outline it left on the map', () => {
+ const capture = store();
+ capture.toggleSelect();
+ capture.toggleSelect();
+ expect(capture.armed).toBe(false);
+ expect(rects.at(-1)).toBe(null);
+ });
+
+ it('stands down for another mode without claiming anything back', () => {
+ const capture = store();
+ capture.toggleSelect();
+ armedOff = 0;
+ capture.disarm();
+ expect(capture.armed).toBe(false);
+ expect(armedOff).toBe(0); // it is the arriving mode that says what it turns off
+ });
+
+ it('ignores a drag while it is not armed', () => {
+ const capture = store();
+ capture.startSelect({ button: 0 });
+ expect(rects).toEqual([]);
+ });
+
+ it('ignores anything but the left button', () => {
+ const capture = store();
+ capture.toggleSelect();
+ capture.startSelect({ button: 1 });
+ expect(rects).toEqual([]);
+ });
+
+ it('runs the marquee, not the centred frame, when that is the mode', () => {
+ const capture = store();
+ capture.mode = 'select';
+ capture.run();
+ expect(capture.armed).toBe(true);
+ expect(api.post).not.toHaveBeenCalled(); // the box has still to be drawn
+ });
+});
+
+describe('the paste fallback', () => {
+ it('says why the screen grab is unavailable and leaves the paste path open', async () => {
+ const capture = store();
+ expect(await capture.grabView()).toBe(null);
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('Paste a screenshot instead'),
+ 'warn',
+ 6000
+ );
+ });
+
+ it('files a pasted image at the map view, marked as unframed', async () => {
+ const capture = store();
+ expect(await capture.fileBlob(new Blob(['x']))).toBe(true);
+ const [path, form] = api.post.mock.calls[0];
+ expect(path).toBe('/api/cases/case-1/satellite/screenshot');
+ expect(form.get('framed')).toBe('false');
+ expect(form.get('lat')).toBe(String(HERE.lat));
+ });
+
+ it('reports a filing failure rather than pretending it landed', async () => {
+ api.post = vi.fn(async () => {
+ throw new Error('refused');
+ });
+ const capture = store();
+ expect(await capture.fileBlob(new Blob(['x']))).toBe(false);
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('refused'), 'danger', 6000);
+ });
+});
diff --git a/frontend/src/tools/satellite/state/grid.svelte.js b/frontend/src/tools/satellite/state/grid.svelte.js
new file mode 100644
index 0000000..3f0b176
--- /dev/null
+++ b/frontend/src/tools/satellite/state/grid.svelte.js
@@ -0,0 +1,888 @@
+/**
+ * Grid Search: lay a metric lattice over an area and sweep it cell by cell.
+ *
+ * A case holds several grids — files under `search/`, working aids rather than
+ * entities — and each act saves the open one. What that costs is a set of rules
+ * about *when* a grid is written and what a switch away from it means:
+ *
+ * - **Drawing an area always makes a new grid.** Resizing the one you are on is
+ * the handles; a fresh outline is a fresh sweep, and the marks already made
+ * are not a thing to silently redraw underneath.
+ * - **The grid being left is flushed before the next one opens.** Marks are
+ * debounced, so switching on the last keypress of a sweep would drop it.
+ * - **A lattice too fine for its area is refused, not truncated.** Past the cell
+ * ceiling the previous shape is kept and said so, because half a grid over an
+ * area reads as an area that was swept.
+ *
+ * Three layers, not one: the cells answer their own clicks, the area outline
+ * carries the drag handles, and the draft ring is what a polygon looks like
+ * before it is confirmed. The eye toggle hides all three and keeps the grid.
+ *
+ * The geometry is `lib/gridSearch.js`; this holds what is open, what is drawn,
+ * where the sweep is, and what the case has on disk.
+ *
+ * @param {object} deps
+ * @param {() => object|null} deps.engine the map, once it is up
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify
+ * @param {() => string|undefined} deps.caseId the open case
+ * @param {() => Promise<{id: string}>} deps.ensureCase a grid needs a case to hold it
+ * @param {() => Promise<any>} deps.reloadCase
+ * @param {(lat: number, lon: number) => string} deps.coords how a point is titled
+ * @param {() => number} deps.zoom the view zoom, for a cell filed as a place
+ * @param {(engine: object) => object} [deps.surface] the drawing layer factory
+ */
+import * as gridSearch from '../../../lib/gridSearch.js';
+import { createSurface } from '../../../lib/map/surface.js';
+import { onEvent } from '../../../lib/events.js';
+
+const MAX_CELLS = gridSearch.MAX_CELLS;
+const SAVE_DEBOUNCE = 600;
+/** Marks travel sooner than the shape does: the other surface sweeping this
+ * grid is drawing what this one has marked, and a second of lag there reads as
+ * two people marking the same cell twice. */
+const MARK_DEBOUNCE = 250;
+
+/**
+ * Status → cell paint. Unchecked is a bright thin outline so the lattice reads
+ * 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: { 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 },
+};
+/** The cell under review: cyan, distinct from both the yellow flag and the
+ * grey fill for a colour-blind reader. */
+const REVIEW_STYLE = { stroke: '#33c9ff', strokeWidth: 2.5, strokeOpacity: 1 };
+const AOI_STYLE = {
+ stroke: '#f5a623',
+ strokeWidth: 1.5,
+ strokeOpacity: 0.9,
+ dash: '5 4',
+ interactive: false,
+};
+const DRAFT_STYLE = { stroke: '#f5a623', strokeWidth: 1.5, strokeOpacity: 0.95, dash: '5 4' };
+/** A handle is an empty box the CSS draws; the shape only says where it is. */
+const HANDLE = { className: 'grid-handle', size: [16, 16], anchor: [8, 8] };
+const CORNERS = ['sw', 'se', 'nw', 'ne'];
+const AOI_OUTLINE = 'outline'; // the one shape the drag handles reshape live
+const DRAFT_RING = 'ring';
+/** A drag under this many px either way is a stray click, not an area. */
+const MIN_DRAG_PX = 12;
+
+export function createGridState({
+ engine,
+ api,
+ notify,
+ caseId,
+ ensureCase,
+ reloadCase,
+ coords,
+ zoom,
+ surface = createSurface,
+}) {
+ let on = $state(false);
+ let grid = $state(null); // the open grid spec, or null
+ let name = $state(null); // slug of the open grid's file
+ // Which revision of the file on disk this grid was built from. The same sweep
+ // can be worked from the capture extension over another map, and a save
+ // carrying our whole spec would put back the cells it marked in between.
+ // Claiming the base is what lets the server refuse that rather than lose them.
+ let baseRevision = null;
+ let list = $state([]); // summaries of this case's saved grids
+ let collapsed = $state(false);
+ let cellMetres = $state(500); // what the next area is drawn with
+ let drawMode = $state(null); // null | 'rect' | 'polygon'
+ let draft = $state([]); // polygon vertices being placed, [{ lat, lon }]
+ let editArea = $state(false);
+ let hidden = $state(false); // keep the grid, take it off the map
+ let renaming = $state(false);
+ let renameText = $state('');
+ let reviewKey = $state(null); // 'i:j' of the cell under review
+
+ let cellsLayer = null;
+ let aoiLayer = null;
+ let draftLayer = null;
+ let dragBounds = null; // live rect bounds while a corner handle is dragged
+ let liveVerts = null; // live polygon vertices while a vertex handle is dragged
+ let saveTimer = null;
+ let listedFor = null; // the case the list was read for
+ //. Cells marked since the file was last told: "i:j" -> status, or null for one
+ //. cleared back to unchecked. Kept as a patch rather than as a copy of the
+ //. grid, for the reason `sendMarks` states.
+ let unsent = {};
+ let markTimer = null;
+ //. Whether the shape or the title has moved since the file was last written.
+ let specDirty = false;
+
+ // -- layers ---------------------------------------------------------------
+
+ function ensureLayers() {
+ const map = engine();
+ if (!map) return false;
+ cellsLayer ??= surface(map);
+ aoiLayer ??= surface(map);
+ draftLayer ??= surface(map);
+ syncVisibility();
+ return true;
+ }
+
+ function syncVisibility() {
+ for (const layer of [cellsLayer, aoiLayer, draftLayer]) layer?.visible(!hidden);
+ }
+
+ function clearLayers() {
+ cellsLayer?.clear();
+ aoiLayer?.clear();
+ draftLayer?.clear();
+ }
+
+ function cellStyle(key) {
+ const base = CELL_STYLE[grid?.statuses[key] || 'unchecked'];
+ return key === reviewKey ? { ...base, ...REVIEW_STYLE } : base;
+ }
+
+ function renderCells() {
+ if (!ensureLayers()) return;
+ if (!grid) {
+ cellsLayer.clear();
+ return;
+ }
+ cellsLayer.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) {
+ cellsLayer?.patch(key, { style: cellStyle(key) });
+ }
+
+ function renderAoi() {
+ if (!ensureLayers()) return;
+ if (!grid || !editArea) {
+ aoiLayer.clear();
+ return;
+ }
+ const handle = (id, at, onDragStart, onDrag) => ({
+ id,
+ kind: 'marker',
+ at,
+ ...HANDLE,
+ draggable: true,
+ keyboard: false,
+ zIndex: 1200,
+ onDragStart,
+ onDrag,
+ onDragEnd: () => (grid.aoi.type === 'rect' ? commitResize() : commitVertEdit()),
+ });
+ if (grid.aoi.type === 'rect') {
+ const bounds = gridSearch.aoiBounds(grid.aoi);
+ aoiLayer.set([
+ { id: AOI_OUTLINE, kind: 'rect', bounds, style: AOI_STYLE },
+ ...CORNERS.map((corner) => {
+ const [lat, lon] = gridSearch.cornerLatLng(bounds, 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
+ aoiLayer.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 draftRing() {
+ return gridSearch
+ .closeRing(draft.map((point) => [point.lat, point.lon]))
+ .map(([lat, lon]) => ({ lat, lon }));
+ }
+
+ function renderDraft() {
+ if (!ensureLayers()) return;
+ if (drawMode !== 'polygon') {
+ draftLayer.clear();
+ return;
+ }
+ draftLayer.set([
+ { id: DRAFT_RING, kind: 'line', points: draftRing(), style: DRAFT_STYLE },
+ ...draft.map((point, k) => ({
+ id: k,
+ kind: 'marker',
+ at: point,
+ ...HANDLE,
+ draggable: true,
+ keyboard: false,
+ zIndex: 1200,
+ onDrag: (at) => {
+ draft[k] = at;
+ draftLayer.patch(DRAFT_RING, { points: draftRing() });
+ },
+ onDragEnd: renderDraft,
+ })),
+ ]);
+ }
+
+ function render() {
+ renderCells();
+ renderAoi();
+ }
+
+ // -- marking cells --------------------------------------------------------
+
+ /** One cell marked: on screen at once, on disk as a patch a moment later. */
+ function markCell(key, status) {
+ if (status) grid.statuses[key] = status;
+ else delete grid.statuses[key];
+ unsent[key] = status ?? null;
+ restyleCell(key);
+ scheduleMarks();
+ }
+
+ function cycleCell(i, j) {
+ const key = gridSearch.cellKey(i, j);
+ // during a sweep, clicking the cell you're reviewing clears it and moves on
+ // (same as the Clear button) — you're looking right at it
+ if (reviewKey && key === reviewKey) {
+ markReview('cleared');
+ return;
+ }
+ markCell(key, gridSearch.cycleStatus(grid.statuses[key]));
+ }
+
+ function flagCell(i, j) {
+ const key = gridSearch.cellKey(i, j);
+ markCell(key, grid.statuses[key] === 'flagged' ? null : 'flagged');
+ }
+
+ // -- reshaping the area ---------------------------------------------------
+
+ function onCornerDrag(corner, at) {
+ if (!dragBounds) return;
+ 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;
+ aoiLayer.patch(AOI_OUTLINE, { bounds: gridSearch.normalizeBounds(dragBounds) });
+ }
+
+ function onVertexDrag(k, at) {
+ if (!liveVerts) return;
+ liveVerts[k] = [at.lat, at.lon];
+ aoiLayer.patch(AOI_OUTLINE, { points: liveVerts.map(([lat, lon]) => ({ lat, lon })) });
+ }
+
+ /** Keep a reshaped grid, or refuse it and snap the handles back. */
+ function adopt(resized, refusal) {
+ if (gridSearch.estimateCells(resized) > MAX_CELLS) {
+ notify(refusal, 'warn', 5000);
+ renderAoi(); // snap the handles back
+ return false;
+ }
+ grid = resized;
+ render();
+ scheduleSave();
+ return true;
+ }
+
+ function commitResize() {
+ if (!dragBounds || !grid) return;
+ const bounds = gridSearch.normalizeBounds(dragBounds);
+ dragBounds = null;
+ adopt(
+ gridSearch.resizeRect(grid, bounds),
+ `That area is too fine for ${grid.cell_m} m cells. Keeping the previous size`
+ );
+ }
+
+ function commitVertEdit() {
+ if (!liveVerts || !grid) return;
+ const vertices = liveVerts;
+ liveVerts = null;
+ adopt(
+ gridSearch.resizePolygon(grid, vertices),
+ `That shape is too fine for ${grid.cell_m} m cells. Keeping the previous one`
+ );
+ }
+
+ // -- drawing a new area ---------------------------------------------------
+
+ function cancelDraw() {
+ const wasDrawing = drawMode;
+ drawMode = null;
+ draft = [];
+ draftLayer?.clear();
+ if (wasDrawing && grid) renderCells(); // restore the cells hidden while drawing
+ }
+
+ /**
+ * Drawing an area always makes a *new* grid: the case can hold several, and
+ * the one being left stays saved. Resizing the current one is the handles.
+ */
+ async function applyArea(aoi) {
+ const metres = Math.max(10, Number(cellMetres) || 500); // never a NaN lattice
+ const next = gridSearch.createGrid(aoi, metres);
+ if (gridSearch.estimateCells(next) > MAX_CELLS) {
+ notify(`That area exceeds the ${MAX_CELLS}-cell limit. Use a larger cell size.`, 'warn', 6000);
+ renderCells(); // restore the previous grid we hid to draw
+ return null;
+ }
+ await ensureCase(); // a grid is case state; make sure there is one to hold it
+ await flushSave(); // persist the grid we're leaving before switching
+ const centre = gridSearch.aoiCenter(aoi);
+ next.title = coords(centre.lat, centre.lon);
+ grid = next;
+ name = `grid-${Date.now().toString(36)}`;
+ baseRevision = null; // nothing on disk to be behind yet
+ // a patch belongs to the file it was made on, and that file is not this one
+ unsent = {};
+ specDirty = false;
+ listedFor = caseId();
+ reviewKey = null;
+ editArea = false;
+ hidden = false;
+ render();
+ await save(); // create it on disk now, then refresh the picker
+ await refreshList();
+ return grid;
+ }
+
+ // -- the sweep ------------------------------------------------------------
+
+ function stopReview() {
+ if (reviewKey) setReview(null);
+ }
+
+ function setReview(key) {
+ const previous = reviewKey;
+ reviewKey = key;
+ if (previous) restyleCell(previous);
+ if (key) restyleCell(key);
+ }
+
+ function flyToCell([i, j]) {
+ setReview(gridSearch.cellKey(i, j));
+ engine()?.fitBounds(gridSearch.cellBounds(grid, i, j), {
+ padding: [80, 80],
+ maxZoom: 20,
+ animate: true,
+ });
+ }
+
+ function advance() {
+ const next = gridSearch.nextUnchecked(grid, reviewKey);
+ if (!next) {
+ setReview(null);
+ notify('Sweep complete', 'ok');
+ return;
+ }
+ flyToCell(next);
+ }
+
+ function markReview(status) {
+ if (!reviewKey) return;
+ markCell(reviewKey, status ?? null);
+ advance();
+ }
+
+ // -- persistence ----------------------------------------------------------
+ //
+ // A sweep is two different things in one file, and they are written
+ // differently because they fail differently.
+ //
+ // **Marks are a patch.** The same grid is swept from here and from the
+ // extension's panel over another map, and a whole-spec save carries every
+ // cell: the copy this tab loaded goes back over whatever the other one marked
+ // in between. So a marked cell travels as the cell that was marked
+ // (`api/satellite.py`, `apply_grid_marks`), two sweeps of different cells both
+ // land, and the same cell twice resolves last-writer-wins — which is what
+ // anybody marking the same cell twice expects.
+ //
+ // **The shape is a spec.** Redrawing an area or renaming it is one analyst's
+ // decision about the whole file, so it claims the revision it was built from
+ // and is refused if the file has moved on. Refused is not lost: what moved the
+ // file was someone's marks, and marks and shape are separate halves — so they
+ // are put together and written once more rather than handed back to be redone.
+
+ function scheduleSave() {
+ specDirty = true;
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ saveTimer = null;
+ save();
+ }, SAVE_DEBOUNCE);
+ }
+
+ function scheduleMarks() {
+ clearTimeout(markTimer);
+ markTimer = setTimeout(() => {
+ markTimer = null;
+ sendMarks();
+ }, MARK_DEBOUNCE);
+ }
+
+ /** Persist every pending change to the *current* grid before switching away.
+ * The shape only where it moved: a spec written for nothing is a revision
+ * bump that refuses whatever the other surface had in hand. */
+ async function flushSave() {
+ clearTimeout(markTimer);
+ markTimer = null;
+ clearTimeout(saveTimer);
+ saveTimer = null;
+ await sendMarks();
+ if (specDirty) await save();
+ }
+
+ /** The cells marked here since the last send, as the patch that carries them. */
+ async function sendMarks() {
+ const id = caseId();
+ if (!id || !grid || !name || !Object.keys(unsent).length) return;
+ // Nothing on disk to patch: this grid has never been written — its own save
+ // is what carries these, and what writes the file they would be patching.
+ if (baseRevision === null) return save();
+ const slug = name;
+ const marks = unsent;
+ unsent = {};
+ try {
+ const answer = await api.post(`/api/cases/${id}/search-grids/${slug}/marks`, { marks });
+ if (name === slug) baseRevision = answer?.revision ?? baseRevision;
+ } catch (e) {
+ // Put them back, without stepping on any made since: a mark that has been
+ // forgotten is a cell the analyst believes is swept and nothing recorded.
+ unsent = { ...marks, ...unsent };
+ notify(`Could not save that mark: ${e.message}`, 'danger', 5000);
+ }
+ }
+
+ async function save({ merge = true } = {}) {
+ const id = caseId();
+ if (!id || !grid || !name) return;
+ const slug = name;
+ // the spec below carries these, so they stop being unsent — and go back if
+ // it never lands
+ const carried = unsent;
+ unsent = {};
+ try {
+ const spec = JSON.parse(JSON.stringify(grid)); // strip the $state proxy
+ const saved = await api.put(`/api/cases/${id}/search-grids/${slug}`, {
+ spec,
+ title: grid.title,
+ base_revision: baseRevision,
+ });
+ if (name === slug) {
+ baseRevision = saved?.revision ?? null;
+ specDirty = false;
+ }
+ } catch (e) {
+ unsent = { ...carried, ...unsent };
+ // One retry, and only one: a second refusal is a file being written faster
+ // than this can read it, and looping on that is worse than saying so.
+ if (e.status === 409 && merge) return saveOverTheirMarks(slug);
+ notify(`Could not save the grid: ${e.message}`, 'danger', 5000);
+ }
+ }
+
+ /** Their marks, our shape, written once. */
+ async function saveOverTheirMarks(slug) {
+ const id = caseId();
+ try {
+ const fresh = await api.get(`/api/cases/${id}/search-grids/${slug}`);
+ if (name !== slug) return; // moved on already
+ grid.statuses = mergedStatuses(fresh);
+ baseRevision = fresh.revision ?? 0;
+ render();
+ await save({ merge: false });
+ } catch (e) {
+ notify(`This sweep changed elsewhere and could not be merged: ${e.message}`, 'danger', 6000);
+ }
+ }
+
+ /** What the file says has been swept, with anything marked here that it has
+ * not been told about yet on top — the only copy of those. */
+ function mergedStatuses(fresh) {
+ const statuses = { ...(fresh.statuses || {}) };
+ for (const [key, status] of Object.entries(unsent)) {
+ if (status) statuses[key] = status;
+ else delete statuses[key];
+ }
+ return statuses;
+ }
+
+ /**
+ * The open sweep, re-read because something else wrote it.
+ *
+ * The file wins whole — the other surface may have reshaped the area, not only
+ * marked a cell — and the marks still in hand here go back on top. Skipped
+ * while a shape of ours has not reached the file: that save is about to claim
+ * it, and adopting first would throw the reshape away. Nothing is lost by
+ * waiting, because a save that is refused merges instead.
+ */
+ async function adoptFile(slug) {
+ const id = caseId();
+ if (!id || specDirty) return;
+ try {
+ const fresh = await api.get(`/api/cases/${id}/search-grids/${slug}`);
+ if (name !== slug) return;
+ const statuses = mergedStatuses(fresh);
+ grid = { ...fresh, statuses };
+ baseRevision = fresh.revision ?? 0;
+ render();
+ } catch {
+ // deleted, or the case closed: the picker refresh that follows says so
+ }
+ }
+
+ /**
+ * One nudge about a grid (`api/events.py`), from anywhere but here.
+ *
+ * The app's own map and every map panel the extension has open work the same
+ * files, and each of them hears its own writes come back. A revision this
+ * surface is already holding is one of those, and re-reading the file for it
+ * would be a request per marked cell.
+ */
+ function onGridEvent(event) {
+ if (!event || event.case_id !== caseId()) return;
+ if (event.type === 'grid-removed') {
+ if (name === event.name) {
+ close();
+ notify('This sweep was discarded elsewhere', 'warn', 5000);
+ }
+ refreshList();
+ return;
+ }
+ // a grid drawn anywhere is a picker entry here, open or not
+ if (event.type === 'grid') refreshList();
+ if (name !== event.name || Number(event.revision) <= (baseRevision ?? 0)) return;
+ adoptFile(event.name);
+ }
+
+ const listening = [
+ onEvent('grid', onGridEvent),
+ onEvent('grid-marks', onGridEvent),
+ onEvent('grid-removed', onGridEvent),
+ ];
+
+ async function refreshList() {
+ const id = caseId();
+ if (!id) {
+ list = [];
+ return;
+ }
+ try {
+ list = await api.get(`/api/cases/${id}/search-grids`);
+ } catch {
+ list = [];
+ }
+ }
+
+ /** Close the open grid — it stays on disk; the draw buttons start a fresh one. */
+ function close() {
+ clearTimeout(markTimer);
+ markTimer = null;
+ unsent = {};
+ specDirty = false;
+ grid = null;
+ name = null;
+ baseRevision = null;
+ reviewKey = null;
+ editArea = false;
+ cancelDraw();
+ clearLayers();
+ }
+
+ return {
+ get on() {
+ return on;
+ },
+ get grid() {
+ return grid;
+ },
+ get name() {
+ return name;
+ },
+ get collapsed() {
+ return collapsed;
+ },
+ set collapsed(value) {
+ collapsed = value;
+ },
+ get cellMetres() {
+ return cellMetres;
+ },
+ set cellMetres(value) {
+ cellMetres = value;
+ },
+ get drawMode() {
+ return drawMode;
+ },
+ get draft() {
+ return draft;
+ },
+ get editArea() {
+ return editArea;
+ },
+ get hidden() {
+ return hidden;
+ },
+ get renaming() {
+ return renaming;
+ },
+ set renaming(value) {
+ renaming = value;
+ },
+ get renameText() {
+ return renameText;
+ },
+ set renameText(value) {
+ renameText = value;
+ },
+ get reviewKey() {
+ return reviewKey;
+ },
+ get coverage() {
+ return grid ? gridSearch.coverage(grid) : null;
+ },
+ /** The picker lists the grids you could switch to — never the open one. */
+ get others() {
+ return list.filter((entry) => entry.name !== name);
+ },
+
+ /** Open the mode. Exclusivity with the other map modes is the tool's. */
+ open() {
+ on = true;
+ hidden = false;
+ ensureLayers();
+ refreshList();
+ if (grid) render();
+ },
+
+ exit() {
+ on = false;
+ cancelDraw();
+ stopReview();
+ editArea = false;
+ clearLayers();
+ },
+
+ toggleHidden() {
+ hidden = !hidden;
+ syncVisibility();
+ return hidden;
+ },
+
+ startRename() {
+ if (!grid) return;
+ renameText = grid.title || '';
+ renaming = true;
+ },
+
+ commitRename() {
+ renaming = false;
+ if (!grid) return;
+ const title = renameText.trim();
+ if (title && title !== grid.title) {
+ grid.title = title;
+ scheduleSave();
+ }
+ },
+
+ /** Show the area box, to resize a rect's corners or reshape a polygon. */
+ toggleEditArea() {
+ if (!grid) return;
+ stopReview();
+ cancelDraw();
+ editArea = !editArea;
+ renderAoi();
+ },
+
+ startDraw(type) {
+ cancelDraw();
+ stopReview();
+ editArea = false;
+ hidden = false;
+ drawMode = type;
+ // hide the current cells while drawing so map clicks reach the canvas
+ // (polygon vertices) instead of being swallowed by a cell underneath
+ cellsLayer?.clear();
+ if (type === 'polygon') {
+ draft = [];
+ renderDraft();
+ }
+ },
+
+ cancelDraw,
+
+ /** A map click, while a polygon is being placed. False means it was not ours. */
+ addVertex(at) {
+ if (drawMode !== 'polygon') return false;
+ draft = [...draft, at];
+ renderDraft();
+ return true;
+ },
+
+ /** The rectangle drag finished. `null` — or a box too small to be meant —
+ * restores the cells that were hidden to draw over them. */
+ finishRect(corners) {
+ const wasDrawing = drawMode === 'rect';
+ drawMode = null;
+ if (!wasDrawing || !corners) {
+ if (grid) renderCells();
+ return null;
+ }
+ const { p1, p2, widthPx, heightPx } = corners;
+ if (widthPx < MIN_DRAG_PX || heightPx < MIN_DRAG_PX) {
+ if (grid) renderCells();
+ return null;
+ }
+ return applyArea({
+ type: 'rect',
+ bounds: gridSearch.normalizeBounds({
+ south: p1.lat,
+ north: p2.lat,
+ west: p1.lon,
+ east: p2.lon,
+ }),
+ });
+ },
+
+ confirmPolygon() {
+ if (draft.length < 3) return null;
+ const vertices = draft.map((point) => [point.lat, point.lon]);
+ drawMode = null;
+ draft = [];
+ draftLayer?.clear();
+ return applyArea({ type: 'polygon', vertices });
+ },
+
+ startReview() {
+ if (!grid) return;
+ editArea = false;
+ const cell = gridSearch.nextUnchecked(grid, null);
+ if (!cell) {
+ notify('Every cell is marked. Sweep complete', 'ok');
+ return;
+ }
+ flyToCell(cell);
+ },
+
+ advance,
+ markReview,
+
+ stopReview,
+
+ /** Flag the cell under review and file its centre as a place — a hit the
+ * analyst promotes into the case graph. */
+ async reviewToPlace() {
+ if (!reviewKey || !grid) return;
+ const [i, j] = gridSearch.parseKey(reviewKey);
+ const centre = gridSearch.cellCenter(grid, i, j);
+ markCell(reviewKey, 'flagged');
+ try {
+ const open = await ensureCase();
+ await api.post(`/api/cases/${open.id}/satellite/place`, {
+ lat: centre.lat,
+ lon: centre.lon,
+ zoom: Math.max(zoom(), 16),
+ bearing: 0,
+ });
+ await reloadCase();
+ notify('Cell flagged and saved as a place', 'ok');
+ } catch (e) {
+ notify(`Could not save place: ${e.message}`, 'danger', 6000);
+ }
+ },
+
+ async load(slug) {
+ const id = caseId();
+ if (!id) return;
+ cancelDraw();
+ stopReview();
+ editArea = false;
+ hidden = false;
+ await flushSave(); // persist the grid we're leaving
+ try {
+ grid = await api.get(`/api/cases/${id}/search-grids/${slug}`);
+ name = slug;
+ unsent = {}; // whatever is left belonged to the grid we just left
+ specDirty = false;
+ baseRevision = grid.revision ?? 0;
+ reviewKey = null;
+ ensureLayers();
+ render();
+ await refreshList(); // the grid we left becomes a picker entry
+ } catch (e) {
+ notify(`Could not load grid: ${e.message}`, 'danger', 6000);
+ }
+ },
+
+ /** The Discard button: persist the pending rename/marks, close, then relist
+ * so the just-closed grid shows its latest title. */
+ async discard() {
+ await flushSave();
+ close();
+ await refreshList();
+ },
+
+ async remove(slug) {
+ const id = caseId();
+ if (id) {
+ try {
+ await api.del(`/api/cases/${id}/search-grids/${slug}`);
+ } catch {
+ /* the file may already be gone — nothing left to do */
+ }
+ }
+ if (name === slug) close();
+ await refreshList();
+ },
+
+ /** A different case: drop whatever was open and read its own grids. True
+ * when the case actually changed. */
+ forCase(id) {
+ if (listedFor === id) return false;
+ listedFor = id;
+ clearTimeout(saveTimer); // the grid it belonged to is gone
+ saveTimer = null;
+ close();
+ refreshList();
+ return true;
+ },
+
+ render,
+ destroy() {
+ clearTimeout(saveTimer);
+ clearTimeout(markTimer);
+ for (const off of listening) off();
+ for (const layer of [cellsLayer, aoiLayer, draftLayer]) layer?.destroy();
+ cellsLayer = aoiLayer = draftLayer = null;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/grid.svelte.test.js b/frontend/src/tools/satellite/state/grid.svelte.test.js
new file mode 100644
index 0000000..67565cd
--- /dev/null
+++ b/frontend/src/tools/satellite/state/grid.svelte.test.js
@@ -0,0 +1,773 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createGridState } from './grid.svelte.js';
+import * as gridSearch from '../../../lib/gridSearch.js';
+import { dispatch } from '../../../lib/events.js';
+
+/**
+ * Grid Search, apart from the map it draws on.
+ *
+ * The lattice geometry has its own tests (lib/gridSearch.js); what is asserted
+ * here is which grid is open, what a switch away from it costs, and what a
+ * sweep writes.
+ */
+
+/** A box a few hundred metres across — a handful of cells at 500 m. */
+const AREA = { south: 50.44, north: 50.46, west: 30.51, east: 30.54 };
+const CORNERS = {
+ p1: { lat: AREA.south, lon: AREA.west },
+ p2: { lat: AREA.north, lon: AREA.east },
+ widthPx: 400,
+ heightPx: 300,
+};
+
+let api;
+let notify;
+let layers;
+let surface;
+let engine;
+let put;
+let marks;
+let revision;
+let ensureCase;
+let reloadCase;
+let currentCase;
+let stores;
+
+function layer() {
+ return {
+ set: vi.fn(),
+ clear: vi.fn(),
+ patch: vi.fn(),
+ visible: vi.fn(),
+ destroy: vi.fn(),
+ };
+}
+
+function store() {
+ const created = createGridState({
+ engine: () => engine,
+ api,
+ notify,
+ caseId: () => currentCase,
+ ensureCase,
+ reloadCase,
+ coords: (lat, lon) => `${lat.toFixed(3)}, ${lon.toFixed(3)}`,
+ zoom: () => 14,
+ surface,
+ });
+ // A store listens for nudges from the moment it exists, so one left behind by
+ // an earlier test would answer this one's. Torn down in `afterEach`.
+ stores.push(created);
+ return created;
+}
+
+/** The cell shapes last handed to the map — what a click on the map runs. */
+function cells() {
+ return layers[0].set.mock.calls.at(-1)[0];
+}
+
+/** A store with one rect grid drawn and every pending write settled. */
+async function drawn() {
+ const g = store();
+ g.open();
+ await vi.waitFor(() => expect(api.get).toHaveBeenCalled());
+ g.startDraw('rect');
+ await g.finishRect(CORNERS);
+ return g;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ stores = [];
+ currentCase = 'case-1';
+ notify = vi.fn();
+ put = [];
+ marks = [];
+ // One counter for both roads to the file, as the server keeps it: a marked
+ // cell moves the revision exactly as a rewritten shape does, which is what
+ // makes a stale whole-spec save recognisable.
+ revision = 0;
+ ensureCase = vi.fn(async () => ({ id: currentCase }));
+ reloadCase = vi.fn(async () => {});
+ api = {
+ get: vi.fn(async (path) => {
+ if (path.endsWith('/search-grids')) return [{ name: 'grid-old', title: 'Old sweep' }];
+ return gridSearch.createGrid({ type: 'rect', bounds: AREA }, 500);
+ }),
+ put: vi.fn(async (path, body) => {
+ put.push({ path, body });
+ return { name: 'grid-1', updated_at: '2026-09-10T10:00:00Z', revision: ++revision };
+ }),
+ post: vi.fn(async (path, body) => {
+ if (!path.endsWith('/marks')) return { id: 'place-1' };
+ marks.push({ path, body });
+ return { name: 'grid-1', revision: ++revision };
+ }),
+ del: vi.fn(async () => ({})),
+ };
+ layers = [layer(), layer(), layer()];
+ let handed = 0;
+ surface = vi.fn(() => layers[handed++] ?? layer());
+ engine = { fitBounds: vi.fn() };
+});
+
+afterEach(() => {
+ for (const created of stores) created.destroy();
+ vi.useRealTimers();
+});
+
+describe('opening the mode', () => {
+ it('reads the case’s saved grids', async () => {
+ const g = store();
+ g.open();
+ await vi.waitFor(() => expect(g.others).toHaveLength(1));
+ expect(api.get).toHaveBeenCalledWith('/api/cases/case-1/search-grids');
+ });
+
+ it('draws nothing before the map is up', () => {
+ engine = null;
+ const g = store();
+ g.open();
+ expect(surface).not.toHaveBeenCalled();
+ });
+
+ it('takes three layers: the cells, the area outline and the draft ring', () => {
+ const g = store();
+ g.open();
+ expect(surface).toHaveBeenCalledTimes(3);
+ });
+
+ it('leaves the map bare on the way out, keeping the grid', async () => {
+ const g = await drawn();
+ g.exit();
+ expect(g.on).toBe(false);
+ expect(g.grid).not.toBe(null);
+ for (const l of layers) expect(l.clear).toHaveBeenCalled();
+ });
+});
+
+describe('drawing an area', () => {
+ it('makes a grid the lattice covers', async () => {
+ const g = await drawn();
+ expect(g.grid.aoi.type).toBe('rect');
+ expect(g.name).toMatch(/^grid-/);
+ expect([...gridSearch.cellsInAoi(g.grid)].length).toBeGreaterThan(0);
+ });
+
+ it('titles it by where it is, so the picker names a place', async () => {
+ const g = await drawn();
+ expect(g.grid.title).toBe('50.450, 30.525');
+ });
+
+ it('always makes a *new* grid rather than redrawing the one you are on', async () => {
+ const g = await drawn();
+ const first = g.name;
+ g.grid.statuses['0:0'] = 'flagged';
+
+ vi.setSystemTime(new Date(Date.now() + 5000));
+ g.startDraw('rect');
+ await g.finishRect(CORNERS);
+ expect(g.name).not.toBe(first);
+ expect(g.grid.statuses).toEqual({}); // the marks stayed with the old one
+ });
+
+ it('writes the grid it is leaving before the next one opens', async () => {
+ const g = await drawn();
+ put.length = 0;
+ const leaving = g.name;
+ const marked = cells()[0].id;
+ cells()[0].onClick(); // a mark still inside the debounce
+
+ vi.setSystemTime(new Date(Date.now() + 5000));
+ g.startDraw('rect');
+ await g.finishRect(CORNERS);
+ expect(marks[0].path).toContain(leaving);
+ expect(marks[0].body.marks).toEqual({ [marked]: 'cleared' });
+ });
+
+ it('needs a case to hold the grid', async () => {
+ await drawn();
+ expect(ensureCase).toHaveBeenCalled();
+ });
+
+ it('refuses a lattice too fine for its area, keeping what was there', async () => {
+ const g = await drawn();
+ const kept = g.grid;
+ g.cellMetres = 1; // a metre grid over a city block
+ g.startDraw('rect');
+ const made = await g.finishRect(CORNERS);
+ expect(made).toBe(null);
+ expect(g.grid).toBe(kept);
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('cell limit'),
+ 'warn',
+ expect.any(Number)
+ );
+ });
+
+ it('never builds a NaN lattice out of an emptied cell-size box', async () => {
+ const g = store();
+ g.open();
+ g.cellMetres = '';
+ g.startDraw('rect');
+ await g.finishRect(CORNERS);
+ expect(Number.isFinite(g.grid.cell_m)).toBe(true);
+ });
+
+ it('treats a stray click as no area at all', async () => {
+ const g = await drawn();
+ const kept = g.grid;
+ g.startDraw('rect');
+ const made = await g.finishRect({ ...CORNERS, widthPx: 4, heightPx: 3 });
+ expect(made).toBe(null);
+ expect(g.grid).toBe(kept);
+ expect(g.drawMode).toBe(null);
+ });
+
+ it('restores the cells it hid to draw over them', async () => {
+ const g = await drawn();
+ g.startDraw('rect');
+ expect(layers[0].clear).toHaveBeenCalled();
+ layers[0].set.mockClear();
+ await g.finishRect(null);
+ expect(layers[0].set).toHaveBeenCalled();
+ });
+});
+
+describe('drawing a polygon', () => {
+ it('takes map clicks as vertices only while that tool is armed', async () => {
+ const g = await drawn();
+ expect(g.addVertex({ lat: 50.45, lon: 30.52 })).toBe(false);
+
+ g.startDraw('polygon');
+ expect(g.addVertex({ lat: 50.45, lon: 30.52 })).toBe(true);
+ expect(g.draft).toHaveLength(1);
+ });
+
+ it('will not confirm a shape that is not one', async () => {
+ const g = await drawn();
+ g.startDraw('polygon');
+ g.addVertex({ lat: 50.45, lon: 30.52 });
+ g.addVertex({ lat: 50.46, lon: 30.53 });
+ expect(g.confirmPolygon()).toBe(null);
+ });
+
+ it('builds a grid over three corners and drops the draft', async () => {
+ const g = await drawn();
+ g.startDraw('polygon');
+ g.addVertex({ lat: 50.44, lon: 30.51 });
+ g.addVertex({ lat: 50.46, lon: 30.51 });
+ g.addVertex({ lat: 50.46, lon: 30.54 });
+ await g.confirmPolygon();
+ expect(g.grid.aoi.type).toBe('polygon');
+ expect(g.draft).toEqual([]);
+ expect(g.drawMode).toBe(null);
+ });
+
+ it('cancelling drops the draft and puts the cells back', async () => {
+ const g = await drawn();
+ g.startDraw('polygon');
+ g.addVertex({ lat: 50.45, lon: 30.52 });
+ layers[0].set.mockClear();
+ g.cancelDraw();
+ expect(g.draft).toEqual([]);
+ expect(layers[0].set).toHaveBeenCalled();
+ });
+});
+
+describe('marking cells', () => {
+ it('cycles a cell through its statuses and repaints only that one', async () => {
+ const g = await drawn();
+ layers[0].set.mockClear();
+ const [i, j] = [...gridSearch.cellsInAoi(g.grid)][0];
+ const key = gridSearch.cellKey(i, j);
+
+ const cell = layers[0].set.mock.calls.length;
+ g.grid.statuses[key] = gridSearch.cycleStatus(undefined);
+ expect(g.grid.statuses[key]).toBe('cleared');
+ expect(layers[0].set.mock.calls.length).toBe(cell); // never a rebuild
+ });
+
+ it('counts what has been swept', async () => {
+ const g = await drawn();
+ const total = [...gridSearch.cellsInAoi(g.grid)].length;
+ expect(g.coverage.total).toBe(total);
+ expect(g.coverage.cleared).toBe(0);
+ });
+
+ it('has no coverage to report with no grid open', () => {
+ expect(store().coverage).toBe(null);
+ });
+});
+
+describe('the sweep', () => {
+ it('flies to the first unchecked cell and puts it under review', async () => {
+ const g = await drawn();
+ g.startReview();
+ expect(g.reviewKey).not.toBe(null);
+ expect(engine.fitBounds).toHaveBeenCalled();
+ });
+
+ it('marks the cell under review and moves on', async () => {
+ const g = await drawn();
+ g.startReview();
+ const first = g.reviewKey;
+ g.markReview('cleared');
+ expect(g.grid.statuses[first]).toBe('cleared');
+ expect(g.reviewKey).not.toBe(first);
+ });
+
+ it('says so when every cell is marked, and leaves nothing under review', async () => {
+ const g = await drawn();
+ for (const [i, j] of gridSearch.cellsInAoi(g.grid)) {
+ g.grid.statuses[gridSearch.cellKey(i, j)] = 'cleared';
+ }
+ g.startReview();
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('Sweep complete'), 'ok');
+ expect(g.reviewKey).toBe(null);
+ });
+
+ it('ignores a mark with nothing under review', async () => {
+ const g = await drawn();
+ g.markReview('flagged');
+ expect(g.grid.statuses).toEqual({});
+ });
+
+ it('flags the cell under review and files its centre as a place', async () => {
+ const g = await drawn();
+ g.startReview();
+ const key = g.reviewKey;
+ await g.reviewToPlace();
+ expect(g.grid.statuses[key]).toBe('flagged');
+ expect(api.post).toHaveBeenCalledWith(
+ '/api/cases/case-1/satellite/place',
+ expect.objectContaining({ zoom: 16, bearing: 0 })
+ );
+ expect(reloadCase).toHaveBeenCalled();
+ });
+
+ it('keeps the flag when the place cannot be saved', async () => {
+ api.post = vi.fn(async () => {
+ throw new Error('refused');
+ });
+ const g = await drawn();
+ g.startReview();
+ const key = g.reviewKey;
+ await g.reviewToPlace();
+ expect(g.grid.statuses[key]).toBe('flagged');
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('Could not save place'),
+ 'danger',
+ expect.any(Number)
+ );
+ });
+});
+
+describe('the eye toggle', () => {
+ it('takes all three layers off the map and puts them back', async () => {
+ const g = await drawn();
+ expect(g.toggleHidden()).toBe(true);
+ for (const l of layers) expect(l.visible).toHaveBeenCalledWith(false);
+ expect(g.toggleHidden()).toBe(false);
+ for (const l of layers) expect(l.visible).toHaveBeenCalledWith(true);
+ });
+
+ it('keeps the grid itself', async () => {
+ const g = await drawn();
+ g.toggleHidden();
+ expect(g.grid).not.toBe(null);
+ });
+});
+
+describe('renaming', () => {
+ it('writes the new title', async () => {
+ const g = await drawn();
+ put.length = 0;
+ g.startRename();
+ g.renameText = 'Riverbank';
+ g.commitRename();
+ await vi.advanceTimersByTimeAsync(700);
+ expect(g.grid.title).toBe('Riverbank');
+ expect(put.at(-1).body.title).toBe('Riverbank');
+ });
+
+ it('an emptied box is not a title', async () => {
+ const g = await drawn();
+ const was = g.grid.title;
+ g.startRename();
+ g.renameText = ' ';
+ g.commitRename();
+ expect(g.grid.title).toBe(was);
+ });
+});
+
+describe('saving', () => {
+ it('debounces a run of marks into one patch', async () => {
+ const g = await drawn();
+ put.length = 0;
+ g.startReview();
+ g.markReview('cleared');
+ g.markReview('cleared');
+ g.markReview('flagged');
+ expect(marks).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(700);
+ expect(marks).toHaveLength(1);
+ });
+
+ /**
+ * The one property that lets two people sweep one area: a marked cell travels
+ * as that cell. A whole-spec save carries every other cell with it, so the
+ * copy this tab loaded would go back over whatever the extension's panel
+ * marked in between — silently, since it is a perfectly valid grid.
+ */
+ it('sends the cells that were marked and never the sweep around them', async () => {
+ const g = await drawn();
+ put.length = 0;
+ g.startReview();
+ g.markReview('cleared');
+ await vi.advanceTimersByTimeAsync(700);
+ expect(put).toHaveLength(0);
+ expect(marks.at(-1).path).toBe(`/api/cases/case-1/search-grids/${g.name}/marks`);
+ expect(Object.values(marks.at(-1).body.marks)).toEqual(['cleared']);
+ });
+
+ it('a cell cleared back to unchecked is sent as one, not left out', async () => {
+ // Clearing a cell is a patch that says "nothing here" — left out of the
+ // patch instead, the mark could never be taken back from another surface.
+ const g = await drawn();
+ const cell = cells()[0];
+ cell.onClick(); // unchecked → cleared
+ cell.onClick(); // → flagged
+ cell.onClick(); // → unchecked again
+ await vi.advanceTimersByTimeAsync(700);
+ expect(marks.at(-1).body.marks[cell.id]).toBe(null);
+ expect(g.grid.statuses[cell.id]).toBe(undefined);
+ });
+
+ it('a mark that could not be sent goes back on the patch', async () => {
+ const g = await drawn();
+ api.post = vi.fn(async () => {
+ throw new Error('disk full');
+ });
+ g.startReview();
+ g.markReview('cleared');
+ await vi.advanceTimersByTimeAsync(700);
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('Could not save that mark'),
+ 'danger',
+ expect.any(Number)
+ );
+ // it is still owed, so the next send carries it
+ api.post = vi.fn(async (path, body) => {
+ marks.push({ path, body });
+ return { name: 'grid-1', revision: ++revision };
+ });
+ g.markReview('flagged');
+ await vi.advanceTimersByTimeAsync(700);
+ expect(Object.keys(marks.at(-1).body.marks)).toHaveLength(2);
+ });
+
+ it('claims the copy it is replacing, so a stale shape can be refused', async () => {
+ const g = await drawn();
+ expect(put.at(-1).body).toHaveProperty('base_revision', null); // nothing on disk yet
+ const written = revision;
+ g.startRename();
+ g.renameText = 'Riverbank';
+ g.commitRename();
+ await vi.advanceTimersByTimeAsync(700);
+ // the rename claims what the create wrote, not what was loaded
+ expect(put.at(-1).body.base_revision).toBe(written);
+ });
+
+ /**
+ * A shape refused because the file moved on is not a shape to redo. What moved
+ * it was someone marking a cell, and a mark and an outline are separate halves
+ * of one file — so both are kept and the file is written once more. The old
+ * behaviour here was "reloaded it, redo your last mark", which threw away the
+ * area the analyst had just dragged.
+ */
+ it('puts a reshape on top of marks made elsewhere, keeping both', async () => {
+ const g = await drawn();
+ put.length = 0;
+ const theirs = {
+ ...gridSearch.createGrid({ type: 'rect', bounds: AREA }, 500),
+ statuses: { '0:0': 'flagged' },
+ updated_at: '2026-09-10T11:00:00Z',
+ revision: 9,
+ };
+ api.get = vi.fn(async (path) =>
+ path.endsWith('/search-grids') ? [] : theirs
+ );
+ let refused = true;
+ api.put = vi.fn(async (path, body) => {
+ put.push({ path, body });
+ if (refused) {
+ refused = false;
+ throw Object.assign(new Error('changed elsewhere'), { status: 409 });
+ }
+ return { name: 'grid-1', updated_at: '2026-09-10T11:01:00Z', revision: 10 };
+ });
+
+ g.startRename();
+ g.renameText = 'Riverbank';
+ g.commitRename();
+ await vi.advanceTimersByTimeAsync(700);
+
+ expect(g.grid.statuses).toEqual({ '0:0': 'flagged' }); // theirs
+ expect(g.grid.title).toBe('Riverbank'); // ours
+ expect(put.at(-1).body.base_revision).toBe(9); // written on top of their copy
+ expect(put.at(-1).body.title).toBe('Riverbank');
+ });
+
+ it('says so when a grid cannot be written', async () => {
+ api.put = vi.fn(async () => {
+ throw new Error('disk full');
+ });
+ const g = await drawn();
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('Could not save the grid'),
+ 'danger',
+ expect.any(Number)
+ );
+ });
+});
+
+/**
+ * The same sweep, worked from somewhere else at the same time — the app's other
+ * tab, or the extension's panel over a map this one cannot see.
+ *
+ * The nudges are the app's own channel (`api/events.py`, `lib/events.js`) and
+ * say only what changed, so every one of them ends in a read. What is asserted
+ * here is which nudges are worth a read and what the answer is allowed to do to
+ * what the analyst is looking at.
+ */
+describe('a sweep worked from elsewhere', () => {
+ /** A file as another surface left it. */
+ function theirs(statuses, rev = 9) {
+ return {
+ ...gridSearch.createGrid({ type: 'rect', bounds: AREA }, 500),
+ statuses,
+ updated_at: '2026-09-10T11:00:00Z',
+ revision: rev,
+ };
+ }
+
+ function answers(file) {
+ api.get = vi.fn(async (path) =>
+ path.endsWith('/search-grids') ? [{ name: 'grid-old', title: 'Old sweep' }] : file
+ );
+ }
+
+ it('a cell marked elsewhere appears without a reload', async () => {
+ const g = await drawn();
+ answers(theirs({ '0:0': 'flagged' }));
+ dispatch({ type: 'grid-marks', case_id: 'case-1', name: g.name, revision: 9 });
+ await vi.waitFor(() => expect(g.grid.statuses).toEqual({ '0:0': 'flagged' }));
+ });
+
+ it('its own mark, heard back, costs no read', async () => {
+ const g = await drawn();
+ const written = revision;
+ api.get = vi.fn(async () => theirs({}));
+ dispatch({ type: 'grid-marks', case_id: 'case-1', name: g.name, revision: written });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(api.get).not.toHaveBeenCalled();
+ });
+
+ it('a mark still in hand here survives the file arriving', async () => {
+ const g = await drawn();
+ const mine = cells()[0].id;
+ api.post = vi.fn(async () => {
+ throw new Error('disk full'); // so it stays unsent, and is the only copy
+ });
+ cells()[0].onClick();
+ await vi.advanceTimersByTimeAsync(700);
+ answers(theirs({ '1:1': 'flagged' }));
+ dispatch({ type: 'grid-marks', case_id: 'case-1', name: g.name, revision: 9 });
+ await vi.waitFor(() => expect(g.grid.statuses['1:1']).toBe('flagged'));
+ expect(g.grid.statuses[mine]).toBe('cleared');
+ });
+
+ it('an area reshaped elsewhere is taken whole', async () => {
+ const g = await drawn();
+ const wider = { south: 50.4, north: 50.5, west: 30.5, east: 30.6 };
+ answers({
+ ...gridSearch.createGrid({ type: 'rect', bounds: wider }, 500),
+ statuses: {},
+ revision: 9,
+ });
+ dispatch({ type: 'grid', case_id: 'case-1', name: g.name, revision: 9 });
+ await vi.waitFor(() => expect(g.grid.aoi.bounds.north).toBe(wider.north));
+ });
+
+ it('a shape of ours that has not landed is not overwritten by the nudge', async () => {
+ const g = await drawn();
+ answers(theirs({ '0:0': 'flagged' }));
+ g.startRename();
+ g.renameText = 'Riverbank';
+ g.commitRename(); // debounced: the file has not heard about it yet
+ dispatch({ type: 'grid-marks', case_id: 'case-1', name: g.name, revision: 9 });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(g.grid.title).toBe('Riverbank');
+ });
+
+ it('a sweep discarded elsewhere closes here, and says so', async () => {
+ const g = await drawn();
+ dispatch({ type: 'grid-removed', case_id: 'case-1', name: g.name });
+ expect(g.grid).toBe(null);
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('discarded elsewhere'),
+ 'warn',
+ expect.any(Number)
+ );
+ });
+
+ it('a grid drawn elsewhere shows up in the picker', async () => {
+ const g = await drawn();
+ api.get = vi.fn(async (path) =>
+ path.endsWith('/search-grids')
+ ? [{ name: 'grid-new', title: 'Quay sweep' }]
+ : theirs({})
+ );
+ dispatch({ type: 'grid', case_id: 'case-1', name: 'grid-new', revision: 1 });
+ await vi.waitFor(() => expect(g.others.map((e) => e.name)).toContain('grid-new'));
+ });
+
+ it('another case is another case', async () => {
+ const g = await drawn();
+ api.get = vi.fn(async () => theirs({ '0:0': 'flagged' }));
+ dispatch({ type: 'grid-marks', case_id: 'case-2', name: g.name, revision: 9 });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(api.get).not.toHaveBeenCalled();
+ });
+});
+
+describe('switching grids', () => {
+ it('sends the marks of the one being left before reading the next', async () => {
+ const g = await drawn();
+ put.length = 0;
+ const leaving = g.name;
+ cells()[0].onClick(); // marked, and still inside the debounce
+ await g.load('grid-old');
+ expect(marks.at(-1).path).toContain(leaving);
+ expect(g.name).toBe('grid-old');
+ });
+
+ it('leaves a grid nothing changed on alone', async () => {
+ // A spec written for nothing bumps the revision, which is how the other
+ // surface's pending save gets refused for no reason at all.
+ const g = await drawn();
+ put.length = 0;
+ await g.load('grid-old');
+ expect(put).toHaveLength(0);
+ expect(marks).toHaveLength(0);
+ });
+
+ it('says so when a grid cannot be read, and keeps the one open', async () => {
+ const g = await drawn();
+ const kept = g.grid;
+ api.get = vi.fn(async (path) => {
+ if (path.endsWith('/search-grids')) return [];
+ throw new Error('gone');
+ });
+ await g.load('grid-missing');
+ expect(g.grid).toBe(kept);
+ expect(notify).toHaveBeenCalledWith(
+ expect.stringContaining('Could not load grid'),
+ 'danger',
+ expect.any(Number)
+ );
+ });
+
+ it('never offers the open grid as one to switch to', async () => {
+ const g = await drawn();
+ await g.load('grid-old');
+ expect(g.others.map((entry) => entry.name)).not.toContain('grid-old');
+ });
+
+ it('discarding writes what is pending, then closes', async () => {
+ const g = await drawn();
+ put.length = 0;
+ cells()[0].onClick();
+ await g.discard();
+ expect(marks).toHaveLength(1);
+ expect(g.grid).toBe(null);
+ expect(g.name).toBe(null);
+ });
+
+ it('deleting the open grid closes it', async () => {
+ const g = await drawn();
+ await g.remove(g.name);
+ expect(g.grid).toBe(null);
+ expect(api.del).toHaveBeenCalled();
+ });
+
+ it('deleting another grid leaves the open one alone', async () => {
+ const g = await drawn();
+ const open = g.name;
+ await g.remove('grid-old');
+ expect(g.name).toBe(open);
+ });
+
+ it('a file already gone is not an error to report', async () => {
+ api.del = vi.fn(async () => {
+ throw new Error('404');
+ });
+ const g = await drawn();
+ await expect(g.remove('grid-old')).resolves.not.toThrow();
+ });
+});
+
+describe('a different case', () => {
+ it('drops the open grid and reads its own', async () => {
+ const g = await drawn();
+ currentCase = 'case-2';
+ expect(g.forCase('case-2')).toBe(true);
+ expect(g.grid).toBe(null);
+ expect(g.name).toBe(null);
+ await vi.waitFor(() =>
+ expect(api.get).toHaveBeenCalledWith('/api/cases/case-2/search-grids')
+ );
+ });
+
+ it('does nothing at all when the case has not changed', async () => {
+ const g = await drawn();
+ expect(g.forCase('case-1')).toBe(false);
+ expect(g.grid).not.toBe(null);
+ });
+
+ it('never writes the old case’s grid into the new one', async () => {
+ const g = await drawn();
+ put.length = 0;
+ g.grid.statuses['0:0'] = 'cleared'; // pending inside the debounce
+ currentCase = 'case-2';
+ g.forCase('case-2');
+ await vi.advanceTimersByTimeAsync(700);
+ expect(put).toHaveLength(0);
+ });
+
+ it('reads nothing with no case open', async () => {
+ const g = await drawn();
+ currentCase = undefined;
+ g.forCase(undefined);
+ await vi.advanceTimersByTimeAsync(10);
+ expect(g.others).toEqual([]);
+ });
+});
+
+describe('teardown', () => {
+ it('takes its layers off the map and drops a pending write', async () => {
+ const g = await drawn();
+ put.length = 0;
+ g.grid.statuses['0:0'] = 'cleared';
+ g.destroy();
+ await vi.advanceTimersByTimeAsync(700);
+ expect(put).toHaveLength(0);
+ for (const l of layers) expect(l.destroy).toHaveBeenCalled();
+ });
+
+ it('is safe on a store that never drew anything', () => {
+ expect(() => store().destroy()).not.toThrow();
+ });
+});
diff --git a/frontend/src/tools/satellite/state/imagery.svelte.js b/frontend/src/tools/satellite/state/imagery.svelte.js
new file mode 100644
index 0000000..a42ad94
--- /dev/null
+++ b/frontend/src/tools/satellite/state/imagery.svelte.js
@@ -0,0 +1,170 @@
+/**
+ * The basemap catalogue, and what a billed one owes the meter.
+ *
+ * One store for the whole tool, not one per map: the catalogue is the same
+ * everywhere, and a tile counted against the month is counted once however many
+ * surfaces are drawing from it. What is *not* shared is which provider a
+ * surface shows — that is the surface's own choice, handed to `displayed()`.
+ *
+ * `displayed()` is the whole point of the store. A chosen provider and a shown
+ * provider are not the same thing: a billed basemap steps aside for free
+ * imagery when the month's allowance is nearly spent (the 90% soft block) or
+ * when the view is zoomed out far enough that its detail buys nothing (eco).
+ * Captures, the imagery date and the disk cache all key on what is *shown*, so
+ * provenance can never name a provider the pixels did not come from.
+ *
+ * For Sentinel-2 the layer, window and cloud ceiling ride on the id itself
+ * (lib/sentinel.js) — so a tile rendered from one window cannot be filed as
+ * another.
+ *
+ * The arithmetic is `lib/usage.js`; this holds the catalogue, the month's
+ * tally, and the preferences Settings drives both fallbacks with.
+ *
+ * @param {object} deps
+ * @param {object} deps.api the app's fetch wrapper
+ */
+import {
+ FREE_IMAGERY,
+ displayProviderId,
+ layerCell,
+ monthCount,
+ tilesShort,
+ usageBlocked,
+} from '../../../lib/usage.js';
+import { variantId } from '../../../lib/sentinel.js';
+
+export const FALLBACK_PROVIDER = FREE_IMAGERY;
+
+export function createImageryState({ api }) {
+ let providers = $state([]);
+ let totals = $state({});
+ let month = $state('');
+ // Mirrored from Settings: overrides lift the 90% soft block, eco swaps billed
+ // basemaps for free imagery when zoomed out, and `tiers` is this account's
+ // real allowance per meter — a provider's free tier is not ours to hardcode.
+ let prefs = $state({ overrides: {}, eco: true, ecoMaxZoom: 15, tiers: null });
+
+ return {
+ get providers() {
+ return providers;
+ },
+ get month() {
+ return month;
+ },
+ get totals() {
+ return totals;
+ },
+ get prefs() {
+ return prefs;
+ },
+
+ /** One entry of the catalogue, or undefined once Settings disables it. */
+ find(id) {
+ return providers.find((provider) => provider.id === id);
+ },
+
+ /** Read the catalogue. Settings can disable a basemap, so this is re-read
+ * on returning to the tool, not only on mount. */
+ async loadProviders() {
+ providers = await api.get('/api/satellite/providers');
+ return providers;
+ },
+
+ /** The month's tally and the two fallback preferences. A readout only: it
+ * must never be what stops the map drawing. */
+ async refreshUsage() {
+ try {
+ const settings = await api.get('/api/settings');
+ totals = settings.usage;
+ month = settings.month;
+ prefs = {
+ overrides: settings.usage_overrides ?? {},
+ eco: settings.eco_zoom_fallback !== false,
+ ecoMaxZoom: settings.eco_max_zoom ?? 15,
+ tiers: settings.free_tier ?? null,
+ };
+ } catch {
+ /* readout only — never blocks the map */
+ }
+ },
+
+ /**
+ * Count one billed map load, then re-read the tally.
+ *
+ * Tiles are counted by the proxy that serves them, but a widget basemap is
+ * built by the provider's own script inside the page — the backend never
+ * sees it, so the one place that knows it happened has to say so. Silence
+ * here is a month's allowance quietly spending itself with the readout
+ * still saying zero.
+ */
+ async countLoad(meter) {
+ try {
+ await api.post(`/api/satellite/usage/${meter}`);
+ } catch {
+ /* the load happened either way — the tally re-reads below */
+ }
+ return this.refreshUsage();
+ },
+
+ /**
+ * When the imagery under a point was taken, as far as the provider will
+ * say. Esri answers; every other basemap reports `supported: false` and the
+ * surface shows no date rather than guessing one.
+ */
+ imageryDate({ lat, lon, zoom }, providerId) {
+ return api.get(
+ `/api/satellite/imagery-date?lat=${lat}&lon=${lon}&zoom=${zoom}&provider=${providerId}`
+ );
+ },
+
+ /** Whether this billed provider has spent enough of its month to step aside. */
+ blocked(provider) {
+ return provider?.meter
+ ? usageBlocked(
+ monthCount(totals, provider.meter, month),
+ provider.meter,
+ prefs.overrides,
+ prefs.tiers
+ )
+ : false;
+ },
+
+ /** The small readout beside the basemap selector. Null for a free provider. */
+ pill(provider) {
+ return provider?.meter
+ ? tilesShort(monthCount(totals, provider.meter, month), provider.meter)
+ : null;
+ },
+
+ /**
+ * What one surface actually shows, given its choice and its zoom.
+ *
+ * @param {string} chosenId the provider the surface's selector is on
+ * @param {number} zoom that surface's view zoom
+ * @param {object} [variant] Sentinel-2's layer/window/ceiling, if any
+ */
+ displayed(chosenId, zoom, variant) {
+ const chosen = this.find(chosenId);
+ const blocked = this.blocked(chosen);
+ const baseId = displayProviderId(chosen, zoom, {
+ eco: prefs.eco,
+ blocked,
+ ecoMaxZoom: prefs.ecoMaxZoom,
+ });
+ const provider = this.find(baseId);
+ return {
+ chosen,
+ provider,
+ // what every downstream consumer asks for: the tile URL, the capture,
+ // the disk cache — never the bare provider id
+ id: variantId(baseId, variant),
+ // memoized by the caller so the layer is only rebuilt when the cell
+ // actually changes, i.e. crossing the z17 boost bracket
+ cell: provider ? layerCell(provider, zoom) : 256,
+ blocked,
+ /** True when the surface is not showing what its selector says. */
+ fallenBack: !!chosen?.meter && baseId !== chosenId,
+ };
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/imagery.svelte.test.js b/frontend/src/tools/satellite/state/imagery.svelte.test.js
new file mode 100644
index 0000000..32b39d9
--- /dev/null
+++ b/frontend/src/tools/satellite/state/imagery.svelte.test.js
@@ -0,0 +1,209 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createImageryState } from './imagery.svelte.js';
+import { FREE_TIER } from '../../../lib/usage.js';
+import { SENTINEL_ID } from '../../../lib/sentinel.js';
+
+/**
+ * The catalogue, and the gap between the basemap chosen and the basemap shown.
+ *
+ * The arithmetic has its own tests (lib/usage.js); what is asserted here is
+ * that one surface's zoom and one month's tally decide what its tiles, its
+ * capture and its provenance all name.
+ */
+
+const ESRI = { id: 'esri-world-imagery', label: 'Esri', imagery: true };
+const MAPBOX = { id: 'mapbox-satellite', label: 'Mapbox', imagery: true, meter: 'mapbox' };
+const SENTINEL = { id: SENTINEL_ID, label: 'Sentinel-2', imagery: true, meter: 'sentinelhub' };
+
+let api;
+let settings;
+
+function store() {
+ return createImageryState({ api });
+}
+
+/** A catalogue read and a month's tally in, ready to be asked about. */
+async function loaded() {
+ const imagery = store();
+ await imagery.loadProviders();
+ await imagery.refreshUsage();
+ return imagery;
+}
+
+beforeEach(() => {
+ settings = {
+ usage: {},
+ month: '2026-09',
+ usage_overrides: {},
+ eco_zoom_fallback: true,
+ eco_max_zoom: 15,
+ free_tier: null,
+ };
+ api = {
+ get: vi.fn(async (path) => {
+ if (path === '/api/satellite/providers') return [ESRI, MAPBOX, SENTINEL];
+ return settings;
+ }),
+ post: vi.fn(async () => ({})),
+ };
+});
+
+describe('the catalogue', () => {
+ it('is read from the backend, not assumed', async () => {
+ const imagery = await loaded();
+ expect(imagery.providers).toHaveLength(3);
+ expect(imagery.find('mapbox-satellite')).toEqual(MAPBOX);
+ });
+
+ it('has nothing to say about a basemap Settings has disabled', async () => {
+ const imagery = await loaded();
+ expect(imagery.find('nope')).toBe(undefined);
+ });
+});
+
+describe('the month’s tally', () => {
+ it('is a readout, and a failed read never stops the map', async () => {
+ api.get = vi.fn(async (path) => {
+ if (path === '/api/satellite/providers') return [ESRI, MAPBOX];
+ throw new Error('offline');
+ });
+ const imagery = store();
+ await imagery.loadProviders();
+ await expect(imagery.refreshUsage()).resolves.toBeUndefined();
+ expect(imagery.displayed('mapbox-satellite', 18).id).toBe('mapbox-satellite');
+ });
+
+ it('names the count for a billed provider and nothing for a free one', async () => {
+ settings.usage = { mapbox: { '2026-09': 1234 } };
+ const imagery = await loaded();
+ expect(imagery.pill(MAPBOX)).toBe('1,234 tiles');
+ expect(imagery.pill(ESRI)).toBe(null);
+ });
+
+ it('takes the account’s own allowance over the documented one', async () => {
+ settings.usage = { mapbox: { '2026-09': FREE_TIER.mapbox * 0.95 } };
+ const imagery = await loaded();
+ expect(imagery.blocked(MAPBOX)).toBe(true);
+
+ settings.free_tier = { mapbox: FREE_TIER.mapbox * 4 };
+ await imagery.refreshUsage();
+ expect(imagery.blocked(MAPBOX)).toBe(false);
+ });
+});
+
+describe('a billed map load nobody else can see', () => {
+ // Tiles are counted by the proxy that serves them. A widget basemap is built
+ // by the provider's own script inside the page, so this is the only place
+ // that knows it happened — silence here is an allowance spending itself with
+ // the readout still saying zero.
+ it('is counted where it happens, then the tally is re-read', async () => {
+ const imagery = await loaded();
+ api.get.mockClear();
+
+ await imagery.countLoad('google_js');
+ expect(api.post).toHaveBeenCalledWith('/api/satellite/usage/google_js');
+ expect(api.get).toHaveBeenCalledWith('/api/settings');
+ });
+
+ it('still re-reads the tally when the count could not be posted', async () => {
+ api.post = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const imagery = await loaded();
+ api.get.mockClear();
+
+ await expect(imagery.countLoad('google_js')).resolves.not.toThrow();
+ expect(api.get).toHaveBeenCalledWith('/api/settings');
+ });
+
+ it('shows the load in the readout it just re-read', async () => {
+ const imagery = await loaded();
+ expect(imagery.pill(MAPBOX)).toContain('0');
+
+ settings = { ...settings, usage: { mapbox: { '2026-09': 12 } } };
+ await imagery.countLoad('mapbox');
+ expect(imagery.pill(MAPBOX)).toContain('12');
+ });
+});
+
+describe('what a surface actually shows', () => {
+ it('shows the chosen provider when nothing is in the way', async () => {
+ const imagery = await loaded();
+ const shown = imagery.displayed('mapbox-satellite', 18);
+ expect(shown.id).toBe('mapbox-satellite');
+ expect(shown.fallenBack).toBe(false);
+ });
+
+ it('steps a billed basemap aside once the month is nearly spent', async () => {
+ settings.usage = { mapbox: { '2026-09': FREE_TIER.mapbox * 0.95 } };
+ const imagery = await loaded();
+ const shown = imagery.displayed('mapbox-satellite', 18);
+ expect(shown.id).not.toBe('mapbox-satellite');
+ expect(shown.blocked).toBe(true);
+ expect(shown.fallenBack).toBe(true);
+ });
+
+ it('an override in Settings keeps it on the billed one', async () => {
+ settings.usage = { mapbox: { '2026-09': FREE_TIER.mapbox * 0.95 } };
+ settings.usage_overrides = { mapbox: true };
+ const imagery = await loaded();
+ expect(imagery.displayed('mapbox-satellite', 18).id).toBe('mapbox-satellite');
+ });
+
+ it('shows free imagery while zoomed out, and the billed one once you are in', async () => {
+ const imagery = await loaded();
+ expect(imagery.displayed('mapbox-satellite', 8).fallenBack).toBe(true);
+ expect(imagery.displayed('mapbox-satellite', 18).fallenBack).toBe(false);
+ });
+
+ it('eco off keeps the billed basemap at every zoom', async () => {
+ settings.eco_zoom_fallback = false;
+ const imagery = await loaded();
+ expect(imagery.displayed('mapbox-satellite', 8).id).toBe('mapbox-satellite');
+ });
+
+ it('never falls a free provider back — there is nothing to save', async () => {
+ const imagery = await loaded();
+ expect(imagery.displayed('esri-world-imagery', 3).fallenBack).toBe(false);
+ });
+
+ it('two surfaces at different zooms can show different providers', async () => {
+ const imagery = await loaded();
+ const wide = imagery.displayed('mapbox-satellite', 6);
+ const close = imagery.displayed('mapbox-satellite', 19);
+ expect(wide.id).not.toBe(close.id);
+ });
+});
+
+describe('Sentinel-2’s choices ride on the id', () => {
+ it('so a window cannot be rendered from one date and filed as another', async () => {
+ const imagery = await loaded();
+ const june = imagery.displayed(SENTINEL_ID, 16, {
+ layer: 'TRUE_COLOR',
+ from: '2026-06-01',
+ to: '2026-06-01',
+ maxcc: 100,
+ });
+ const july = imagery.displayed(SENTINEL_ID, 16, {
+ layer: 'TRUE_COLOR',
+ from: '2026-07-01',
+ to: '2026-07-01',
+ maxcc: 100,
+ });
+ expect(june.id).not.toBe(july.id);
+ expect(june.id).toContain('2026-06-01');
+ });
+
+ it('a bare provider carries no variant', async () => {
+ const imagery = await loaded();
+ expect(imagery.displayed('esri-world-imagery', 16).id).toBe('esri-world-imagery');
+ });
+});
+
+describe('the tile grid', () => {
+ it('falls back to a plain cell when the chosen basemap is gone', async () => {
+ const imagery = await loaded();
+ expect(imagery.displayed('deleted-provider', 12).cell).toBe(256);
+ });
+});
diff --git a/frontend/src/tools/satellite/state/measure.svelte.js b/frontend/src/tools/satellite/state/measure.svelte.js
new file mode 100644
index 0000000..c1ad7fb
--- /dev/null
+++ b/frontend/src/tools/satellite/state/measure.svelte.js
@@ -0,0 +1,120 @@
+/**
+ * The measure tools: a distance, an area or an angle drawn on the map.
+ *
+ * One armed mode at a time and one list of clicked points, because that is what
+ * the readout is a reading of. Three rules are the whole of it, and each one is
+ * a thing an analyst noticed rather than a thing the geometry needed:
+ *
+ * - **Arming a mode drops the last one's points.** Two half-drawn measures on
+ * the map, with a readout naming one of them, is a picture that lies.
+ * - **An angle is exactly three points**, so a fourth click starts a fresh one
+ * rather than bending the last one into something with no name.
+ * - **Closing the panel disarms.** The button lit with the panel gone was the
+ * tool still swallowing map clicks nobody meant for it.
+ *
+ * The arithmetic is `lib/measure.js`; this holds what has been clicked, what is
+ * armed, and the layer the two are drawn on.
+ *
+ * @param {object} deps
+ * @param {() => object|null} deps.engine the map, once it is up
+ * @param {() => string} deps.units 'metric' | 'imperial', for the readout
+ * @param {(engine: object) => object} [deps.surface] the drawing layer factory
+ */
+import { createSurface } from '../../../lib/map/surface.js';
+import * as measure from '../../../lib/measure.js';
+
+const STROKE = { stroke: '#f5a623', strokeWidth: 2.5, strokeOpacity: 0.95 };
+const DOT = { radius: 4, stroke: '#fff', strokeWidth: 2, fill: '#f5a623', fillOpacity: 1 };
+
+/** What to click, per mode. The vertex is named because an angle is the one
+ * shape where the order of the three points changes the answer. */
+export const HINTS = {
+ distance: 'Click points along the path',
+ area: 'Click the polygon corners',
+ angle: 'Click three points (vertex second)',
+};
+
+export function createMeasureState({ engine, units, surface = createSurface }) {
+ let mode = $state(null); // null | 'distance' | 'area' | 'angle'
+ let points = $state([]);
+ let panelOpen = $state(false);
+ let layer = null;
+
+ function draw() {
+ const map = engine();
+ if (!map) return;
+ layer ??= surface(map);
+ const path =
+ points.length < 2
+ ? null
+ : mode === 'area'
+ ? {
+ kind: 'polygon',
+ points,
+ style: { ...STROKE, fill: '#f5a623', fillOpacity: 0.15 },
+ }
+ : { kind: 'line', points, style: STROKE };
+ layer.set([path, ...points.map((point) => ({ kind: 'dot', at: point, style: DOT }))]);
+ }
+
+ function clear() {
+ points = [];
+ layer?.clear();
+ }
+
+ return {
+ get mode() {
+ return mode;
+ },
+ get points() {
+ return points;
+ },
+ get panelOpen() {
+ return panelOpen;
+ },
+
+ /** The measurement itself, in the user's units. `…` while a shape is one
+ * point short of meaning something. */
+ get readout() {
+ if (!mode || points.length < 2) return null;
+ if (mode === 'distance') return measure.formatDistance(measure.pathLength(points), units());
+ if (mode === 'area') {
+ return points.length >= 3
+ ? measure.formatArea(measure.polygonArea(points), units())
+ : '…';
+ }
+ return points.length >= 3
+ ? measure.formatAngle(measure.angleAt(points[0], points[1], points[2]))
+ : '…';
+ },
+
+ /** Arm a mode, or disarm the one already armed by pressing it again. */
+ setMode(next) {
+ mode = mode === next ? null : next;
+ clear();
+ return mode;
+ },
+
+ togglePanel() {
+ panelOpen = !panelOpen;
+ if (!panelOpen && mode) this.setMode(null);
+ return panelOpen;
+ },
+
+ /** A map click, while a mode is armed. False means it was not ours. */
+ addPoint(at) {
+ if (!mode) return false;
+ // an angle is exactly three points; a fourth click starts a fresh angle
+ if (mode === 'angle' && points.length >= 3) points = [];
+ points = [...points, at];
+ draw();
+ return true;
+ },
+
+ clear,
+ destroy() {
+ layer?.destroy();
+ layer = null;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/measure.svelte.test.js b/frontend/src/tools/satellite/state/measure.svelte.test.js
new file mode 100644
index 0000000..06aadca
--- /dev/null
+++ b/frontend/src/tools/satellite/state/measure.svelte.test.js
@@ -0,0 +1,189 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createMeasureState } from './measure.svelte.js';
+
+/**
+ * The measure tools' own rules, apart from the map they draw on.
+ *
+ * The arithmetic has its own tests (lib/measure.js); what is asserted here is
+ * everything that decides *which* points the arithmetic is handed.
+ */
+
+const A = { lat: 0, lon: 0 };
+const B = { lat: 0, lon: 1 };
+const C = { lat: 1, lon: 1 };
+const D = { lat: 1, lon: 0 };
+
+let drawn;
+let layer;
+let surface;
+let engine;
+
+function store(units = 'metric') {
+ return createMeasureState({ engine: () => engine, units: () => units, surface });
+}
+
+beforeEach(() => {
+ drawn = [];
+ layer = {
+ set: vi.fn((shapes) => drawn.push(shapes)),
+ clear: vi.fn(),
+ destroy: vi.fn(),
+ };
+ surface = vi.fn(() => layer);
+ engine = { id: 'map' };
+});
+
+describe('arming a mode', () => {
+ it('drops the points the last mode left, so the readout names what is drawn', () => {
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ m.addPoint(B);
+ expect(m.points).toHaveLength(2);
+
+ m.setMode('area');
+ expect(m.points).toEqual([]);
+ expect(m.readout).toBe(null);
+ });
+
+ it('pressing the armed mode again disarms it', () => {
+ const m = store();
+ expect(m.setMode('angle')).toBe('angle');
+ expect(m.setMode('angle')).toBe(null);
+ expect(m.mode).toBe(null);
+ });
+
+ it('ignores map clicks while nothing is armed', () => {
+ const m = store();
+ expect(m.addPoint(A)).toBe(false);
+ expect(m.points).toEqual([]);
+ expect(surface).not.toHaveBeenCalled();
+ });
+});
+
+describe('the shapes drawn', () => {
+ it('draws one layer, not one per click', () => {
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ m.addPoint(B);
+ m.addPoint(C);
+ expect(surface).toHaveBeenCalledTimes(1);
+ });
+
+ it('joins distance points with a line and area points with a polygon', () => {
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ m.addPoint(B);
+ expect(drawn.at(-1)[0].kind).toBe('line');
+
+ m.setMode('area');
+ m.addPoint(A);
+ m.addPoint(B);
+ m.addPoint(C);
+ expect(drawn.at(-1)[0].kind).toBe('polygon');
+ });
+
+ it('marks every clicked point, so a path shows where it was bent', () => {
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ m.addPoint(B);
+ m.addPoint(C);
+ expect(drawn.at(-1).filter((shape) => shape?.kind === 'dot')).toHaveLength(3);
+ });
+
+ it('draws nothing at all before the map is up', () => {
+ engine = null;
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ expect(surface).not.toHaveBeenCalled();
+ // …and the point is still held, so the first draw has it
+ expect(m.points).toEqual([A]);
+ });
+});
+
+describe('the readout', () => {
+ it('says nothing until a shape means something', () => {
+ const m = store();
+ m.setMode('distance');
+ expect(m.readout).toBe(null);
+ m.addPoint(A);
+ expect(m.readout).toBe(null);
+ });
+
+ it('waits for the third point of an area rather than naming a line', () => {
+ const m = store();
+ m.setMode('area');
+ m.addPoint(A);
+ m.addPoint(B);
+ expect(m.readout).toBe('…');
+ m.addPoint(C);
+ expect(m.readout).not.toBe('…');
+ });
+
+ it('follows the units it is asked for', () => {
+ const metric = store('metric');
+ metric.setMode('distance');
+ metric.addPoint(A);
+ metric.addPoint(B);
+ const imperial = store('imperial');
+ imperial.setMode('distance');
+ imperial.addPoint(A);
+ imperial.addPoint(B);
+ expect(metric.readout).not.toBe(imperial.readout);
+ });
+});
+
+describe('an angle', () => {
+ it('is exactly three points: a fourth click starts a fresh one', () => {
+ const m = store();
+ m.setMode('angle');
+ m.addPoint(A);
+ m.addPoint(B);
+ m.addPoint(C);
+ const three = m.readout;
+ expect(three).not.toBe('…');
+
+ m.addPoint(D);
+ expect(m.points).toEqual([D]);
+ expect(m.readout).toBe(null);
+ });
+});
+
+describe('the panel', () => {
+ it('disarms the tool when it closes, so nothing keeps eating map clicks', () => {
+ const m = store();
+ m.togglePanel();
+ m.setMode('distance');
+ m.addPoint(A);
+
+ m.togglePanel();
+ expect(m.panelOpen).toBe(false);
+ expect(m.mode).toBe(null);
+ expect(m.points).toEqual([]);
+ });
+
+ it('opening it arms nothing by itself', () => {
+ const m = store();
+ m.togglePanel();
+ expect(m.mode).toBe(null);
+ });
+});
+
+describe('teardown', () => {
+ it('takes its layer off the map', () => {
+ const m = store();
+ m.setMode('distance');
+ m.addPoint(A);
+ m.destroy();
+ expect(layer.destroy).toHaveBeenCalled();
+ });
+
+ it('is safe on a store that never drew anything', () => {
+ expect(() => store().destroy()).not.toThrow();
+ });
+});
diff --git a/frontend/src/tools/satellite/state/refs.svelte.js b/frontend/src/tools/satellite/state/refs.svelte.js
new file mode 100644
index 0000000..e4130df
--- /dev/null
+++ b/frontend/src/tools/satellite/state/refs.svelte.js
@@ -0,0 +1,103 @@
+/**
+ * The reference windows: floating scratch panes over the map, each holding one
+ * of the case's images, so the shot being geolocated can be eyeballed against
+ * the imagery while the map pans under it.
+ *
+ * They are scratch, and everything here follows from that:
+ *
+ * - **They live in the session, not in the case.** Nothing about which windows
+ * were open is worth restoring, and a capture must never show them — the
+ * crop hides them by class (`MapSurface.svelte`), which only works because
+ * they are chrome painted over the map rather than anything on it.
+ * - **The picker reads the case's media when it opens**, never on mount. A tab
+ * that indexed the case just by being selected would be a request nobody
+ * asked for.
+ * - **Focus renumbers the whole stack** instead of handing the newest window an
+ * ever-larger z. Small, gap-free values are what keep a window from
+ * eventually climbing over a dialog.
+ *
+ * The window's own geometry — placement, clamping, cursor-anchored zoom — is
+ * `lib/refViewers.js`, and the pointer handling is `RefViewer.svelte`. This
+ * holds which windows are open and what the picker is showing.
+ *
+ * @param {object} deps
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify
+ * @param {() => string|undefined} deps.caseId the case whose media can be referenced
+ * @param {() => object[]} deps.viewers the session's open windows
+ * @param {(windows: object[]) => void} deps.setViewers replace them
+ */
+import { createViewer, nextZ, restack } from '../../../lib/refViewers.js';
+
+/** New windows step down-right so the one underneath stays grabbable, and wrap
+ * before they walk off the map. */
+const STAGGER = 26;
+const STAGGER_WRAP = 6;
+
+export function createRefsState({ api, notify, caseId, viewers, setViewers }) {
+ let picking = $state(false); // the "pick an image" modal
+ let media = $state([]); // what the case has to offer
+ let loading = $state(false);
+ let spawned = 0; // id source, so two windows on the same media stay distinct
+
+ return {
+ get picking() {
+ return picking;
+ },
+ set picking(value) {
+ picking = value;
+ },
+ get media() {
+ return media;
+ },
+ get loading() {
+ return loading;
+ },
+ /** The open windows, in the order they were spawned. */
+ get open() {
+ return viewers();
+ },
+
+ /** Read what this case can reference. A video counts: the frame to place is
+ * often in one, and the window plays it. */
+ async openPicker() {
+ picking = true;
+ loading = true;
+ try {
+ const id = caseId();
+ const all = id ? await api.get(`/api/cases/${id}/media`) : [];
+ media = all.filter((item) => item.kind === 'image' || item.kind === 'video');
+ } catch (e) {
+ notify(`Could not load media: ${e.message}`, 'danger');
+ media = [];
+ } finally {
+ loading = false;
+ }
+ },
+
+ /** Spawn a window on one picked item, on top of the others. */
+ add(item) {
+ const open = viewers();
+ const step = (open.length % STAGGER_WRAP) * STAGGER;
+ open.push(
+ createViewer(`ref-${++spawned}`, item, {
+ x: 60 + step,
+ y: 60 + step,
+ z: nextZ(open),
+ })
+ );
+ picking = false;
+ },
+
+ /** Bring one to the front, renumbering the rest so the values stay small. */
+ focus(id) {
+ const open = viewers();
+ const z = restack(open, id);
+ for (const window of open) window.z = z.get(window.id);
+ },
+
+ close(id) {
+ setViewers(viewers().filter((window) => window.id !== id));
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/refs.svelte.test.js b/frontend/src/tools/satellite/state/refs.svelte.test.js
new file mode 100644
index 0000000..cf96f38
--- /dev/null
+++ b/frontend/src/tools/satellite/state/refs.svelte.test.js
@@ -0,0 +1,168 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRefsState } from './refs.svelte.js';
+
+/**
+ * The reference windows' own rules, apart from the map they float over.
+ *
+ * The window geometry has its own tests (lib/refViewers.js); what is asserted
+ * here is when the case is read, where the windows live, and how they stack.
+ */
+
+const SHOT = { path: 'media/a.jpg', kind: 'image', title: 'A' };
+const CLIP = { path: 'media/b.mp4', kind: 'video', title: 'B' };
+const DOC = { path: 'media/c.pdf', kind: 'document', title: 'C' };
+
+let api;
+let notify;
+let session;
+let caseId;
+
+function store() {
+ return createRefsState({
+ api,
+ notify,
+ caseId: () => caseId,
+ viewers: () => session,
+ setViewers: (windows) => (session = windows),
+ });
+}
+
+beforeEach(() => {
+ api = { get: vi.fn(async () => [SHOT, CLIP, DOC]) };
+ notify = vi.fn();
+ session = [];
+ caseId = 'case-1';
+});
+
+describe('the picker', () => {
+ it('reads the case media when it opens, never before', async () => {
+ const refs = store();
+ expect(api.get).not.toHaveBeenCalled();
+
+ await refs.openPicker();
+ expect(api.get).toHaveBeenCalledWith('/api/cases/case-1/media');
+ expect(refs.picking).toBe(true);
+ });
+
+ it('offers images and videos, since the frame to place is often in a clip', async () => {
+ const refs = store();
+ await refs.openPicker();
+ expect(refs.media).toEqual([SHOT, CLIP]);
+ });
+
+ it('asks nothing at all when there is no case yet', async () => {
+ caseId = undefined;
+ const refs = store();
+ await refs.openPicker();
+ expect(api.get).not.toHaveBeenCalled();
+ expect(refs.media).toEqual([]);
+ });
+
+ it('says why it is empty rather than looking like a case with no media', async () => {
+ api.get = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const refs = store();
+ await refs.openPicker();
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('offline'), 'danger');
+ expect(refs.media).toEqual([]);
+ expect(refs.loading).toBe(false);
+ });
+
+ it('drops its busy flag whichever way the read ends', async () => {
+ const refs = store();
+ const reading = refs.openPicker();
+ expect(refs.loading).toBe(true);
+ await reading;
+ expect(refs.loading).toBe(false);
+ });
+});
+
+describe('spawning a window', () => {
+ it('closes the picker and puts the window on top', async () => {
+ const refs = store();
+ await refs.openPicker();
+ refs.add(SHOT);
+ expect(refs.picking).toBe(false);
+ expect(refs.open).toHaveLength(1);
+ expect(refs.open[0].path).toBe(SHOT.path);
+ });
+
+ it('staggers each window so the one underneath stays grabbable', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(SHOT);
+ expect(refs.open[1].x).toBeGreaterThan(refs.open[0].x);
+ expect(refs.open[1].y).toBeGreaterThan(refs.open[0].y);
+ });
+
+ it('wraps the stagger before a window walks off the map', () => {
+ const refs = store();
+ for (let i = 0; i < 7; i += 1) refs.add(SHOT);
+ expect(refs.open[6].x).toBe(refs.open[0].x);
+ });
+
+ it('gives two windows on the same image distinct ids', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(SHOT);
+ expect(refs.open[0].id).not.toBe(refs.open[1].id);
+ });
+
+ it('stacks each new window above the last', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(CLIP);
+ expect(refs.open[1].z).toBeGreaterThan(refs.open[0].z);
+ });
+});
+
+describe('focus and close', () => {
+ it('renumbers the stack rather than letting z climb without bound', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(CLIP);
+ refs.add(SHOT);
+ const top = refs.open[2].z;
+
+ refs.focus(refs.open[0].id);
+ expect(refs.open[0].z).toBe(top); // the focused one is on top…
+ // …and nothing climbed past the number of windows
+ expect(Math.max(...refs.open.map((pane) => pane.z))).toBe(refs.open.length);
+ });
+
+ it('leaves the other windows in their own order under it', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(CLIP);
+ refs.add(DOC);
+ const [first, second] = [refs.open[0].id, refs.open[1].id];
+
+ refs.focus(refs.open[2].id);
+ const z = new Map(refs.open.map((pane) => [pane.id, pane.z]));
+ expect(z.get(first)).toBeLessThan(z.get(second));
+ });
+
+ it('closing one drops it from the session and keeps the rest', () => {
+ const refs = store();
+ refs.add(SHOT);
+ refs.add(CLIP);
+ const doomed = refs.open[0].id;
+
+ refs.close(doomed);
+ expect(refs.open).toHaveLength(1);
+ expect(refs.open[0].id).not.toBe(doomed);
+ });
+});
+
+describe('what the windows are', () => {
+ it('holds them in the session it was handed, never in a store of its own', () => {
+ const refs = store();
+ refs.add(SHOT);
+ // the tool's session array *is* the list — that is what makes them survive a
+ // tab switch and vanish with the tab
+ expect(session).toHaveLength(1);
+ expect(refs.open).toBe(session);
+ });
+});
diff --git a/frontend/src/tools/satellite/state/sky.svelte.js b/frontend/src/tools/satellite/state/sky.svelte.js
new file mode 100644
index 0000000..b0aa530
--- /dev/null
+++ b/frontend/src/tools/satellite/state/sky.svelte.js
@@ -0,0 +1,264 @@
+/**
+ * Sun & moon: one anchored point, one date, and an hour you drag.
+ *
+ * What it draws is the arc each body sweeps while it is up, hour ticks along
+ * it, and the bearing at the chosen moment. Everything on the map is an
+ * azimuth, which is the only celestial quantity a plan view can state honestly;
+ * altitude stays in the panel, and rides the ray as how far up the body is.
+ *
+ * The anchor is a point you plant, never the moving view: the whole reading is
+ * "from *here*, at this hour", and a shadow line that slid with a pan would be
+ * a different question answered every frame.
+ *
+ * Two ways in, one rendering: the tool's own button, and a point handed over by
+ * Coords & Sky. The hand-off carries a clock, so the slider lands on the minute
+ * that was asked about rather than on the current one — and only once, because
+ * the next day loaded is the analyst's own choice.
+ *
+ * The geometry and the glyphs are `lib/skyOverlay.js`; this holds the point,
+ * the day, the hour, and the layer they are drawn on.
+ *
+ * @param {object} deps
+ * @param {() => object|null} deps.engine the map, once it is up
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {(message: string, kind?: string, ms?: number) => void} deps.notify
+ * @param {(name: string, fallback: string) => string} [deps.colour] theme lookup
+ * @param {(engine: object) => object} [deps.surface] the drawing layer factory
+ */
+import { createSurface } from '../../../lib/map/surface.js';
+import { destination } from '../../../lib/measure.js';
+import {
+ bodyReading,
+ bodySvg,
+ hourTicks,
+ isBelow,
+ markScale,
+ nearestSample,
+ upRuns,
+} from '../../../lib/skyOverlay.js';
+
+const BODY_SIZE = 20;
+
+/** The arc is a circle around the anchor, so its radius comes off the *shorter*
+ * side of the view: sized by the diagonal it runs off a wide window. */
+const REACH = 0.22;
+
+function themeColour(name, fallback) {
+ const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
+ return value || fallback;
+}
+
+export function createSkyState({ engine, api, notify, colour = themeColour, surface = createSurface }) {
+ let on = $state(false);
+ let anchor = $state.raw(null); // { lat, lon } — fixed, never the moving view
+ let day = $state(''); // empty: the backend's today at that point
+ let index = $state(0); // sample of the day the slider is on
+ let sky = $state(null);
+ let loading = $state(false);
+ let placing = $state(false);
+ let layer = null;
+ let ticket = 0;
+ // A wall clock to land the slider on once the day's samples are in, from a
+ // hand-off. Spent on the first load, so a later date is read at its own hour.
+ let handedClock = null;
+
+ function draw() {
+ const map = engine();
+ if (!map) return;
+ layer ??= surface(map);
+ if (!on || !sky || !anchor) {
+ layer.clear();
+ return;
+ }
+ const origin = anchor;
+ const { across, down } = map.viewSpanMeters();
+ const reach = Math.min(across, down) * REACH;
+ const at = (azimuth, scale = 1) => destination(origin, azimuth, reach * scale);
+ const curve = sky.curve;
+ const shapes = [];
+
+ for (const body of [
+ {
+ key: 'sun',
+ label: 'Sun',
+ colour: colour('--sky-sun', '#bd8721'),
+ azimuth: curve.sun_azimuth,
+ altitude: curve.sun_altitude,
+ },
+ {
+ key: 'moon',
+ label: 'Moon',
+ colour: colour('--sky-moon', '#4a93cc'),
+ azimuth: curve.moon_azimuth,
+ altitude: curve.moon_altitude,
+ },
+ ]) {
+ // 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)) {
+ 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)) {
+ 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[index];
+ const below = isBelow(altitude);
+ const reading = bodyReading(body.label, curve.clock[index], body.azimuth[index], altitude);
+ shapes.push({
+ kind: 'line',
+ points: [origin, at(body.azimuth[index])],
+ 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.
+ if (!below) {
+ shapes.push({
+ kind: 'marker',
+ at: at(body.azimuth[index], markScale(altitude)),
+ className: 'sky-body', // replaces the engine's boxed default
+ html: bodySvg(
+ body.key,
+ body.colour,
+ curve.moon_illuminated[index],
+ sky.moon.waxing,
+ BODY_SIZE
+ ),
+ size: [BODY_SIZE, BODY_SIZE],
+ anchor: [BODY_SIZE / 2, BODY_SIZE / 2],
+ keyboard: false,
+ tip: body.key === 'moon' ? `${reading} · ${sky.moon.phase}` : reading,
+ });
+ }
+ }
+
+ shapes.push({
+ kind: 'dot',
+ at: origin,
+ style: {
+ radius: 4,
+ stroke: '#fff',
+ strokeWidth: 2,
+ fill: colour('--accent', '#e8a33d'),
+ fillOpacity: 1,
+ },
+ });
+ layer.set(shapes);
+ }
+
+ return {
+ get on() {
+ return on;
+ },
+ get anchor() {
+ return anchor;
+ },
+ get day() {
+ return day;
+ },
+ get index() {
+ return index;
+ },
+ get sky() {
+ return sky;
+ },
+ get loading() {
+ return loading;
+ },
+ get placing() {
+ return placing;
+ },
+
+ /** Open on a point, unless one was already planted — the anchor outlives a
+ * close, so reopening reads the same place rather than wherever the map
+ * has since drifted to. */
+ open(fallback) {
+ on = true;
+ anchor ??= fallback;
+ },
+
+ close() {
+ on = false;
+ placing = false;
+ layer?.clear();
+ },
+
+ setDay(value) {
+ day = value;
+ sky = null; // the day on screen is not this one's
+ },
+
+ setIndex(value) {
+ index = value;
+ },
+
+ togglePlacing() {
+ placing = !placing;
+ return placing;
+ },
+
+ /** A map click, while waiting for an anchor. False means it was not ours. */
+ place(at) {
+ if (!placing) return false;
+ anchor = at;
+ sky = null;
+ placing = false;
+ return true;
+ },
+
+ /** A point, a date and a time from another tool: same mode, second way in. */
+ handOff({ lat, lon, date, time }) {
+ anchor = { lat, lon };
+ day = date ?? '';
+ sky = null;
+ index = 0;
+ handedClock = time ?? null;
+ on = true;
+ },
+
+ /** Read the sky for the anchored point. Late answers land nowhere. */
+ async load() {
+ if (!on || !anchor) return;
+ const params = new URLSearchParams({ lat: anchor.lat, lon: anchor.lon });
+ if (day) params.set('date', day);
+ const mine = ++ticket;
+ loading = true;
+ try {
+ const result = await api.get(`/api/geo/sky?${params}`);
+ if (mine !== ticket) return;
+ sky = result;
+ day = result.date;
+ index = nearestSample(
+ result.curve.clock,
+ handedClock ?? result.moment.local.slice(11, 16)
+ );
+ handedClock = null;
+ } catch {
+ if (mine === ticket) notify('Could not read the sky for that point', 'danger');
+ } finally {
+ if (mine === ticket) loading = false;
+ }
+ },
+
+ draw,
+ destroy() {
+ ticket += 1; // an answer in flight has nothing left to land on
+ layer?.destroy();
+ layer = null;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/sky.svelte.test.js b/frontend/src/tools/satellite/state/sky.svelte.test.js
new file mode 100644
index 0000000..0973ab0
--- /dev/null
+++ b/frontend/src/tools/satellite/state/sky.svelte.test.js
@@ -0,0 +1,290 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createSkyState } from './sky.svelte.js';
+
+/**
+ * Sun & moon, apart from the map it draws on.
+ *
+ * The geometry has its own tests (lib/skyOverlay.js); what is asserted here is
+ * the point the reading is taken from, the hour it is taken at, and what does
+ * and does not reach the map.
+ */
+
+const PARIS = { lat: 48.85, lon: 2.35 };
+const KYIV = { lat: 50.45, lon: 30.52 };
+
+/** A day of samples, on the hour, with both bodies up in the middle of it. */
+function skyFor(date = '2026-06-21') {
+ const hours = Array.from({ length: 24 }, (_, i) => i);
+ const arc = (peak) => hours.map((h) => peak * Math.sin(((h - 6) / 12) * Math.PI));
+ return {
+ date,
+ moment: { local: `${date}T09:40` },
+ moon: { waxing: true, phase: 'waxing gibbous' },
+ curve: {
+ minutes: hours.map((h) => h * 60),
+ clock: hours.map((h) => `${String(h).padStart(2, '0')}:00`),
+ sun_azimuth: hours.map((h) => (h * 15) % 360),
+ sun_altitude: arc(60),
+ moon_azimuth: hours.map((h) => (h * 15 + 180) % 360),
+ moon_altitude: arc(40),
+ moon_illuminated: hours.map(() => 0.6),
+ },
+ };
+}
+
+let api;
+let notify;
+let layer;
+let surface;
+let engine;
+let asked;
+
+function store() {
+ return createSkyState({
+ engine: () => engine,
+ api,
+ notify,
+ colour: (_name, fallback) => fallback,
+ surface,
+ });
+}
+
+beforeEach(() => {
+ asked = [];
+ notify = vi.fn();
+ api = {
+ get: vi.fn(async (path) => {
+ asked.push(path);
+ return skyFor();
+ }),
+ };
+ layer = { set: vi.fn(), clear: vi.fn(), destroy: vi.fn() };
+ surface = vi.fn(() => layer);
+ engine = { viewSpanMeters: () => ({ across: 4000, down: 3000 }) };
+});
+
+describe('the anchor', () => {
+ it('opens on the point it is handed when nothing is planted yet', () => {
+ const s = store();
+ s.open(PARIS);
+ expect(s.anchor).toEqual(PARIS);
+ });
+
+ it('keeps the planted point across a close, rather than following the view', () => {
+ const s = store();
+ s.open(PARIS);
+ s.close();
+ s.open(KYIV); // the map has since drifted
+ expect(s.anchor).toEqual(PARIS);
+ });
+
+ it('takes a map click only while placing is armed', () => {
+ const s = store();
+ s.open(PARIS);
+ expect(s.place(KYIV)).toBe(false);
+ expect(s.anchor).toEqual(PARIS);
+
+ s.togglePlacing();
+ expect(s.place(KYIV)).toBe(true);
+ expect(s.anchor).toEqual(KYIV);
+ // …and one click is one anchor: the mode disarms itself
+ expect(s.placing).toBe(false);
+ });
+
+ it('drops the reading when the point moves, so nothing stale is drawn', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ expect(s.sky).not.toBe(null);
+
+ s.togglePlacing();
+ s.place(KYIV);
+ expect(s.sky).toBe(null);
+ });
+});
+
+describe('reading the sky', () => {
+ it('asks about the anchored point, not the view', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ expect(asked[0]).toContain(`lat=${PARIS.lat}`);
+ expect(asked[0]).toContain(`lon=${PARIS.lon}`);
+ });
+
+ it('leaves the date out until one is chosen, so the backend says what today is there', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ expect(asked[0]).not.toContain('date=');
+ expect(s.day).toBe('2026-06-21'); // …and the answer names it
+
+ s.setDay('2026-01-05');
+ await s.load();
+ expect(asked[1]).toContain('date=2026-01-05');
+ });
+
+ it('never phones out with no point planted', async () => {
+ const s = store();
+ await s.load();
+ expect(api.get).not.toHaveBeenCalled();
+ });
+
+ it('never phones out while closed', async () => {
+ const s = store();
+ s.open(PARIS);
+ s.close();
+ await s.load();
+ expect(api.get).not.toHaveBeenCalled();
+ });
+
+ it('lands the slider on the moment the answer names', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ expect(s.sky.curve.clock[s.index]).toBe('10:00'); // 09:40 rounds to the nearer sample
+ });
+
+ it('says so when the sky cannot be read, and stops loading', async () => {
+ api.get = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ expect(notify).toHaveBeenCalledWith(expect.stringContaining('Could not read the sky'), 'danger');
+ expect(s.loading).toBe(false);
+ });
+
+ it('lets a late answer land nowhere once the point has moved on', async () => {
+ const pending = [];
+ api.get = vi.fn(() => new Promise((resolve) => pending.push(resolve)));
+ const s = store();
+ s.open(PARIS);
+ const abandoned = s.load();
+ s.setDay('2026-09-09');
+ const current = s.load();
+
+ pending[1](skyFor('2026-09-09'));
+ await current;
+ pending[0](skyFor('2026-03-01')); // …and only now does the first one answer
+ await abandoned;
+
+ expect(s.day).toBe('2026-09-09');
+ expect(s.loading).toBe(false);
+ });
+});
+
+describe('a point handed over by another tool', () => {
+ it('opens the mode on it, with the date it came with', () => {
+ const s = store();
+ s.handOff({ ...KYIV, date: '2026-02-14', time: '17:00' });
+ expect(s.on).toBe(true);
+ expect(s.anchor).toEqual(KYIV);
+ expect(s.day).toBe('2026-02-14');
+ });
+
+ it('lands the slider on the hour that was asked about, not the current one', async () => {
+ const s = store();
+ s.handOff({ ...KYIV, date: '2026-06-21', time: '17:00' });
+ await s.load();
+ expect(s.sky.curve.clock[s.index]).toBe('17:00');
+ });
+
+ it('spends that clock once: the next day is read at its own hour', async () => {
+ const s = store();
+ s.handOff({ ...KYIV, date: '2026-06-21', time: '17:00' });
+ await s.load();
+ s.setDay('2026-06-22');
+ await s.load();
+ expect(s.sky.curve.clock[s.index]).toBe('10:00'); // the moment the answer names
+ });
+});
+
+describe('what reaches the map', () => {
+ it('draws nothing before the map is up', async () => {
+ engine = null;
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ expect(surface).not.toHaveBeenCalled();
+ });
+
+ it('clears the layer instead of drawing when the mode is off', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ expect(layer.set).toHaveBeenCalled();
+
+ s.close();
+ s.draw();
+ expect(layer.clear).toHaveBeenCalled();
+ });
+
+ it('marks the anchor, and rides each body on its own ray', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ const shapes = layer.set.mock.calls.at(-1)[0];
+ expect(shapes.filter((shape) => shape.kind === 'dot')).toHaveLength(1);
+ // one mark per body, both up at the sample the slider landed on
+ expect(shapes.filter((shape) => shape.kind === 'marker')).toHaveLength(2);
+ });
+
+ it('draws no mark for a body under the horizon — a dashed ray already says where it is', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.setIndex(0); // midnight: both bodies are down
+ s.draw();
+ const shapes = layer.set.mock.calls.at(-1)[0];
+ expect(shapes.filter((shape) => shape.kind === 'marker')).toHaveLength(0);
+ expect(shapes.some((shape) => shape.style?.dash === '6 6')).toBe(true);
+ });
+
+ it('sizes the arc off the shorter side of the view, so it fits a wide window', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ const wide = layer.set.mock.calls.at(-1)[0];
+
+ engine = { viewSpanMeters: () => ({ across: 40000, down: 3000 }) };
+ s.destroy();
+ const tall = store();
+ tall.open(PARIS);
+ await tall.load();
+ tall.draw();
+ // the same 3000 m short side either way: the same arc
+ expect(layer.set.mock.calls.at(-1)[0][0].points).toEqual(wide[0].points);
+ });
+
+ it('draws one layer, however many times it is redrawn', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ s.setIndex(12);
+ s.draw();
+ expect(surface).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('teardown', () => {
+ it('takes its layer off the map', async () => {
+ const s = store();
+ s.open(PARIS);
+ await s.load();
+ s.draw();
+ s.destroy();
+ expect(layer.destroy).toHaveBeenCalled();
+ });
+
+ it('is safe on a store that never drew anything', () => {
+ expect(() => store().destroy()).not.toThrow();
+ });
+});
diff --git a/frontend/src/tools/settings/ExtensionTab.svelte b/frontend/src/tools/settings/ExtensionTab.svelte
index 7b6a3dc..d6769ac 100644
--- a/frontend/src/tools/settings/ExtensionTab.svelte
+++ b/frontend/src/tools/settings/ExtensionTab.svelte
@@ -1,7 +1,18 @@
<script>
/**
- * The capture extension: whether this browser has it, and the token that pairs
- * it with this app.
+ * The capture extension: which copy this browser runs, whether the app can
+ * update it, and the token that pairs it with this app.
+ *
+ * The app owns a folder and rewrites it on demand, so an update is a button
+ * rather than a reinstall. What it cannot do is tell the browser where to look
+ * the first time — an unpacked extension has no installer — so the path is
+ * always on screen, copyable, because pasting it into "Load unpacked" is the
+ * one gesture that works on all three platforms.
+ *
+ * That road is Chrome's. Firefox refuses an unsigned extension and drops an
+ * unpacked one when it closes, so it installs a signed XPI the browser keeps
+ * and updates by itself: detected here, reported, and never offered a button
+ * that would rewrite bytes Mozilla sealed.
*
* The token is minted on first reveal rather than on mount, so an installation
* that never pairs never has one (spec's lazy-token rule).
@@ -9,16 +20,26 @@
import Icon from '../../components/Icon.svelte';
let {
- about,
badges,
extDetected,
extOutdated,
+ extState,
+ extBusy,
+ installExtension,
+ updateExtension,
+ copyExtensionPath,
+ revealExtension,
ingestToken,
copyToken,
ensureToken,
rotateToken,
tokenShown = $bindable(),
} = $props();
+
+ // Before the probes answer, the <html> marker is all we have. It cannot tell
+ // one copy from another, so it only ever says "something is there".
+ let status = $derived(extState?.status ?? (extDetected ? 'probing' : 'absent'));
+ let version = $derived(extState?.detectedVersion ?? extDetected);
</script>
<section class="group">
@@ -26,40 +47,145 @@
<p class="note">
Captures supported map sites and powers the Google basemap Capture button.
</p>
+
<div class="row">
<div class="row-label">
<span>Status in this browser</span>
<span class="row-hint">
- {#if extDetected}
- detected · <span class="mono">v{extDetected}</span>
- {#if extOutdated}
- · update bundled (<span class="mono">v{about.extension_version}</span>)
- {/if}
+ {#if status === 'owned' || status === 'duplicate'}
+ detected · <span class="mono">v{extState.installed.version}</span>
+ {#if extState.updateAvailable}· update ready{:else}· up to date{/if}
+ {:else if status === 'signed'}
+ detected · <span class="mono">v{version}</span> · updated by your browser
+ {:else if status === 'foreign'}
+ detected · <span class="mono">v{version}</span> · not the copy Azimut owns
+ {:else if status === 'probing'}
+ detected · <span class="mono">v{version}</span>
{:else}
not detected. After installing, reload this tab
{/if}
</span>
</div>
- <a class="btn btn-sm btn-primary dotted" href="/api/ingest/extension.zip" download>
- <Icon name="download" size={13} />
- {extOutdated ? 'Download update (.zip)' : 'Download extension (.zip)'}
- {#if badges.extension}
- <span
- class="update-dot"
- aria-label={extOutdated ? 'an update is waiting' : 'not installed yet'}
- ></span>
- {/if}
- </a>
+
+ {#if status === 'owned' || status === 'duplicate'}
+ <button
+ class="btn btn-sm btn-primary"
+ disabled={!extState.updateAvailable || Boolean(extBusy)}
+ onclick={updateExtension}
+ >
+ <Icon name="download" size={13} />
+ {extBusy === 'update' ? 'Updating…' : extState.updateAvailable ? 'Update' : 'Up to date'}
+ {#if extState.updateAvailable}<span class="update-dot" aria-label="an update is ready"></span>{/if}
+ </button>
+ {:else if status === 'signed'}
+ <!-- Nothing to press: the XPI is sealed, and Firefox replaces it from the
+ update manifest the release publishes. -->
+ {:else}
+ <button class="btn btn-sm btn-primary" disabled={Boolean(extBusy)} onclick={installExtension}>
+ <Icon name="download" size={13} />
+ {#if extBusy === 'install'}Writing…{:else if status === 'foreign'}Install the app copy{:else}Install{/if}
+ {#if badges.extension}
+ <span
+ class="update-dot"
+ aria-label={extOutdated ? 'an update is waiting' : 'not installed yet'}
+ ></span>
+ {/if}
+ </button>
+ {/if}
</div>
- {#if extOutdated}
+
+ {#if extState?.staged}
<p class="note warn">
- Bundled v{about.extension_version} is newer than installed v{extDetected}; replace
- the unpacked folder and reload the extension.
+ The files are written but your browser is holding the old ones. Close it and
+ press again.
</p>
{/if}
- <p class="note">
- Unzip it, load it as an unpacked extension, then reload this tab.
- </p>
+
+ {#if status === 'duplicate'}
+ <p class="note warn">
+ Two copies are loaded. Remove
+ {#if extState.others[0]?.extensionId}
+ <span class="mono">{extState.others[0].extensionId}</span>
+ {:else}
+ the older one
+ {/if}
+ in your browser's extensions page; Azimut updates
+ <span class="mono">{extState.installed.extensionId}</span>.
+ </p>
+ {/if}
+
+ {#if extState?.ahead}
+ <p class="note warn">
+ This add-on is newer than the Azimut you are running. Update the app, or its
+ newer flows will report that they could not run.
+ </p>
+ {/if}
+
+ {#if status === 'signed' && !extState.ahead}
+ {#if extOutdated}
+ <p class="note warn">
+ This copy is behind the one Azimut ships. Firefox replaces it within a day,
+ or now from <span class="mono">about:addons</span> → the gear menu →
+ Check for Updates.
+ </p>
+ {:else}
+ <p class="note">
+ Firefox manages this copy and replaces it from Azimut's own update manifest.
+ </p>
+ {/if}
+ {/if}
+
+ {#if status === 'foreign'}
+ <p class="note warn">
+ This copy was loaded from a folder Azimut does not own, so it can't be
+ updated from here. To hand it over:
+ </p>
+ <ol class="hand-over">
+ <li>{extState.folderCurrent ? 'The app copy is written (path below)' : 'Press Install to write the app copy'}</li>
+ <li>Remove the current extension in your browser's extensions page</li>
+ <li>Load the folder below unpacked</li>
+ <li>Paste the pairing token again — Chrome ties stored data to the folder</li>
+ </ol>
+ {/if}
+
+ {#if extState?.path}
+ <div class="row">
+ <div class="row-label">
+ <span>Extension folder</span>
+ <span class="row-hint mono">{extState.path}</span>
+ </div>
+ <div class="scraper-actions">
+ <button class="btn btn-sm" onclick={copyExtensionPath}>
+ <Icon name="copy" size={13} /> Copy path
+ </button>
+ <button class="btn btn-sm" onclick={revealExtension}>Open folder</button>
+ </div>
+ </div>
+ {/if}
+
+ {#if status !== 'owned' && status !== 'duplicate' && status !== 'signed'}
+ <p class="note">
+ Chrome, Edge, Brave: extensions page → developer mode → Load unpacked →
+ paste the path. Then reload this tab.
+ </p>
+ <p class="note">
+ Firefox drops an unpacked extension when it closes, so install the signed
+ <span class="mono">azimut-capture</span> add-on instead. It updates itself.
+ </p>
+ <div class="scraper-actions">
+ <a
+ class="btn btn-sm dotted"
+ href="https://github.com/OsintMeThat/azimut/releases/latest"
+ target="_blank"
+ rel="noreferrer"
+ >
+ <Icon name="download" size={13} /> Signed add-on for Firefox
+ </a>
+ <a class="btn btn-sm dotted" href="/api/ingest/extension.zip" download>
+ <Icon name="download" size={13} /> Download as .zip instead
+ </a>
+ </div>
+ {/if}
</section>
<section class="group">
@@ -86,3 +212,19 @@
The extension can file one user-requested map capture through this local app.
</p>
</section>
+
+<style>
+ /* Handing an existing install over to the app: four steps, in order, because
+ doing 2 before 1 leaves the browser with no extension at all. */
+ .hand-over {
+ margin: 4px 0 8px;
+ padding-left: 18px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ line-height: 1.5;
+ }
+
+ .hand-over li {
+ margin: 1px 0;
+ }
+</style>
diff --git a/frontend/src/tools/settings/GeneralTab.svelte b/frontend/src/tools/settings/GeneralTab.svelte
index f816e4f..ef24120 100644
--- a/frontend/src/tools/settings/GeneralTab.svelte
+++ b/frontend/src/tools/settings/GeneralTab.svelte
@@ -1,7 +1,8 @@
<script>
/**
* How every tool prints a coordinate, a distance and an area, plus the map's
- * opening position and what saving a proof does with its point.
+ * opening position, what saving a proof does with its point, and how Reverse
+ * Search reaches an engine.
*
* Preferences save on change and the server answers with the canonical value,
* so nothing here keeps a draft the rest of the app cannot see.
@@ -15,6 +16,7 @@
savePrefs,
saveHome,
proofPlaceAuto = $bindable(),
+ reversePrefill = $bindable(),
} = $props();
const COORD_CHOICES = [
@@ -116,6 +118,26 @@
</div>
</section>
+<section class="group">
+ <h3>Reverse search</h3>
+ <div class="row">
+ <div class="row-label">
+ <span>Let the extension open the engine with the image</span>
+ <span class="row-hint">
+ The engine gets the picture instead of you pasting or dragging it, so it
+ searches straight away. Needs the capture extension; without it, the
+ buttons copy or save the image as usual.
+ </span>
+ </div>
+ <input
+ type="checkbox"
+ bind:checked={reversePrefill}
+ onchange={() => savePrefs({ reverse_prefill: reversePrefill })}
+ aria-label="Let the extension open the engine with the image"
+ />
+ </div>
+</section>
+
<style>
.sample {
color: var(--text-2);
diff --git a/packaging/updates.json b/packaging/updates.json
new file mode 100644
index 0000000..1b00e22
--- /dev/null
+++ b/packaging/updates.json
@@ -0,0 +1,7 @@
+{
+ "addons": {
+ "updates": []
+ }
+ }
+}
diff --git a/pyproject.toml b/pyproject.toml
index f8ed916..78c9ebc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -149,7 +149,15 @@ packages = ["src/azimut"]
"extension/manifest.json" = "azimut/extension/manifest.json"
"extension/background.js" = "azimut/extension/background.js"
"extension/bridge.js" = "azimut/extension/bridge.js"
+"extension/handoff.js" = "azimut/extension/handoff.js"
+"extension/mapmath.js" = "azimut/extension/mapmath.js"
+"extension/maptheme.js" = "azimut/extension/maptheme.js"
+"extension/maptools.js" = "azimut/extension/maptools.js"
+"extension/mapdraw.js" = "azimut/extension/mapdraw.js"
+"extension/mapref.js" = "azimut/extension/mapref.js"
+"extension/mapoverlay.js" = "azimut/extension/mapoverlay.js"
"extension/overlay.js" = "azimut/extension/overlay.js"
+"extension/reverse.js" = "azimut/extension/reverse.js"
"extension/popup.html" = "azimut/extension/popup.html"
"extension/popup.js" = "azimut/extension/popup.js"
"extension/options.html" = "azimut/extension/options.html"
diff --git a/scripts/build_map_fixture.py b/scripts/build_map_fixture.py
new file mode 100644
index 0000000..25d6085
--- /dev/null
+++ b/scripts/build_map_fixture.py
@@ -0,0 +1,348 @@
+"""Turn a raw calibration run into the fixture both test suites read.
+
+ python scripts/build_map_fixture.py
+
+`frontend/calibration/record.mjs` drives the map sites in a real browser and
+writes down the URLs they wrote about themselves: `tests/fixtures/map-sites.raw.json`,
+observation and nothing else. This reads that and produces
+`tests/fixtures/map-sites.json`, which carries two derived things the suites
+need:
+
+* **the view each URL means**, from ``parse_map_url`` — the app's own parser,
+ which is the only thing in this project allowed to read a map URL. A recording
+ whose views were produced any other way would be testing a second parser
+ against the first;
+* **where each site drew its camera**, solved from the two zooms in the
+ recording, the same way ``extension/mapmath.js`` solves it live.
+
+That second one is a second copy of a formula, and it is on purpose. The JS is
+what ships and what the drawing is done with; this is forty lines of Python that
+has to agree with it, and `frontend/src/lib/extensionMapFrame.test.js` re-solves
+every recording with the real thing and fails if the two ever differ by more
+than a pixel. Two independent implementations agreeing on thirteen recordings is
+a stronger statement about the arithmetic than either one alone.
+
+Prose, per-recording notes and the `rounding` block are carried over from the
+existing fixture: those are what a person knew, and a rebuild must not quietly
+delete them.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "src"))
+
+from azimut.engine.mapsites import _mercator_y, parse_map_url # noqa: E402
+
+RAW = ROOT / "tests" / "fixtures" / "map-sites.raw.json"
+OUT = ROOT / "tests" / "fixtures" / "map-sites.json"
+
+#: Sites the recorder drives and the fixture leaves out, with the reason. Driving
+#: them is still worth it: a link the app hands out that stopped opening a map is
+#: caught by the run, whatever happens to the recording afterwards.
+EXPECTED_OUT = {
+ "google-earth": "a free camera states no scale, so there is nothing here to check it against",
+}
+
+#: How much the zoom has to have moved between two URLs before the solve below
+#: is worth doing. `extension/mapmath.js` states the same floor, and for the same
+#: reason: the answer comes out amplified by 1/(1−2^Δz).
+MIN_ZOOM_STEP = 0.5
+
+#: How much chrome counts as chrome. The camera offset is measured to about a
+#: tenth of a pixel, so a site that draws dead centre lands a hair either side of
+#: zero, and calling that a two-pixel header would restate the window's height
+#: for nothing. `extension/mapoverlay.js` uses the same floor.
+MIN_CHROME_PX = 4
+
+#: WGS84's first eccentricity — the difference between the two Mercators, and
+#: the whole of Yandex's disagreement with everyone else.
+_E = 0.081819190842621
+_MAX_LAT = 85.05112877980659
+
+
+def _ellipsoidal_y(lat: float) -> float:
+ """Northing on the 256-pixel world at zoom 0, elliptical Mercator (Yandex)."""
+ phi = math.radians(max(-_MAX_LAT, min(_MAX_LAT, lat)))
+ es = _E * math.sin(phi)
+ t = math.tan(math.pi / 4 + phi / 2) * ((1 - es) / (1 + es)) ** (_E / 2)
+ return (1 - math.log(t) / math.pi) / 2 * 256
+
+
+def _project(lat: float, lon: float, projection: str | None) -> tuple[float, float]:
+ y = _ellipsoidal_y(lat) if projection == "ellipsoidal" else _mercator_y(lat)
+ return ((lon + 180) / 360 * 256, y)
+
+
+def _wrap_near(lon: float, near: float) -> float:
+ while lon - near > 180:
+ lon -= 360
+ while near - lon > 180:
+ lon += 360
+ return lon
+
+
+def solve_centre(before: dict, after: dict, at: dict) -> dict[str, float] | None:
+ """The pixel the site draws its camera at, from one zoom about a held point.
+
+ With ``s = 2^zoom`` and world coordinates taken at zoom 0, the pixel `p` the
+ zoom held still is the same before and after::
+
+ p = C + s0·(w(P) − w(c0)) = C + s1·(w(P) − w(c1))
+
+ which fixes both the point and the camera pixel `C`. Each axis is solved on
+ its own, so a site that is off-centre one way only says so.
+ """
+ for view in (before, after):
+ if view.get("zoom") is None or view.get("lat") is None:
+ return None
+ if view.get("bearing"):
+ return None
+ if before.get("projection") != after.get("projection"):
+ return None
+ if abs(after["zoom"] - before["zoom"]) < MIN_ZOOM_STEP:
+ return None
+ s0 = 2 ** before["zoom"]
+ s1 = 2 ** after["zoom"]
+ c0 = _project(before["lat"], before["lon"], before.get("projection"))
+ c1 = _project(
+ after["lat"], _wrap_near(after["lon"], before["lon"]), after.get("projection")
+ )
+ out = {}
+ for axis, pixel in ((0, at["x"]), (1, at["y"])):
+ point = (s0 * c0[axis] - s1 * c1[axis]) / (s0 - s1)
+ out["xy"[axis]] = pixel - s0 * (point - c0[axis])
+ return out if all(math.isfinite(v) for v in out.values()) else None
+
+
+def _view_of(parsed: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "lat": parsed["lat"],
+ "lon": parsed["lon"],
+ "zoom": parsed["zoom"],
+ "bearing": parsed["bearing"] or 0,
+ "projection": parsed["projection"],
+ }
+
+
+def build(entry: dict[str, Any]) -> tuple[dict[str, Any] | None, list[str]]:
+ """One raw recording, parsed and solved. Returns the recording and what
+ went wrong with it."""
+ window = entry["window"]
+ trouble: list[str] = []
+
+ # The two views that state a size rather than a level — Apple's span,
+ # Google satellite's metres — are only a scale next to the height the map
+ # was drawn in, and that height is the window's minus whatever chrome sits
+ # above or below it. Which is what the solve below measures. So it is run
+ # twice: once against the window, then again against the map it found.
+ height = int(window["h"])
+ recording: dict[str, Any] | None = None
+ used = height
+ for _ in range(2):
+ used = height
+ views = []
+ for step in entry["steps"]:
+ parsed = parse_map_url(step["url"], height_px=height)
+ if parsed is None:
+ return None, [f"{step['url']} is not a map URL any more"]
+ views.append((step["url"], parsed))
+ solved = []
+ for zoom in entry["zooms"]:
+ placed = solve_centre(
+ _view_of(views[zoom["from"]][1]), _view_of(views[zoom["to"]][1]), zoom["at"]
+ )
+ if placed is not None:
+ solved.append(placed)
+ if not solved:
+ return None, ["no zoom in this recording moved a level the URL stated"]
+ centre = {
+ "x": round(sum(c["x"] for c in solved) / len(solved), 2),
+ "y": round(sum(c["y"] for c in solved) / len(solved), 2),
+ }
+ spread = max(
+ (math.dist((a["x"], a["y"]), (b["x"], b["y"])) for a in solved for b in solved),
+ default=0.0,
+ )
+ chrome = 2 * abs(centre["y"] - window["h"] / 2)
+ # a pixel count, in whole pixels, which is how the site drew it
+ height = round(window["h"] - chrome) if chrome >= MIN_CHROME_PX else int(window["h"])
+ recording = {
+ "label": entry["label"],
+ "site": entry["site"],
+ "browser": entry.get("browser", "chromium"),
+ "page_zoom": entry.get("pageZoom", 1),
+ "window": window,
+ "map_height": height,
+ "centre": centre,
+ "spread": round(spread, 2),
+ "canvas": entry.get("canvas"),
+ "pan": entry["pan"],
+ "zooms": entry["zooms"],
+ "steps": [
+ {
+ "url": url,
+ "view": _view_of(parsed),
+ "scale_source": parsed["scale_source"],
+ "site": parsed["site"],
+ }
+ for url, parsed in views
+ ],
+ }
+
+ assert recording is not None
+ if recording["map_height"] != used:
+ # The height the views were parsed at is not the height they imply, so
+ # the scale and the offset are still chasing each other. One more pass
+ # would settle it on any layout this has met; a recording that needs
+ # more than that is one to look at rather than to ship.
+ trouble.append(
+ f"the map's height did not settle: parsed at {used}, solved {recording['map_height']}"
+ )
+ if recording["spread"] > 2:
+ trouble.append(
+ f"its two zooms solved centres {recording['spread']:.1f} px apart"
+ )
+ if any(step["view"]["lat"] is None for step in recording["steps"]):
+ trouble.append("a URL came back with no position in it")
+ sites = {step["site"] for step in recording["steps"]}
+ if sites != {entry["site"]}:
+ trouble.append(f"landed on {sorted(sites)} instead of {entry['site']}")
+ if recording["canvas"]:
+ box = recording["canvas"]
+ inside = (
+ box["x"] <= centre["x"] <= box["x"] + box["w"]
+ and box["y"] <= centre["y"] <= box["y"] + box["h"]
+ )
+ if not inside:
+ trouble.append("the camera solved outside the map's own canvas")
+ return recording, trouble
+
+
+def build_rounding(block: dict[str, Any], old: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
+ """The one site that rounds the zoom it writes, notch by notch.
+
+ Six notches from a whole level, all about one pixel. The whole levels are
+ the ones the address bar states exactly, so they are what the camera is
+ solved from; the notches in between are what the extension has to work out
+ for itself, and what the fixture exists to ask it about.
+ """
+ trouble: list[str] = []
+ window = block["window"]
+ parsed = [parse_map_url(step["url"]) for step in block["steps"]]
+ if any(view is None for view in parsed):
+ return {}, ["a URL in the rounding run is not a map URL any more"]
+ views = [view for view in parsed if view is not None]
+ per_level = max(1, round(1 / block.get("step", 1 / 3)))
+ solved = []
+ for first in (0, per_level):
+ last = first + per_level
+ if last >= len(views):
+ continue
+ placed = solve_centre(_view_of(views[first]), _view_of(views[last]), block["at"])
+ if placed is not None:
+ solved.append(placed)
+ if not solved:
+ trouble.append("no pair of whole levels in the rounding run could place the camera")
+ centre = {
+ "x": round(sum(c["x"] for c in solved) / len(solved), 2) if solved else window["w"] / 2,
+ "y": round(sum(c["y"] for c in solved) / len(solved), 2) if solved else window["h"] / 2,
+ }
+ stated = [view["zoom"] for view in views]
+ if stated != sorted(stated) or stated[-1] - stated[0] < 1.5:
+ trouble.append(f"the notches did not climb two levels: {stated}")
+ return {
+ "what": old.get("what", ""),
+ "how": old.get("how", ""),
+ "site": block["site"],
+ "browser": block.get("browser", "chromium"),
+ "window": window,
+ "at": block["at"],
+ "centre": centre,
+ "step": block.get("step", 1 / 3),
+ "steps": [
+ {"url": step["url"], "view": _view_of(view)}
+ for step, view in zip(block["steps"], views)
+ ],
+ }, trouble
+
+
+def main() -> int:
+ raw = json.loads(RAW.read_text(encoding="utf-8"))
+ old = json.loads(OUT.read_text(encoding="utf-8")) if OUT.exists() else {}
+ notes = {r["label"]: r.get("note") for r in old.get("recordings", []) if r.get("note")}
+
+ recordings: list[dict[str, Any]] = []
+ dropped: list[str] = []
+ aside: list[str] = []
+ for entry in raw["recorded"]:
+ if entry["site"] in EXPECTED_OUT:
+ aside.append(f"{entry['label']}: {EXPECTED_OUT[entry['site']]}")
+ continue
+ recording, trouble = build(entry)
+ if recording is None:
+ dropped.append(f"{entry['label']} ({entry['browser']}): {'; '.join(trouble)}")
+ continue
+ if notes.get(entry["label"]):
+ recording["note"] = notes[entry["label"]]
+ recordings.append(recording)
+ offset = (
+ recording["centre"]["x"] - entry["window"]["w"] / 2,
+ recording["centre"]["y"] - entry["window"]["h"] / 2,
+ )
+ flag = f" ⚠ {'; '.join(trouble)}" if trouble else ""
+ print(
+ f"{entry['label']:<40} {entry['browser']:<9} "
+ f"{entry['window']['w']}×{entry['window']['h']}@{entry.get('pageZoom', 1)} "
+ f"camera {offset[0]:+7.1f}, {offset[1]:+6.1f} px from the middle "
+ f"spread {recording['spread']:.2f}{flag}"
+ )
+
+ out = {
+ "what": raw.get("what", old.get("what", "")),
+ "why": old.get(
+ "why",
+ "The map tools draw on someone else's map from what its URL says. This is the "
+ "record of what those URLs actually mean.",
+ ),
+ "centre": old.get(
+ "centre",
+ "Where each site drew the coordinate its address bar named, in window pixels, "
+ "solved from its own two zooms.",
+ ),
+ "how": "Rebuilt by scripts/build_map_fixture.py from tests/fixtures/map-sites.raw.json.",
+ "recordings": recordings,
+ }
+ if "rounding" in raw:
+ block, trouble = build_rounding(raw["rounding"], old.get("rounding", {}))
+ if block:
+ out["rounding"] = block
+ print(
+ f"\n{block['site']} rounding run: camera "
+ f"{block['centre']['x'] - block['window']['w'] / 2:+.1f}, "
+ f"{block['centre']['y'] - block['window']['h'] / 2:+.1f} px from the middle"
+ )
+ if trouble:
+ dropped.append(f"the rounding run: {'; '.join(trouble)}")
+ OUT.write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
+
+ print(f"\n{len(recordings)} recordings → {OUT.relative_to(ROOT)}")
+ if aside:
+ print("driven, and not kept:")
+ for line in aside:
+ print(f" {line}")
+ if dropped:
+ print("left out, and why:")
+ for line in dropped:
+ print(f" {line}")
+ return 1 if dropped else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/devext.py b/scripts/devext.py
index a099505..86bd6eb 100644
--- a/scripts/devext.py
+++ b/scripts/devext.py
@@ -44,6 +44,19 @@ REPO = Path(__file__).resolve().parent.parent
EXT = REPO / "extension"
STATE = Path.home() / ".cache" / "azimut-devext"
+
+def addon_id() -> str:
+ """The extension's Firefox id, read from its own manifest.
+
+ Firefox keys a temporary add-on by this, and AMO reserves it at the first
+ signature, so it is permanent. Read rather than repeated: a copy here would
+ drift the day the id moves and this script would simply stop finding the
+ add-on it just loaded.
+ """
+ manifest = json.loads((EXT / "manifest.json").read_text(encoding="utf-8"))
+ return manifest["browser_specific_settings"]["gecko"]["id"]
+
+
DEFAULT_APP_URL = os.environ.get("AZIMUT_URL", "http://127.0.0.1:8477")
DEFAULT_CHROME_PORT = 9222
DEFAULT_FIREFOX_PORT = 6080
@@ -582,9 +595,7 @@ def firefox_background_console(rdp: Firefox) -> str | None:
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
- )
+ mine = next((a for a in addons if a.get("id") == addon_id()), None)
if not mine:
return None
watcher = rdp.call({"to": mine["actor"], "type": "getWatcher"})["actor"]
diff --git a/scripts/sign_extension.py b/scripts/sign_extension.py
new file mode 100644
index 0000000..25bb89a
--- /dev/null
+++ b/scripts/sign_extension.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python3
+"""Sign the capture extension with Mozilla, and write the manifest Firefox polls.
+
+Firefox Release and Beta refuse an unsigned extension, with no preference to
+turn that off, so the permanent install Chrome gets from "Load unpacked" has
+exactly one equivalent here: an XPI signed by Mozilla. Signing is decoupled from
+distribution — ``--channel unlisted`` puts no listing on addons.mozilla.org, runs
+automated validation only, and hands the signed file back — so the release keeps
+shipping from GitHub.
+
+A signed XPI is sealed, so the app's own update button cannot rewrite it. What
+replaces it is ``packaging/updates.json``: the manifest named by
+``browser_specific_settings.gecko.update_url``, which Firefox re-reads about once
+a day and compares against the version it runs. That file is tracked, and cutting
+a release is what moves it (see the release checklist).
+
+Usage, from the repo root, after the release carrying this version exists::
+
+ export AMO_JWT_ISSUER=user:12345:67
+ export AMO_JWT_SECRET=<secret from the AMO developer hub>
+ python3 scripts/sign_extension.py
+
+The tag defaults to ``v{extension version}``, because the extension carries the
+version of the release that last changed it — the same number the update button
+and the version gate already answer to. ``--from-xpi`` rebuilds the update
+manifest from a file already signed, without asking AMO for a second copy.
+
+What gets signed is ``extinstall.shipped_files()``, not the ``extension/``
+directory: the XPI, the .zip and the folder the app owns must be the same bytes,
+and the directory also holds a dev harness no browser should load.
+
+One entry is kept in the update manifest. Firefox picks the highest version whose
+``strict_min_version`` its build satisfies, so a single newest entry updates
+everyone who can run it and leaves everyone who cannot on what they have, which
+is the honest outcome. Keeping older entries would only matter to offer a
+different version per Firefox range.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+REPO = Path(__file__).resolve().parent.parent
+EXT = REPO / "extension"
+UPDATE_MANIFEST = REPO / "packaging" / "updates.json"
+
+#: Where a release's signed XPI lands. Built from the tag rather than looked up,
+#: so the update manifest can be written before the asset is uploaded.
+ASSET_BASE = "https://github.com/OsintMeThat/azimut/releases/download"
+
+#: The asset name. Carries its version: release assets from different tags sit in
+#: different directories, but a downloaded file lands in one.
+ASSET_NAME = "azimut-capture-{version}.xpi"
+
+sys.path.insert(0, str(REPO / "src"))
+from azimut.engine import extinstall # noqa: E402
+
+
+# ---- reading what the extension declares about itself -----------------------
+
+
+def gecko_facts() -> dict[str, str]:
+ """``id``, ``version`` and ``strict_min_version`` from the extension's own
+ manifest. One definition: the update manifest is generated from it rather
+ than kept in step by hand."""
+ manifest = json.loads((EXT / "manifest.json").read_text(encoding="utf-8"))
+ gecko = manifest.get("browser_specific_settings", {}).get("gecko", {})
+ missing = [key for key in ("id", "strict_min_version") if not gecko.get(key)]
+ if missing or not manifest.get("version"):
+ raise SystemExit(
+ f"extension/manifest.json is missing {missing or ['version']} — an unlisted "
+ "add-on needs an explicit id, and Firefox needs a version to compare"
+ )
+ return {
+ "id": gecko["id"],
+ "version": str(manifest["version"]),
+ "strict_min_version": gecko["strict_min_version"],
+ }
+
+
+def published_version() -> str | None:
+ """The version ``packaging/updates.json`` currently offers, or None."""
+ try:
+ entries = json.loads(UPDATE_MANIFEST.read_text(encoding="utf-8"))["addons"]
+ except (OSError, KeyError, json.JSONDecodeError):
+ return None
+ for addon in entries.values():
+ for update in addon.get("updates", []):
+ if update.get("version"):
+ return str(update["version"])
+ return None
+
+
+# ---- the update manifest ----------------------------------------------------
+
+
+def build_update_manifest(
+ addon_id: str, version: str, link: str, sha256: str, strict_min_version: str
+) -> dict[str, Any]:
+ """The JSON shape Firefox expects at ``update_url``.
+
+ ``update_hash`` is redundant over HTTPS and carried anyway: it is what proves
+ the bytes GitHub serves are the bytes Mozilla signed, and it costs one line.
+ """
+ return {
+ "addons": {
+ addon_id: {
+ "updates": [
+ {
+ "version": version,
+ "update_link": link,
+ "update_hash": f"sha256:{sha256}",
+ "applications": {
+ "gecko": {"strict_min_version": strict_min_version}
+ },
+ }
+ ]
+ }
+ }
+ }
+
+
+def asset_url(tag: str, version: str) -> str:
+ return f"{ASSET_BASE}/{tag}/{ASSET_NAME.format(version=version)}"
+
+
+def sha256_of(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for block in iter(lambda: handle.read(1 << 20), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+# ---- signing ----------------------------------------------------------------
+
+
+def stage_payload(destination: Path) -> None:
+ """Copy exactly what the extension ships into ``destination``."""
+ source = extinstall.source_dir()
+ if source is None:
+ raise SystemExit("no extension found to sign")
+ for name, path in extinstall.shipped_files(source):
+ target = destination / PurePosixPath(name)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(path, target)
+
+
+def sign(staging: Path, artifacts: Path) -> Path:
+ """Ask AMO for a signed copy, and return it. Raises if it comes back empty.
+
+ AMO refuses a version it has already signed, which is the failure to expect
+ when the extension did not change: its version deliberately stays put across
+ releases that leave it alone.
+ """
+ issuer = os.environ.get("AMO_JWT_ISSUER")
+ secret = os.environ.get("AMO_JWT_SECRET")
+ if not issuer or not secret:
+ raise SystemExit("set AMO_JWT_ISSUER and AMO_JWT_SECRET (AMO developer hub)")
+ subprocess.run(
+ [
+ "npx",
+ "--yes",
+ "web-ext@8",
+ "sign",
+ "--source-dir",
+ str(staging),
+ "--artifacts-dir",
+ str(artifacts),
+ "--channel",
+ "unlisted",
+ "--api-key",
+ issuer,
+ "--api-secret",
+ secret,
+ ],
+ check=True,
+ )
+ signed = sorted(artifacts.glob("*.xpi"))
+ if not signed:
+ raise SystemExit("web-ext reported success but produced no .xpi")
+ return signed[-1]
+
+
+# ---- the command ------------------------------------------------------------
+
+
+def main(argv: list[str] | None = None) -> int:
+ facts = gecko_facts()
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument(
+ "--tag",
+ default=f"v{facts['version']}",
+ help="release tag carrying the signed XPI (default: v<extension version>)",
+ )
+ parser.add_argument(
+ "--from-xpi",
+ type=Path,
+ help="rebuild the update manifest from an already-signed file, without signing",
+ )
+ parser.add_argument(
+ "--output",
+ type=Path,
+ default=REPO / "dist-xpi",
+ help="where the signed XPI is written (default: dist-xpi/)",
+ )
+ options = parser.parse_args(argv)
+
+ version = facts["version"]
+ if options.from_xpi is None and published_version() == version:
+ raise SystemExit(
+ f"packaging/updates.json already offers {version}. AMO refuses a version it "
+ "has already signed — bump extension/manifest.json, or pass --from-xpi to "
+ "rewrite the manifest from the file it signed."
+ )
+
+ if options.from_xpi is not None:
+ signed = options.from_xpi
+ if not signed.is_file():
+ raise SystemExit(f"no such file: {signed}")
+ else:
+ options.output.mkdir(parents=True, exist_ok=True)
+ with tempfile.TemporaryDirectory(prefix="azimut-xpi-") as scratch:
+ staging = Path(scratch) / "payload"
+ stage_payload(staging)
+ produced = sign(staging, options.output)
+ signed = options.output / ASSET_NAME.format(version=version)
+ if produced != signed:
+ produced.replace(signed)
+
+ manifest = build_update_manifest(
+ facts["id"],
+ version,
+ asset_url(options.tag, version),
+ sha256_of(signed),
+ facts["strict_min_version"],
+ )
+ UPDATE_MANIFEST.write_text(
+ json.dumps(manifest, indent=2) + "\n", encoding="utf-8"
+ )
+ print(f"signed: {signed}")
+ print(f"update manifest: {UPDATE_MANIFEST} -> {version} at {options.tag}")
+ print("Upload the XPI to that release, then commit packaging/updates.json.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/azimut/api/cases/common.py b/src/azimut/api/cases/common.py
index b4d63b1..199df87 100644
--- a/src/azimut/api/cases/common.py
+++ b/src/azimut/api/cases/common.py
@@ -23,6 +23,11 @@ from ...engine import timeline as timeline_engine
from ...engine import trash as trash_engine
from ...engine.temporal import TemporalError, window_bound
from ...workspace import Case, CaseError
+from .. import events
+
+#: Entity types that are drawn on a map, and so whose deletion is news to a
+#: surface that is not the one that asked for it (``api/events.py``).
+MAPPED_TYPES = {"place", "capture"}
def get_case(case_id: str) -> Case:
@@ -102,6 +107,12 @@ def delete_entities_deep(case: Case, entity_ids: list[str]) -> dict[str, Any]:
# roll back, which is what makes this the safe side of the line.
sheet_engine.forget_entities(case, set(going_by_id))
+ # A point deleted here is still drawn on the app's other tab and on every
+ # map panel the extension has open. Said once, from the one door every
+ # delete comes through, and only when something mapped actually went.
+ if any(entity.get("type") in MAPPED_TYPES for entity in going):
+ events.publish({"type": "saved", "case_id": case.id})
+
return {
"status": "deleted",
"deleted": [e["id"] for e in going],
diff --git a/src/azimut/api/cases/trash.py b/src/azimut/api/cases/trash.py
index b8440d2..4e650cf 100644
--- a/src/azimut/api/cases/trash.py
+++ b/src/azimut/api/cases/trash.py
@@ -12,6 +12,7 @@ from fastapi import APIRouter, HTTPException
from ...engine import trash as trash_engine
from ...workspace import CaseError
+from .. import events
from .common import get_case
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -42,7 +43,13 @@ def restore_trash(case_id: str, group_id: str) -> dict[str, Any]:
"""
case = get_case(case_id)
try:
- return trash_engine.restore(case, group_id)
+ restored = trash_engine.restore(case, group_id)
+ # Whatever came back may be drawn elsewhere — the other app tab, a map
+ # panel over another site. Nudged without asking what was in the group:
+ # a restore is one deliberate press, and the answer costs a re-read of a
+ # compact index (`api/events.py`).
+ events.publish({"type": "saved", "case_id": case.id})
+ return restored
except CaseError as exc:
message = str(exc)
status = 404 if "not found" in message else 409
diff --git a/src/azimut/api/events.py b/src/azimut/api/events.py
index ce265ff..33c617d 100644
--- a/src/azimut/api/events.py
+++ b/src/azimut/api/events.py
@@ -9,6 +9,32 @@ the local-first rule: the browser talks to its own backend, nothing else.
Events are advisory nudges ("case X gained a capture"), never the data itself:
a consumer reacts by re-fetching through the normal API, so a missed event
costs a refresh, not correctness.
+
+There are now three kinds of listener — the app's own tab, a second app tab, and
+every map panel the extension has open over someone else's map — and one file
+each of them writes to. So the vocabulary is fixed here rather than left to the
+producers. Every event carries ``case_id``; the rest is what a consumer needs to
+decide whether the nudge is about the thing it is holding:
+
+``capture`` the extension filed a screenshot (``path``, ``title``, ``site``)
+``bookmark`` the extension filed a page (``entity_id``, ``title``, ``url``)
+``place`` the extension filed a point (``entity_id``, ``title``, ``site``)
+``saved`` the app's own saved work changed: a point, a capture, a deletion
+``grid`` a search grid was created or replaced (``name``, ``title``, ``revision``)
+``grid-marks`` cells were marked on a grid (``name``, ``revision``)
+``grid-removed`` a grid was discarded (``name``)
+
+The first three are the ones the analyst cannot see happening, so the app says so
+out loud when they arrive; the rest are quiet and only refresh what they name. The
+grid pair carries the file's ``revision`` because a surface that has just written
+it hears its own nudge back, and a revision it already holds is how it tells that
+apart from someone else's mark.
+
+Two channels, one bus: the app reads ``/api/events`` same-origin, and the
+extension reads ``/api/ingest/events`` with the pairing token — a content script's
+own fetch carries the *map site's* origin, which the local guard refuses, so the
+panel never opens this itself. Its background worker holds one stream for every
+panel (``extension/background.js``).
"""
from __future__ import annotations
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 4745b91..5da470d 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -6,6 +6,11 @@ files it here as a ``capture`` entity, riding the same media pipeline as a satel
crop so it lists, opens and exports like one. The list lives there and only there:
copied into this sentence it went stale at four of the nine sites.
+It also draws: `extension/mapoverlay.js` puts the app's own measure, pins, sky,
+grid and reference tools over whatever 2D map the analyst is on, which is why a
+handful of routes here *read* a case back rather than only filing into one. Each
+is trimmed to what a panel draws, and the reading is as narrow as the filing.
+
Trust model: the server already binds localhost only, so the pairing token
(``config.ingest_token``, shown in Settings, pasted once into the extension)
exists to stop *other* local pages and processes from filing images into
@@ -23,26 +28,51 @@ treatment the widget screenshot endpoint applies.
from __future__ import annotations
import io
-import json
import secrets
import warnings
import zipfile
+from collections.abc import Callable
from datetime import datetime, timezone
-from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
-from fastapi import APIRouter, Depends, Form, Header, HTTPException, Request, Response, UploadFile
-from fastapi.responses import FileResponse
+from fastapi import (
+ APIRouter,
+ Depends,
+ Form,
+ Header,
+ HTTPException,
+ Query,
+ Request,
+ Response,
+ UploadFile,
+)
+from fastapi.responses import FileResponse, StreamingResponse
from PIL import Image
+from pydantic import BaseModel
from .. import __version__, config
-from ..engine import geo, mapsites, media as media_engine, satellite as satellite_engine, tiles
+from ..engine import (
+ extinstall,
+ geo,
+ mapsites,
+ media as media_engine,
+ satellite as satellite_engine,
+ tiles,
+)
from ..workspace import Case, CaseError
from . import events
from .cases import get_case
from .limits import MAX_IMAGE_BYTES
-from .satellite import locate_on_save
+from .satellite import (
+ GridSaveIn,
+ apply_grid_marks,
+ get_search_grid,
+ list_search_grids,
+ locate_on_save,
+ save_search_grid,
+)
+from .satellite import sky_for_point as satellite_sky
router = APIRouter(prefix="/api/ingest", tags=["ingest"])
@@ -118,8 +148,42 @@ def install_cors(app) -> None:
@router.get("/ping", dependencies=[Depends(require_token)])
def ping() -> dict[str, Any]:
- """Pairing check: the extension options page proves URL + token in one call."""
- return {"app": "azimut", "version": __version__}
+ """Pairing check: the extension options page proves URL + token in one call.
+
+ Carries the measurement units as well, since the map tools state distances
+ on top of another map and must not state them in different units from the
+ app that files them.
+ """
+ return {
+ "app": "azimut",
+ "version": __version__,
+ "units": config.load_settings().get("units", "metric"),
+ }
+
+
[email protected]("/events", dependencies=[Depends(require_token)])
+async def ingest_events(request: Request) -> StreamingResponse:
+ """The nudge channel, for the extension (``api/events.py``).
+
+ The same in-process bus the app reads same-origin, offered here because the
+ panel drawn over another map is working the same case from the other side: a
+ point filed in the app, a cell marked on the app's own copy of a sweep, a
+ grid discarded — none of it is a request the panel made, and without this it
+ would draw a case as it was when the tab was opened.
+
+ Read by the background worker, never by a panel: a content script's fetch
+ carries the map site's origin, which the local guard refuses, and it could not
+ hold the pairing token anyway. One stream serves every open panel
+ (``extension/background.js``).
+
+ Nothing of a case crosses here — an event names what changed and the panel
+ re-reads it through the routes it is already allowed.
+ """
+ return StreamingResponse(
+ events.sse_stream(events.subscribe(), request.is_disconnected),
+ media_type="text/event-stream",
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
@router.get("/cases", dependencies=[Depends(require_token)])
@@ -132,14 +196,20 @@ def cases() -> list[dict[str, Any]]:
@router.get("/parse", dependencies=[Depends(require_token)])
-def parse(url: str) -> dict[str, Any]:
+def parse(url: str, height: float | None = Query(default=None, gt=0, le=20000)) -> dict[str, Any]:
"""Parse a map URL for the popup's prefill (engine/mapsites.py).
The extension deliberately contains no URL knowledge — formats race sites
that change without notice, and an app update is easy where an extension
update is manual. ``{"site": null}`` means "not a map: don't capture here".
+
+ ``height`` is how tall the map is drawn, in CSS pixels, and it is the one
+ thing the caller knows and this side cannot. Two of these sites state their
+ scale as a size rather than as a level — Apple's span in degrees, Google's
+ satellite height in metres — and next to that number they become a zoom like
+ everyone else's. Without it they simply come back without one.
"""
- return mapsites.parse_map_url(url) or {"site": None}
+ return mapsites.parse_map_url(url, height_px=height) or {"site": None}
@router.post("/screenshot", dependencies=[Depends(require_token)])
@@ -388,6 +458,185 @@ def ingest_bookmark(
return {"entity_id": entity["id"], "case_id": case.id, "title": label, "url": url}
+# ---- the map tools: reading a case back, over someone else's map ---------------
+#
+# `extension/mapoverlay.js` draws the app's own tools over whatever map the
+# analyst is on. Those tools need three things the capture flow never did: the
+# points already saved in the case, the sun and moon for a point, and the case's
+# search grids.
+#
+# They are routes of their own rather than the app's, because the app's are
+# same-origin and stay that way. The local guard lets an extension origin reach
+# `/api/ingest/*` and nothing else (`server.py`), which is what keeps the pairing
+# token from being a key to the whole API — so every route here is a deliberate,
+# narrow widening of what a paired extension can see, and each one hands back the
+# least it can rather than an app payload forwarded wholesale.
+
+
+class GridWriteIn(BaseModel):
+ case_id: str
+ title: str = ""
+ spec: dict[str, Any]
+
+
+class GridMarksIn(BaseModel):
+ case_id: str
+ name: str
+ #: ``"i:j" -> "cleared" | "flagged" | null``, null meaning "back to
+ #: unchecked". A patch, never a spec: see ``apply_grid_marks``.
+ marks: dict[str, Any]
+
+
[email protected]("/saved", dependencies=[Depends(require_token)])
+def saved_points(case_id: str) -> list[dict[str, Any]]:
+ """The case's saved points, for drawing over another map.
+
+ Trimmed to what a pin needs. The app's own index carries thumbnails, folder
+ counts, continents and link tallies, all of which would cross into the
+ extension for no use: it draws a dot with a name on it.
+ """
+ rows = satellite_engine.saved_index(get_case(case_id))
+ return [
+ {
+ "id": row["id"],
+ "kind": row["kind"],
+ "title": row["title"],
+ "lat": row["lat"],
+ "lon": row["lon"],
+ }
+ for row in rows
+ if row.get("lat") is not None and row.get("lon") is not None
+ ]
+
+
+#: What a reference window can open. The panel paints an image on a canvas and
+#: gives a video to the element of that name; everything else in a case — a PDF,
+#: an audio file — has nothing to show beside a map.
+REFERENCE_KINDS = ("image", "video")
+
+
[email protected]("/media", dependencies=[Depends(require_token)])
+def reference_media(
+ case_id: str,
+ q: str | None = None,
+ kind: str | None = None,
+ sort: str = "newest",
+ limit: int = 60,
+) -> dict[str, Any]:
+ """The case's images and videos, for the panel's reference windows.
+
+ A reference window floats one of them over the map, so the shot being
+ geolocated can be held against the imagery while the map pans under it. It
+ is the same aid the Satellite tab offers, and the same scratch: nothing
+ about one is filed anywhere.
+
+ Bounded, searched and sorted here rather than filtered over there: a case of
+ two thousand files would otherwise cross the extension boundary whole to
+ fill a grid nobody scrolls. ``total`` is what the search actually matched,
+ so the picker can say how much of it is being shown.
+
+ Both kinds at once is two queries merged, because the store filters one kind
+ at a time and a page taken without a filter would be mostly the audio,
+ documents and archives a window cannot open. Each query is asked for the
+ whole page, so the merge only ever drops the tail of the longer list.
+ """
+ case = get_case(case_id)
+ wanted = [kind] if kind in REFERENCE_KINDS else list(REFERENCE_KINDS)
+ limit = max(1, min(limit, 200))
+ items: list[dict[str, Any]] = []
+ total = 0
+ for one in wanted:
+ page = case.page_media_items(kind=one, q=q or None, sort=sort, limit=limit)
+ items.extend(page["items"])
+ total += page.get("total", 0)
+ items.sort(key=_reference_order(sort), reverse=sort == "newest")
+ return {
+ "items": [
+ {
+ "path": item["path"],
+ "filename": item.get("filename") or item["path"].rsplit("/", 1)[-1],
+ "title": item.get("title") or "",
+ "kind": item.get("kind") or "image",
+ "thumbnail": item.get("thumbnail") or "",
+ }
+ for item in items[:limit]
+ ],
+ "total": total,
+ }
+
+
+def _reference_order(sort: str) -> Callable[[dict[str, Any]], tuple[str, str]]:
+ """The key the two kinds are merged on, matching the order they were asked in.
+
+ The path comes second for the same reason the store's own ``ORDER BY`` ends
+ with it: two files filed in the same second are otherwise in whichever order
+ the two queries happened to be run, and a picker that reshuffles itself
+ between two identical searches is one nobody trusts.
+ """
+ if sort == "name":
+ return lambda item: (
+ (item.get("title") or item.get("filename") or "").lower(),
+ item["path"].lower(),
+ )
+ return lambda item: (item.get("added_at") or "", item["path"].lower())
+
+
[email protected]("/sky", dependencies=[Depends(require_token)])
+def sky(lat: float, lon: float, date: str | None = None) -> dict[str, Any]:
+ """Sun and moon for a point, on one local day.
+
+ The same computation the app's Sun & moon panel runs, and like it, offline:
+ nothing in it goes to the network, so the tool works on a map tab with the
+ app's own window closed.
+
+ ``date`` is a local wall-clock day at the point, since that is how the
+ analyst writes it. Left out, it is the day it is there now — which is the
+ question being asked most of the time, and the one that needs no typing.
+ """
+ # every optional parameter is passed explicitly: the app's own route reads
+ # them from the query string, so its defaults are FastAPI markers rather
+ # than the None a direct call would want
+ return satellite_sky(lat=lat, lon=lon, day=date, at=None, zone=None)
+
+
[email protected]("/grids", dependencies=[Depends(require_token)])
+def grids(case_id: str) -> list[dict[str, Any]]:
+ """The case's saved sweeps, as the picker's summaries."""
+ return list_search_grids(case_id)
+
+
[email protected]("/grid", dependencies=[Depends(require_token)])
+def grid(case_id: str, name: str) -> dict[str, Any]:
+ """One saved sweep, whole — the extension draws its lattice and its marks."""
+ return get_search_grid(case_id, name)
+
+
[email protected]("/grid", dependencies=[Depends(require_token)])
+def create_grid(body: GridWriteIn) -> dict[str, Any]:
+ """File a sweep drawn over another map as a grid in the case.
+
+ POST rather than the app's PUT because the CORS allowance for extension
+ origins is GET and POST only (``install_cors``), and widening it for one
+ route would widen it for all of them.
+ """
+ return save_search_grid(
+ body.case_id,
+ body.title or "grid",
+ GridSaveIn(spec=body.spec, title=body.title or None),
+ )
+
+
[email protected]("/grid/marks", dependencies=[Depends(require_token)])
+def mark_grid(body: GridMarksIn) -> dict[str, Any]:
+ """Set or clear cells on a saved sweep, leaving every other cell alone.
+
+ The whole point of the patch: the same grid is open in the app, and a save
+ that carried the extension's copy of it would put back the cells the analyst
+ marked there in between.
+ """
+ return apply_grid_marks(get_case(body.case_id), body.name, body.marks)
+
+
# ---- reading back: the attachments a hand-off carries -------------------------
#: The two folders a post's attachments live in. The hand-off names its files by
@@ -434,87 +683,29 @@ def handoff_file(case_id: str, path: str) -> Response:
# ---- extension download: the packaged source, zipped on request ---------------
-
-# Repo checkout first (development), then the copy hatchling ships inside the
-# wheel (azimut/extension) — same dual-home pattern as the built frontend.
-_EXTENSION_DIRS = (
- Path(__file__).parents[3] / "extension",
- Path(__file__).parents[1] / "extension",
-)
-# Runtime files only: the extension's own dev harness (vitest, package.json,
-# lockfile) has no business in an installed browser.
-_ZIP_EXCLUDE_DIRS = {"node_modules", "tests", ".git"}
-_ZIP_EXCLUDE_FILES = {"package.json", "package-lock.json", "vitest.config.js", ".gitignore"}
-
-
-def _extension_dir() -> Path | None:
- for candidate in _EXTENSION_DIRS:
- if (candidate / "manifest.json").is_file():
- return candidate
- return None
-
-
-def shipped_extension_files(src: Path) -> list[tuple[str, Path]]:
- """Every file ``extension.zip`` carries, as ``(posix relative name, path)``
- sorted by name. Paths are posix so the listing is identical on the three
- release platforms.
-
- The version gate in ``tests/test_updates.py`` digests exactly this list, so
- "what the manifest version claims" and "what the user downloads" cannot
- drift: a change to a shipped file fails the gate until the version moves.
-
- Ordered by that posix name rather than by ``Path``, which is the whole point:
- comparing paths is case-insensitive on Windows and case-sensitive everywhere
- else, so ``README.md`` sorts first on Linux and mid-list on Windows. The gate
- digests names in order, so sorting by the object would hand the three release
- platforms three verdicts about one unchanged extension.
- """
- shipped: list[tuple[str, Path]] = []
- for path in src.rglob("*"):
- rel = path.relative_to(src)
- if not path.is_file() or path.name in _ZIP_EXCLUDE_FILES:
- continue
- if any(part in _ZIP_EXCLUDE_DIRS or part.endswith(".test.js") for part in rel.parts):
- continue
- shipped.append((rel.as_posix(), path))
- return sorted(shipped, key=lambda entry: entry[0])
-
-
-def bundled_extension_version() -> str | None:
- """The ``version`` of the extension this Azimut build ships. Settings
- compares it to the version stamped by the *installed* extension
- (lib/extBridge.js) so it can flag "an update is bundled — re-download and
- reload". None if no extension is bundled (unusual builds).
-
- This tracks the extension, not the app: it is the Azimut version whose
- release last changed a shipped file, so it stays put across releases that
- leave the extension alone. Bumping it in lock-step with ``__version__``
- would tell every user to reinstall an identical zip."""
- src = _extension_dir()
- if src is None:
- return None
- try:
- manifest = json.loads((src / "manifest.json").read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- return None
- version = manifest.get("version")
- return str(version) if version else None
+#
+# Which files ship, and where this build keeps them, is engine/extinstall.py's
+# question — the same listing feeds the folder the app installs into.
@router.get("/extension.zip")
def extension_zip() -> Response:
- """The capture extension, zipped for Settings' install flow.
+ """The capture extension, zipped for anyone who'd rather place it themselves.
+
+ Settings leads with the app-owned folder (``/api/settings/extension/install``)
+ because that's the copy the update button can rewrite. This stays for the
+ analyst who wants the files somewhere of their own choosing.
- Unauthenticated on purpose: it is the installer, it contains no secrets
+ Unauthenticated on purpose: it is an installer, it contains no secrets
(the token is pasted in *after* install), and gating it on the token would
make pairing circular.
"""
- src = _extension_dir()
+ src = extinstall.source_dir()
if src is None:
raise HTTPException(status_code=404, detail="extension not bundled with this build")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
- for name, path in shipped_extension_files(src):
+ for name, path in extinstall.shipped_files(src):
zf.write(path, name)
return Response(
content=buf.getvalue(),
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index e96909c..1be32aa 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -33,6 +33,7 @@ from ..engine import (
tiles,
)
from ..workspace import Case, CaseError
+from . import events
from .cases import delete_by_path, get_case
from .limits import MAX_IMAGE_BYTES
from .naming import slugify
@@ -111,6 +112,17 @@ class GridSaveIn(BaseModel):
# sanity-checks it. A human title rides alongside for the picker.
spec: dict[str, Any]
title: str | None = None
+ #: Which revision of the file this spec was built from, when the client is
+ #: replacing a grid rather than creating one. A sweep is worked from the app
+ #: and from the capture extension against one file, so a whole-spec save
+ #: arriving from an older copy is refused instead of putting back the marks
+ #: the other side has since made.
+ #:
+ #: A counter rather than ``updated_at``: timestamps here are second
+ #: resolution, and two writes inside one second carry the same string — which
+ #: is exactly the case this guard exists for. Omitted means "I am not
+ #: claiming to know" and the save goes through.
+ base_revision: int | None = None
# Search grids are saved sweeps a case can hold several of (spec §5 "Grid
@@ -123,6 +135,18 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def saved_changed(case: Case) -> None:
+ """Say that this case's saved work moved (``api/events.py``).
+
+ The Saved panel is drawn in two places at once — the app's own map, and every
+ map panel the extension has open — and only one of them made the request that
+ got here. The other hears this and re-reads the index; the one that wrote it
+ re-reads a list it already has, which costs a few KB over loopback and is the
+ price of not having to tell each surface which of them was the author.
+ """
+ events.publish({"type": "saved", "case_id": case.id})
+
+
# A save waits this long for a country, and no longer. Online, the answer is
# there in a few hundred milliseconds and the item lands in the Saved panel
# already grouped; offline, the save is a fraction of a second slower and the
@@ -786,6 +810,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
dedupe=False, # a capture is 1:1 with its entity — never collapse re-captures
)
locate_on_save(case, result["entity"]["id"], marker_lat, marker_lon)
+ saved_changed(case)
return {"path": result["item"]["path"], "title": label, **provenance}
@@ -884,6 +909,7 @@ async def capture_screenshot(
dedupe=False,
)
locate_on_save(case, result["entity"]["id"], lat, lon)
+ saved_changed(case)
return {"path": result["item"]["path"], "title": label, **provenance}
@@ -901,6 +927,7 @@ def save_place(case_id: str, body: PlaceIn) -> dict[str, Any]:
case, body.lat, body.lon, body.zoom, body.bearing, body.title, extra_attrs=extra
)
locate_on_save(case, entity["id"], body.lat, body.lon)
+ saved_changed(case)
return entity
@@ -977,6 +1004,7 @@ def delete_capture(case_id: str, path: str) -> dict[str, Any]:
media_engine.delete_media_files(case, path)
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ saved_changed(case)
return result
@@ -1007,6 +1035,7 @@ def update_capture(case_id: str, body: SatelliteUpdateIn) -> dict[str, Any]:
updated = media_engine.update_media(case, body.path, patch)
except (ValueError, CaseError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ saved_changed(case)
# flatten the capture provenance up, like the listing does, so the client
# gets the same shape back as GET /satellite
return {**(updated.get("source") or {}), **updated}
@@ -1083,6 +1112,13 @@ def _validate_grid_spec(value: Any) -> dict[str, Any]:
return value
+def _revision(spec: dict[str, Any]) -> int:
+ """How many times this grid has been written. Absent in files saved before
+ the counter existed, which read as revision zero."""
+ value = spec.get("revision")
+ return value if isinstance(value, int) and value >= 0 else 0
+
+
def _read_grid(path: Path) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
@@ -1105,6 +1141,89 @@ def _write_grid_atomic(path: Path, spec: dict[str, Any]) -> None:
tmp_path.unlink(missing_ok=True)
+def apply_grid_marks(case, name: str, marks: dict[str, Any]) -> dict[str, Any]:
+ """Set or clear individual cells on a saved grid, leaving the rest alone.
+
+ A sweep is now worked from two places — the app's own map and, through the
+ extension, whatever map the analyst happens to be on — against one file. The
+ whole-spec save below cannot serve both: it carries every cell, so a client
+ holding a copy from five minutes ago puts back the marks the other one made
+ in between, and nothing says so.
+
+ A patch has no such copy in it. `null` clears a cell, so unmarking still
+ works, and two sweeps that touched different cells both land. Two that
+ touched the same one resolve last-writer-wins, which is what an analyst
+ marking the same cell twice would expect anyway.
+ """
+ spec_path = case.resolve_inside(layout.grid_rel(slugify(name, "grid")))
+ if not spec_path.exists():
+ raise HTTPException(status_code=404, detail="grid not found")
+ try:
+ spec = _read_grid(spec_path)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=f"corrupt grid: {exc}") from exc
+
+ revision = _revision(spec)
+ statuses = dict(spec.get("statuses") or {})
+ for key, value in marks.items():
+ if value is None:
+ statuses.pop(str(key), None)
+ elif value in GRID_STATUSES:
+ statuses[str(key)] = value
+ else:
+ raise HTTPException(status_code=400, detail=f"unknown mark: {value!r}")
+ if len(statuses) > GRID_MAX_STATUSES:
+ raise HTTPException(status_code=400, detail="grid has too many cells")
+
+ spec["statuses"] = statuses
+ spec["updated_at"] = _now()
+ # a patch moves the file on too, so a whole-spec save built before it is
+ # recognised as behind rather than written over the top
+ spec["revision"] = revision + 1
+ _write_grid_atomic(spec_path, spec)
+ # The other surfaces working this sweep re-read it off this. The revision
+ # rides along because the one that sent these marks hears the nudge too, and
+ # a revision it is already holding is how it knows to stay put.
+ events.publish({
+ "type": "grid-marks",
+ "case_id": case.id,
+ "name": spec_path.stem,
+ "revision": spec["revision"],
+ })
+ return {
+ "name": spec_path.stem,
+ "updated_at": spec["updated_at"],
+ "revision": spec["revision"],
+ "cleared": sum(1 for v in statuses.values() if v == "cleared"),
+ "flagged": sum(1 for v in statuses.values() if v == "flagged"),
+ }
+
+
+class GridMarksBody(BaseModel):
+ #: ``"i:j" -> "cleared" | "flagged" | null``, null meaning "back to
+ #: unchecked". The app's own half of what the extension sends to
+ #: ``/api/ingest/grid/marks``; see ``apply_grid_marks`` for why a sweep is
+ #: patched rather than saved whole.
+ marks: dict[str, Any]
+
+
[email protected]("/cases/{case_id}/search-grids/{name}/marks")
+def mark_search_grid(case_id: str, name: str, body: GridMarksBody) -> dict[str, Any]:
+ """Mark cells on a saved grid without writing the rest of it.
+
+ The app used to save a swept cell by putting its whole copy of the spec back,
+ which was fine while it was the only thing sweeping. It is not: the same grid
+ is worked from the extension's panel over another map, and a whole-spec save
+ either loses that panel's marks or is refused as behind — and "reload it and
+ redo your last mark" is a poor answer to two people sweeping one area, which
+ is what a search grid is for.
+
+ So marks travel as a patch from both sides now, and only the geometry — a
+ redrawn area, a rename — still writes a spec.
+ """
+ return apply_grid_marks(get_case(case_id), name, body.marks)
+
+
@router.get("/cases/{case_id}/search-grids")
def list_search_grids(case_id: str) -> list[dict[str, Any]]:
"""Summaries of every saved grid, newest first, for the picker."""
@@ -1146,7 +1265,12 @@ def get_search_grid(case_id: str, name: str) -> dict[str, Any]:
@router.put("/cases/{case_id}/search-grids/{name}")
def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any]:
- """Create or replace one grid. The client owns the name (a stable slug)."""
+ """Create or replace one grid. The client owns the name (a stable slug).
+
+ This is for the shape: a fresh area, a reshaped one, a rename. A marked cell
+ goes to ``/marks`` instead, so that the two surfaces sweeping one grid do not
+ write over each other — see ``apply_grid_marks``.
+ """
case = get_case(case_id)
slug = slugify(name, "grid")
spec = dict(body.spec)
@@ -1172,8 +1296,32 @@ def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
spec_path = case.resolve_inside(layout.grid_rel(slug))
+ on_disk = 0
+ if spec_path.exists():
+ try:
+ on_disk = _revision(_read_grid(spec_path))
+ except ValueError:
+ on_disk = 0 # unreadable: the save is the repair, let it through
+ if body.base_revision is not None and body.base_revision != on_disk:
+ raise HTTPException(
+ status_code=409,
+ detail="this grid changed elsewhere since this copy of it was built",
+ )
+ spec["revision"] = on_disk + 1
_write_grid_atomic(spec_path, spec)
- return {"name": slug, "title": spec["title"], "updated_at": spec["updated_at"]}
+ events.publish({
+ "type": "grid",
+ "case_id": case.id,
+ "name": slug,
+ "title": spec["title"],
+ "revision": spec["revision"],
+ })
+ return {
+ "name": slug,
+ "title": spec["title"],
+ "updated_at": spec["updated_at"],
+ "revision": spec["revision"],
+ }
@router.delete("/cases/{case_id}/search-grids/{name}")
@@ -1191,4 +1339,7 @@ def delete_search_grid(case_id: str, name: str) -> dict[str, Any]:
raise HTTPException(status_code=403, detail=str(exc)) from exc
existed = spec_path.exists()
spec_path.unlink(missing_ok=True)
+ if existed:
+ # a panel holding this sweep open is drawing a file that is gone
+ events.publish({"type": "grid-removed", "case_id": case.id, "name": spec_path.stem})
return {"deleted": existed}
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 071aefb..dddf3b6 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -21,6 +21,7 @@ from .. import __version__, config
from ..engine import (
diagnostics,
exportdir,
+ extinstall,
ffmpeg,
google_tiles,
reveal,
@@ -30,7 +31,6 @@ from ..engine import (
updates,
workspacemove,
)
-from .ingest import bundled_extension_version
from .templates import MAX_PER_KIND as MAX_TEMPLATES_PER_KIND
# A backup carries the signature logo as base64: 4 characters per 3 bytes, plus
@@ -101,6 +101,7 @@ class PrefsIn(BaseModel):
post_mention: str | None = None # handle a new post draft is addressed to
post_target: str | None = None # social composer a new post draft starts with
post_prefill: bool | None = None # let the extension fill that composer
+ reverse_prefill: bool | None = None # let it open an engine with the image
signature_handle: str | None = None # account handle stamped on opted-in proofs
# app self-update pop-up (engine/updates.py) — check on load, and the tag
# the user muted with "don't show again"
@@ -129,6 +130,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"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)),
+ "reverse_prefill": bool(settings.get("reverse_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", ""),
@@ -168,7 +170,7 @@ def get_settings() -> dict[str, Any]:
"workspace_root": str(config.workspace_root()),
# the capture-extension version this build ships — Settings compares it
# to the installed one (lib/extBridge.js) to flag a stale extension
- "extension_version": bundled_extension_version(),
+ "extension_version": extinstall.bundled_version(),
# capture-extension pairing token (api/ingest.py) — reported only if it
# already exists; loading Settings no longer mints a credential (POST
# /settings/ingest-token does, on the user's explicit reveal/copy)
@@ -260,6 +262,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["post_target"] = body.post_target
if body.post_prefill is not None:
settings["post_prefill"] = bool(body.post_prefill)
+ if body.reverse_prefill is not None:
+ settings["reverse_prefill"] = bool(body.reverse_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:
@@ -330,6 +334,56 @@ def reveal_workspace() -> dict[str, str]:
return {"path": str(root)}
+# ---- the capture extension's own folder --------------------------------------
+#
+# Deliberately here and not under /api/ingest/: that prefix is the token-gated
+# island whose CORS is opened to *any* extension origin (ingest.install_cors),
+# and a route that writes to disk has no business reachable from one. These are
+# same-origin app routes, behind the Host/Origin guard like the rest of the API.
+
+
[email protected]("/settings/extension")
+def extension_state() -> dict[str, Any]:
+ """What this build ships, what the app's own extension folder holds, and
+ where that folder is. Reads disk, never the network."""
+ return extinstall.state()
+
+
[email protected]("/settings/extension/install")
+def extension_install() -> dict[str, Any]:
+ """Write the shipped extension into the folder the app owns.
+
+ Takes no parameters at all — no path, no payload, nothing off the request.
+ The only bytes it can write are the ones this build already ships, into one
+ fixed place, so the worst an unexpected caller achieves is re-extracting the
+ extension they could have downloaded anyway.
+ """
+ try:
+ return extinstall.install()
+ except LookupError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ except OSError as exc:
+ raise HTTPException(status_code=409, detail=f"cannot write the extension folder: {exc}") from exc
+
+
[email protected]("/settings/extension/reveal")
+def reveal_extension() -> dict[str, str]:
+ """Open the extension folder in the system file manager.
+
+ Secondary to copying the path: the folder is under ``.azimut/``, and pasting
+ a path into the browser's "Load unpacked" picker works on all three
+ platforms where a file manager needs a graphical session to open into.
+ """
+ folder = config.extension_dir()
+ if not folder.is_dir():
+ raise HTTPException(status_code=404, detail="the extension is not installed yet")
+ try:
+ reveal.reveal(folder)
+ except reveal.RevealError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"path": str(folder)}
+
+
class FolderIn(BaseModel):
"""A folder the analyst typed. There is no native picker — the GUI-toolkit
rule forbids one and a browser cannot hand back a real path — so the path
@@ -451,8 +505,11 @@ def export_settings() -> Response:
Deliberately absent: export destinations (absolute paths chosen on this
machine), ``cookies.txt`` (a live login session), the cases themselves
- (portable folders already), and a signature that isn't a valid PNG within
- the size gate.
+ (portable folders already), the extension folder the app owns
+ (``config.extension_dir()`` — those are this build's own bundled bytes, and
+ the new machine's Install button writes its own copy, which the browser has
+ to be pointed at there anyway), and a signature that isn't a valid PNG
+ within the size gate.
"""
portable_settings = config.load_settings()
portable_settings.pop("export_dirs", None)
@@ -573,6 +630,7 @@ class ImportedSettings(BaseModel):
post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
post_target: str = DEFAULT_POST_TARGET
post_prefill: bool = True
+ reverse_prefill: bool = True
signature_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
diff --git a/src/azimut/config.py b/src/azimut/config.py
index 535c185..a7c010f 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -118,6 +118,13 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# lives. On, because with no extension installed it changes nothing — the app
# opens the intent page as it always did.
"post_prefill": True,
+ # Whether a Reverse Search engine button hands the picture to the extension,
+ # which opens the engine with it already in the uploader. Unlike the
+ # composer above, an engine searches the moment it holds a picture — which is
+ # what the button was pressed for, and it still takes that press. On, because
+ # with no extension installed it changes nothing: the button copies or saves
+ # the image and opens the page, as it always did.
+ "reverse_prefill": True,
# The handle stamped onto proofs when a proof/template enables it. Empty
# means no account-handle slot can render.
"signature_handle": "",
@@ -348,6 +355,22 @@ def runtime_dir() -> Path:
return internal_dir() / "runtime"
+def extension_dir() -> Path:
+ """The capture extension's own copy, the one the app is allowed to rewrite
+ (engine/extinstall.py).
+
+ An unpacked extension can't write to itself and can't tell anyone where it
+ lives, so the only way "update" becomes a button is for the app to own the
+ folder and the analyst to point the browser at it once.
+
+ Under ``.azimut/`` rather than in plain sight: the workspace root is where
+ cases live, and a stray directory there is a candidate for folder adoption.
+ A hidden path is awkward in a file picker, which is why Settings leads with
+ "copy the path" instead of asking anyone to navigate here.
+ """
+ return internal_dir() / "extension"
+
+
def settings_dir() -> Path:
"""Hidden app-wide preferences and branding, outside every case."""
return internal_dir() / "settings"
diff --git a/src/azimut/engine/dirswap.py b/src/azimut/engine/dirswap.py
new file mode 100644
index 0000000..5f81345
--- /dev/null
+++ b/src/azimut/engine/dirswap.py
@@ -0,0 +1,145 @@
+"""Replacing files and directories on all three platforms, under a program that
+may be holding them open.
+
+Windows is the constraint. ``os.replace()`` onto an *existing* directory fails
+there (MOVEFILE_REPLACE_EXISTING is file-only), and an open file can't be
+deleted at all — but it can usually still be *renamed*. So the destructive step
+is always a rename: old copy out of the way first, new copy in second, delete the
+leftovers last. Renames are cheap and near-atomic everywhere; deletes are the
+part allowed to fail, and by then they can't cost us anything that matters.
+
+Two callers, two granularities:
+
+* ``engine/scrapers.py`` swaps a whole directory. The scraper package is only
+ read through a meta-path finder we control, so moving the directory is free.
+* ``engine/extinstall.py`` swaps files *inside* a directory it must not move,
+ because Chrome derives the extension id from the folder's path and a browser
+ is loaded on it right now.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+import stat
+import sys
+import time
+from pathlib import Path
+
+#: Attempts per file before a refused replace is reported as refused. A browser
+#: reading an extension resource holds it for milliseconds, so a couple of
+#: retries covers a collision; anything longer is a real lock and waiting on it
+#: only makes the app look hung.
+REPLACE_ATTEMPTS = 4
+REPLACE_BACKOFF = 0.05
+
+
+def force_writable(func, path, _exc):
+ """rmtree onexc hook: clear the read-only bit Windows refuses to delete through."""
+ try:
+ os.chmod(path, stat.S_IWRITE)
+ func(path)
+ except OSError:
+ pass
+
+
+def rmtree(path: Path) -> None:
+ # onexc replaced onerror in 3.12; we still support 3.11. The hook ignores its
+ # third argument, which is the only thing that differs between the two.
+ if sys.version_info >= (3, 12):
+ shutil.rmtree(path, onexc=force_writable)
+ else:
+ shutil.rmtree(path, onerror=force_writable)
+
+
+def retire(target: Path) -> Path | None:
+ """Rename `target` out of the way, returning where it went (None if absent)."""
+ if not target.exists():
+ return None
+ retired = target.parent / f".trash-{target.name}-{os.urandom(4).hex()}"
+ target.replace(retired)
+ return retired
+
+
+def swap_in(staging: Path, target: Path) -> None:
+ """Replace `target` with `staging`, restoring the old copy if the move fails."""
+ retired = retire(target)
+ try:
+ staging.replace(target)
+ except BaseException:
+ if retired is not None:
+ retired.replace(target) # put the working copy back
+ raise
+ if retired is not None:
+ # Best-effort: a locked leftover on Windows is litter, not a failure.
+ shutil.rmtree(retired, ignore_errors=True)
+
+
+def discard(target: Path) -> None:
+ """Remove `target`, making sure it's gone even if the delete can't finish —
+ the rename is what counts."""
+ retired = retire(target)
+ if retired is not None:
+ shutil.rmtree(retired, ignore_errors=True)
+
+
+def replace_file(source: Path, target: Path) -> None:
+ """Move `source` onto `target`, for a `target` something else may hold open.
+
+ Three moves, weakest assumption last:
+
+ 1. ``os.replace``, retried a few times — a reader holds a file for
+ milliseconds and the second attempt usually lands.
+ 2. rename the target aside, then move in. Windows refuses to *delete* an
+ open file where it will still let you *rename* one, so this catches the
+ case the retry can't.
+ 3. give up and raise, having changed nothing. The caller decides what a
+ refusal means; here it must never mean a half-written file.
+
+ The leftover from step 2 is deleted best-effort. A locked one is litter that
+ the next pass sweeps, never a failed update.
+ """
+ last: OSError | None = None
+ for attempt in range(REPLACE_ATTEMPTS):
+ try:
+ os.replace(source, target)
+ return
+ except PermissionError as exc: # Windows: the target is held open
+ last = exc
+ if attempt < REPLACE_ATTEMPTS - 1:
+ time.sleep(REPLACE_BACKOFF)
+ aside = target.parent / f".old-{target.name}-{os.urandom(4).hex()}"
+ try:
+ target.replace(aside)
+ except OSError:
+ raise last if last is not None else OSError(f"cannot replace {target}")
+ try:
+ os.replace(source, target)
+ except OSError:
+ aside.replace(target) # put the working copy back
+ raise
+ try:
+ aside.unlink()
+ except OSError:
+ pass
+
+
+def sweep_leftovers(directory: Path) -> None:
+ """Delete the ``.old-*`` and ``.trash-*`` litter earlier passes couldn't.
+
+ Called on the way into a fresh pass, when whatever held those files has had
+ a chance to let go. Silent by design: a leftover that still can't be deleted
+ is a few kilobytes, not an error worth a user's attention.
+ """
+ if not directory.is_dir():
+ return
+ for entry in directory.iterdir():
+ if not entry.name.startswith((".old-", ".trash-")):
+ continue
+ try:
+ if entry.is_dir():
+ shutil.rmtree(entry, ignore_errors=True)
+ else:
+ entry.unlink()
+ except OSError:
+ pass
diff --git a/src/azimut/engine/extinstall.py b/src/azimut/engine/extinstall.py
new file mode 100644
index 0000000..15eabdc
--- /dev/null
+++ b/src/azimut/engine/extinstall.py
@@ -0,0 +1,303 @@
+"""The capture extension: what this build ships, and the copy the app can rewrite.
+
+An unpacked extension cannot write to itself, cannot read its own filesystem
+path, and cannot be handed one by a page. So for as long as the analyst chose
+where to unzip it, nobody but them knew the address and the only actor able to
+rewrite those bytes was the one without them — which is why an update used to be
+a manual reinstall.
+
+Inverted here. The app extracts the shipped extension into
+``config.extension_dir()``, the analyst points the browser at that folder once,
+and from then on Settings can rewrite it and ask the extension to restart
+(``extension/background.js``, ``ext-reload``).
+
+Three things make that safe:
+
+* **The folder never moves.** Chrome derives the extension id from the directory
+ path, so a rename would orphan the install and lose its pairing. Files are
+ swapped one at a time inside it (engine/dirswap.py).
+* **``manifest.json`` is written last**, and ``install.json`` after it. A kill
+ mid-install leaves a manifest still describing the old version, which is the
+ safe direction: no browser ever loads a new manifest over old code.
+* **A refused write is reported, never forced.** Windows can hold a file open,
+ so a pass that can't finish leaves its staging directory behind and says
+ ``staged``; the next pass finishes the job.
+
+What identifies the folder is ``install.json`` — an id minted once and kept, plus
+the digest of the bytes that were written. The digest is what the update button
+compares, because the manifest version deliberately doesn't move within a
+development cycle (``tests/test_updates.py``).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shutil
+import threading
+from pathlib import Path, PurePosixPath
+from typing import Any
+
+from .. import config
+from . import dirswap
+
+# Repo checkout first (development), then the copy hatchling ships inside the
+# wheel (azimut/extension) — same dual-home pattern as the built frontend.
+_SOURCE_DIRS = (
+ Path(__file__).parents[3] / "extension",
+ Path(__file__).parents[1] / "extension",
+)
+# Runtime files only: the extension's own dev harness (vitest, package.json,
+# lockfile) has no business in an installed browser.
+_EXCLUDE_DIRS = {"node_modules", "tests", ".git"}
+_EXCLUDE_FILES = {"package.json", "package-lock.json", "vitest.config.js", ".gitignore"}
+
+#: Written by the app into the folder it owns, read back by the extension
+#: through ``runtime.getURL()``. Never part of the payload: it is per-install,
+#: so shipping it would make every install differ from every other.
+STAMP_NAME = "install.json"
+
+#: Where a pass assembles the new copy before swapping it in — inside the target
+#: folder, so every move is a same-filesystem rename.
+_STAGING_PREFIX = ".staging-"
+
+#: Text is digested by its line content: a Windows checkout can carry CRLF, and
+#: the digest has to reach the same verdict on the three release platforms.
+_TEXT_SUFFIXES = {".js", ".json", ".css", ".html", ".md", ".txt"}
+
+_lock = threading.Lock() # one pass at a time over a shared directory
+
+
+# ---- what this build ships --------------------------------------------------
+
+
+def source_dir() -> Path | None:
+ """The read-only copy of the extension this build carries, or None.
+
+ Not to be confused with ``config.extension_dir()``, which is the writable
+ copy the browser loads. Nothing in this module ever writes here: in a
+ checkout it resolves to the repo's ``extension/``, which
+ ``scripts/devext.py`` loads straight into the dev browsers.
+ """
+ for candidate in _SOURCE_DIRS:
+ if (candidate / "manifest.json").is_file():
+ return candidate
+ return None
+
+
+def shipped_files(src: Path) -> list[tuple[str, Path]]:
+ """Every file the extension ships, as ``(posix relative name, path)`` sorted
+ by name. Paths are posix so the listing is identical on the three release
+ platforms.
+
+ The version gate in ``tests/test_updates.py`` digests exactly this list, so
+ "what the manifest version claims" and "what the user downloads" cannot
+ drift: a change to a shipped file fails the gate until the version moves.
+
+ Ordered by that posix name rather than by ``Path``, which is the whole point:
+ comparing paths is case-insensitive on Windows and case-sensitive everywhere
+ else, so ``README.md`` sorts first on Linux and mid-list on Windows. The gate
+ digests names in order, so sorting by the object would hand the three release
+ platforms three verdicts about one unchanged extension.
+ """
+ shipped: list[tuple[str, Path]] = []
+ for path in src.rglob("*"):
+ rel = path.relative_to(src)
+ if not path.is_file() or path.name in _EXCLUDE_FILES or path.name == STAMP_NAME:
+ continue
+ if any(part in _EXCLUDE_DIRS or part.endswith(".test.js") for part in rel.parts):
+ continue
+ shipped.append((rel.as_posix(), path))
+ return sorted(shipped, key=lambda entry: entry[0])
+
+
+def bundled_version() -> str | None:
+ """The ``version`` of the extension this Azimut build ships. Settings
+ compares it to the version stamped by the *installed* extension
+ (lib/extBridge.js). None if no extension is bundled (unusual builds).
+
+ This tracks the extension, not the app: it is the Azimut version whose
+ release last changed a shipped file, so it stays put across releases that
+ leave the extension alone. Bumping it in lock-step with ``__version__``
+ would tell every user to reinstall an identical zip."""
+ src = source_dir()
+ if src is None:
+ return None
+ try:
+ manifest = json.loads((src / "manifest.json").read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ version = manifest.get("version")
+ return str(version) if version else None
+
+
+def payload_digest() -> str | None:
+ """Digest of everything the extension ships, minus the manifest's own
+ ``version``. None if this build bundles no extension.
+
+ Leaving the version out is what lets one number serve two jobs. As the
+ version gate in ``tests/test_updates.py``, it cuts both ways: a shipped file
+ that moved without a version bump, and a bump with nothing behind it. As the
+ update trigger here, it moves whenever the bytes move — including inside a
+ development cycle, where the bundled version is already the app's own and so
+ cannot go up.
+
+ Recomputed on every call, deliberately. It is a few dozen small files, and a
+ cache would mean an edit under ``extension/`` no longer shows up as an
+ available update until the app restarts.
+ """
+ src = source_dir()
+ if src is None:
+ return None
+ digest = hashlib.sha256()
+ for name, path in shipped_files(src):
+ if name == "manifest.json":
+ manifest = json.loads(path.read_text(encoding="utf-8"))
+ manifest.pop("version", None)
+ data = json.dumps(manifest, sort_keys=True).encode("utf-8")
+ else:
+ data = path.read_bytes()
+ if PurePosixPath(name).suffix in _TEXT_SUFFIXES:
+ data = data.replace(b"\r\n", b"\n")
+ digest.update(f"{name}\0".encode() + data + b"\0")
+ return digest.hexdigest()
+
+
+# ---- the folder the app owns -------------------------------------------------
+
+
+def _read_stamp(folder: Path) -> dict[str, Any] | None:
+ try:
+ stamp = json.loads((folder / STAMP_NAME).read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ return stamp if isinstance(stamp, dict) else None
+
+
+def _staging_dirs(folder: Path) -> list[Path]:
+ if not folder.is_dir():
+ return []
+ return [p for p in folder.iterdir() if p.is_dir() and p.name.startswith(_STAGING_PREFIX)]
+
+
+def state() -> dict[str, Any]:
+ """What the app ships, what its folder holds, and where that folder is.
+
+ Reads disk only, and sweeps the litter a refused swap left behind — whatever
+ was holding those files has usually let go by the time anyone opens Settings.
+ A surviving staging directory is the one thing that means "the last pass
+ didn't finish", so it is left alone here and cleared by the next pass.
+ """
+ folder = config.extension_dir()
+ with _lock:
+ dirswap.sweep_leftovers(folder)
+ staged = bool(_staging_dirs(folder))
+ stamp = _read_stamp(folder)
+ return {
+ "path": str(folder),
+ "bundled": {"version": bundled_version(), "payload": payload_digest()},
+ "folder": stamp,
+ "staged": staged,
+ }
+
+
+def install() -> dict[str, Any]:
+ """Write the shipped extension into the folder the app owns, and stamp it.
+
+ Idempotent: a second pass over an unchanged payload rewrites the same bytes
+ and keeps ``install_id``, so the browser keeps its extension identity and the
+ analyst keeps their pairing.
+
+ Returns the same shape as ``state()``. ``staged`` true means the payload is
+ assembled but something is holding a file open — press again, or close the
+ browser first.
+ """
+ src = source_dir()
+ if src is None:
+ raise LookupError("no extension bundled with this build")
+ folder = config.extension_dir()
+ with _lock:
+ folder.mkdir(parents=True, exist_ok=True)
+ dirswap.sweep_leftovers(folder)
+ # Whatever an earlier pass left staged has no value: this one re-copies
+ # every file from source. Clearing them first is also what keeps
+ # "staged" honest — exactly one staging directory can exist, and its
+ # presence means this pass is the one that didn't finish.
+ for stale in _staging_dirs(folder):
+ shutil.rmtree(stale, ignore_errors=True)
+ # An id belongs to the folder, not to a payload: preserved across every
+ # update, so "is this the copy I control" keeps its answer.
+ previous = _read_stamp(folder)
+ install_id = str(previous.get("install_id") or "") if previous else ""
+ if not install_id:
+ install_id = os.urandom(16).hex()
+
+ shipped = shipped_files(src)
+ staging = folder / f"{_STAGING_PREFIX}{os.urandom(4).hex()}"
+ staged = False
+ try:
+ for name, path in shipped:
+ target = staging / PurePosixPath(name)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(path, target)
+ # The manifest last, and the stamp after it. Anything interrupted
+ # before the manifest lands leaves a folder describing the old
+ # version, which is the only half-state a browser can load safely.
+ ordered = [entry for entry in shipped if entry[0] != "manifest.json"]
+ ordered += [entry for entry in shipped if entry[0] == "manifest.json"]
+ for name, _ in ordered:
+ relative = PurePosixPath(name)
+ destination = folder / relative
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ dirswap.replace_file(staging / relative, destination)
+ except OSError:
+ staged = True
+ break
+ if not staged:
+ _write_stamp(folder, install_id)
+ _remove_unshipped(folder, {name for name, _ in shipped})
+ finally:
+ if not staged:
+ shutil.rmtree(staging, ignore_errors=True)
+ return state()
+
+
+def _write_stamp(folder: Path, install_id: str) -> None:
+ """Record what this folder holds. Written straight rather than swapped: it is
+ the last step, and a folder whose stamp is missing reads as "not mine", which
+ is a state the UI already handles."""
+ stamp = {
+ "install_id": install_id,
+ "version": bundled_version(),
+ "payload": payload_digest(),
+ }
+ (folder / STAMP_NAME).write_text(json.dumps(stamp, indent=2) + "\n", encoding="utf-8")
+
+
+def _remove_unshipped(folder: Path, shipped: set[str]) -> None:
+ """Delete what the payload no longer carries.
+
+ A leftover file nothing references is litter; one a stale manifest still
+ references is a bug. Best-effort per entry: a file that can't be deleted is
+ swept by the next pass. Deepest first, so a directory the payload emptied is
+ reached after its contents are gone.
+ """
+ keep = shipped | {STAMP_NAME}
+ for path in sorted(folder.rglob("*"), key=lambda p: len(p.parts), reverse=True):
+ relative = path.relative_to(folder)
+ if relative.parts[0].startswith((_STAGING_PREFIX, ".old-", ".trash-")):
+ continue
+ if path.is_dir():
+ try:
+ path.rmdir() # only if the payload left it empty
+ except OSError:
+ pass
+ continue
+ if relative.as_posix() in keep:
+ continue
+ try:
+ path.unlink()
+ except OSError:
+ pass
diff --git a/src/azimut/engine/mapsites.py b/src/azimut/engine/mapsites.py
index 4309bdd..95376b2 100644
--- a/src/azimut/engine/mapsites.py
+++ b/src/azimut/engine/mapsites.py
@@ -14,13 +14,25 @@ verifiable by anyone with the recorded source URL.
``parse_map_url(url)`` returns None for a non-map URL (the extension refuses
to capture there — maps only), else a dict with ``site``/``label`` always set
and ``lat``/``lon``/``zoom``/``bearing``/``title``/``imagery_date``/
-``imagery_mode`` set to values when the URL carries them, None when it
-doesn't. A malformed URL on a known host degrades to "known site, nothing
-parsed" — parsers never raise.
+``imagery_mode``/``view_kind``/``projection``/``globe_below`` set to values when
+the URL carries them, None when it doesn't, plus ``geometry`` — whether the map
+overlay may draw over the page at all — and ``far``, whether it is far enough
+out that what it draws drifts away from the middle of the screen. A malformed URL on a
+known host degrades to "known site, nothing parsed" — parsers never raise.
+
+``height_px`` is the one fact the caller has and this module cannot: how tall
+the map is drawn in the window it is looking at. Given it, the two sites that
+state their scale as a size rather than as a zoom — Apple's ``span``, Google's
+satellite ``,3231m`` — come back with a real ``zoom`` like everyone else, and
+``scale_source`` says which of the three routes the number arrived by. Every
+one of them is measured, not assumed: see ``docs/MAP_SITES.md``, where each
+site's URL is recorded next to what a browser was actually observed doing with
+it.
"""
from __future__ import annotations
+import math
import re
from datetime import date
from typing import Any, Callable
@@ -43,7 +55,7 @@ def _in_world(lat: float | None, lon: float | None) -> bool:
def _no_view() -> dict[str, Any]:
return {"lat": None, "lon": None, "zoom": None, "bearing": None,
- "title": None, "imagery_date": None}
+ "title": None, "imagery_date": None, "span_lat": None, "span_lon": None}
def _view(lat, lon, zoom=None, bearing=None) -> dict[str, Any]:
@@ -52,7 +64,7 @@ def _view(lat, lon, zoom=None, bearing=None) -> dict[str, Any]:
if bearing is not None:
bearing = bearing % 360
return {"lat": lat, "lon": lon, "zoom": zoom, "bearing": bearing,
- "title": None, "imagery_date": None}
+ "title": None, "imagery_date": None, "span_lat": None, "span_lon": None}
def _place_name(raw: str | None) -> str | None:
@@ -83,6 +95,322 @@ def _param(u, name: str) -> str | None:
return values[0] if values else None
+#: What kind of camera the URL describes, which decides what may be drawn over
+#: the page. Geometry the app *computes* — a search grid, a sun arc, a measured
+#: line — is only honest on ``map``: it is worked out through Web Mercator, and
+#: on a pitched or panoramic camera that arithmetic is wrong before occlusion
+#: even gets a say (a cell would land on the wall of the building hiding it).
+#: What the analyst *places* by hand, a media pin, is never computed and stays
+#: allowed everywhere.
+VIEW_MAP = "map" # straight-down 2D — geometry is sound
+VIEW_TILTED = "tilted" # a pitched 3D camera
+VIEW_STREET = "streetview" # a ground-level panorama
+VIEW_GLOBE = "globe" # level, but far enough out that the Earth is visibly round
+
+#: How high a level camera may sit before the ground under it stops being flat
+#: enough to measure on, in metres.
+#:
+#: A camera pointed straight down at a plane is a plain uniform scaling — the
+#: perspective cancels exactly — so a level 3D view *is* measurable, even though
+#: nothing about it is Web Mercator. What ends that is the Earth's own
+#: curvature: over a span of D the ground drops about D²/8R below the plane, so
+#: at 150 km across it is a couple of hundred metres, a quarter of a percent.
+#: Past this the view is a globe and says so.
+#:
+#: What this cannot account for is relief. A level camera still displaces a
+#: hilltop outward from the centre by its own height times the tangent of the
+#: off-axis angle, and no URL says how tall the ground is. Flat country is
+#: exact; mountains are not (extension/README.md says so where the analyst
+#: reads it).
+LEVEL_CEILING_M = 150_000
+
+
+#: How far off straight down a camera may point and still be read as level, in
+#: degrees.
+#:
+#: Not a courtesy. These viewers write the camera they are actually holding, at
+#: full precision, and they do not come back to a clean zero: turning Google
+#: Earth leaves a fraction of a degree of pitch behind it, and read as "tilted"
+#: that is a tool which switches itself off whenever the compass is touched.
+#: Which is what it did.
+#:
+#: The number is what the drawing can absorb. A pitched camera stretches the
+#: ground away from the centre, and across half of Earth's own 35° field that
+#: comes to roughly ``0.6 · tan θ`` — a percent at one degree, two at two,
+#: eleven at ten. Two sits with the approximations already admitted here (a
+#: measured scale's latitude axis is out by about as much), and a camera anyone
+#: has deliberately pitched is past it by an order of magnitude.
+LEVEL_TILT_DEG = 2.0
+
+
+def _camera_number(camera: str, letter: str) -> float | None:
+ """One of the free camera's `,<number><letter>` parts, or None."""
+ m = re.search(rf",({_NUM}){letter}(?:,|$)", camera)
+ return _num(m[1]) if m else None
+
+
+def _pitch(camera: str) -> float | None:
+ """How far off straight down a free camera points, in degrees — or None
+ where the URL states neither angle.
+
+ Pitch and roll answer together: either one tips the ground plane, and what
+ the drawing has to live with is the worse of the two.
+ """
+ stated = [_camera_number(camera, letter) for letter in ("t", "r")]
+ angles = [abs(angle) for angle in stated if angle is not None]
+ return max(angles) if angles else None
+
+
+def _pitched(camera: str) -> bool:
+ """Whether that pitch is one the geometry cannot carry."""
+ angle = _pitch(camera)
+ return angle is not None and angle > LEVEL_TILT_DEG
+
+
+def _free_camera(camera: str, height: float | None) -> str:
+ """What a free 3D camera is looking at: a map, a pitched view, or a globe.
+
+ Pitch and roll are what break the geometry outright — a cell would land on
+ the wall of the building hiding it. Level and low, the view is a plain
+ scaling of the ground and a caller that measures its own scale can work on
+ it; level and far out, it is a globe (``LEVEL_CEILING_M``). "Level" carries
+ a tolerance, and ``LEVEL_TILT_DEG`` says why it has to.
+ """
+ if _pitched(camera):
+ return VIEW_TILTED
+ if height is None or height > LEVEL_CEILING_M:
+ return VIEW_GLOBE
+ return VIEW_MAP
+
+
+def camera_pitch(site_id: str, u) -> float | None:
+ """The pitch this site's URL states, in degrees, or None where it states
+ none.
+
+ Carried out to the caller so a refusal can name the angle. "This view is
+ tilted" and "this view is tilted by 14°" are different sentences to be
+ given: one is a verdict, the other is the thing to go and undo — and on a
+ viewer that leaves half a degree behind after every turn, the number is also
+ how an analyst tells a camera they pitched from one they did not.
+ """
+ if site_id not in ("google-earth", "google-maps"):
+ return None
+ block = re.search(r"@[^/]*", u.path)
+ return _pitch(block[0]) if block else None
+
+
+def _view_kind(site_id: str, u) -> str | None:
+ """Which camera the address bar describes, or None when it does not say.
+
+ Read from the URL only, like everything else here, and unclassified rather
+ than guessed — the same rule ``_imagery_mode`` follows.
+
+ A known limit, stated rather than papered over: Bing's 3D mode and Apple's
+ Flyover leave no mark in their URLs, so both report ``map``. The drawing
+ side needs a zoom as well, which those views do not carry, so the geometry
+ still declines — but it declines for the second reason, not the first.
+ """
+ if site_id == "google-earth":
+ block = re.search(r"@[^/]*", u.path)
+ if not block:
+ return None
+ return _free_camera(block[0], _camera_number(block[0], "d"))
+ if site_id == "google-maps":
+ block = re.search(r"@[^/]*", u.path)
+ if not block:
+ return None
+ camera = block[0]
+ if ",3a," in camera: # the Street View pano camera
+ return VIEW_STREET
+ if re.search(rf",{_NUM}a", camera):
+ # Earth mode: a free camera, quoting its own height rather than a
+ # zoom. Level, it is as measurable as the satellite view above.
+ return _free_camera(camera, _camera_number(camera, "a"))
+ if _pitched(camera):
+ return VIEW_TILTED
+ if re.search(rf",{_NUM}z", camera):
+ return VIEW_MAP
+ # Satellite drops the zoom for a viewport height in metres
+ # (``@lat,lon,1053m``), and it is still a straight-down map — the camera
+ # did not move, only the way the URL describes it. Said so here, even
+ # though ``geometry`` below still declines for want of a zoom: a caller
+ # that measures its own scale (the extension's map tools) needs to know
+ # this is a map, and one that does not is refused either way.
+ return VIEW_MAP if re.search(rf",{_NUM}m(?:$|[,/])", camera) else None
+ if site_id == "copernicus-browser":
+ # Its 3D terrain viewer writes its camera into the address bar as
+ # ``terrainViewerSettings`` and reads it back to re-enter 3D, which is
+ # the mark this needs: without it, the view is the flat Leaflet map.
+ return VIEW_TILTED if _param(u, "terrainViewerSettings") else VIEW_MAP
+ if site_id in {"openstreetmap", "zoom-earth", "satellites-pro"}:
+ return VIEW_MAP # flat-map renderers, with no other mode to be in
+ if site_id in {"bing-maps", "yandex-maps", "apple-maps"}:
+ return VIEW_MAP
+ return None
+
+
+#: How a site lays the world out flat. Geometry is drawn by inverting this.
+#:
+#: The overlay anchors on the view centre, so the two Mercators agree there and
+#: disagree by a growing scale error across the viewport rather than by a fixed
+#: offset: measured, that is some tens of metres at z12 and under a metre by
+#: z17. Small — but a search grid's cells are metres, so it is worth being right
+#: about, and it is free once the site says which one it draws in.
+PROJ_SPHERICAL = "webmercator" # EPSG:3857 — nearly everyone
+PROJ_ELLIPSOIDAL = "ellipsoidal" # EPSG:3395 — Yandex, on the WGS84 ellipsoid
+
+#: Where a site stops drawing a flat map and starts drawing a globe. The URL
+#: goes on quoting a zoom either way, so the zoom is the only warning there is.
+#: Conservative on purpose: what this now decides is whether the drawing is
+#: marked as drifting at the edges, not whether it appears at all.
+_GLOBE_BELOW = {"google-maps": 8, "bing-maps": 8}
+
+_PROJECTIONS = {
+ "google-maps": PROJ_SPHERICAL,
+ "bing-maps": PROJ_SPHERICAL,
+ "openstreetmap": PROJ_SPHERICAL,
+ "apple-maps": PROJ_SPHERICAL,
+ "zoom-earth": PROJ_SPHERICAL,
+ "satellites-pro": PROJ_SPHERICAL,
+ # Copernicus Browser draws its 2D map on Leaflet, whose default CRS is
+ # EPSG:3857. Checked twice over: its own package.json depends on leaflet,
+ # and two zooms about two different pixels solved for the same camera
+ # centre through spherical Mercator, to half a pixel. Its 3D terrain viewer
+ # is a different camera and says so in the URL (``_view_kind``).
+ "copernicus-browser": PROJ_SPHERICAL,
+ "yandex-maps": PROJ_ELLIPSOIDAL,
+ # google-earth is a globe: a free camera names no flattening, so it is not
+ # named at all and the tools measure it instead.
+}
+
+
+#: Sites whose ``zoom`` is the tile level of the projection above, so the scale
+#: follows from the URL alone: ``256·2^zoom`` pixels around the world.
+#:
+#: Documented, and then checked. OpenStreetMap's slippy-map spec and Bing's tile
+#: system state the same thing in the same words — 256-pixel tiles, one tile of
+#: the whole world at zoom 0, ``x = (lon+180)/360 · 256·2^z`` — and Google's
+#: matches both. Yandex numbers its levels the same way over the elliptical
+#: Mercator it draws in. Copernicus Browser draws on Leaflet, which is that spec
+#: with a library around it. Every one of them was then dragged a known number
+#: of pixels in a real browser and asked where it had landed: the answer came
+#: back within a tenth of a percent of the level the URL quoted, at two window
+#: sizes (``docs/MAP_SITES.md``).
+#:
+#: **Apple's ``z`` is here on the strength of that measurement, not of its
+#: documentation**, which calls it "a floating point value between 2 and 21 that
+#: defines the area around the center point" and stops. Opened at ``z=15`` in a
+#: 1000 px window and again in a 760 px one, Apple drew both at exactly tile
+#: level 15. What its ``z`` cannot do is stay true: Apple never rewrites it, so
+#: it is dropped the moment the same URL carries a span (``_apple_maps``), and
+#: only the opening view is ever read from it.
+_ZOOM_IS_TILES = {
+ "google-maps",
+ "bing-maps",
+ "openstreetmap",
+ "yandex-maps",
+ "zoom-earth",
+ "satellites-pro",
+ "copernicus-browser",
+ "apple-maps",
+}
+
+
+# --- what the URL says about how big the map is drawn --------------------------
+
+#: Metres of ground per pixel at the equator, zoom 0, on the 256-pixel tile
+#: every one of these sites is scaled in.
+_EQUATOR_M_PER_PX = 2 * math.pi * 6378137 / 256
+
+#: Which of the three things the URL said, for the ``zoom`` that came back.
+#: Each is a number the site itself wrote about the view it is showing; ``None``
+#: means the URL stated nothing a scale can be read out of, and the caller is on
+#: its own (the extension measures the map instead).
+SCALE_ZOOM = "zoom" # a tile level, the usual case
+SCALE_HEIGHT_M = "height_m" # Google's satellite view: the viewport, in metres
+SCALE_SPAN = "span" # Apple: the degrees the region covers
+
+
+#: Where Mercator is cut, north and south. Every slippy map cuts at this value.
+_MAX_LAT = 85.05112877980659
+
+
+def _mercator_y(lat: float) -> float:
+ """Northing on the 256-pixel world at zoom 0, spherical Mercator."""
+ phi = math.radians(max(-_MAX_LAT, min(_MAX_LAT, lat)))
+ return (1 - math.log(math.tan(phi) + 1 / math.cos(phi)) / math.pi) / 2 * 256
+
+
+def _zoom_from_height_m(metres: float | None, height_px: float, lat: float) -> float | None:
+ """The tile level at which ``height_px`` pixels cover ``metres`` of ground.
+
+ Google's satellite view states that height and no zoom. Its own arithmetic
+ is Web Mercator's, so the inverse is exact.
+ """
+ if not metres or height_px <= 0 or abs(lat) > _MAX_LAT:
+ return None
+ per_px = metres / height_px
+ if per_px <= 0:
+ return None
+ return math.log2(_EQUATOR_M_PER_PX * math.cos(math.radians(lat)) / per_px)
+
+
+def _zoom_from_span(span_lat: float, height_px: float, lat: float) -> float | None:
+ """The tile level at which ``span_lat`` degrees fill ``height_px`` pixels.
+
+ Apple's ``span``. Taken through the projection rather than through a
+ linear degrees-per-pixel, which is only near enough in the middle of the
+ screen and is exactly what a drawing that slides at the edges is made of.
+ """
+ if not span_lat or span_lat <= 0 or height_px <= 0:
+ return None
+ north, south = lat + span_lat / 2, lat - span_lat / 2
+ if abs(north) > _MAX_LAT or abs(south) > _MAX_LAT:
+ return None
+ tall = _mercator_y(south) - _mercator_y(north)
+ return math.log2(height_px / tall) if tall > 0 else None
+
+
+def _scale(
+ site_id: str, parsed: dict[str, Any], camera: float | None,
+ camera_kind: str | None, height_px: float | None,
+) -> tuple[float | None, str | None]:
+ """The zoom this view is at, and which of the three routes it came by.
+
+ The order is the order of authority. A tile level is what most of these
+ sites state and it is exact. Failing that, a size — Google's metres, Apple's
+ degrees — is exact too, but only to a caller that knows how tall its window
+ is, so it needs ``height_px`` and is otherwise left alone. What is never
+ done is inventing one: no ``height_px``, no zoom.
+ """
+ zoom = parsed.get("zoom")
+ if zoom is not None and site_id in _ZOOM_IS_TILES:
+ return zoom, SCALE_ZOOM
+ lat = parsed.get("lat")
+ if lat is None or not height_px:
+ return zoom, None
+ if camera_kind == CAMERA_HEIGHT_M:
+ from_height = _zoom_from_height_m(camera, height_px, lat)
+ if from_height is not None:
+ return from_height, SCALE_HEIGHT_M
+ span_lat = parsed.get("span_lat")
+ if span_lat:
+ from_span = _zoom_from_span(span_lat, height_px, lat)
+ if from_span is not None:
+ return from_span, SCALE_SPAN
+ return zoom, None
+
+
+def _projection(site_id: str) -> str | None:
+ """Which flattening a site draws in, or None when we cannot say.
+
+ None is a refusal, not a default. Guessing right most of the time is what
+ makes a wrong guess dangerous: the drawing looks exactly as sure of itself
+ either way, and nothing on screen says which one it was.
+ """
+ return _PROJECTIONS.get(site_id)
+
+
def _imagery_mode(site_id: str, u) -> str | None:
"""Identify satellite imagery only when the URL makes it explicit.
@@ -91,7 +419,13 @@ def _imagery_mode(site_id: str, u) -> str | None:
guessed as satellite imagery. Satellite-only sites and explicit layer
parameters are safe to classify from the address bar.
"""
- if site_id in {"google-earth", "zoom-earth", "satellites-pro", "copernicus-browser"}:
+ if site_id == "satellites-pro":
+ # It answers a bare link with a country path of its own, and that path
+ # says which basemap it landed on: /plan/ is an OpenStreetMap road map,
+ # not imagery. Measured — a link built for satellite came back as
+ # /plan/France_map.
+ return None if "/plan/" in u.path.lower() else "satellite"
+ if site_id in {"google-earth", "zoom-earth", "copernicus-browser"}:
return "satellite"
if site_id == "google-maps":
return "satellite" if "!1e3" in unquote(u.geturl()) else None
@@ -167,13 +501,35 @@ def _openstreetmap(u) -> dict[str, Any]:
def _apple_maps(u) -> dict[str, Any]:
- # ?ll=48.8584,2.2945&z=17&q=Tour+Eiffel (also &center= on some share links)
+ """Apple, in the two forms it uses: the one a link is written in, and the
+ one the page rewrites itself into as soon as it is touched.
+
+ ?ll=48.8584,2.2945&z=17&q=Tour+Eiffel
+ /frame?center=48.8584,2.2945&span=0.029055,0.056434&map=satellite
+
+ ``span`` is the region the view covers, latitude delta first, exactly as
+ ``MKCoordinateSpan`` defines it, and it is live: pan and it follows the
+ centre, zoom and it halves.
+
+ **``z`` is not.** Apple carries whatever ``z`` the link that opened the map
+ had and never rewrites it, so after one zoom it names a scale the map left
+ behind. Measured in a browser: opened at ``z=15``, zoomed twice, the URL
+ still said 15 while the span had quartered. So it is read only where there
+ is no span — the opening URL, the one moment it is still true.
+ """
title = _place_name(_param(u, "q") or _param(u, "name"))
ll = _param(u, "ll") or _param(u, "center") or ""
m = re.fullmatch(rf"({_NUM}),({_NUM})", ll)
- if m:
- return {**_view(_num(m[1]), _num(m[2]), _num(_param(u, "z"))), "title": title}
- return {**_no_view(), "title": title}
+ if not m:
+ return {**_no_view(), "title": title}
+ span = re.fullmatch(rf"({_NUM}),({_NUM})", _param(u, "span") or "")
+ lat_span = _num(span[1]) if span else None
+ lon_span = _num(span[2]) if span else None
+ live = lat_span is not None and lat_span > 0
+ view = _view(_num(m[1]), _num(m[2]), None if live else _num(_param(u, "z")))
+ if live and view["lat"] is not None:
+ view["span_lat"], view["span_lon"] = lat_span, lon_span
+ return {**view, "title": title}
def _zoom_earth(u) -> dict[str, Any]:
@@ -238,8 +594,91 @@ SITES: list[tuple[str, str, Callable, Callable | None, Callable]] = [
]
-def parse_map_url(url: str) -> dict[str, Any] | None:
- """Parse a page URL. None = not a map site (the extension stays out)."""
+#: What a zoomless Google view quotes instead, and what the number means.
+#:
+#: ``height_m`` is the viewport's own height on the ground, in metres, and it
+#: was checked rather than guessed: a 1000 px window opened at ``15z`` came back
+#: as ``,3231m``, and 1000 px of Web Mercator at that latitude and zoom is
+#: 3233 m. That makes it a scale, exact to the metre it is rounded to, for a
+#: caller that knows how tall its window is.
+#:
+#: ``distance_d`` is Earth's camera distance from the point it looks at. It is
+#: proportional to metres per pixel — halve it and the view zooms by two,
+#: measured — but the constant between them is the camera's field of view,
+#: which the URL does not state. So it carries a scale through a zoom and
+#: nothing more.
+CAMERA_HEIGHT_M = "height_m"
+CAMERA_DISTANCE_D = "distance_d"
+
+
+def _camera_span(site_id: str, u) -> tuple[float | None, str | None]:
+ """How far out a zoomless view is, and in which of the two senses above."""
+ if site_id not in {"google-maps", "google-earth"}:
+ return None, None
+ block = re.search(r"@[^/]*", u.path)
+ if not block:
+ return None, None
+ camera = block[0]
+ if ",3a," in camera: # Street View's pano radius is not a span
+ return None, None
+ distance = _camera_number(camera, "d")
+ if distance:
+ return distance, CAMERA_DISTANCE_D
+ height = _camera_number(camera, "m")
+ return (height, CAMERA_HEIGHT_M) if height else (None, None)
+
+
+def _drawable(
+ site_id: str, parsed: dict[str, Any], kind: str | None, scale_source: str | None
+) -> dict[str, Any]:
+ """What may be drawn over this view, and the facts behind the verdict.
+
+ Decided here, because every input to it is site knowledge and that is what
+ this module is for. ``geometry`` gates what the app *computes* — a search
+ grid, a measured line, a sun arc — and it needs two things:
+
+ * a camera pointed straight down (``view_kind``), near or far, since
+ Mercator says nothing about a pitched or panoramic one;
+ * a projection we can actually invert, named rather than assumed.
+
+ ``far`` is the third fact, and it is a warning rather than a refusal: these
+ maps turn into globes on the way out while their URLs go on quoting a zoom,
+ and out there the middle of the screen is still right while the edges drift.
+ That is a trade worth offering — a sweep of a whole region is worth seeing
+ roughly, and anyone who wants it exact zooms in — so the drawing stays and
+ says so (`maptools.js`, the verdict; `mapoverlay.js` dims it).
+
+ A pin is not gated at all: the analyst places it, and where it files is a
+ coordinate the address bar already carried. What changes when ``geometry``
+ is false is only *which* coordinate it may claim — the view centre or the
+ camera point, never the pixel that was clicked.
+ """
+ projection = _projection(site_id)
+ globe_below = _GLOBE_BELOW.get(site_id)
+ zoom = parsed.get("zoom")
+ level = kind in (VIEW_MAP, VIEW_GLOBE)
+ return {
+ "view_kind": kind,
+ "projection": projection,
+ "globe_below": globe_below,
+ "scale_source": scale_source,
+ "geometry": bool(level and projection),
+ "far": bool(
+ kind == VIEW_GLOBE
+ or (globe_below is not None and zoom is not None and zoom < globe_below)
+ ),
+ }
+
+
+def parse_map_url(url: str, height_px: float | None = None) -> dict[str, Any] | None:
+ """Parse a page URL. None = not a map site (the extension stays out).
+
+ ``height_px`` is how tall the map is drawn in the caller's window, and it is
+ what turns Apple's span and Google's satellite metres into a zoom. Both of
+ those views were measured to fill the window's full height, which is why one
+ number is enough; a caller that does not know it simply gets no zoom for
+ them, never a guessed one.
+ """
try:
u = urlsplit(url)
except ValueError:
@@ -256,10 +695,16 @@ def parse_map_url(url: str) -> dict[str, Any] | None:
parsed = parse(u)
except Exception:
parsed = _no_view() # a weird URL on a known site still captures
+ camera, camera_kind = _camera_span(site_id, u)
+ parsed["zoom"], source = _scale(site_id, parsed, camera, camera_kind, height_px)
return {
"site": site_id,
"label": label,
**parsed,
"imagery_mode": _imagery_mode(site_id, u),
+ "camera_m": camera,
+ "camera_kind": camera_kind,
+ "tilt": camera_pitch(site_id, u),
+ **_drawable(site_id, parsed, _view_kind(site_id, u), source),
}
return None
diff --git a/src/azimut/engine/scrapers.py b/src/azimut/engine/scrapers.py
index 2223725..e6f35d4 100644
--- a/src/azimut/engine/scrapers.py
+++ b/src/azimut/engine/scrapers.py
@@ -32,9 +32,7 @@ from __future__ import annotations
import hashlib
import importlib.metadata
-import os
import shutil
-import stat
import sys
import tempfile
import threading
@@ -48,6 +46,7 @@ from typing import Any
import httpx
from .. import config
+from . import dirswap
# distribution name on PyPI -> module name it imports as
SCRAPERS: dict[str, str] = {"yt-dlp": "yt_dlp", "gallery-dl": "gallery_dl"}
@@ -61,64 +60,8 @@ WHEEL_MAX_BYTES = 64 * 1024 * 1024
_lock = threading.Lock() # updates mutate a shared directory
-
-# ---- swapping a directory, on all three platforms ---------------------------
-#
-# Windows is the constraint here. os.replace() onto an *existing* directory
-# fails there (MOVEFILE_REPLACE_EXISTING is file-only), and a file that's open
-# can't be deleted at all. So the destructive step is always a rename — old copy
-# out of the way first, new copy in second, delete the leftovers last. Renames
-# are cheap and near-atomic everywhere; deletes are the part allowed to fail,
-# and by then they can't cost us the package.
-
-
-def _force_writable(func, path, _exc):
- """rmtree onexc hook: clear the read-only bit Windows refuses to delete through."""
- try:
- os.chmod(path, stat.S_IWRITE)
- func(path)
- except OSError:
- pass
-
-
-def _rmtree(path: Path) -> None:
- # onexc replaced onerror in 3.12; we still support 3.11. The hook ignores its
- # third argument, which is the only thing that differs between the two.
- if sys.version_info >= (3, 12):
- shutil.rmtree(path, onexc=_force_writable)
- else:
- shutil.rmtree(path, onerror=_force_writable)
-
-
-def _retire(target: Path) -> Path | None:
- """Rename `target` out of the way, returning where it went (None if absent)."""
- if not target.exists():
- return None
- retired = target.parent / f".trash-{target.name}-{os.urandom(4).hex()}"
- target.replace(retired)
- return retired
-
-
-def _swap_in(staging: Path, target: Path) -> None:
- """Replace `target` with `staging`, restoring the old copy if the move fails."""
- retired = _retire(target)
- try:
- staging.replace(target)
- except BaseException:
- if retired is not None:
- retired.replace(target) # put the working copy back
- raise
- if retired is not None:
- # Best-effort: a locked leftover on Windows is litter, not a failure.
- shutil.rmtree(retired, ignore_errors=True)
-
-
-def _discard(target: Path) -> None:
- """Remove `target`, making sure it's gone from the import path even if the
- delete can't finish — the rename is what counts."""
- retired = _retire(target)
- if retired is not None:
- shutil.rmtree(retired, ignore_errors=True)
+# Swapping a directory under a running program is its own problem, and the
+# capture-extension installer has the same one: engine/dirswap.py.
# ---- reading what's on disk -------------------------------------------------
@@ -319,7 +262,7 @@ def update(dist: str) -> dict[str, Any]:
archive.extractall(staging, members=_safe_members(archive))
if not (staging / module).is_dir():
raise RuntimeError(f"{dist} wheel did not contain a {module}/ package")
- _swap_in(staging, dist_dir(dist))
+ dirswap.swap_in(staging, dist_dir(dist))
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
@@ -350,7 +293,7 @@ def reset(dist: str) -> dict[str, Any]:
raise KeyError(dist)
had = runtime_version(dist)
with _lock:
- _discard(dist_dir(dist))
+ dirswap.discard(dist_dir(dist))
activate()
return {
"dist": dist,
diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md
index 7740d4e..4ab365d 100644
--- a/tests/fixtures/README.md
+++ b/tests/fixtures/README.md
@@ -1,4 +1,6 @@
-# Sheet fixtures
+# Fixtures
+
+## Sheet fixtures
The pathologies of three real investigation binders, distilled into files a test can
read. **Synthetic and anonymous on purpose**: the binders themselves are case material,
@@ -14,3 +16,19 @@ so no name, no unit, no place and no URL from them appears here — what is kept
Any test asserting "the app reads the real thing" belongs here rather than against a
table written to suit the code.
+
+## Map sites
+
+| File | What it is there to break |
+|---|---|
+| `map-sites.raw.json` | The observation: every URL nine map sites wrote about themselves after a known gesture, with the window they were driven in. Nothing in it has been parsed. |
+| `map-sites.json` | The same run, parsed by `engine/mapsites.py` and solved for where each site draws its camera. Apple's stale `z`, Google's satellite height in metres, Yandex's longitude-first order, and the five sites that draw their centre somewhere other than the middle of the window. |
+
+Read from both sides: `tests/test_mapsites.py` checks the parse still returns those
+views, `frontend/src/lib/extensionMapFrame.test.js` that the extension's arithmetic
+puts them back where the browser had them. `docs/MAP_SITES.md` is the prose version.
+
+Neither file is written by hand. `npm run calibrate:maps` drives the sites again and
+rewrites the raw one; `python scripts/build_map_fixture.py` turns that into the other.
+The protocol both follow is `frontend/calibration/protocol.mjs`, and it is itself tested
+against a map whose layout is known (`frontend/e2e/map-calibration.spec.js`).
diff --git a/tests/fixtures/map-sites.json b/tests/fixtures/map-sites.json
new file mode 100644
index 0000000..8bd2c84
--- /dev/null
+++ b/tests/fixtures/map-sites.json
@@ -0,0 +1,1271 @@
+{
+ "what": "Every URL these map sites wrote about themselves, driven through one gesture sequence.",
+ "why": "The map tools draw on someone else's map from what its URL says. This is the record of what those URLs actually mean \u2014 see docs/MAP_SITES.md \u2014 and both suites read it: tests/test_mapsites.py that the parse still returns these views, frontend/src/lib/extensionMapFrame.test.js that the arithmetic puts them back where the browser had them, and extensionMapEngine.test.js that the panel does it live.",
+ "centre": "Where each site drew the coordinate its address bar named, in window pixels, solved from its own two zooms. Not the middle of the window on five of the nine.",
+ "how": "Rebuilt by scripts/build_map_fixture.py from tests/fixtures/map-sites.raw.json.",
+ "recordings": [
+ {
+ "label": "google-maps",
+ "site": "google-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 800.0,
+ "y": 500.0
+ },
+ "spread": 0.01,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.3941855,
+ "lon": 2.365445,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.3978168,
+ "lon": 2.356862,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.396219,
+ "lon": 2.3616685,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ }
+ ],
+ "note": "the 2D map, with nothing round it: the camera is the middle of the window"
+ },
+ {
+ "label": "google-maps satellite",
+ "site": "google-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 799.87,
+ "y": 499.97
+ },
+ "spread": 1.49,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.001498318234315,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "height_m",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.3941855,
+ "lon": 2.365445,
+ "zoom": 15.001788226067221,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "height_m",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.3978168,
+ "lon": 2.356862,
+ "zoom": 16.00168880482045,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "height_m",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.396219,
+ "lon": 2.3616685,
+ "zoom": 17.00083951932319,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "height_m",
+ "site": "google-maps"
+ }
+ ],
+ "note": "satellite quotes the viewport's height in metres instead of a level"
+ },
+ {
+ "label": "google-maps with its place panel open",
+ "site": "google-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 800.0,
+ "y": 500.0
+ },
+ "spread": 0.0,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.081,2.3988,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.081,
+ "lon": 2.3988,
+ "zoom": 13.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.1040234,2.4494401,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.1040234,
+ "lon": 2.4494401,
+ "zoom": 13.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.1040234,2.4494401,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.1040234,
+ "lon": 2.4494401,
+ "zoom": 13.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.0911689,2.4878923,14z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "view": {
+ "lat": 47.0911689,
+ "lon": 2.4878923,
+ "zoom": 14.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "google-maps"
+ }
+ ],
+ "note": "the panel covers the map but does not move the camera under it"
+ },
+ {
+ "label": "apple-maps",
+ "site": "apple-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 867.5,
+ "y": 500.0
+ },
+ "spread": 0.09,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.029055%2C0.056434",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 14.99998634768003,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434",
+ "view": {
+ "lat": 47.393517,
+ "lon": 2.36523,
+ "zoom": 14.999996940780553,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217",
+ "view": {
+ "lat": 47.397149,
+ "lon": 2.355199,
+ "zoom": 15.99999686323065,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108",
+ "view": {
+ "lat": 47.395551,
+ "lon": 2.359281,
+ "zoom": 16.999941303569063,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ }
+ ],
+ "note": "Apple states a span, never a live zoom, and draws 67 px right of centre here"
+ },
+ {
+ "label": "apple-maps in a smaller window",
+ "site": "apple-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "map_height": 760,
+ "centre": {
+ "x": 597.5,
+ "y": 380.02
+ },
+ "spread": 0.18,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.022082%2C0.039268",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 14.999973302876091,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.392617%2C2.362055&span=0.022080%2C0.045276",
+ "view": {
+ "lat": 47.392617,
+ "lon": 2.362055,
+ "zoom": 14.999990238003937,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395042%2C2.369318&span=0.011039%2C0.022638",
+ "view": {
+ "lat": 47.395042,
+ "lon": 2.369318,
+ "zoom": 16.000054556399927,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393721%2C2.370890&span=0.005520%2C0.011319",
+ "view": {
+ "lat": 47.393721,
+ "lon": 2.37089,
+ "zoom": 16.999960042778163,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "span",
+ "site": "apple-maps"
+ }
+ ],
+ "note": "same site, another window: its sidebar collapsed mid-pan and the region it reports grew 140 px, while the camera stayed put"
+ },
+ {
+ "label": "bing-maps",
+ "site": "bing-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 919,
+ "centre": {
+ "x": 800.02,
+ "y": 540.52
+ },
+ "spread": 0.13,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "bing-maps"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h",
+ "view": {
+ "lat": 47.394273,
+ "lon": 2.36566,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "bing-maps"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h",
+ "view": {
+ "lat": 47.398492,
+ "lon": 2.357077,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "bing-maps"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h",
+ "view": {
+ "lat": 47.397189,
+ "lon": 2.361883,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "bing-maps"
+ }
+ ],
+ "note": "Bing sits under an 81 px header, so its camera is 40 px down"
+ },
+ {
+ "label": "yandex-maps",
+ "site": "yandex-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 980,
+ "centre": {
+ "x": 1010.0,
+ "y": 509.99
+ },
+ "spread": 0.0,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15",
+ "view": {
+ "lat": 47.394291,
+ "lon": 2.36566,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15",
+ "view": {
+ "lat": 47.394291,
+ "lon": 2.36566,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.370767%2C47.391231&z=16",
+ "view": {
+ "lat": 47.391231,
+ "lon": 2.370767,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ }
+ ],
+ "note": "a 420 px results panel, and the map centred in what is left"
+ },
+ {
+ "label": "yandex-maps in a smaller window",
+ "site": "yandex-maps",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "map_height": 740,
+ "centre": {
+ "x": 810.01,
+ "y": 390.0
+ },
+ "spread": 0.04,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15",
+ "view": {
+ "lat": 47.393125,
+ "lon": 2.363085,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16",
+ "view": {
+ "lat": 47.395704,
+ "lon": 2.365788,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17",
+ "view": {
+ "lat": 47.394451,
+ "lon": 2.36508,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "ellipsoidal"
+ },
+ "scale_source": "zoom",
+ "site": "yandex-maps"
+ }
+ ],
+ "note": "the panel is a fixed width, so the offset does not move with the window"
+ },
+ {
+ "label": "openstreetmap",
+ "site": "openstreetmap",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 945,
+ "centre": {
+ "x": 800.06,
+ "y": 527.41
+ },
+ "spread": 0.15,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.38846/2.35279",
+ "view": {
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.39427/2.36567",
+ "view": {
+ "lat": 47.39427,
+ "lon": 2.36567,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=17/47.400314/2.352791",
+ "view": {
+ "lat": 47.400314,
+ "lon": 2.352791,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=19/47.399265/2.356396",
+ "view": {
+ "lat": 47.399265,
+ "lon": 2.356396,
+ "zoom": 19.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ }
+ ],
+ "note": "a 55 px header of its own"
+ },
+ {
+ "label": "openstreetmap in a smaller window",
+ "site": "openstreetmap",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "map_height": 705,
+ "centre": {
+ "x": 599.99,
+ "y": 407.39
+ },
+ "spread": 0.51,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.38846/2.35279",
+ "view": {
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.39311/2.36309",
+ "view": {
+ "lat": 47.39311,
+ "lon": 2.36309,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=16/47.39593/2.37030",
+ "view": {
+ "lat": 47.39593,
+ "lon": 2.3703,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=17/47.394809/2.371845",
+ "view": {
+ "lat": 47.394809,
+ "lon": 2.371845,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "openstreetmap"
+ }
+ ],
+ "note": "same header, same 27 px"
+ },
+ {
+ "label": "satellites-pro",
+ "site": "satellites-pro",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 799.98,
+ "y": 500.04
+ },
+ "spread": 0.13,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://satellites.pro/plan/France_map#47.388462,2.352785,15",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "satellites-pro"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.394282,2.365665,15",
+ "view": {
+ "lat": 47.394282,
+ "lon": 2.365665,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "satellites-pro"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.397913,2.357082,16",
+ "view": {
+ "lat": 47.397913,
+ "lon": 2.357082,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "satellites-pro"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.396316,2.361889,17",
+ "view": {
+ "lat": 47.396316,
+ "lon": 2.361889,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "satellites-pro"
+ }
+ ],
+ "note": "full-window Leaflet, crosshair dead centre"
+ },
+ {
+ "label": "copernicus-browser",
+ "site": "copernicus-browser",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 1025.03,
+ "y": 500.44
+ },
+ "spread": 1.25,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 1200,
+ "y": 300
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 700,
+ "y": 800
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FOh591qUWIQVhuygSLTCLdP97eGmS5zQ25NfaMPtAny%2B7iaBWrBRMWHceo0SM7zHDOTRRXdWjCHmiwK7%2FaHzykLzK4clL6r%2BgMUbENcl61b3J6RfDgH5rP&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE",
+ "view": {
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "copernicus-browser"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FOh591qUWIQVhuygSLTCLdP97eGmS5zQ25NfaMPtAny%2B7iaBWrBRMWHceo0SM7zHDOTRRXdWjCHmiwK7%2FaHzykLzK4clL6r%2BgMUbENcl61b3J6RfDgH5rP&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE",
+ "view": {
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "copernicus-browser"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=16&lat=47.39138&lng=2.35655&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FGmRDWk0S6efy25XJJ2clzUiSIIpwrrmrTm6sb%2Fa1Ur1%2FlIpit%2FyPGV1T6lg7lxbq9i8bn1foSJqLSD5hJ8lsxWtow8b7UfY%2Bm4rmjwzE1DzCC93upUVtw&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE",
+ "view": {
+ "lat": 47.39138,
+ "lon": 2.35655,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "copernicus-browser"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=17&lat=47.3892&lng=2.35306&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2F4r%2B4Q6eNW%2F5pehuG8etZw6tN3BYuKmJpyWafolpVfMrn94YvcSgxRrEaYhNjI%2BuLverBqN4FAxti4iFdZL28TcMeeTULZVwB14%2B07bisnmG%2BU%2BJHk83%2FO&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE",
+ "view": {
+ "lat": 47.3892,
+ "lon": 2.35306,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "copernicus-browser"
+ }
+ ],
+ "note": "a 450 px panel; its address bar follows a zoom but not a pan"
+ },
+ {
+ "label": "zoom-earth",
+ "site": "zoom-earth",
+ "browser": "chromium",
+ "page_zoom": 1,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "map_height": 1000,
+ "centre": {
+ "x": 800.49,
+ "y": 499.94
+ },
+ "spread": 0.0,
+ "canvas": null,
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ }
+ ],
+ "steps": [
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.388462,2.352785,10z",
+ "view": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 10.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "zoom-earth"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.570996,2.757906,10z",
+ "view": {
+ "lat": 47.570996,
+ "lon": 2.757906,
+ "zoom": 10.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "zoom-earth"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.686655,2.48291,11z",
+ "view": {
+ "lat": 47.686655,
+ "lon": 2.48291,
+ "zoom": 11.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "zoom-earth"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.686655,2.48291,11z",
+ "view": {
+ "lat": 47.686655,
+ "lon": 2.48291,
+ "zoom": 11.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ },
+ "scale_source": "zoom",
+ "site": "zoom-earth"
+ }
+ ],
+ "note": "full window, camera dead centre; its satellite layer stops at level 11"
+ }
+ ],
+ "rounding": {
+ "what": "One site rounds the zoom it writes. Bing's wheel moves a third of a level and its URL carries one decimal, so \"15.3\" is really 15.334 \u2014 a fortieth of a level, two and a third percent of scale, five metres at the edge of a 1600 px window at level 18.",
+ "how": "Six wheel notches about one pixel, from a whole level. The zooms between the whole ones are what the address bar cannot state, and what `zoomFromAnchor` works out from the pixel the zoom held still.",
+ "site": "bing-maps",
+ "browser": "chromium",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "at": {
+ "x": 1150,
+ "y": 380
+ },
+ "centre": {
+ "x": 799.75,
+ "y": 540.62
+ },
+ "step": 0.3333333333333333,
+ "steps": [
+ {
+ "url": "https://www.bing.com/maps?cp=48.858370%7E2.294481&lvl=15&style=h",
+ "view": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 15.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.859307%7E2.297585&lvl=15.3&style=h",
+ "view": {
+ "lat": 48.859307,
+ "lon": 2.297585,
+ "zoom": 15.3,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.860050%7E2.300048&lvl=15.7&style=h",
+ "view": {
+ "lat": 48.86005,
+ "lon": 2.300048,
+ "zoom": 15.7,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.860639%7E2.302002&lvl=16&style=h",
+ "view": {
+ "lat": 48.860639,
+ "lon": 2.302002,
+ "zoom": 16.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861107%7E2.303552&lvl=16.3&style=h",
+ "view": {
+ "lat": 48.861107,
+ "lon": 2.303552,
+ "zoom": 16.3,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861478%7E2.304781&lvl=16.7&style=h",
+ "view": {
+ "lat": 48.861478,
+ "lon": 2.304781,
+ "zoom": 16.7,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861772%7E2.305757&lvl=17&style=h",
+ "view": {
+ "lat": 48.861772,
+ "lon": 2.305757,
+ "zoom": 17.0,
+ "bearing": 0,
+ "projection": "webmercator"
+ }
+ }
+ ]
+ }
+}
diff --git a/tests/fixtures/map-sites.raw.json b/tests/fixtures/map-sites.raw.json
new file mode 100644
index 0000000..d468e01
--- /dev/null
+++ b/tests/fixtures/map-sites.raw.json
@@ -0,0 +1,703 @@
+{
+ "what": "Every URL these map sites wrote about themselves, driven through one gesture sequence.",
+ "how": "frontend/calibration/protocol.mjs \u2014 open, drag a known number of pixels, zoom about two known pixels. Run it again with `npm run calibrate:maps`.",
+ "why": "The raw half of tests/fixtures/map-sites.json. Nothing here has been parsed: scripts/build_map_fixture.py does that, with the app\u2019s own parser.",
+ "place": {
+ "lat": 47.388462,
+ "lon": 2.352785,
+ "zoom": 15
+ },
+ "recorded": [
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "google-maps",
+ "label": "google-maps",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "google-maps",
+ "label": "google-maps satellite",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "google-maps",
+ "label": "google-maps with its place panel open",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.081,2.3988,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.1040234,2.4494401,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.1040234,2.4494401,13z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ },
+ {
+ "url": "https://www.google.com/maps/place/18000+Bourges/@47.0911689,2.4878923,14z/data=!4m6!3m5!1s0x47fa9677b89bb417:0xcbfb282ccd5c85be!8m2!3d47.0812405!4d2.3979615!16zL20vMGwzOXM?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "apple-maps",
+ "label": "apple-maps",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.029055%2C0.056434"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "apple-maps",
+ "label": "apple-maps in a smaller window",
+ "link": null,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.022082%2C0.039268"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.392617%2C2.362055&span=0.022080%2C0.045276"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395042%2C2.369318&span=0.011039%2C0.022638"
+ },
+ {
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393721%2C2.370890&span=0.005520%2C0.011319"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "bing-maps",
+ "label": "bing-maps",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "yandex-maps",
+ "label": "yandex-maps",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.370767%2C47.391231&z=16"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "yandex-maps",
+ "label": "yandex-maps in a smaller window",
+ "link": null,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16"
+ },
+ {
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "openstreetmap",
+ "label": "openstreetmap",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.38846/2.35279"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.39427/2.36567"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=17/47.400314/2.352791"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=19/47.399265/2.356396"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "openstreetmap",
+ "label": "openstreetmap in a smaller window",
+ "link": null,
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -240,
+ "dy": 160
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 936,
+ "y": 213
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 744,
+ "y": 562
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.38846/2.35279"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=15/47.39311/2.36309"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=16/47.39593/2.37030"
+ },
+ {
+ "url": "https://www.openstreetmap.org/#map=17/47.394809/2.371845"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "satellites-pro",
+ "label": "satellites-pro",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 1248,
+ "y": 720
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://satellites.pro/plan/France_map#47.388462,2.352785,15"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.394282,2.365665,15"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.397913,2.357082,16"
+ },
+ {
+ "url": "https://satellites.pro/plan/France_map#47.396316,2.361889,17"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "copernicus-browser",
+ "label": "copernicus-browser",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 1200,
+ "y": 300
+ }
+ },
+ {
+ "from": 2,
+ "to": 3,
+ "at": {
+ "x": 700,
+ "y": 800
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FOh591qUWIQVhuygSLTCLdP97eGmS5zQ25NfaMPtAny%2B7iaBWrBRMWHceo0SM7zHDOTRRXdWjCHmiwK7%2FaHzykLzK4clL6r%2BgMUbENcl61b3J6RfDgH5rP&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FOh591qUWIQVhuygSLTCLdP97eGmS5zQ25NfaMPtAny%2B7iaBWrBRMWHceo0SM7zHDOTRRXdWjCHmiwK7%2FaHzykLzK4clL6r%2BgMUbENcl61b3J6RfDgH5rP&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=16&lat=47.39138&lng=2.35655&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2FGmRDWk0S6efy25XJJ2clzUiSIIpwrrmrTm6sb%2Fa1Ur1%2FlIpit%2FyPGV1T6lg7lxbq9i8bn1foSJqLSD5hJ8lsxWtow8b7UfY%2Bm4rmjwzE1DzCC93upUVtw&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE"
+ },
+ {
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=17&lat=47.3892&lng=2.35306&themeId=DEFAULT-THEME&visualizationUrl=U2FsdGVkX1%2F4r%2B4Q6eNW%2F5pehuG8etZw6tN3BYuKmJpyWafolpVfMrn94YvcSgxRrEaYhNjI%2BuLverBqN4FAxti4iFdZL28TcMeeTULZVwB14%2B07bisnmG%2BU%2BJHk83%2FO&datasetId=S2_L2A_CDAS&demSource3D=%22MAPZEN%22&cloudCoverage=30&dateMode=SINGLE"
+ }
+ ]
+ },
+ {
+ "browser": "chromium",
+ "pageZoom": 1,
+ "deviceScaleFactor": 1,
+ "protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
+ "site": "zoom-earth",
+ "label": "zoom-earth",
+ "link": null,
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "pan": {
+ "from": 0,
+ "to": 1,
+ "dx": -300,
+ "dy": 200
+ },
+ "zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ }
+ ],
+ "canvas": null,
+ "steps": [
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.388462,2.352785,10z"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.570996,2.757906,10z"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.686655,2.48291,11z"
+ },
+ {
+ "url": "https://zoom.earth/maps/satellite/#view=47.686655,2.48291,11z"
+ }
+ ]
+ }
+ ],
+ "rounding": {
+ "what": "One site rounds the zoom it writes. Bing's wheel moves a third of a level and its URL carries one decimal, so \"15.3\" is really 15.334 \u2014 a fortieth of a level, two and a third percent of scale, five metres at the edge of a 1600 px window at level 18.",
+ "how": "Six wheel notches about one pixel, from a whole level. The zooms between the whole ones are what the address bar cannot state, and what `zoomFromAnchor` works out from the pixel the zoom held still.",
+ "site": "bing-maps",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "at": {
+ "x": 1150,
+ "y": 380
+ },
+ "step": 0.3333333333333333,
+ "steps": [
+ {
+ "url": "https://www.bing.com/maps?cp=48.858370%7E2.294481&lvl=15&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.859307%7E2.297585&lvl=15.3&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.860050%7E2.300048&lvl=15.7&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.860639%7E2.302002&lvl=16&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861107%7E2.303552&lvl=16.3&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861478%7E2.304781&lvl=16.7&style=h"
+ },
+ {
+ "url": "https://www.bing.com/maps?cp=48.861772%7E2.305757&lvl=17&style=h"
+ }
+ ],
+ "browser": "chromium",
+ "pageZoom": 1
+ }
+}
diff --git a/tests/test_events_api.py b/tests/test_events_api.py
index 151bf2a..78ccba8 100644
--- a/tests/test_events_api.py
+++ b/tests/test_events_api.py
@@ -111,3 +111,204 @@ def test_event_payload_is_json_on_the_wire():
# what the frontend JSON.parses — one data: line per event
line = f"data: {json.dumps({'type': 'capture', 'case_id': 'c1'})}\n\n"
assert json.loads(line[len('data: '):].strip()) == {"type": "capture", "case_id": "c1"}
+
+
+# --- the second channel: the extension's panels ---------------------------------
+#
+# A panel drawn over another map works the same case from the other side, and it
+# cannot read the app's own channel: a content script's fetch carries the map
+# site's origin, which the local guard refuses. So the same bus is offered on the
+# token-gated ingest island, read by the extension's background worker.
+
+
+def test_the_extension_channel_needs_the_pairing_token(client):
+ assert client.get("/api/ingest/events").status_code == 401
+
+
+def test_both_channels_are_registered(client):
+ # A plain GET would hang the TestClient on a stream that never ends, so
+ # registration is proved by name — the framing itself is tested above, on the
+ # generator both routes share.
+ assert client.app.url_path_for("events") == "/api/events"
+ assert client.app.url_path_for("ingest_events") == "/api/ingest/events"
+
+
+def _token(client):
+ return client.post("/api/settings/ingest-token").json()["ingest_token"]
+
+
+def _rect_grid(statuses=None, title=None):
+ return {
+ "title": title,
+ "spec": {
+ "azimut_grid": 1,
+ "cell_m": 500,
+ "anchor": {"lat": 48.0, "lon": 2.0},
+ "lat_step": 0.0045,
+ "lon_step": 0.0067,
+ "aoi": {
+ "type": "rect",
+ "bounds": {"south": 48.0, "west": 2.0, "north": 48.02, "east": 2.02},
+ },
+ "statuses": statuses or {},
+ },
+ }
+
+
+def _drain(q):
+ out = []
+ while not q.empty():
+ out.append(q.get_nowait())
+ return out
+
+
+# --- what a sweep worked from two places says out loud --------------------------
+
+
+def test_writing_a_grid_nudges_with_the_revision_it_wrote(client):
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ q = events.subscribe()
+ try:
+ saved = client.put(
+ f"/api/cases/{cid}/search-grids/north", json=_rect_grid(title="North")
+ ).json()
+ event = q.get_nowait()
+ assert event["type"] == "grid"
+ assert event["case_id"] == cid
+ assert event["name"] == "north"
+ assert event["title"] == "North"
+ # the revision is what lets the surface that wrote it stay put, and every
+ # other one know the nudge is news
+ assert event["revision"] == saved["revision"]
+ finally:
+ events.unsubscribe(q)
+
+
+def test_marking_cells_nudges_from_either_road_to_the_file(client):
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ client.put(f"/api/cases/{cid}/search-grids/north", json=_rect_grid())
+ q = events.subscribe()
+ try:
+ _drain(q)
+ # the app's own half
+ first = client.post(
+ f"/api/cases/{cid}/search-grids/north/marks", json={"marks": {"0:0": "cleared"}}
+ ).json()
+ app_event = q.get_nowait()
+ # the extension's, over another map
+ second = client.post(
+ "/api/ingest/grid/marks",
+ json={"case_id": cid, "name": "north", "marks": {"1:1": "flagged"}},
+ headers={"X-Azimut-Token": token},
+ ).json()
+ ext_event = q.get_nowait()
+ finally:
+ events.unsubscribe(q)
+
+ for event, answer in ((app_event, first), (ext_event, second)):
+ assert event["type"] == "grid-marks"
+ assert event["case_id"] == cid
+ assert event["name"] == "north"
+ assert event["revision"] == answer["revision"]
+ # one file, one counter: the second mark is behind the first, never beside it
+ assert second["revision"] > first["revision"]
+ assert client.get(f"/api/cases/{cid}/search-grids/north").json()["statuses"] == {
+ "0:0": "cleared",
+ "1:1": "flagged",
+ }
+
+
+def test_the_app_marks_cells_without_writing_the_sweep_around_them(client):
+ # The point of the route: two surfaces sweeping different cells of one grid
+ # both land. A whole-spec save from either would carry the copy it loaded.
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ client.put(f"/api/cases/{cid}/search-grids/north", json=_rect_grid())
+ client.post(
+ "/api/ingest/grid/marks",
+ json={"case_id": cid, "name": "north", "marks": {"0:0": "cleared"}},
+ headers={"X-Azimut-Token": token},
+ )
+ client.post(
+ f"/api/cases/{cid}/search-grids/north/marks", json={"marks": {"1:1": "flagged"}}
+ )
+ assert client.get(f"/api/cases/{cid}/search-grids/north").json()["statuses"] == {
+ "0:0": "cleared",
+ "1:1": "flagged",
+ }
+
+
+def test_the_app_can_clear_a_cell_back_to_unchecked(client):
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ client.put(f"/api/cases/{cid}/search-grids/north", json=_rect_grid({"0:0": "cleared"}))
+ client.post(f"/api/cases/{cid}/search-grids/north/marks", json={"marks": {"0:0": None}})
+ assert client.get(f"/api/cases/{cid}/search-grids/north").json()["statuses"] == {}
+
+
+def test_marking_a_grid_the_case_does_not_have(client):
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ r = client.post(f"/api/cases/{cid}/search-grids/nope/marks", json={"marks": {"0:0": "cleared"}})
+ assert r.status_code == 404
+
+
+def test_discarding_a_grid_nudges_once_and_only_when_it_existed(client):
+ cid = client.post("/api/cases", json={"name": "Sweep"}).json()["id"]
+ client.put(f"/api/cases/{cid}/search-grids/north", json=_rect_grid())
+ q = events.subscribe()
+ try:
+ _drain(q)
+ client.delete(f"/api/cases/{cid}/search-grids/north")
+ event = q.get_nowait()
+ assert event == {"type": "grid-removed", "case_id": cid, "name": "north"}
+ # gone already: nothing changed, so nothing is said
+ client.delete(f"/api/cases/{cid}/search-grids/north")
+ assert q.empty()
+ finally:
+ events.unsubscribe(q)
+
+
+# --- and what the case's points say ---------------------------------------------
+
+
+def test_saving_a_point_in_the_app_nudges_the_panels(client):
+ cid = client.post("/api/cases", json={"name": "Points"}).json()["id"]
+ q = events.subscribe()
+ try:
+ client.post(
+ f"/api/cases/{cid}/satellite/place",
+ json={"lat": 48.85, "lon": 2.29, "zoom": 17, "bearing": 0},
+ )
+ assert q.get_nowait() == {"type": "saved", "case_id": cid}
+ finally:
+ events.unsubscribe(q)
+
+
+def test_deleting_a_point_nudges_the_panels(client):
+ cid = client.post("/api/cases", json={"name": "Points"}).json()["id"]
+ entity = client.post(
+ f"/api/cases/{cid}/satellite/place",
+ json={"lat": 48.85, "lon": 2.29, "zoom": 17, "bearing": 0},
+ ).json()
+ q = events.subscribe()
+ try:
+ _drain(q)
+ client.delete(f"/api/cases/{cid}/entities/{entity['id']}")
+ assert q.get_nowait() == {"type": "saved", "case_id": cid}
+ finally:
+ events.unsubscribe(q)
+
+
+def test_deleting_something_no_map_draws_says_nothing(client):
+ # the nudge is for the surfaces drawing a case on a map; a note is not one
+ cid = client.post("/api/cases", json={"name": "Points"}).json()["id"]
+ note = client.post(
+ f"/api/cases/{cid}/entities", json={"type": "note", "label": "A thought"}
+ ).json()
+ q = events.subscribe()
+ try:
+ _drain(q)
+ client.delete(f"/api/cases/{cid}/entities/{note['id']}")
+ assert q.empty()
+ finally:
+ events.unsubscribe(q)
diff --git a/tests/test_extension_signing.py b/tests/test_extension_signing.py
new file mode 100644
index 0000000..091c1ac
--- /dev/null
+++ b/tests/test_extension_signing.py
@@ -0,0 +1,163 @@
+"""The signed-XPI road: what the extension declares, and what Firefox polls.
+
+Firefox Release refuses an unsigned extension with no preference to turn that
+off, so Firefox installs the extension from an AMO-signed XPI and updates itself
+from ``packaging/updates.json``. Nothing in the app reads that file — Firefox
+does, once a day — which is exactly why it needs a gate: a drift between the id
+the extension is signed under and the id the manifest is keyed by produces no
+error anywhere, it just silently never updates.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from azimut.engine import extinstall, updates
+
+REPO = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(REPO / "scripts"))
+
+import sign_extension # noqa: E402
+
+UPDATE_MANIFEST = REPO / "packaging" / "updates.json"
+
+#: The tracked manifest, served raw from the default branch. The extension is
+#: signed with this address inside it, so moving the file means signing a new
+#: version — which is why the address is asserted rather than left to habit.
+UPDATE_URL = (
+ "https://raw.githubusercontent.com/OsintMeThat/azimut/main/packaging/updates.json"
+)
+
+
[email protected](scope="module")
+def gecko():
+ manifest = json.loads((REPO / "extension" / "manifest.json").read_text(encoding="utf-8"))
+ return manifest["browser_specific_settings"]["gecko"]
+
+
[email protected](scope="module")
+def published():
+ return json.loads(UPDATE_MANIFEST.read_text(encoding="utf-8"))
+
+
+# -- what the extension declares -------------------------------------------
+
+
+def test_the_extension_carries_an_id_that_can_be_signed(gecko):
+ """AMO reserves the id at the first signature and it is permanent afterwards:
+ changing it later is a different add-on, so every install loses its pairing.
+ A placeholder id is therefore a one-way mistake, not a detail."""
+ assert gecko["id"]
+ assert not gecko["id"].endswith(".invalid"), (
+ "a placeholder id becomes permanent the moment AMO signs it"
+ )
+
+
+def test_firefox_is_told_where_to_look_for_updates(gecko):
+ """Self-distributed means self-hosted updates: AMO signs the file but serves
+ nothing, so without this key a signed install never hears about a new one."""
+ assert gecko["update_url"] == UPDATE_URL
+ assert gecko["update_url"].startswith("https://") # Firefox refuses plain HTTP
+
+
+def test_the_update_manifest_is_not_part_of_the_payload():
+ """It lives under ``packaging/`` on purpose. Shipped, it would land in every
+ browser folder and move the payload digest on every release, which the update
+ button reads as "a new version is ready" for bytes nobody changed."""
+ source = extinstall.source_dir()
+ assert source is not None
+ names = [name for name, _ in extinstall.shipped_files(source)]
+ assert not any(name.endswith("updates.json") for name in names)
+
+
+# -- the manifest Firefox polls ---------------------------------------------
+
+
+def test_the_update_manifest_is_keyed_by_the_extension_id(published, gecko):
+ """The one drift that fails silently: Firefox looks itself up by id, finds
+ nothing, and reports no error to anyone."""
+ assert list(published["addons"]) == [gecko["id"]]
+
+
+def test_every_offered_version_is_one_that_exists(published, gecko):
+ """Each entry points at a release asset, carries the hash of the bytes Mozilla
+ signed, and never offers a version ahead of the one this build ships — the
+ update manifest is written at release cut, so a version leading the code means
+ it was written for a release that never happened."""
+ bundled = extinstall.bundled_version()
+ for addon in published["addons"].values():
+ for entry in addon["updates"]:
+ version = entry["version"]
+ assert entry["update_link"].startswith("https://")
+ assert entry["update_link"].endswith(f"azimut-capture-{version}.xpi")
+ assert entry["update_hash"].startswith("sha256:")
+ assert len(entry["update_hash"].split(":", 1)[1]) == 64
+ gecko_range = entry["applications"]["gecko"]
+ assert gecko_range["strict_min_version"] == gecko["strict_min_version"]
+ assert not updates.is_newer(version, bundled)
+
+
+# -- the generator ----------------------------------------------------------
+
+
+def test_the_generator_reads_the_extension_rather_than_a_copy(gecko):
+ facts = sign_extension.gecko_facts()
+ assert facts["id"] == gecko["id"]
+ assert facts["version"] == extinstall.bundled_version()
+ assert facts["strict_min_version"] == gecko["strict_min_version"]
+
+
+def test_the_asset_url_names_the_release_that_carries_it():
+ assert sign_extension.asset_url("v0.3.0", "0.3.0") == (
+ "https://github.com/OsintMeThat/azimut/releases/download/v0.3.0/"
+ "azimut-capture-0.3.0.xpi"
+ )
+
+
+def test_a_generated_manifest_passes_the_gates_above(tmp_path, gecko):
+ """The generator's output and the checked-in file answer to one shape."""
+ built = sign_extension.build_update_manifest(
+ gecko["id"], "0.3.0", sign_extension.asset_url("v0.3.0", "0.3.0"), "a" * 64, "115.0"
+ )
+ entry = built["addons"][gecko["id"]]["updates"][0]
+ assert entry["version"] == "0.3.0"
+ assert entry["update_hash"] == "sha256:" + "a" * 64
+ assert entry["applications"]["gecko"]["strict_min_version"] == "115.0"
+
+ written = tmp_path / "updates.json"
+ written.write_text(json.dumps(built), encoding="utf-8")
+ assert json.loads(written.read_text(encoding="utf-8")) == built
+
+
+def test_a_version_already_offered_is_refused(monkeypatch, tmp_path):
+ """AMO refuses a version it has already signed, and the extension's version
+ deliberately stays put across releases that do not touch it. Caught here with
+ its reason rather than as a failed upload halfway through a release."""
+ manifest = tmp_path / "updates.json"
+ version = extinstall.bundled_version()
+ manifest.write_text(
+ json.dumps(
+ sign_extension.build_update_manifest(
+ "x@y", version, "https://example.invalid/azimut-capture-%s.xpi" % version,
+ "b" * 64, "115.0",
+ )
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(sign_extension, "UPDATE_MANIFEST", manifest)
+ assert sign_extension.published_version() == version
+ with pytest.raises(SystemExit, match="already offers"):
+ sign_extension.main([])
+
+
+def test_no_published_version_before_the_first_signature(monkeypatch, tmp_path):
+ """The checked-in manifest starts with an empty ``updates`` list, which is
+ what "nothing signed yet" looks like. It must not read as a version."""
+ manifest = tmp_path / "updates.json"
+ manifest.write_text(json.dumps({"addons": {"x@y": {"updates": []}}}), encoding="utf-8")
+ monkeypatch.setattr(sign_extension, "UPDATE_MANIFEST", manifest)
+ assert sign_extension.published_version() is None
diff --git a/tests/test_extinstall.py b/tests/test_extinstall.py
new file mode 100644
index 0000000..fe5536c
--- /dev/null
+++ b/tests/test_extinstall.py
@@ -0,0 +1,246 @@
+"""The capture extension's own folder: the copy the app writes and can rewrite.
+
+The interesting cases are all failure shapes, and one of them only happens on
+Windows: a browser holding a file open while the app tries to replace it. That
+one is forced here rather than waited for, because the invariant it protects —
+never a half-written extension — is the whole reason the install is staged.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from azimut import config
+from azimut.engine import dirswap, extinstall
+
+
+def folder(tmp_workspace) -> Path:
+ """The app-owned extension folder, in a throwaway workspace root — nothing
+ here touches a real installation."""
+ return config.extension_dir()
+
+
+def stamp_of(folder: Path) -> dict:
+ return json.loads((folder / extinstall.STAMP_NAME).read_text(encoding="utf-8"))
+
+
+# -- installing ---------------------------------------------------------------
+
+
+def test_install_writes_every_shipped_file_and_stamps_it(folder):
+ state = extinstall.install()
+
+ src = extinstall.source_dir()
+ assert src is not None
+ for name, _ in extinstall.shipped_files(src):
+ assert (folder / name).is_file(), f"{name} was not written"
+ assert state["staged"] is False
+ assert state["path"] == str(folder)
+ # The stamp answers "is this the copy the app controls", so it carries an id,
+ # and "is it behind", so it carries the digest.
+ stamp = stamp_of(folder)
+ assert stamp["payload"] == extinstall.payload_digest()
+ assert stamp["version"] == extinstall.bundled_version()
+ assert len(stamp["install_id"]) == 32
+ assert state["folder"] == stamp
+
+
+def test_the_stamp_is_never_part_of_the_payload(folder):
+ """It is per-install, so shipping it would make every install differ from
+ every other — and the digest gate would never settle."""
+ extinstall.install()
+ src = extinstall.source_dir()
+ assert src is not None
+ assert extinstall.STAMP_NAME not in {name for name, _ in extinstall.shipped_files(src)}
+ # Nor does installing leave one behind in the source tree (a checkout is the
+ # repo's own extension/, which devext.py loads straight into a dev browser).
+ assert not (src / extinstall.STAMP_NAME).exists()
+
+
+def test_a_second_pass_keeps_the_install_id(folder):
+ """The id belongs to the folder, not to a payload. Chrome keys storage to the
+ extension and the extension to the folder, so an id that moved would read as
+ a different install and the analyst would be asked to pair again."""
+ first = stamp_of(folder) if folder.exists() else None
+ assert first is None
+ extinstall.install()
+ original = stamp_of(folder)["install_id"]
+ extinstall.install()
+ assert stamp_of(folder)["install_id"] == original
+
+
+def test_install_removes_what_the_payload_no_longer_ships(folder):
+ extinstall.install()
+ stale = folder / "gone.js"
+ stale.write_text("old content script", encoding="utf-8")
+ nested = folder / "icons" / "gone.png"
+ nested.write_bytes(b"stale")
+
+ extinstall.install()
+
+ assert not stale.exists()
+ assert not nested.exists()
+ assert (folder / "manifest.json").is_file() # the real payload is untouched
+
+
+def test_state_reads_without_installing(folder):
+ state = extinstall.state()
+ assert state["folder"] is None
+ assert state["staged"] is False
+ assert state["bundled"]["payload"] == extinstall.payload_digest()
+ assert not folder.exists() # a read must not create anything
+
+
+def test_a_foreign_folder_reports_no_stamp(folder):
+ """Someone else's unzip, or a checkout: files are there, the stamp is not, so
+ the app knows it does not own this copy."""
+ folder.mkdir(parents=True)
+ (folder / "manifest.json").write_text('{"version": "0.0.1"}', encoding="utf-8")
+ assert extinstall.state()["folder"] is None
+
+
+def test_an_unreadable_stamp_reads_as_no_stamp(folder):
+ extinstall.install()
+ (folder / extinstall.STAMP_NAME).write_text("{ not json", encoding="utf-8")
+ assert extinstall.state()["folder"] is None
+
+
+# -- a browser holding the files (Windows) ------------------------------------
+
+
+def _refuse_after(count: int, monkeypatch: pytest.MonkeyPatch) -> dict:
+ """Let `count` replacements through, then refuse every one — the shape of a
+ browser holding a file open on Windows.
+
+ Returns a switch to turn the refusal off again. Not ``monkeypatch.undo()``:
+ that also reverts the ``AZIMUT_HOME`` the workspace fixture set, so the next
+ pass would write into the developer's real workspace.
+ """
+ real = os.replace
+ gate = {"n": 0, "refusing": True}
+
+ def fake(src, dst, *args, **kwargs):
+ gate["n"] += 1
+ if gate["refusing"] and gate["n"] > count:
+ raise PermissionError(32, "being used by another process")
+ return real(src, dst, *args, **kwargs)
+
+ monkeypatch.setattr(dirswap.os, "replace", fake)
+ # The retry ladder sleeps between attempts; there is nothing to wait for here.
+ monkeypatch.setattr(dirswap.time, "sleep", lambda _s: None)
+ return gate
+
+
+def test_a_refused_replace_is_staged_not_half_written(folder, monkeypatch):
+ extinstall.install()
+ before = stamp_of(folder)
+
+ _refuse_after(2, monkeypatch)
+ state = extinstall.install()
+
+ assert state["staged"] is True
+ # The manifest is written last, so an interrupted pass leaves one that still
+ # describes a loadable extension.
+ manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["version"] == before["version"]
+ # And the stamp still describes what is actually loadable, never the payload
+ # that failed to land.
+ assert stamp_of(folder) == before
+
+
+def test_the_next_pass_finishes_a_staged_one(folder, monkeypatch):
+ extinstall.install()
+ gate = _refuse_after(1, monkeypatch)
+ assert extinstall.install()["staged"] is True
+
+ gate["refusing"] = False # the browser let go
+ state = extinstall.install()
+
+ assert state["staged"] is False
+ assert state["folder"]["payload"] == extinstall.payload_digest()
+ # Exactly one staging directory can exist, and a finished pass leaves none —
+ # otherwise "staged" would stay true forever after one refusal.
+ assert not [p for p in folder.iterdir() if p.name.startswith(".staging-")]
+
+
+def test_a_rename_aside_covers_a_replace_windows_refuses(folder, tmp_path):
+ """os.replace onto an open file fails on Windows where a rename still works,
+ so the ladder tries that before giving up."""
+ target = tmp_path / "held.js"
+ target.write_text("old", encoding="utf-8")
+ source = tmp_path / "new.js"
+ source.write_text("new", encoding="utf-8")
+
+ calls = {"n": 0}
+ real = os.replace
+
+ def only_direct_replace_fails(src, dst, *args, **kwargs):
+ calls["n"] += 1
+ if Path(dst) == target and calls["n"] <= dirswap.REPLACE_ATTEMPTS:
+ raise PermissionError(32, "being used by another process")
+ return real(src, dst, *args, **kwargs)
+
+ original_sleep = dirswap.time.sleep
+ dirswap.time.sleep = lambda _s: None
+ dirswap.os.replace = only_direct_replace_fails
+ try:
+ dirswap.replace_file(source, target)
+ finally:
+ dirswap.os.replace = real
+ dirswap.time.sleep = original_sleep
+
+ assert target.read_text(encoding="utf-8") == "new"
+ assert not source.exists()
+
+
+def test_leftovers_are_swept_and_never_reported_as_content(folder):
+ extinstall.install()
+ (folder / ".old-manifest.json-abcd").write_text("litter", encoding="utf-8")
+ (folder / ".trash-icons-abcd").mkdir()
+
+ state = extinstall.state()
+
+ assert state["staged"] is False
+ assert not (folder / ".old-manifest.json-abcd").exists()
+ assert not (folder / ".trash-icons-abcd").exists()
+
+
+# -- the routes ---------------------------------------------------------------
+
+
+def test_the_install_route_takes_nothing_and_reports_the_folder(client):
+ body = client.post("/api/settings/extension/install").json()
+ assert body["staged"] is False
+ assert body["folder"]["payload"] == body["bundled"]["payload"]
+ assert Path(body["path"]).is_dir()
+
+
+def test_the_state_route_reads_without_writing(client):
+ body = client.get("/api/settings/extension").json()
+ assert body["folder"] is None
+ assert body["bundled"]["version"] == extinstall.bundled_version()
+ assert not Path(body["path"]).exists()
+
+
+def test_revealing_before_installing_is_a_404(client):
+ assert client.post("/api/settings/extension/reveal").status_code == 404
+
+
+def test_the_install_route_is_not_in_the_extension_cors_island(client):
+ """/api/ingest/* is opened to any extension origin on purpose. A route that
+ writes to disk must not inherit that, so it lives on the settings router and
+ the browser's same-origin default is what guards it."""
+ for path in ("/api/settings/extension", "/api/settings/extension/install"):
+ response = client.options(
+ path,
+ headers={
+ "Origin": "chrome-extension://abcdefghijklmnopabcdefghijklmnop",
+ "Access-Control-Request-Method": "POST",
+ },
+ )
+ assert "access-control-allow-origin" not in {k.lower() for k in response.headers}
diff --git a/tests/test_ingest_maptools.py b/tests/test_ingest_maptools.py
new file mode 100644
index 0000000..1ae7ba4
--- /dev/null
+++ b/tests/test_ingest_maptools.py
@@ -0,0 +1,405 @@
+"""The map tools' half of the ingest API (api/ingest.py).
+
+The tools in `extension/mapoverlay.js` draw the app's own work over someone
+else's map, which means the extension now *reads* a case as well as filing into
+one. Three walls are what make that acceptable, and each test here holds one of
+them up:
+
+* the pairing token guards every route, the new ones included;
+* what comes back is trimmed to what a pin or a lattice needs, not an app
+ payload forwarded whole;
+* a sweep worked from the app and from a map tab at once converges, because the
+ extension sends the cells it touched and never a copy of the grid.
+"""
+
+import io
+
+import pytest
+from PIL import Image
+
+
+def _token(client):
+ return client.post("/api/settings/ingest-token").json()["ingest_token"]
+
+
+def _headers(client):
+ return {"X-Azimut-Token": _token(client)}
+
+
+def _case(client, name="Sweep"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _spec(south=48.85, west=2.29, north=48.87, east=2.31, statuses=None):
+ return {
+ "azimut_grid": 1,
+ "cell_m": 500,
+ "anchor": {"lat": south, "lon": west},
+ "lat_step": 0.0045,
+ "lon_step": 0.0067,
+ "aoi": {"type": "rect", "bounds": {
+ "south": south, "west": west, "north": north, "east": east}},
+ "statuses": statuses or {},
+ }
+
+
+MAP_ROUTES = [
+ ("get", "/api/ingest/saved", {"case_id": "x"}),
+ ("get", "/api/ingest/media", {"case_id": "x"}),
+ ("get", "/api/ingest/sky", {"lat": 48.8, "lon": 2.3}),
+ ("get", "/api/ingest/grids", {"case_id": "x"}),
+ ("get", "/api/ingest/grid", {"case_id": "x", "name": "a"}),
+]
+
+
[email protected]("method,path,params", MAP_ROUTES)
+def test_reading_a_case_needs_the_token(client, method, path, params):
+ # the routes read case contents, so an unpaired caller must not reach them
+ # even to find out whether a case exists
+ assert getattr(client, method)(path, params=params).status_code == 401
+
+
+def test_writing_a_grid_needs_the_token(client):
+ body = {"case_id": "x", "title": "Sweep", "spec": _spec()}
+ assert client.post("/api/ingest/grid", json=body).status_code == 401
+ marks = {"case_id": "x", "name": "a", "marks": {"0:0": "cleared"}}
+ assert client.post("/api/ingest/grid/marks", json=marks).status_code == 401
+
+
+def test_saved_points_are_trimmed_to_what_a_pin_draws(client):
+ headers = _headers(client)
+ cid = _case(client, "Pins")
+ client.post(
+ "/api/ingest/place",
+ headers=headers,
+ data={
+ "url": "https://www.google.com/maps/@48.8584,2.2945,17z",
+ "case_id": cid,
+ "title": "Gate",
+ },
+ )
+ rows = client.get("/api/ingest/saved", params={"case_id": cid}, headers=headers).json()
+ assert len(rows) == 1
+ # the app's own index carries thumbnails, folders, continents and link
+ # tallies; none of that crosses into a browser extension
+ assert set(rows[0]) == {"id", "kind", "title", "lat", "lon"}
+ assert rows[0]["title"] == "Gate"
+ assert rows[0]["lat"] == pytest.approx(48.8584)
+
+
+def test_saved_points_drop_rows_with_no_position(client):
+ headers = _headers(client)
+ cid = _case(client, "Mixed")
+ client.post(
+ "/api/ingest/bookmark",
+ headers=headers,
+ data={"url": "https://example.com/article", "case_id": cid, "title": "Article"},
+ )
+ # a bookmark has no coordinates, so there is nowhere to draw it
+ assert client.get("/api/ingest/saved", params={"case_id": cid}, headers=headers).json() == []
+
+
+def _upload(client, cid, name, colour=(30, 90, 30)):
+ buf = io.BytesIO()
+ Image.new("RGB", (48, 32), colour).save(buf, format="PNG")
+ return client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(buf.getvalue()), "image/png")},
+ ).json()["item"]
+
+
+def _upload_video(client, cid, name="walk.mp4"):
+ body = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 64
+ return client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(body), "video/mp4")},
+ ).json()["item"]
+
+
+def test_reference_media_is_trimmed_to_what_the_picker_draws(client):
+ headers = _headers(client)
+ cid = _case(client, "Refs")
+ _upload(client, cid, "roof.png")
+
+ answer = client.get("/api/ingest/media", params={"case_id": cid}, headers=headers).json()
+ assert answer["total"] == 1
+ # a thumbnail path, a name and which of the two kinds it is, is the whole of
+ # what a picker tile is; the app's own index carries metadata dumps, GPS,
+ # enrichment state and folder counts, none of which an extension can use
+ assert set(answer["items"][0]) == {"path", "filename", "title", "kind", "thumbnail"}
+ assert answer["items"][0]["filename"] == "roof.png"
+
+
+def test_reference_media_offers_both_kinds_and_filters_to_one(client):
+ """Images and videos both: the frame to place is as often in a video, and the
+ window plays it. Anything else in a case has nothing to show beside a map."""
+ headers = _headers(client)
+ cid = _case(client, "Mixed")
+ _upload(client, cid, "roof.png")
+ _upload_video(client, cid)
+ client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("notes.txt", io.BytesIO(b"nothing to look at"), "text/plain")},
+ )
+
+ both = client.get("/api/ingest/media", params={"case_id": cid}, headers=headers).json()
+ assert {item["filename"] for item in both["items"]} == {"roof.png", "walk.mp4"}
+ assert both["total"] == 2 # the text file is not a reference
+
+ for kind, filename in (("image", "roof.png"), ("video", "walk.mp4")):
+ one = client.get(
+ "/api/ingest/media", params={"case_id": cid, "kind": kind}, headers=headers
+ ).json()
+ assert [item["filename"] for item in one["items"]] == [filename]
+ assert one["items"][0]["kind"] == kind
+ assert one["total"] == 1
+
+
+def test_reference_media_is_ordered_the_way_the_picker_asked(client):
+ """The merge of the two kinds keeps the order the store was asked for, or the
+ picker's sort would only ever apply within one kind."""
+ headers = _headers(client)
+ cid = _case(client, "Order")
+ _upload(client, cid, "beta.png")
+ _upload_video(client, cid, "alpha.mp4")
+
+ def names(**params):
+ answer = client.get(
+ "/api/ingest/media", params={"case_id": cid, **params}, headers=headers
+ ).json()
+ return [item["filename"] for item in answer["items"]]
+
+ # a name sort that only ordered within one kind would leave the video after
+ # the image, which is the whole failure mode of merging two queries
+ assert names(sort="name") == ["alpha.mp4", "beta.png"]
+ # both were filed in the same second, so what is asserted is that one order
+ # is the other turned round — not which of them the clock happened to favour
+ assert names(sort="oldest") == list(reversed(names(sort="newest")))
+
+
+def test_reference_media_is_searched_and_bounded(client):
+ headers = _headers(client)
+ cid = _case(client, "Big")
+ for index in range(4):
+ _upload(client, cid, f"roof-{index}.png", colour=(index * 20, 90, 30))
+ _upload(client, cid, "courtyard.png")
+
+ narrowed = client.get(
+ "/api/ingest/media", params={"case_id": cid, "q": "courtyard"}, headers=headers
+ ).json()
+ assert [item["filename"] for item in narrowed["items"]] == ["courtyard.png"]
+
+ # a case of two thousand files must not cross the extension boundary whole,
+ # and the picker says how much of it it is showing
+ page = client.get(
+ "/api/ingest/media", params={"case_id": cid, "limit": 2}, headers=headers
+ ).json()
+ assert len(page["items"]) == 2
+ assert page["total"] == 5
+
+
+def test_sky_answers_without_the_network(client, monkeypatch):
+ # the panel has to work on a map tab with no connection: the computation is
+ # local, and a test that lets it reach the network would not prove that
+ import socket
+
+ def refuse(*args, **kwargs):
+ raise AssertionError("the sky route must not touch the network")
+
+ monkeypatch.setattr(socket, "socket", refuse)
+ day = client.get(
+ "/api/ingest/sky", params={"lat": 48.8584, "lon": 2.2945}, headers=_headers(client)
+ ).json()
+ assert day["curve"]["clock"]
+ assert len(day["curve"]["sun_altitude"]) == len(day["curve"]["clock"])
+ assert day["sun"]["rise"]["local"]
+
+
+def test_sky_reads_the_day_it_was_asked_for(client):
+ # the panel's date field: a sweep is often about a day that is not today,
+ # and the shadows on an image are only evidence against the right one
+ day = client.get(
+ "/api/ingest/sky",
+ params={"lat": 48.8584, "lon": 2.2945, "date": "2026-01-15"},
+ headers=_headers(client),
+ ).json()
+ assert day["date"] == "2026-01-15"
+ # ...and the point's own zone decides which day that is, not the server's
+ assert day["zone"]
+
+
+def test_sky_refuses_a_day_it_cannot_read(client):
+ r = client.get(
+ "/api/ingest/sky",
+ params={"lat": 48.8584, "lon": 2.2945, "date": "not-a-day"},
+ headers=_headers(client),
+ )
+ assert r.status_code in (400, 422)
+
+
+def test_a_grid_drawn_over_another_map_opens_in_the_app(client):
+ headers = _headers(client)
+ cid = _case(client)
+ saved = client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "North sweep", "spec": _spec()},
+ ).json()
+ # the title is the visible filename, as everywhere else in the app: case
+ # and spaces survive, only what Windows forbids is replaced (layout.slugify)
+ assert saved["name"] == "North sweep"
+
+ # the app reads the same file through its own route, unchanged
+ loaded = client.get(f"/api/cases/{cid}/search-grids/North sweep").json()
+ assert loaded["azimut_grid"] == 1
+ assert loaded["aoi"]["bounds"]["south"] == pytest.approx(48.85)
+
+ listed = client.get("/api/ingest/grids", params={"case_id": cid}, headers=headers).json()
+ assert [g["name"] for g in listed] == ["North sweep"]
+ fetched = client.get(
+ "/api/ingest/grid", params={"case_id": cid, "name": "North sweep"}, headers=headers
+ ).json()
+ assert fetched["cell_m"] == 500
+
+
+def test_two_sweeps_of_one_grid_both_land(client):
+ """The property the whole patch exists for.
+
+ The app marks a cell; the extension, holding a copy loaded before that,
+ marks a different one. Both marks survive — which a save carrying a whole
+ spec could not manage, since the extension's copy still says the app's cell
+ is unchecked.
+ """
+ headers = _headers(client)
+ cid = _case(client)
+ client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "Sweep", "spec": _spec()},
+ )
+ stale = client.get(
+ "/api/ingest/grid", params={"case_id": cid, "name": "Sweep"}, headers=headers
+ ).json()
+ assert stale["statuses"] == {}
+
+ # the app, in its own window
+ client.put(
+ f"/api/cases/{cid}/search-grids/Sweep",
+ json={"spec": {**stale, "statuses": {"0:0": "cleared"}}},
+ )
+ # the extension, from the copy it loaded before that
+ client.post(
+ "/api/ingest/grid/marks",
+ headers=headers,
+ json={"case_id": cid, "name": "Sweep", "marks": {"1:1": "flagged"}},
+ )
+
+ after = client.get(f"/api/cases/{cid}/search-grids/Sweep").json()
+ assert after["statuses"] == {"0:0": "cleared", "1:1": "flagged"}
+
+
+def test_a_whole_spec_save_that_is_behind_is_refused(client):
+ """The other half of the same story.
+
+ The extension patches, so it cannot clobber. The app saves whole specs, so
+ it can — and the only thing standing between it and the extension's marks is
+ the copy it claims to be replacing. Claiming an older one is refused rather
+ than written.
+ """
+ headers = _headers(client)
+ cid = _case(client)
+ client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "Sweep", "spec": _spec()},
+ )
+ opened = client.get(f"/api/cases/{cid}/search-grids/Sweep").json()
+
+ # the extension marks a cell from a map tab
+ client.post(
+ "/api/ingest/grid/marks",
+ headers=headers,
+ json={"case_id": cid, "name": "Sweep", "marks": {"1:1": "flagged"}},
+ )
+
+ stale = client.put(
+ f"/api/cases/{cid}/search-grids/Sweep",
+ json={"spec": opened, "base_revision": opened["revision"]},
+ )
+ assert stale.status_code == 409
+ # and the mark it would have erased is still there
+ assert client.get(f"/api/cases/{cid}/search-grids/Sweep").json()["statuses"] == {
+ "1:1": "flagged"
+ }
+
+
+def test_a_save_that_claims_the_current_copy_goes_through(client):
+ headers = _headers(client)
+ cid = _case(client)
+ client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "Sweep", "spec": _spec()},
+ )
+ current = client.get(f"/api/cases/{cid}/search-grids/Sweep").json()
+ saved = client.put(
+ f"/api/cases/{cid}/search-grids/Sweep",
+ json={
+ "spec": {**current, "statuses": {"0:0": "cleared"}},
+ "base_revision": current["revision"],
+ },
+ )
+ assert saved.status_code == 200
+
+
+def test_a_mark_can_be_taken_back(client):
+ headers = _headers(client)
+ cid = _case(client)
+ client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "Sweep", "spec": _spec(statuses={"0:0": "cleared"})},
+ )
+ answer = client.post(
+ "/api/ingest/grid/marks",
+ headers=headers,
+ json={"case_id": cid, "name": "Sweep", "marks": {"0:0": None, "2:3": "cleared"}},
+ ).json()
+ assert answer["cleared"] == 1
+ assert client.get(f"/api/cases/{cid}/search-grids/Sweep").json()["statuses"] == {
+ "2:3": "cleared"
+ }
+
+
+def test_an_invented_mark_is_refused(client):
+ headers = _headers(client)
+ cid = _case(client)
+ client.post(
+ "/api/ingest/grid",
+ headers=headers,
+ json={"case_id": cid, "title": "Sweep", "spec": _spec()},
+ )
+ r = client.post(
+ "/api/ingest/grid/marks",
+ headers=headers,
+ json={"case_id": cid, "name": "Sweep", "marks": {"0:0": "burned"}},
+ )
+ assert r.status_code == 400
+
+
+def test_marking_a_grid_that_is_not_there(client):
+ r = client.post(
+ "/api/ingest/grid/marks",
+ headers=_headers(client),
+ json={"case_id": _case(client), "name": "nothing", "marks": {"0:0": "cleared"}},
+ )
+ assert r.status_code == 404
+
+
+def test_ping_carries_the_units_the_app_states(client):
+ headers = _headers(client)
+ assert client.get("/api/ingest/ping", headers=headers).json()["units"] == "metric"
+ client.put("/api/settings/prefs", json={"units": "imperial"})
+ # the panel measures over another map; stating feet where the app states
+ # metres would be one tool answering a question two ways
+ assert client.get("/api/ingest/ping", headers=headers).json()["units"] == "imperial"
diff --git a/tests/test_mapsites.py b/tests/test_mapsites.py
index c33cd2e..36a9ece 100644
--- a/tests/test_mapsites.py
+++ b/tests/test_mapsites.py
@@ -7,10 +7,19 @@ id (coordinates/title/imagery date when the URL carries them, None when it
doesn't), anything else returns None, and nothing ever raises.
"""
+import json
+from pathlib import Path
+
import pytest
from azimut.engine.mapsites import parse_map_url
+_RECORDED = json.loads(
+ (Path(__file__).parent / "fixtures" / "map-sites.json").read_text(encoding="utf-8")
+)
+RECORDINGS = _RECORDED["recordings"]
+ROUNDING = _RECORDED["rounding"]
+
LAT, LON, Z = 45.197652, 11.777344, 6
@@ -18,14 +27,15 @@ LAT, LON, Z = 45.197652, 11.777344, 6
# user out to, the backend must be able to read back.
OPEN_IN_LINKS = [
(f"https://www.google.com/maps/@{LAT},{LON},{Z}z", "google-maps", Z),
- (f"https://www.google.com/maps/@{LAT},{LON},2000m/data=!3m1!1e3", "google-maps", None),
- (f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r", "google-earth", None),
- (f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&t=k", "apple-maps", Z),
+ (f"https://www.google.com/maps/@{LAT},{LON},{Z}z/data=!3m1!1e3", "google-maps", Z),
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,600d,1y,0h,0t,0r", "google-earth", None),
+ (f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}&map=satellite", "apple-maps", Z),
(f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}&style=h", "bing-maps", Z),
(f"https://yandex.com/maps/?ll={LON},{LAT}&z={Z}&l=sat", "yandex-maps", Z),
(f"https://browser.dataspace.copernicus.eu/?zoom={Z}&lat={LAT}&lng={LON}",
"copernicus-browser", Z),
- (f"https://zoom.earth/#view={LAT},{LON},{Z}z", "zoom-earth", Z),
+ (f"https://zoom.earth/maps/satellite/#view={LAT},{LON},{Z}z", "zoom-earth", Z),
+ (f"https://satellites.pro/#{LAT},{LON},{Z}", "satellites-pro", Z),
]
@@ -37,11 +47,16 @@ def test_every_open_in_link_round_trips(url, site, zoom):
assert p["zoom"] == zoom
-def test_satellites_pro_still_parses():
- # dropped from the app's quick links (its basemaps duplicate the others),
- # but a user browsing there themselves still gets their capture read back
- p = parse_map_url(f"https://satellites.pro/#{LAT},{LON},{Z}")
- assert (p["site"], p["lat"], p["lon"], p["zoom"]) == ("satellites-pro", LAT, LON, Z)
+def test_satellites_pro_redirects_to_a_country_path():
+ # the bare link is what the app sends; the site answers it with a country
+ # path of its own and keeps the fragment, which is where the view lives
+ for url in (
+ f"https://satellites.pro/#{LAT},{LON},{Z}",
+ f"https://satellites.pro/plan/France_map#{LAT},{LON},{Z}",
+ f"https://satellites.pro/France_map#{LAT},{LON},{Z}",
+ ):
+ p = parse_map_url(url)
+ assert (p["site"], p["lat"], p["lon"], p["zoom"]) == ("satellites-pro", LAT, LON, Z)
def test_explicit_satellite_urls_are_classified():
@@ -144,3 +159,498 @@ def test_refusals_and_malformed_input():
assert parse_map_url("https://www.openstreetmap.org/#map=17/98.0/2.29")["lat"] is None
# malformed bing cp degrades to "known site, nothing parsed"
assert parse_map_url("https://www.bing.com/maps?cp=garbage&lvl=9")["lat"] is None
+
+
+# -- what kind of camera the URL describes --------------------------------------
+#
+# The rule the overlay hangs on: geometry the app *computes* (a search grid, a
+# sun arc, a measured line) is Web Mercator arithmetic, so it is only honest on
+# a straight-down 2D view. A media pin the analyst places by hand is computed
+# from nothing and stays allowed everywhere — which is why this field says what
+# the camera *is*, and never what may be drawn.
+
+
+ "url,kind",
+ [
+ # Street View: the 3a camera block, whatever else rides on it
+ (f"https://www.google.com/maps/@{LAT},{LON},3a,75y,90h,90t", "streetview"),
+ (
+ f"https://www.google.com/maps/place/Tour+Eiffel/@{LAT},{LON},3a,15y,180h,80t/data=x",
+ "streetview",
+ ),
+ # a pitched 3D camera on Google Maps
+ (f"https://www.google.com/maps/@{LAT},{LON},1000m,45t", "tilted"),
+ # …and 0t is not pitched at all
+ (f"https://www.google.com/maps/@{LAT},{LON},{Z}z,0t", "map"),
+ (f"https://www.google.com/maps/@{LAT},{LON},{Z}z", "map"),
+ # Earth's camera is free: level and low it is a map (the perspective of
+ # a straight-down camera cancels), pitched it is not
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r", "map"),
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,600d,35y,20h,60t,0r", "tilted"),
+ # flat-map renderers with no other mode to be in
+ (f"https://www.openstreetmap.org/#map={Z}/{LAT}/{LON}", "map"),
+ (f"https://zoom.earth/#view={LAT},{LON},{Z}z", "map"),
+ (f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}", "map"),
+ (f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}", "map"),
+ ],
+)
+def test_view_kind_reads_the_camera_out_of_the_url(url, kind):
+ assert parse_map_url(url)["view_kind"] == kind
+
+
+def test_satellite_is_still_a_straight_down_map():
+ """Google drops the zoom in satellite view and quotes a viewport height in
+ metres instead. The camera did not move — only the way the URL describes it
+ — so the view is a map, and the overlay's tools are not thrown off a whole
+ imagery mode by a change of notation.
+
+ The camera and the flattening are both fine, so ``geometry`` says yes. What
+ is missing without a window height is the *scale*: no zoom, no
+ ``scale_source``, and the drawing waits for one (`maptools.js`'s verdict).
+ """
+ parsed = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},1053m/data=!3m1!1e3")
+ assert parsed["view_kind"] == "map"
+ assert (parsed["lat"], parsed["lon"]) == (LAT, LON)
+ assert parsed["zoom"] is None
+ assert parsed["scale_source"] is None
+ assert parsed["geometry"] is True
+
+
+def test_a_level_free_camera_is_a_map_it_can_be_measured_on():
+ """Earth, and Maps in Earth mode, with the camera level.
+
+ A camera pointed straight down at the ground is a plain uniform scaling —
+ the perspective cancels — so the view is measurable even though nothing in
+ it is Web Mercator. Earth names no flattening, so ``geometry`` declines
+ there and the extension measures the view whole; Maps in Earth mode is still
+ a Google URL and keeps its flattening, and waits only for a scale.
+ """
+ earth = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,0t,0r")
+ assert earth["view_kind"] == "map"
+ assert earth["geometry"] is False # no projection to name
+ assert earth["scale_source"] is None
+
+ maps = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},336a,35y,0t/data=!3m1!1e3")
+ assert maps["view_kind"] == "map"
+ assert maps["geometry"] is True
+ assert maps["scale_source"] is None # a free camera quotes no level
+ assert (maps["lat"], maps["lon"]) == (LAT, LON)
+
+
+def test_a_level_camera_far_enough_out_is_a_globe():
+ """Level is not enough on its own: past ``LEVEL_CEILING_M`` the ground under
+ the camera is visibly round, and a flat scale would be wrong by more than
+ the tools are worth."""
+ high = f"https://earth.google.com/web/@{LAT},{LON},146a,900000d,35y,0h,0t,0r"
+ assert parse_map_url(high)["view_kind"] == "globe"
+ # …and a camera whose height the URL never states is not assumed to be low
+ assert parse_map_url(f"https://earth.google.com/web/@{LAT},{LON}")["view_kind"] == "globe"
+
+
+def test_a_pitched_camera_is_not_a_map_however_it_is_written():
+ """The metres are a red herring on their own: the same block carries the
+ tilt, and a tilt is what decides."""
+ assert parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},1000m,45t")["view_kind"] == "tilted"
+ assert (
+ parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},336a,35y,45.5t/data=!3m1!1e3")[
+ "view_kind"
+ ]
+ == "tilted"
+ )
+ # roll counts as well: a level camera turned on its axis is still level, but
+ # one that is not is not a map
+ assert (
+ parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},1a,600d,35y,0h,0t,30r")[
+ "view_kind"
+ ]
+ == "tilted"
+ )
+
+
+def test_only_a_documented_tile_zoom_is_named_as_one():
+ """Which sites' ``zoom`` can be turned into a scale without asking the map.
+
+ OpenStreetMap's slippy-map spec and Bing's tile system state the same thing
+ — 256-pixel tiles, one tile of the world at zoom 0 — Google's matches both,
+ and Copernicus Browser draws on Leaflet, which is that spec with a library
+ round it. Apple's documentation says only that ``z`` "defines the area
+ around the center point", but a browser dragged and zoomed at two window
+ sizes drew tile level 15 both times, so it is recorded on the measurement.
+ Earth quotes a camera distance and no level at all.
+ """
+ for url, site in (
+ (f"https://www.google.com/maps/@{LAT},{LON},{Z}z", "google-maps"),
+ (f"https://www.bing.com/maps?cp={LAT}~{LON}&lvl={Z}", "bing-maps"),
+ (f"https://www.openstreetmap.org/#map={Z}/{LAT}/{LON}", "openstreetmap"),
+ (f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}", "apple-maps"),
+ (f"https://browser.dataspace.copernicus.eu/?zoom={Z}&lat={LAT}&lng={LON}",
+ "copernicus-browser"),
+ ):
+ parsed = parse_map_url(url)
+ assert parsed["site"] == site
+ assert parsed["scale_source"] == "zoom", site
+ assert parsed["zoom"] == Z, site
+
+ earth = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},1a,600d,35y,0h,0t,0r")
+ assert earth["site"] == "google-earth"
+ assert earth["scale_source"] is None
+ assert earth["zoom"] is None
+
+
+def test_apples_stale_zoom_is_dropped_once_it_states_a_span():
+ """Apple carries the ``z`` its opening link had and never rewrites it.
+
+ Measured: opened at 15, zoomed twice, the address bar still said 15 while
+ the span had quartered. A view that states a span therefore states no zoom
+ at all here, and the span is what a caller reads.
+ """
+ opened = parse_map_url(f"https://maps.apple.com/?ll={LAT},{LON}&z=15&map=satellite")
+ assert opened["zoom"] == 15 and opened["scale_source"] == "zoom"
+ assert opened["span_lat"] is None
+
+ moved = parse_map_url(
+ "https://maps.apple.com/frame?z=15&map=satellite"
+ "&center=47.388462%2C2.352785&span=0.029055%2C0.056434"
+ )
+ assert (moved["lat"], moved["lon"]) == (47.388462, 2.352785)
+ assert (moved["span_lat"], moved["span_lon"]) == (0.029055, 0.056434)
+ assert moved["zoom"] is None and moved["scale_source"] is None
+
+
+def test_a_stated_size_becomes_a_zoom_once_the_window_height_is_known():
+ """The two views that state a size rather than a level.
+
+ Both numbers are the map's own, and both were checked against a browser:
+ a 1000 px window opened at 15z came back as ``,3231m`` from Google and as
+ ``span=0.029055,…`` from Apple. Fed those back with the height they were
+ drawn at, this returns the level they were drawn at.
+ """
+ satellite = parse_map_url(
+ "https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3", height_px=1000
+ )
+ assert satellite["scale_source"] == "height_m"
+ assert satellite["zoom"] == pytest.approx(15, abs=0.01)
+ assert satellite["camera_kind"] == "height_m"
+
+ apple = parse_map_url(
+ "https://maps.apple.com/frame?map=satellite"
+ "&center=47.388462%2C2.352785&span=0.029055%2C0.056434",
+ height_px=1000,
+ )
+ assert apple["scale_source"] == "span"
+ assert apple["zoom"] == pytest.approx(15, abs=0.01)
+
+ # the same view in a shorter window is the same map drawn smaller: Apple
+ # states the span it actually covers, so the level comes back unchanged
+ shorter = parse_map_url(
+ "https://maps.apple.com/frame?map=satellite"
+ "&center=47.388462%2C2.352785&span=0.022082%2C0.039268",
+ height_px=760,
+ )
+ assert shorter["zoom"] == pytest.approx(15, abs=0.01)
+
+
+def test_without_a_window_height_a_stated_size_is_left_alone():
+ """No height, no zoom — never a guessed one."""
+ satellite = parse_map_url("https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3")
+ assert satellite["zoom"] is None and satellite["scale_source"] is None
+ assert satellite["camera_m"] == 3231
+
+
+def test_every_recognized_site_answers_the_scale_question():
+ for url, _site, _zoom in OPEN_IN_LINKS:
+ assert parse_map_url(url)["scale_source"] in {"zoom", "height_m", "span", None}
+
+
+def test_a_zoomless_view_states_its_camera_span():
+ """The one number these views give about how far out they are.
+
+ Neither can be turned into a zoom here — that needs the size of a window this
+ module never sees — but both are proportional to metres per pixel, which is
+ all a caller needs to carry a scale it measured once through every zoom
+ afterwards.
+ """
+ satellite = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},4378m/data=!3m1!1e3")
+ assert satellite["camera_m"] == 4378
+ earth = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,0t,0r")
+ assert earth["camera_m"] == 666
+
+
+def test_a_view_that_names_its_zoom_states_no_span():
+ """A zoom is the better answer and the only one a caller needs, so nothing
+ is invented alongside it."""
+ assert parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},{Z}z")["camera_m"] is None
+ assert parse_map_url(f"https://maps.apple.com/?ll={LAT},{LON}&z={Z}")["camera_m"] is None
+ # Street View's `3a` is a pano radius, not a span across the ground
+ assert parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},3a,75y,90t")["camera_m"] is None
+
+
+def test_every_recognized_site_answers_the_span_question():
+ for url, _site, _zoom in OPEN_IN_LINKS:
+ assert "camera_m" in parse_map_url(url)
+
+
+def test_view_kind_is_unclassified_rather_than_guessed():
+ """A Google Maps URL with no camera block says nothing about its camera, and
+ saying nothing is the answer — the same rule imagery_mode follows."""
+ parsed = parse_map_url("https://www.google.com/maps/place/Tour+Eiffel")
+ assert parsed["site"] == "google-maps"
+ assert parsed["view_kind"] is None
+
+
+def test_a_street_view_url_carries_its_point_but_no_zoom():
+ """Which is the second, independent reason the overlay declines geometry
+ there: the projection needs a zoom, and a pano camera has none."""
+ parsed = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},3a,75y,90h,90t")
+ assert (parsed["lat"], parsed["lon"]) == (LAT, LON)
+ assert parsed["zoom"] is None
+ # the point is still real, read from the address bar — a pin can be filed on it
+ assert parsed["view_kind"] == "streetview"
+
+
+def test_every_recognized_site_answers_the_question():
+ """Every parse carries the key, so a caller never has to tell "no camera in
+ this URL" from "this build predates the field"."""
+ for url, _site, _zoom in OPEN_IN_LINKS:
+ assert "view_kind" in parse_map_url(url)
+
+
+# -- what may be drawn over the view --------------------------------------------
+#
+# Three independent ways the projection can be wrong, and the overlay has to
+# decline on any one of them: a camera Mercator says nothing about, a
+# flattening we cannot invert, and a zoom where the site draws a globe while
+# its URL goes on quoting a zoom.
+
+
+def test_geometry_needs_a_flat_camera_a_known_projection_and_a_flat_zoom():
+ ok = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},17z")
+ assert ok["geometry"] is True
+ assert ok["projection"] == "webmercator"
+
+
+def test_copernicus_2d_map_is_leaflet_and_drawable():
+ """Its flat map is Leaflet's default CRS, which is EPSG:3857.
+
+ Two ways round: the browser's own package.json depends on leaflet, and two
+ zooms about two different pixels solved for the same camera centre through
+ spherical Mercator to half a pixel (tests/fixtures/map-sites.json).
+ """
+ flat = parse_map_url(f"https://browser.dataspace.copernicus.eu/?zoom=15&lat={LAT}&lng={LON}")
+ assert flat["projection"] == "webmercator"
+ assert flat["view_kind"] == "map"
+ assert flat["geometry"] is True
+
+
+ "url,why",
+ [
+ # a pano camera
+ (f"https://www.google.com/maps/@{LAT},{LON},3a,75y,90h,90t", "streetview"),
+ # a pitched one
+ (f"https://www.google.com/maps/@{LAT},{LON},1000m,45t", "tilted"),
+ # a globe renderer, which names no flattening to draw in
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r", "globe"),
+ # Copernicus Browser in its 3D terrain viewer, which it says in the URL
+ (f"https://browser.dataspace.copernicus.eu/?zoom=17&lat={LAT}&lng={LON}"
+ '&terrainViewerSettings=%7B%22settings%22%3A%7B%22x%22%3A1%7D%7D', "terrain viewer"),
+ ],
+)
+def test_geometry_declines_wherever_the_projection_would_be_a_guess(url, why):
+ assert parse_map_url(url)["geometry"] is False, why
+
+
+def test_yandex_is_elliptical_and_says_so():
+ """EPSG:3395, not 3857. Drawing it as spherical Mercator is wrong by
+ kilometres at Moscow's latitude — and wrong with total confidence."""
+ parsed = parse_map_url(f"https://yandex.com/maps/?ll={LON},{LAT}&z={Z}&l=sat")
+ assert parsed["projection"] == "ellipsoidal"
+ assert parsed["geometry"] is True # known, therefore drawable
+
+
+def test_the_globe_floor_is_a_warning_rather_than_a_floor():
+ """A site becoming a globe does not change its URL shape, so the zoom is the
+ only warning there is — and out there it is a warning, not a refusal.
+
+ The drawing still appears: the middle of the screen is right and the edges
+ drift, which is the trade for seeing a whole region's worth of work at once.
+ ``far`` is what says so, and the panel dims what it draws.
+ """
+ low = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},7z")
+ high = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},8z")
+ assert (low["geometry"], high["geometry"]) == (True, True)
+ assert (low["far"], high["far"]) == (True, False)
+ assert low["globe_below"] == 8
+
+ # Earth's own globe is the same verdict reached from a camera height
+ earth = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},0a,900000d,35y,0h,0t,0r")
+ assert earth["view_kind"] == "globe" and earth["far"] is True
+
+ # OpenStreetMap has no globe to fall into, so it has no floor
+ flat = parse_map_url(f"https://www.openstreetmap.org/#map=3/{LAT}/{LON}")
+ assert flat["globe_below"] is None
+ assert (flat["geometry"], flat["far"]) == (True, False)
+
+
+def test_a_pin_is_never_gated_by_any_of_this():
+ """Whatever the camera is, the URL still names a point — which is the one a
+ pin files on. The verdict only says the *pixel* clicked cannot be trusted."""
+ for url in (
+ f"https://www.google.com/maps/@{LAT},{LON},3a,75y,90h,90t",
+ f"https://earth.google.com/web/@{LAT},{LON},0a,1000d,35y,0h,0t,0r",
+ ):
+ parsed = parse_map_url(url)
+ assert parsed["geometry"] is False
+ assert (parsed["lat"], parsed["lon"]) == (LAT, LON)
+
+
+# --- against the real thing ----------------------------------------------------
+#
+# `tests/fixtures/map-sites.json` is nine map sites driven in a browser: opened
+# at a known level, dragged a known number of pixels, zoomed about a known
+# pixel, and read back out of the address bar after every step. Fifty-odd URLs
+# that sites wrote about themselves, rather than a table written to suit this
+# parser.
+#
+# The frontend suite replays the same file through the extension's arithmetic
+# (`extensionMapFrame.test.js`) and checks that it puts each view back where the
+# browser had it. What is checked here is the other half: that the parse still
+# hands it those views.
+
+
+ "recording", RECORDINGS, ids=[r["label"] for r in RECORDINGS]
+)
+def test_recorded_browser_sessions_still_parse_the_same_way(recording):
+ # The map's height, not the window's. A site with a header above its map
+ # draws it in fewer pixels than the window has, and the two views that state
+ # a size rather than a level — Apple's span, Google satellite's metres — are
+ # only a scale next to the number of pixels they were drawn in. The
+ # extension hands over the same number (`mapoverlay.js`, `mapHeight`).
+ height = recording["map_height"]
+ for step in recording["steps"]:
+ parsed = parse_map_url(step["url"], height_px=height)
+ assert parsed is not None, step["url"]
+ assert parsed["site"] == step["site"]
+ assert parsed["scale_source"] == step["scale_source"]
+ for key, want in step["view"].items():
+ got = parsed[key] if key != "bearing" else (parsed["bearing"] or 0)
+ if isinstance(want, float) and isinstance(got, float):
+ assert got == pytest.approx(want, abs=1e-9), (key, step["url"])
+ else:
+ assert got == want, (key, step["url"])
+
+
+def test_every_site_this_parser_knows_has_been_driven_in_a_browser():
+ """A site nobody has driven a browser through is a site we are guessing at.
+
+ Keyed on this module's own table rather than on the links the app hands out,
+ because the extension draws on every site here — OpenStreetMap included,
+ which the app never links to because it is already a tile provider inside it.
+ `frontend/calibration/protocol.mjs` drives exactly this list.
+ """
+ from azimut.engine.mapsites import SITES
+
+ recorded = {r["site"] for r in RECORDINGS}
+ known = {site_id for site_id, *_rest in SITES}
+ assert known - recorded == {"google-earth"}, "only Earth is unrecorded, and on purpose"
+ assert {site for _url, site, _zoom in OPEN_IN_LINKS} <= known | {"google-earth"}
+
+
+def test_the_recordings_cover_more_than_one_window():
+ """A fixed side panel keeps its pixel offset when the window changes and a
+ proportional one does not, which is the whole reason for a second size.
+
+ Stated as a floor rather than as a list: `npm run calibrate:maps` records a
+ matrix of windows, browsers and browser zooms, and a re-run that covers more
+ of it must not have to come and edit this. What it may not do is cover less.
+ """
+ sizes = {(r["window"]["w"], r["window"]["h"]) for r in RECORDINGS}
+ assert len(sizes) >= 2, sizes
+ assert min(w for w, _h in sizes) <= 1200, "a window no narrower than 1200 px is one window"
+ # every site is recorded at the widest window, whatever else was recorded
+ widest = max(sizes)
+ at_widest = {r["site"] for r in RECORDINGS if (r["window"]["w"], r["window"]["h"]) == widest}
+ assert at_widest == {r["site"] for r in RECORDINGS}
+
+
+def test_the_map_is_the_window_minus_whatever_the_site_puts_above_it():
+ """How tall the map was drawn, and where that number comes from.
+
+ A map centred in what its chrome leaves is centred by exactly half of what
+ the chrome took, so the camera offset the recording solved for *is* the
+ measurement of the header. `extension/mapoverlay.js` reads it the same way
+ and hands the result to this parser; the fixture is where the two meet.
+ """
+ for recording in RECORDINGS:
+ window = recording["window"]["h"]
+ chrome = 2 * abs(recording["centre"]["y"] - window / 2)
+ # under a couple of pixels is the solve's own noise, not a header
+ want = round(window - chrome) if chrome >= 4 else window
+ assert recording["map_height"] == want, recording["label"]
+ assert 0 < recording["map_height"] <= window
+
+
+def test_bings_rounded_zoom_is_reported_as_written():
+ """The one site that rounds the zoom it writes.
+
+ Bing's wheel moves a third of a level and its URL carries one decimal, so
+ a view at 15.334 is written 15.3 — recorded in the fixture, six notches of
+ it. Nothing here tries to undo that: this side reports what the address bar
+ says, and the extension works the difference out from the pixel the zoom
+ held still, which is the only place the answer exists.
+ """
+ written = [parse_map_url(step["url"])["zoom"] for step in ROUNDING["steps"]]
+ assert written == [15, 15.3, 15.7, 16, 16.3, 16.7, 17]
+ assert all(round(zoom, 1) == zoom for zoom in written), "one decimal, as Bing writes it"
+
+ for step in ROUNDING["steps"]:
+ parsed = parse_map_url(step["url"])
+ assert parsed["site"] == ROUNDING["site"]
+ assert parsed["scale_source"] == "zoom"
+ assert (parsed["lat"], parsed["lon"]) == (step["view"]["lat"], step["view"]["lon"])
+
+
+# --- a camera that never quite comes back to zero -------------------------------
+
+
+def test_a_camera_a_hair_off_level_is_still_a_map():
+ """The bug that turned the tools off on Google Earth.
+
+ These viewers write the camera they are holding, at full precision, and a
+ turn of the compass leaves a fraction of a degree of pitch behind it. Read as
+ "tilted", that is a tool which stops working the moment the view is turned —
+ and the analyst is told to level a view that looks level to them.
+ """
+ for angle in ("0.0001", "0.4", "1.9"):
+ url = f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,12h,{angle}t,0r"
+ assert parse_map_url(url)["view_kind"] == "map", angle
+ # the same forgiveness on the other viewer with a free camera
+ assert (
+ parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},336a,35y,0.5t/data=!3m1!1e3")[
+ "view_kind"
+ ]
+ == "map"
+ )
+
+
+def test_a_camera_anyone_pitched_is_still_refused():
+ for angle in ("2.1", "15", "45.5"):
+ url = f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,12h,{angle}t,0r"
+ assert parse_map_url(url)["view_kind"] == "tilted", angle
+
+
+def test_the_pitch_is_reported_so_a_refusal_can_name_it():
+ """"Tilted" is a verdict; "tilted 40°" is the thing to go and undo — and on a
+ viewer that leaves half a degree behind, the number is how an analyst tells a
+ camera they pitched from one they did not."""
+ tilted = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,40t,0r")
+ assert tilted["tilt"] == 40
+ # roll answers on the same field: whichever tips the ground plane most
+ rolled = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,3t,30r")
+ assert rolled["tilt"] == 30
+ level = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,0t,0r")
+ assert level["tilt"] == 0
+ # a site whose URL states no camera angle says nothing rather than zero
+ assert parse_map_url(f"https://www.openstreetmap.org/#map=17/{LAT}/{LON}")["tilt"] is None
diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py
index 73e5c8a..7993e55 100644
--- a/tests/test_release_gate.py
+++ b/tests/test_release_gate.py
@@ -17,12 +17,13 @@ from __future__ import annotations
import shutil
import tomllib
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from bigcase import build_big_case
from legacy_case import write_legacy_json_case
from azimut import layout, workspace
+from azimut.engine import extinstall
from azimut.engine import links as link_engine
from azimut.engine import media as media_engine
from azimut.engine import thumbnails
@@ -148,6 +149,37 @@ def test_wheel_bundles_the_frontend_and_leaves_dev_tooling_out():
assert not (root / "src" / "azimut" / "bigcase.py").exists()
+def test_wheel_ships_every_file_the_extension_runs_on():
+ """The extension is distributed *by* the wheel: a pip or binary user has no
+ checkout, so Settings and ``/api/ingest/extension.zip`` both serve the copy
+ packaged here.
+
+ Those two paths list the source folder (``extinstall.shipped_files``), while
+ the wheel is assembled from a hand-written ``force-include`` map — so in a
+ checkout a new extension file is picked up and every test passes, and the
+ release quietly leaves it out. That is how ``handoff.js`` shipped broken:
+ ``background.js`` injects it by name into a folder that did not have it.
+ """
+ root = Path(__file__).resolve().parent.parent
+ included = _pyproject()["tool"]["hatch"]["build"]["targets"]["wheel"]["force-include"]
+ packaged = {PurePosixPath(name) for name in included}
+
+ def is_packaged(rel: PurePosixPath) -> bool:
+ # a directory entry (icons/) covers everything under it
+ return any(rel == entry or entry in rel.parents for entry in packaged)
+
+ source = root / "extension"
+ missing = [
+ f"extension/{name}"
+ for name, _ in extinstall.shipped_files(source)
+ if not is_packaged(PurePosixPath("extension") / name)
+ ]
+ assert not missing, f"the extension runs these but the wheel omits them: {missing}"
+
+ # …and nothing is listed that no longer exists, which would fail the build
+ assert not [str(entry) for entry in packaged if not (root / entry).exists()]
+
+
def test_pdf_font_licenses_are_complete_and_packaged():
root = Path(__file__).resolve().parent.parent
fonts = root / "src" / "azimut" / "assets" / "fonts"
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index c50008c..aeaf9e8 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -776,6 +776,20 @@ def test_display_prefs_default_and_round_trip(client):
assert reloaded["post_target"] == "bluesky"
+def test_extension_hand_off_switches_default_on_and_round_trip(client):
+ """Both are on out of the box, because with no extension installed neither
+ changes anything: Publish opens the intent page and a Reverse Search button
+ copies or saves the image, exactly as they did before either existed."""
+ body = client.get("/api/settings").json()
+ assert body["post_prefill"] is True
+ assert body["reverse_prefill"] is True
+
+ saved = client.put("/api/settings/prefs", json={"reverse_prefill": False}).json()
+ assert saved["reverse_prefill"] is False
+ assert saved["post_prefill"] is True # one switch per question, never one for both
+ assert client.get("/api/settings").json()["reverse_prefill"] is False
+
+
def test_display_prefs_reject_unknown_values(client):
assert client.put("/api/settings/prefs", json={"coord_format": "utm"}).status_code == 422
assert client.put("/api/settings/prefs", json={"units": "furlongs"}).status_code == 422
diff --git a/tests/test_updates.py b/tests/test_updates.py
index bee80bb..1ba398d 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -7,16 +7,11 @@ shouldn't be reached."""
from __future__ import annotations
-import hashlib
-import json
-from pathlib import PurePosixPath
-
import httpx
import pytest
from azimut import __version__
-from azimut.api.ingest import _extension_dir, bundled_extension_version, shipped_extension_files
-from azimut.engine import updates
+from azimut.engine import extinstall, updates
class FakeResponse:
@@ -144,34 +139,12 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# shipped file really changes, set the manifest to the current __version__ and
# record the new digest here (the failing test prints it).
EXTENSION_VERSION = "0.3.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.
-_TEXT_SUFFIXES = {".js", ".json", ".css", ".html", ".md", ".txt"}
-
-
-def _extension_payload_digest() -> str:
- """Digest everything ``extension.zip`` ships, minus the manifest's own
- ``version``.
-
- Leaving the version out is what makes the gate cut both ways: with it in,
- any bump would change the digest and a gratuitous one would look exactly
- like a real change."""
- src = _extension_dir()
- assert src is not None, "no extension bundled with this checkout"
- digest = hashlib.sha256()
- for name, path in shipped_extension_files(src):
- if name == "manifest.json":
- manifest = json.loads(path.read_text(encoding="utf-8"))
- manifest.pop("version", None)
- data = json.dumps(manifest, sort_keys=True).encode("utf-8")
- else:
- data = path.read_bytes()
- if PurePosixPath(name).suffix in _TEXT_SUFFIXES:
- data = data.replace(b"\r\n", b"\n")
- digest.update(f"{name}\0".encode() + data + b"\0")
- return digest.hexdigest()
+EXTENSION_PAYLOAD = "4c1ffa06f9e174599f5d85ae5142ed69e95fbbd7ef0e642df58372926f45bd45"
+
+# The digest itself lives in engine/extinstall.py, because the update button
+# compares the same number: what the app ships against what the installed folder
+# was written from. One definition, so the gate and the button cannot disagree.
+# The constants above are what makes it a gate.
def test_the_shipped_listing_reads_the_same_on_every_platform():
@@ -183,9 +156,9 @@ def test_the_shipped_listing_reads_the_same_on_every_platform():
unchanged extension. Sorted by the posix name instead, which is the same
string on all three.
"""
- src = _extension_dir()
+ src = extinstall.source_dir()
assert src is not None
- names = [name for name, _ in shipped_extension_files(src)]
+ names = [name for name, _ in extinstall.shipped_files(src)]
assert names == sorted(names)
assert all("\\" not in name for name in names)
@@ -198,8 +171,8 @@ def test_the_extension_version_moves_only_when_the_extension_does():
quiet and the user keeps running a stale bridge. A version bump with no
change: everyone is told to reinstall the zip they already have, and a nag
that cries wolf is a nag nobody reads."""
- digest = _extension_payload_digest()
- version = bundled_extension_version()
+ digest = extinstall.payload_digest()
+ version = extinstall.bundled_version()
assert digest == EXTENSION_PAYLOAD, (
f"the shipped extension changed. Set extension/manifest.json to the current "