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

Complete the GEOINT map workflow for v0.3.0 (#75)

OsintMeThat845165092eb7
diff --git a/README.md b/README.md
index a1f47d5..4e90849 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ to fix a point on the map.*
| **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. 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. |
+| **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 with an optional scale bar and north arrow, map rotation, measurement tools, a right-click menu on any point, stacked overlays (borders, roads, railways, power lines, fires, night lights) and editable AOI grids for area review. Esri/OSM by default, plus the Esri Wayback archive and Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. Open it in several tabs and they stay in sync. |
| **Coords & Sky** | Convert common coordinate formats, copy the result, open map or geocoding links, and read the sun and moon at that point on a date: rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle, in local time and UTC, computed offline. |
| **Geo Proof** | Start a named proof from a reusable house style, or from a published post whose pictures become its panels. Compose case panels in a grid or free layout, annotate with colored shapes, fills, symbols, freehand and text, state every place and every source the proof argues, and export `proof.png` plus a re-editable spec. |
| **Geo Report** | Turn a proof into a prepared thread for X or Bluesky: coordinates, plus code, attribution, target-specific character counts, media, and a structured Markdown case note with linked evidence. |
@@ -73,31 +73,27 @@ extension, and cross-platform binaries with a bundled ffmpeg.
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
-## New in v0.2.9
-
-A table you can work in, and a proof that can argue more than one point.
-
-- **Sheet**, a new tool: the case's own CSV files in a spreadsheet-style grid.
- They still open in Excel, and the grid notices when they change on disk.
-- Type a column (state, list, yes/no, number, coordinates, date, image) and the
- sheet sorts, filters and maps it properly. Excel workbooks import one tab per
- sheet.
-- Turn a prepared sheet into entities, places and dated statements after reading
- a row-by-row plan, or build a worklist out of what the case already holds.
-- Geocode a column of addresses, check a column of links, list every proof in the
- case, or build one proof per row from columns of links and coordinates.
-- A proof can state several points, name them, mark the camera position, and list
- several sources, downloading supporting files for a link the case lacks.
-- Import a published post as a proof: its pictures become panels and its text is
- read for coordinates, with a preview to approve first.
-- Fill shapes at a chosen opacity, stamp ready-made symbols, and move or recolour
- several at once.
-- Export a Graph or Timeline view as an SVG or PNG plate carrying the case, the
- question, the period and a legend.
-- The map's search box suggests as you type from saved places, pasted coordinates
- and 34,000 bundled cities, and only calls the geocoder once you stop.
-- Saved views can be renamed and sorted, Board rows delete as one undoable batch,
- and removing a relation or an imported entity photo now asks first.
+## New in v0.3.0
+
+A new map with much more on it, and Azimut's tools drawn over other map sites.
+
+- The map runs on MapLibre, with modes in one rail, layers in a side panel and a
+ status line. Right-click the ground to copy, save, measure, read the sky or open
+ the point's imagery history.
+- **Esri Wayback** as a basemap, narrowed to the releases that changed the point
+ and dated by when the picture was taken.
+- Key-less overlays (borders, roads, railways, power lines, sea marks, GPS
+ traces), NASA FIRMS fires and VIIRS night lights for a chosen day.
+- Several map tabs sharing one camera, with saved points and grid sweeps synced
+ live between them.
+- Captures can carry a scale bar and a north arrow, and a place's uncertainty can
+ be traced as a shape.
+- The capture extension draws measure, saved points, sun and moon, search grids,
+ fires and case media over third-party map sites, and updates from Settings.
+ Firefox gets a signed, self-updating add-on.
+- Geo Report fills the X or Bluesky composer with the whole thread, and Reverse
+ Search drops the picture straight into the engine's uploader.
+- The app opens on a case Home, and `?` opens a Guide on the current tool.
- Existing cases open unchanged, and older bundles still import.
## Cases on disk
@@ -361,7 +357,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, and
publishes to PyPI. **Don't publish by hand.**
```bash
-git tag v0.2.9 && git push origin v0.2.9
+git tag v0.3.0 && git push origin v0.3.0
```
One-time setup: register the repo as a
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.md
index fdc210a..9c96f56 100644
--- a/docs/IMAGERY_PROVIDERS.md
+++ b/docs/IMAGERY_PROVIDERS.md
@@ -24,6 +24,7 @@
| Provider | `needs_key` | auth style | `capturable` | `cacheable` (tile disk cache) | attribution source |
|----------|:-----------:|------------|:------------:|:-----------------------------:|--------------------|
| Esri World Imagery | no | — | yes | yes | static string |
+| Esri Wayback | no | — | yes | yes (a release never changes) | static string, release in provenance |
| OpenStreetMap | no | — | yes | yes | static string |
| OpenTopoMap | no | — | yes | yes | static string (CC-BY-SA² ) |
| **Mapbox Satellite** | yes | access token in URL | yes | yes¹ | `© Mapbox © OpenStreetMap` (+ Maxar) |
@@ -326,6 +327,78 @@ project), Mapbox 200k/month then $0.50/1k (alerts only, no hard cap). Metered
tiles are proxied through the backend so the counter matches billing exactly;
browser cache hits never re-count.
+## NASA FIRMS is a keyed layer, not a basemap
+
+Active fire detections (`engine/firms.py`) are the one keyed thing here that is
+not a picture of the ground: they are laid **over** whichever basemap is
+showing, so the key buys a layer and the card in Settings → Imagery carries no
+meter, no free-allowance box and no eco threshold. Nothing about it is billed.
+
+| | |
+|---|---|
+| Credential | one `MAP_KEY`, from the FIRMS page; it serves the global and the US/Canada services alike |
+| Where it goes | **in the path** of every request, which is why the browser never builds one: `/api/firms/tiles/{z}/{x}/{y}` for the app, `/api/ingest/firms` for the extension |
+| Asking | WMS `GetMap` in EPSG:3857 — the projection the tile grid is already in, so a tile is its own square and nothing is reprojected |
+| Live | `fires_viirs_24 / _48 / _72 / _7`, and the same for `fires_viirs_snpp`, `fires_viirs_noaa20` and `fires_modis` |
+| History | the same layer names without the suffix, dated with `TIME=from/to`, up to **31 days** per request |
+| Zoom ceiling | z14. FIRMS draws a fixed symbol per detection and VIIRS resolves 375 m; deeper is a screen of overlapping marks, and the route refuses it |
+| Allowance | 5,000 requests per 10 minutes, and a long range counts as several. Nothing polls, and a layer that is off asks for nothing |
+| Caching | none on disk. The live layers are what is burning now (upstream refreshes every 15 minutes) and a cached fire is a lie with a timestamp; the browser holds one for 5 minutes |
+
+NOAA-21 is left out on purpose: FIRMS gives it the rolling layers and no dated
+one, and a sensor that could answer "now" but not "that day" is a trap in a tool
+whose second question is always the date.
+
+The extension asks differently for the same reason it draws differently: it has
+no tile grid to hang tiles on, so it asks for **one picture of the ground it can
+see** per settled view and lays it under its own drawing, rotated with the map.
+That is also one request where tiles would be a dozen.
+
+## Esri Wayback is one release at a time
+
+Every published release of World Imagery stays online under its own number
+(`engine/wayback.py`). Same imagery, same terms and same attribution as the
+default basemap, and no key. Three services, all asked only after the analyst
+picks the basemap or opens its picker:
+
+| Service | What it answers | Notes |
+|---|---|---|
+| `waybackconfig.json` (S3) | every release: number, title with its date, metadata service | read once per 6 h; numbers are not in date order, so the date sorts. Only metadata services on `metadata.maptiles.arcgis.com` are followed |
+| `MapServer/tilemap/{release}/{z}/{row}/{col}` | `select`: the release that tile was really published in | walking it backwards from the newest lists a point's changes, one small request per change |
+| `World_Imagery_Metadata_*/MapServer/{layer}/query` | `SRC_DATE2` (epoch ms), provider, satellite | layer = 23 − zoom, capped at 13. Slow, a couple of seconds each, so a walk asks up to 12 at once |
+
+What the tilemap calls a change is a change of bytes. Esri republishes pictures
+often, so two filters run over the walk, both keeping the older release: equal
+tile sizes are compared by hash, and neighbours stating the same acquisition day
+and satellite are one picture (observed 2026-09 in Mariupol: three releases over
+one GE01 acquisition of 2023-10-04, re-coloured). A tile or a metadata answer
+that cannot be read is an unknown and never merges anything.
+
+A tile asked of a release it did not change answers `301` to the release that
+did; the proxy follows it and caches under the release asked for. The variant id
+`esri-wayback~{release}` is digits only, since it becomes a path segment and a
+cache directory; the plain `esri-wayback` resolves to the newest release, so its
+id and its cache always name one.
+
+## Key-less overlays
+
+Drawn over any basemap, fetched by the browser straight from their own servers
+(all answer cross-origin), never through the proxy, never cached on disk, never
+in a capture, and never asked for before their switch is on
+(`frontend/src/lib/map/basemap.js`). Checked 2026-09-13.
+
+| Layer | Source | Licence / terms | Notes |
+|---|---|---|---|
+| OSM labels | CARTO `voyager_only_labels` | © OSM contributors © CARTO | imagery only |
+| Borders | Esri `Reference/World_Boundaries_and_Places` | Esri terms, as World Imagery | |
+| Roads | Esri `Reference/World_Transportation` | Esri terms, as World Imagery | imagery only |
+| OSM railways | OpenRailwayMap `standard` | © OSM contributors, style © OpenRailwayMap | |
+| Power lines | Open Infrastructure Map vector tiles (`/map/power`, `/telecoms`, `/petroleum`) | data ODbL, analysis CC-BY 4.0, credit and link required | no published tile usage policy, so the style is ours, requests only follow the view, and nothing is prefetched |
+| Sea marks | OpenSeaMap `seamark` | © OpenSeaMap contributors (CC-BY-SA) | |
+| GPS traces | `gps.tile.openstreetmap.org/lines` | OSMF tile policy | |
+| Night lights | NASA GIBS WMTS, `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` (from 2024-03-25), `VIIRS_SNPP_…` (from 2020-11-18, with gaps), `VIIRS_Black_Marble` 2016 | public domain | Level 8 (750 m); opaque, drawn lowest at 85% |
+| Active fires | NASA FIRMS, keyed, through the app | see above | |
+
## Deliberately not basemaps
Street View and Google Photorealistic 3D Tiles are not basemap providers. They
diff --git a/docs/MAP_SITES.md b/docs/MAP_SITES.md
index 0abd74c..d2e87a1 100644
--- a/docs/MAP_SITES.md
+++ b/docs/MAP_SITES.md
@@ -25,7 +25,7 @@ rather than an afternoon with a browser. See *Recalibrating* at the end.
|---|---|---|---|
| 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 |
+| Google Earth | `earth.google.com/web/@47.388462,2.352785,194.5a,2206.63d,35y,0h,0t,0r` | lat, lon | `d`, camera distance to the ground, and `y`, field of view: the window is `2·d·tan(y/2)` metres tall; `a` ground height, `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 |
@@ -77,20 +77,45 @@ 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`).
+**Google Earth draws a flat map and states it as a camera.** Its default 2D view
+is Web Mercator at every distance, however much of the world is on screen, and
+its address bar describes it as a camera `d` metres above the ground under the
+middle of the window, with `y` degrees of field of view across the window's
+height. So the window covers `2·d·tan(y/2)` metres top to bottom, which is a zoom
+next to the window's height, exactly like Google satellite's `,3231m`. Earth
+honours `y`: the app's own link once wrote `1y` and opened every place 35 times
+too close.
+
+That was measured without dragging anything (`npm run calibrate:earth`): a camera
+opened again a known step east, a known step north and at half the distance, and
+the screenshots registered against each other. Across three window shapes, two
+fields of view, three latitudes, a mountain range and a camera 400 km out, the
+picture moved what the formula says to a thousandth or better at 35°, north over
+east came out at spherical Mercator's `1/cos(lat)` rather than the ground's own
+ratio, and the camera was the middle of the window to a third of a pixel
+(`tests/fixtures/earth-scale.json`).
+
+**`d` is a distance to the ground only once Earth has put the camera there.** Any
+gesture makes Earth write the ground's height into `a`, and from then on `d`
+follows the ground under the centre: pan over a hill and `d` shrinks while the
+camera stays up, which is the map being drawn bigger, and `d` says so. A link
+typed as `0a` is not placed, and Earth draws it as a camera `d` above sea level:
+over ground 200 m up that is 7% nearer than `d` says. So a `0a` with a whole `d`,
+which is how a link is written and never how Earth writes, states no scale until
+the map moves. Two more states are refused the same way, both seen on loading a
+link: a `d` under the 25 m Earth's map stops at (`1518a,10d`, for a camera 1528 m
+up), and an `a` no ground has.
+
+**Its 3D mode is another camera.** Earth's "3D" button pitches the camera and adds
+field 5 to the protobuf after `/data=`, and pressing it again takes both away. A
+pitched camera is refused like any other. A 3D camera brought back to level is
+drawn as a map in close and refused past `LEVEL_CEILING_M` as a globe; a `data=`
+that cannot be read is taken as 3D.
+
+**Earth writes several addresses for one zoom.** It rewrites the URL as its camera
+eases, each one true for the moment it was written. The panel keeps the drawing
+dimmed until the address bar has stopped changing for 400 ms, and re-solves the
+camera centre from every reading in between.
**"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
@@ -103,21 +128,10 @@ 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
+the nine 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.
@@ -131,14 +145,29 @@ amount of scale accuracy, since a pan slides the offset along with the map.
| 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.
+| Google Earth | 800, 500 | the map fills the window; its toolbar and status bar sit over it |
+
+The extension **measures** the offset rather than trusting a table, 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.
+
+**But it starts somewhere, and the middle of the window is a table entry too.**
+It was the one the extension used to ship, and it is wrong on four of these
+sites — 210 px on Yandex, 225 on Copernicus, and nothing on screen saying so
+until the analyst happened to zoom. So the four whose offset held steady across
+both recorded window shapes are shipped as starting answers
+(`engine/mapsites.py`, `_CAMERA_CENTRE`), handed to the panel with the parse of
+the URL and replaced by the first offset it measures for itself. A measurement
+on the machine in front of the analyst always wins: over the table, and over one
+taken in another window.
+
+Apple is the exception and stays unhinted. Its sidebar folds away below some
+width its URL never states, so its offset is 67 px in a 1600 px window and
+nothing in a 1200 px one — a starting answer that is right half the time is
+worse than none. `tests/test_mapsites.py` re-checks every entry against the
+recordings above and fails on a site that drifts off-centre without one.
**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
@@ -184,8 +213,9 @@ nothing else. Both claims are held by tests rather than by this paragraph
**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
+the three views that state a size rather than a level: a span, a height in
+metres and Earth's distance 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.
@@ -211,22 +241,85 @@ 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.
+## Following a linked view
+
+The panel's link button moves a site's map by writing a camera into its address
+(`extension/maplink.js`), so what each site does with a written address decides
+how a follow looks. Measured on 2026-09-13 in Chromium, opening a view over the
+Cher and one at level 23 over Paris, then dragging to make the site write the view
+it was really on.
+
+| Site | Written how | Reloads | Deepest level a link reaches | Address true on arrival |
+|---|---|---|---|---|
+| Google Maps and satellite | `@lat,lon,17z`, layer kept | yes, 3–4 s | 21 | a whole level only: `16.5z` and `1142m` both open at 16 and keep saying 16.5 |
+| Bing | `cp=`, `lvl=` to one decimal | yes, ~2 s | 22 | yes, and past 22 it rewrites the level |
+| Apple | `/frame?center=…&z=` | yes, ~2 s | 19 over Paris | yes: `z` is read on load and the span it writes is live |
+| Copernicus | `zoom=`, `lat=`, `lng=`, acquisition kept | yes, ~3 s | 18 (its wheel goes to 25) | not past 18: `zoom=23` keeps saying 23 |
+| Google Earth | `@lat,lon,a,d,y…`, `data=` kept | yes, ~12 s without a GPU, flying in from space | the 25 m camera floor | yes once placed; `a` is kept, so the scale is out by the change in ground height until a gesture |
+| OpenStreetMap | `#map=17/lat/lon` | no | 19 | not past 19: `#map=20` keeps saying 20 |
+| Zoom Earth | `#view=lat,lon,11z`, day kept | no | 11, Live and HD alike | yes, it rewrites the level |
+| Yandex, Satellites.pro | `ll=`, `#lat,lon,z` | unmeasured | unmeasured | both refuse a headless browser (a bot page, a Cloudflare check) |
+
+Two rules come out of it. A site is given **whole levels** unless a fraction was
+seen to land true (Bing, and Apple and Earth, whose size is read back), because the
+tools take their scale from that address the moment it lands. And a site that
+keeps a level it cannot draw has what is *written* capped at the level it draws
+(`WRITE_CEILING`: Google 21, OpenStreetMap 19, Copernicus 18); the view being
+followed is never capped. `tests/fixtures/map-link-writes.json` holds one write per
+site, written by the extension's test and read back by `tests/test_map_link_writes.py`.
+
+Apple has two more. It opens no view nearer a pole than ±70.4956°, whatever the
+address says and at every zoom, though a drag goes on past it with the address
+following (`OPEN_LAT_LIMIT`); the panel says where it stopped. So a view past the
+limit is **written as the latitude Apple opens** rather than as it was asked, for
+the same reason a level is capped: the address is what the tools read the ground
+from, and one stating a pole the map is not at draws every mark there until Apple
+rewrites it. Written that way, a map already stopped at the limit is where the
+next view asks it to be, so it is left alone instead of reloading once per gesture
+on the map it follows — which is what used to undo the drag the panel had just
+asked for. And a click on a
+label or a long press opens a place card that swaps the address for
+`/place?…&coordinate=…` with no camera in it until the card is closed, so the
+panel says to close it, and a linked view written there closes it.
+
+A follow only ever happens in a tab that is on screen. A panel whose tab is in the
+background keeps the last view it was sent and writes it when the tab is looked at
+again — `document.hidden`, so the front tab of a window that is merely unfocused
+still follows live. Reloading a page nobody is watching costs one reload per gesture
+on the map being led, and each of those races the next: a page still loading has no
+panel to hand the following view to, and a browser that allowed the tools on one
+page can refuse them on the page after it.
+
+`history.pushState` with a `popstate` moves only Earth without a reload; every
+other site ignores it, so it is not used.
+
## 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.
+There are two of these and they get different answers, because they are not the
+same thing.
-Out there the drawing is **kept, dimmed, and labelled** rather than refused. A
+**A flat map drawn far out** is Google and Bing below level 8: the renderer
+curves while the URL goes on quoting a tile level, so the zoom is the only
+warning there is. Out there the drawing is **kept, dimmed and labelled**. 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
+away from it, so the middle of the screen is right and the edges drift — 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.
+
+**A globe camera** is Earth's 3D mode past `LEVEL_CEILING_M` (150 km of camera
+distance), and Google's Earth mode with it. That is a perspective view of a
+sphere, not a map drawn small: there is no anchor point Mercator is right about
+and no edge the error is confined to, so nothing is drawn at all — no marks, no
+grid, no fire picture — and the panel says *"The camera is on a globe this far
+out, so zoom in"*. Dimming it instead would ask the analyst to judge how wrong a
+drawing is, with nothing on screen to judge it by. Come down under the ceiling
+and everything draws. Earth's 2D map is neither of the two: it is Web Mercator
+all the way out, and exact there.
+
+Two things neither of them does out there: it never *measures* anything from a
+view that far out — the camera centre and the rounded-zoom correction are 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.
@@ -239,9 +332,16 @@ 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
+cd frontend && npm run calibrate:earth # Earth's scale, from registered screenshots
+python scripts/build_earth_fixture.py /tmp/azimut-earth-calibration
npm test && python -m pytest tests/test_mapsites.py
```
+Earth has its own run because a drag is too blunt to check a formula against. It
+drags nothing: it opens cameras a known step apart and registers the pictures, in
+a headless browser on SwiftShader, about a minute a case. Earth is in the drag
+and zoom run too, which is what shows its wheel zooms about the cursor.
+
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`
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 8aef85c..1f8d840 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -399,12 +399,15 @@ biodiversity records two decades ago.
| `verbatim` | `verbatimLocality` | what the source said, word for word |
| `method` | `georeferenceProtocol` | how this point was arrived at |
-Three of Darwin Core's rules are kept as written, and each is a test:
+Four of Darwin Core's rules are kept as written, and each is a test:
- **The radius is the smallest enclosing circle**, not a standard deviation, so two
analysts write the same number.
- **Zero is not a valid radius.** Empty means *unknown*, a different and honest state;
`0` would claim infinite precision. Hence a floor of one metre.
+- **A footprint contains the point it belongs to.** A shape traced beside its pin
+ describes somewhere else, and the map let that happen: the polygon drew where it was
+ clicked and the pin stayed where it was.
- **`verbatim` outlives every reinterpretation.** It is the field people wish they had
kept.
@@ -427,14 +430,18 @@ for graph edges and lineage, and Time for dated statements and intrinsic dates.
The saved index (`GET /cases/{id}/satellite/index`) carries `radius_m` and
`footprint` so the map overlay draws them without fetching each place: a footprint
-renders as its own polygon, a radius as a circle in metres, and a footprint wins when
-both are set. The map popup states the spread in words (`±500 m`, `traced area`) and
-never edits it.
-
-**`footprint` is stored, validated and drawn, but not yet traceable.** No map offers
-the gesture, so the field is API-only and the panel hides it until a shape exists.
-The tracing tool (SPEC §6, v2) completes it; nothing else about the field changes
-when it lands.
+renders as its own polygon and a radius as a circle in metres. The map popup states
+the spread in words (`±500 m`, `traced area`) and never edits it.
+
+**The two geometries are one claim, so a place holds one of them.** They answer the
+same question in two forms and the map can draw only one, which meant a radius typed
+over a traced shape vanished from the map without a word. So a write that sets one
+asks for the other to be cleared with it, and the surface doing the writing is the one
+that gets the analyst's consent: tracing says what it replaces before Save, Details
+asks before dropping a shape for a radius. The rule is judged on the patch and not on
+the stored result, so a place written before it holds both and stays editable in every
+other respect — the overlay still prefers its shape. `footprint` is traced on the map
+(UI §7) and never typed, so the panel hides the field until a shape exists.
### What a source is worth ✅
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index b1d997e..b01e1cd 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -1,88 +1,77 @@
-# Azimut v0.2.9
+# Azimut v0.3.0
Azimut is a local OSINT workspace: media, geolocation work, proofs and notes in
one portable case folder, on your own machine.
-This release adds a table you can work in, and lets a proof argue more than one
-point.
-
-## Sheet, a new tool
-
-A spreadsheet-style grid over the case's own CSV files.
-
-- Each sheet is a plain `.csv` in the case folder, so it also opens in Excel or
- LibreOffice. If you edit it there while Azimut has it open, the grid tells you
- and asks whether to reload or overwrite.
-- Sort, filter, rename, merge, pin or hide a column from its own heading, and
- clean up a pasted column (trim, lowercase, de-duplicate, split) after seeing
- how many cells it would change.
-- Give a column a type: state, list, yes/no, number, coordinates, date or image.
- The sheet then sorts and filters it correctly, and can show it on the map, on
- the Timeline or as a progress count.
-- Import an Excel workbook, one sheet per tab.
-- A cell can point at a person, a place or a media item already in the case.
-- Copy the rows you are looking at as a Markdown table, or save them as a CSV.
-
-### From a sheet into the case, and back
-
-- Turn a prepared sheet into entities, places, bookmarks and dated statements in
- one go. You see a row-by-row plan first, and nothing is written until you
- accept it.
-- Or the other way round: build a worklist from what the case already holds, for
- example forty places to check with a column for your verdict.
-- Geocode a column of addresses, check a column of links, or send a column of
- coordinates to the map.
-- List every proof in the case, one per row, and build one proof per row out of
- columns holding links and coordinates.
-
-## Geo Proof
-
-- A proof can now state several points, not one. Name them, mark which one is
- the camera position, and the first row stays the proof's conclusion.
-- It can also list several sources. For a link the case has nothing from, Azimut
- offers to download its files as supporting material.
-- Import a published post as a proof: its pictures become the panels, its text
- is read for coordinates, and any video it links is downloaded. You approve a
- preview before anything is saved.
-- New drawing options: filled boxes and ellipses with adjustable opacity, a set
- of ready-made symbols, and multi-select to recolour or move several shapes at
- once.
+This release rebuilds the map and gives it much more to show, and lets the
+capture extension draw Azimut's own tools over other map sites.
+
+## A new map
+
+The Satellite map now runs on MapLibre. Your providers, captures and map rotation
+work as before, including the Google basemap.
+
+- The screen is laid out again: modes in one rail, layers in the right panel,
+ imagery in the map corner, and your position in a status line underneath.
+- Right-click the ground to copy that point in every format, look it up, save it,
+ measure from it, read the sun and moon there, open its imagery history, or open
+ it on another map site.
+- **Esri Wayback** is a basemap now. Pick any World Imagery release, or list only
+ the releases that brought a new picture of the point you are looking at. The
+ chip gives the date the picture was taken, which is often long before the
+ release.
+- Stack overlays that need no key: borders, roads, railways, power lines, sea
+ marks and GPS traces. Add NASA FIRMS fire detections (with a free FIRMS key in
+ Settings) and VIIRS night lights for a day you pick.
+- Filter the pins drawn on the map by kind and by folder.
+- Open the map in several tabs. The view is in the address, two tabs can share one
+ camera, and a point saved or a grid swept in one appears at once in the others.
+- A capture can carry a scale bar and a north arrow.
+- Trace a place's uncertainty as a shape around its pin, for a quay or a treeline
+ that a circle describes badly.
+
+## Capture extension
+
+- On a 2D map site, the extension can now draw Azimut's tools over the page:
+ measure, the case's saved points, sun and moon, a search grid that opens in the
+ app afterwards, NASA FIRMS fires, and floating windows holding the case's own
+ pictures and videos.
+- The scale is read from what each site writes in its address bar, checked site by
+ site in a real browser. On a view the tools cannot work with, such as Street View
+ or a tilted 3D camera, they switch off and say which view they need.
+- Geo Report fills the X or Bluesky composer with the whole thread, one box per
+ post with its pictures attached. Posting stays your click.
+- Reverse Search puts the picture straight into the Lens, Yandex, Bing or TinEye
+ uploader, so one press runs the search.
+- On Chrome, Edge and Brave, updating the extension is a button in Settings.
+ Firefox gets a signed add-on that updates itself, and Settings tells you when
+ your copy is out of step with the app.
+- Mastodon is no longer a Geo Report target. A draft saved for it opens on X.
## Elsewhere
-- Export a Graph or Timeline view as an SVG or PNG plate, with the case name,
- the question, the period and a legend around the drawing.
-- The map's search box now suggests as you type, from your saved places, from
- coordinates you paste and from a list of 34,000 cities bundled with the app.
- It only calls the online geocoder once you stop typing.
-- Saved views can be renamed and sorted, and each says when it was last changed.
-- Select several rows in the Board and delete them in one step, undoable from
- the toast.
-- Downloads behind a login explain what the site actually asked for, and offer
- to reuse your browser session.
-- Removing a relation, or deleting a photo you imported into an entity, now asks
- for confirmation, because neither can be undone.
-
-## Fixes and hardening
-
-- A sheet no longer removes a relation you stated yourself. Clicking a filter
- dropped the entities you had linked to the sheet by hand, and promoting the
- same rows a second time dropped the sources you had added to a statement.
-- A point that a batch build filed for a proof can now be taken off it, and its
- camera marker is read from that proof's own footage. Deleting the row used to
- do nothing, and the point came back the next time you opened the proof.
-- A camera position marked on a coordinate written twice is kept, instead of
- being dropped with the repeated line.
-- A batch proof build no longer overwrites an existing proof that happens to
- share its title; it stops and tells you about the name clash.
-- Large uploads are refused by size before being read, including the proof
- composer's save.
-- A malformed extension pairing token is rejected properly instead of returning
- a server error.
-- Auto-stitch says that the pieces do not solve, instead of failing with a server
- error, when they overlap too little to be placed.
-- Filing several downloads at once no longer fails one of them on a locked
- database, which mostly affected Windows.
+- The app opens on **Home**: what is left to do in the case, what was filed
+ recently, and the case's points on a small map. With no case open, it explains
+ what Azimut is and helps you start one.
+- A **Guide** with one section per tool and a few worked examples. The `?` in the
+ top bar opens it on the tool you are using.
+- New case folders keep the name you typed, spaces, accents and non-Latin scripts
+ included, instead of a lowercase ASCII version of it.
+- The Media Library no longer lists satellite captures and extension screenshots by
+ default. Satellite's Saved panel is where they live, and the library's switch
+ still shows them.
+- Auto-stitch sizes the collage canvas to the panorama instead of shrinking it to
+ fit, and you can set the canvas size by hand.
+- In Geo Proof, a shape you just drew stays selected so you can restyle it straight
+ away. The stamp tool stays in hand for marking several things in a row.
+- Sheets are listed newest first.
+
+## Fixes
+
+- Thumbnails and metadata enrichment no longer stop for the rest of the session
+ when the background worker dies unexpectedly.
+- Naming a proof's first point, or marking it as the camera position, is now saved
+ when its coordinate field was left empty.
## Install or upgrade
@@ -96,5 +85,9 @@ On Intel Macs (macOS 14 or newer), install the Python package instead:
The downloads are unsigned, so your system will warn you the first time. The
README explains the prompt for each platform.
+Firefox users install the signed `azimut-capture-0.3.0.xpi` attached to this
+release. Chrome, Edge and Brave users install or update the extension from
+Settings → Capture extension.
+
Your existing cases open as they are. No export, migration or manual step is
needed, and older case bundles still import.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index c2e6fff..6fd601b 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -1,6 +1,6 @@
# Azimut product overview
-Status: **spec v0.3** (2026-08-21). Read in order: Done → Roadmap → Loose ideas.
+Status: **spec v0.3** (2026-09-13). Read in order: Done → Roadmap → Loose ideas.
Implementation detail belongs in code and tests; see
[IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), [UI.md](UI.md),
[ONTOLOGY.md](ONTOLOGY.md) and
@@ -132,7 +132,7 @@ proof for publication.
| ✅ **Case utilities** | Opens case folders, reports scrubbed diagnostics, keeps filenames in sync and offers explicit Doctor repairs. |
| ✅ **Workspace portability** | Moves or adopts a workspace safely, recovers hand-added cases and prevents two live instances from sharing it silently. |
| ✅ **Updates & paste** | Reports available app, downloader and extension updates, then files supported clipboard content from the main case surfaces. |
-| ✅ **Evidence on the map** | Places proofs and derived media through their evidence chain, with stated point uncertainty and traced footprints. |
+| ✅ **Evidence on the map** | Places proofs and derived media through their evidence chain, with stated point uncertainty and footprints drawn under their pins. |
| ✅ **Map search** | Answers the search box while typing from saved work, a coordinate parse and a bundled gazetteer, and asks the geocoder only once typing stops. |
| ✅ **Ontology connections** | Keeps Relations, Mentions, Claim connectors and artifact lineage separate under one validated verb registry. |
| ✅ **Board & entities** | Provides the sortable Case Board, shared Details, typed creation, primary entity photos and a ticked selection deleted as one recoverable act. |
@@ -143,7 +143,7 @@ proof for publication.
| ✅ **Temporal Claims** | Dates a Claim with guided point, timestamp or interval input and files its subjects, places and evidence atomically. |
| ✅ **Case Timeline** | Aligns dated statements and media on a windowed axis read in UTC or a civil zone, with uncertainty, density, direct edits and Undated work. |
| ✅ **Timeline readings** | Builds coloured tracks from presets or Search+, then saves a changing Live view or a fixed Snapshot. |
-| ✅ **Shared analysis views** | Shares one filter, saved-view family and fact-time window between Board, Graph and Map, while Timeline keeps readings built for tracks. |
+| ✅ **Shared analysis views** | Shares one filter, saved-view family and fact-time window between Board and Graph, while Timeline keeps readings built for tracks and the Map only exchanges a window with them. |
| ✅ **Analysis view export** | Writes the Graph or the Timeline out as a vector plate carrying its lens, question, window, clock and legend, or copies it as an image. |
| ✅ **Case Sheet** | Opens and builds case CSVs in a plain grid: keyed rows, sorts, filters, row colour, clipboard both ways, bulk fill, undo, cells that point at case entities, and a reading handed out as CSV or Markdown. |
| ✅ **Typed columns** | Types a column in the sidecar as a state, a list, a yes/no, a number, a point, a date or a picture, and lets the sort, the filters, the vocabulary, the map, the Timeline, the progress and the link check read it. |
@@ -155,20 +155,22 @@ proof for publication.
| ✅ **Drawing on a proof** | Stamps a fixed set of marks, fills boxes and ellipses at a chosen opacity, keeps every shape tool in hand, and recolours, restyles, nudges, drags or deletes a picked family at once. |
| ✅ **A proof of several points** | States every place a proof argues, each optionally named and one of them the camera's, files them as places under one title, and carries them into the tweet and onto the exported picture. |
-### v3 GEOINT expansion (unreleased)
+### v3 GEOINT expansion (shipped as GitHub `v0.3.0+`)
| Tool | What it does |
|------|--------------|
-| ✅ **Map engine** | Draws the map on MapLibre GL behind `lib/map`'s façade, at parity: same providers, same captures, same bearing, and the Google widget basemap kept alive under the map's own transparent canvas. |
-| ✅ **Composer hand-off** | Fills X's or Bluesky's own composer with a prepared thread: each post in its own box with its pictures, the thread button pressed between them, every box read back afterwards, and Post left to the analyst. |
-| ✅ **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`). |
+| ✅ **Map engine** | Draws the map on MapLibre GL behind the `lib/map` façade, with the same providers, captures and bearing. |
+| ✅ **Map chrome** | Puts modes in one rail, layers in the right panel, imagery in the map corner and position in a status line, each tool declared once. |
+| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, and links it out. |
+| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links map tabs and extension panels on other sites to one camera, and syncs saved points, grids and sweeps live to every tab and extension panel. |
+| ✅ **Map layers** | Stacks key-less overlays (borders, roads, railways, power lines, sea marks, GPS traces), NASA FIRMS fires and VIIRS night lights for a chosen day, and filters drawn pins by kind and folder. |
+| ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed to the ones that changed the point, and dates the pixels apart from the release. |
+| ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. |
+| ✅ **Footprint tracing** | Traces a place's uncertainty as a polygon around its pin, in place of the radius. |
+| ✅ **Extension map tools** | Draws measure, media pins, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |
+| ✅ **Extension updates** | Updates the unpacked extension in one click, installs a signed self-updating Firefox add-on, and flags a copy out of step with the app. |
+| ✅ **Site hand-offs** | Fills the X or Bluesky composer with a prepared thread and uploads a case picture straight into Lens, Yandex, Bing or TinEye. |
+| ✅ **Home & Guide** | Opens on a case dashboard or a front door when no case is open, and `?` opens the Guide on the current tab. |
---
@@ -184,25 +186,24 @@ 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. |
-| **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. |
+| **Capture graticule** | The rest of what a plate states about itself: a latitude/longitude grid over app and extension captures, beside the scale bar and north arrow that already ship. |
| **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. |
+| **Georeferenced overlay** | Pins an image to the ground by three or four matching points: a commercial satellite shot from a post, a drone frame, an old plan. It draws under the map's own marks with an opacity slider, reprojects as the map pans, and is saved in the case with its control points so the fit can be checked. |
| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |
| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |
| **Sky sessions** | Saves a sun or moon lookup as a case artifact: the point, the date and the time, never the numbers they produce. It reopens where it was left, a proof can show its reading, and a statement can cite it. |
| **Grid sessions in the graph** | Brings the saved AOI grids into the case as entities, adopting the specs already on disk. Grid Search is the last saved tool state living outside the graph, so today nothing can say "this sweep is how I found it". |
| **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 (the live pass and the archive back to 2000, each sensor's real reach asked rather than assumed), archived weather and METAR. |
+| **Event layers** | The rest of what dates an event from the sky: archived weather and METAR, beside the fire detections that already ship. |
| **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. |
| **Ground Imagery** | Ground-level photos: Panoramax/Mapillary/KartaView key-less first; Street View easy link, optional keyed in-app view. |
| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Inspect; still to do: sample a video window directly, seam blending. |
| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes, numbered markers, a redaction/blur box; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
-| **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. |
+| **Detached tool windows** | The rule the map already follows, applied to the rest: a read-and-work surface (Board, Graph, Timeline) opens as many tabs as wanted and the tab it left stays live; a document editor opens one window per document and is greyed out where it was. Cross-tool handoffs route to wherever the tool now lives. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
Edit Provenance rests on three facts about Adobe renders, kept here so the tool
@@ -289,7 +290,6 @@ stops making sense.
- **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.
- **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
diff --git a/docs/UI.md b/docs/UI.md
index 26bfe7c..d792cce 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -1242,12 +1242,92 @@ Editing a place or a capture (**Edit** on any row) sets its title, note, relatio
and My-work folder in one dialog, and is the only place a new folder is created
from the map.
-Map controls sit in two clusters. **Tools** (measure, sun & moon, grid search,
-reference image) float top-left. A tool with settings opens its panel beside that
-cluster, never beneath it, because beneath it is where the map's own controls
-live. **View** — fullscreen, OSM labels, saved work — continues the zoom column
-beneath `+`/`−`, because none of them changes what you are doing, only what you
-see.
+Map chrome sorts into four kinds, each with one place, and a tool declares
+which it is (`lib/map/tools.js`) rather than adding a button somewhere.
+
+- **Modes** — what the pointer does: measure, grid search, sun & moon, and the
+ capture marquee, which is armed from the Capture button rather than from a
+ toolbox. Exactly one is ever armed: arming any of them closes the rest, and
+ Escape disarms whatever is. They sit in the **rail**, a column floating in the
+ map's top-left corner with the zoom buttons stacked under it, grouped by a
+ hairline. An armed seat wears the accent as an edge, not as a filled square.
+ Adding a reference window is in the rail too, as a seat that runs instead of
+ arming.
+- **Its settings** open in the rail's one **panel slot**, beside it. One mode is
+ armed, so one panel is open; a panel cannot cross another or the map's own
+ controls.
+- **Layers** — what is drawn over the imagery: OSM labels, borders, roads, OSM
+ railways, power lines, sea marks, GPS traces, active fires, night lights, the
+ case's saved work, and the points another tool handed over (a sheet's
+ coordinate column, a Timeline window). None of them changes what the
+ pointer does, so none takes a rail seat: they are a list in the Saved panel,
+ each with its own switch. A handoff appears in the list when it arrives and
+ leaves when it is closed, and keeps a Close beside its switch, since hiding a
+ layer and being done with it are two different things. A layer that is a
+ question answers it under its own switch rather than in a card floating over
+ the map: a fixed handful of answers as a row of chips under its own label, an
+ open-ended one — the folders the analyst named — as a list.
+- **The picture** — the provider, the Sentinel-2 layer and date, when the pixels
+ were taken, the eco and usage pills, and the compass — belongs to the
+ *surface*, in its own top-right corner. Which imagery is on screen is a
+ property of that map and not of the tool, which is what lets two surfaces sit
+ side by side each saying its own.
+
+A capture can carry a **scale bar and a north arrow**, ticked in the capture
+menu: the bar bottom-left in the analyst's own units, the needle top-right,
+turned so it points at true north on a map that was rotated. Off until asked
+for, then remembered for every capture after it — it is a house style rather
+than a decision per shot. Neither mark is ever invented: the bar states the
+crop's own resolution, the needle the bearing it was filed with, and a pasted
+screenshot gets neither, since its coordinates describe the map view at filing
+time rather than the picture itself. What was drawn is written into the
+capture's provenance.
+
+Underneath, the **status line** reads where you are (coordinates, zoom, and the
+armed tool's own measurement) on the left, and carries the two acts that take
+something off the map — Save place and Capture — on the right. What marks the
+point, and whether that point is the map's centre or a pin dropped somewhere,
+is one small menu beside them: both are set once and the two acts are pressed
+all day. The engine's scale bracket reads under the coordinates, where how far
+a pixel goes and where you are make one instrument. Fullscreen sits with the
+tool's title, because it is what the window does with the tool rather than what
+the tool does with the map.
+
+**Active fires** are NASA FIRMS, and answer two questions with the same marks:
+what is burning now (the last 24, 48 or 72 hours, or the week) and what was
+burning on a given day (any range back through the archive, up to 31 days).
+Which instrument and which stretch of time are chosen in the row itself. It
+needs a key, and says so with the reason rather than failing on the first tile;
+a key pasted into Settings is picked up on the way back to the map. The
+detections stop being drawn past z14, where FIRMS's fixed symbol per detection
+stops meaning one detection.
+
+**The reference layers** are key-less and each is simply on or off: Esri's
+borders (country, region, district, with names) and roads, Open Infrastructure
+Map's power lines, OpenSeaMap's buoys and harbours, and the raw GPS traces people
+uploaded to OSM, which show tracks nobody has mapped yet. None of them fetches a
+tile before its switch is pressed, and the roads follow the labels' rule: over a
+street map they are greyed, since it already draws them. Power lines are drawn
+from vector tiles in the app's own small style, coloured by voltage on Open
+Infrastructure Map's scale, dashed where the line is buried, with towers from
+zoom 14, substations, plants, pipelines and telecom masts. No overlay reaches a
+capture: a capture stitches one provider.
+
+**Night lights** are one night's VIIRS pass from NASA GIBS, around 01:30 local
+time, or the 2016 cloud-free composite to hold it against. The row picks the
+satellite (NOAA-20 back to 2024-03-25, Suomi NPP back to 2020-11-18) and the
+night, from a calendar that stops at each record's first night and at
+yesterday, since today's pass is still being processed. It sits lowest in the
+stack, slightly see-through so the lit street can be named, and the row says
+that cloud hides lights too.
+
+A date is picked from a calendar the app draws, in the panel rather than over
+it. The browser's own opens at its own size, in its own locale, and half
+outside a panel docked to this edge — and a field reading `12/09/2026` in an app
+that writes `2026-09-12` everywhere else is a date nobody can check. The month
+pushes the rows under it down, walks month by month between the bounds the
+service accepts, and greys the days outside them. The extension's panel draws
+the same calendar from its own copy of the arithmetic.
**Sun & moon** draws one date's path from an anchored point: the arc each body
sweeps while it is up, hour ticks along it, and the bearing at an hour you drag.
@@ -1259,7 +1339,12 @@ body is under the horizon. The anchor is a point and not the map centre, so pann
leaves the path alone. Coords & Sky opens the same mode with its own point, date
and time, and hands over no computed value.
-The saved-work layer is off by default and session-only: places draw as outlined
+The saved-work layer answers two questions under its own switch: **what kind**
+(all, places, captures, proofs) and **which folder**, offered only where the
+case has more than one to choose between. They are the Saved panel's own
+filter, so a map read here and the panel beside it can never disagree about
+what the case holds, and the layer's count is what is drawn rather than what is
+filed. It is off by default and session-only: places draw as outlined
pins, captures and screenshots as filled ones, items at the same spot collapse
into one counted mark, and clicking any mark opens a card
with its preview, provider, dates and note. A mark whose capture carries proofs
@@ -1279,6 +1364,95 @@ 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.
+**A place's card traces its footprint.** A pin dropped on a guess is what this
+fixes: "somewhere on the north quay" is a quay, and the case has always been
+able to hold that shape — until now the only way to fill it was to paste
+GeoJSON into Details. **Trace footprint** on a saved place arms the map, clicks
+drop the corners, and the panel names the place the whole time, counts what is
+missing and takes back the last corner. Nothing is written before Save, so
+Cancel leaves the place exactly as it was, and two shapes are refused here
+rather than by the store: one under three corners, and one that does not contain
+the pin it belongs to. Saved, it draws under its pin like any other footprint,
+and it replaces whatever said how precise the point was — its earlier shape, or
+the circle a radius drew. The panel names what it is replacing before Save, and
+a radius typed back over a traced shape asks in Details before dropping it: the
+map draws one of the two, so a place states its precision once.
+
+**The place dialog hands over to the full editor.** Title, folder, note and
+*Relate to…* are what an analyst fills at the moment of saving; how precise the
+point is, the source's own wording and how the point was found are edited in the
+panel every other surface opens. **Edit more details** on an existing place opens
+that panel — the same body as the case sidebar — and asks first if the short form
+holds something Save has not taken, since the panel opens on what the case holds.
+
+**Esri Wayback is a basemap of every World Imagery release.** Picking it puts a
+chip beside the provider naming the release on screen, and the chip opens a
+slider through time, oldest left, with a step either way and the list under it.
+The list opens on **Changes here**: only the releases that brought a new picture
+of the tile under the crosshair. Esri's tilemap says which release a tile really
+comes from, and walking it backwards finds each change; a picture Esri published
+again, re-encoded or re-coloured, is folded into its first publication by
+comparing the tile's bytes and the acquisition date and satellite its metadata
+states. Each row carries its release date and, beside it, when the picture was
+taken; the pill under the chip dates the pixels on screen the same way. Narrowed
+to changes, the newest release is named by the change it shows rather than by a
+date no row carries. **Every release** lists all of them, where neighbours
+often look identical because nothing changed there. The history is read when the
+picker opens, takes some seconds (Esri's metadata service is slow), and is read
+again once the map settles in another tile; until it arrives, and when it
+fails, every release stays on offer. The release rides on the provider id
+(`esri-wayback~64776`), so tiles are cached and captures credited under it.
+
+**Right-click the ground** and a menu acts on that point rather than on the
+centre: copy it in every coordinate format, the analyst's own first; ask what
+is there, answered inside the menu; save a place there; start a distance from
+it; anchor the sun and moon on it; open its Wayback history; centre the map
+on it; or open it in another map site. A right-click on a shape that answers
+its own (a search-grid cell) stays that shape's. The menu flips away from the
+map's edges, walks with the arrow keys, and closes on Escape, a press outside,
+or a zoom that moves the ground from under it.
+
+**The map opens in as many tabs as there are screens.** `⧉` beside the title
+opens this map again in a tab of its own, on the view it is showing — a tab
+rather than a pop-up window, because a tab can be torn onto the second screen
+and put back, and is what a browser does not refuse. It opens on the map alone:
+the workspace rail, the case bar and the tab strip are how you get somewhere
+else, and they stay in the window they belong to. It is still a whole map, and
+the tab it left is not greyed out: a read-and-work surface takes as many windows
+as are wanted, while a document editor (Geo Proof, Notebook, Sheet) stays one
+window per document.
+
+What is per window is the camera: where it is pointed, at what zoom and bearing,
+over which imagery. That rides in the window's own address
+(`#satellite?ll=48.8566,2.3522&z=17&b=215&p=esri`), which is what makes a reload
+come back to the same ground and a view worth keeping as a link. An address is
+something a person can type, so a coordinate or a zoom it cannot vouch for
+leaves the map where it was rather than flying it nowhere. Panning rewrites the
+address in place: a back button holding four hundred camera positions would be
+worse than none. Everything else — the case, its saved points, a sweep in
+progress — is shared already, below.
+
+A detached tab carries its number in its title and its heading, because two
+identical maps on a second screen cannot otherwise be told apart, and `solo=1`
+in the same address, which is what keeps it the map alone across a reload. The
+first window is unnumbered. The browser can refuse a second tab, and says so.
+
+**⛓ points the tabs at one camera.** It is greyed until a second map tab is
+open, because linking one tab to nothing is a button that does nothing — the
+tabs say hello to each other on the same channel the camera travels on, and a
+link already on is dropped when the last of them goes. Pressing it hands the
+other linked tabs this tab's view, and from then on a pan or a zoom in any of
+them carries the rest. It is per tab and off by default: two maps are worth linking while they
+are being compared and in the way of each other the rest of the time. Two
+linked tabs on two providers are a first version of Compare — and the camera
+travels between tabs of the same browser, never over the network, because a
+view is not case state. The extension's map tools join the same link from
+Google, Bing, Earth and the other sites they draw on: an open panel counts as a
+second map, follows this tab's camera and leads it (`extension/README.md`). A
+panel in a background tab keeps the view until that tab is looked at, because
+following one costs those sites a reload; the app's own tabs have none to pay
+and follow wherever they are.
+
**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
@@ -2289,3 +2463,19 @@ instrument style of QGIS, Google Earth Pro, Resolve and Lightroom.
entities with provenance so Suggestions/Details work.
4. Tests accompany the tool (repo rule); pure logic goes in `lib/` with a
`.test.js`.
+
+## Adding a tool to the map (checklist)
+
+A tool that works *on* the map is not a rail seat of its own: it joins the map's
+own registry.
+
+1. Declare it in `lib/map/tools.js` — a mode (it changes what a click means), an
+ action (it runs and arms nothing), or a layer (it is drawn and toggled).
+2. A mode says which cursor the surface wears while it is armed, and whether it
+ brings a panel. Its store answers `isOn` / `open` / `close`, plus `pointing`
+ when being armed is not the same as waiting for a click. Exclusion is then
+ automatic — nothing else has to be told the new tool exists.
+3. A mode's reading goes in the status line, not in its panel: a number the map
+ is telling you belongs beside the coordinates.
+4. Keep the rail at seven seats or fewer. The eighth files itself under an
+ existing group with a flyout.
diff --git a/extension/README.md b/extension/README.md
index c5ac851..272cf16 100644
--- a/extension/README.md
+++ b/extension/README.md
@@ -11,10 +11,15 @@ app.
It supports six flows:
- On a supported map site, the popup can capture a selected area or save its
- coordinates as a place.
+ coordinates as a place. A capture can carry a scale bar and a north arrow,
+ ticked in the popup and remembered from then on; the app draws them, from the
+ zoom and the pixel ratio the grab was taken at. Most of these sites write no
+ rotation into their URL, so the needle waits for a bearing in the field above
+ rather than pointing at a guess.
- 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.
+ pins, sun and moon, a search grid, the case's own images and videos held over
+ the map, and NASA FIRMS fire detections laid over whatever that map is
+ showing.
- 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
@@ -95,7 +100,7 @@ than hidden:
## 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:
+on. Press it again to close it. Six tools share it:
| Tool | What it does |
|---|---|
@@ -104,11 +109,43 @@ on. Press it again to close it. Five tools share it:
| 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. |
+| Fires | Lays NASA FIRMS thermal detections over the site: the last 24 h to 7 days, or any past day or range up to 31 days picked from a calendar drawn inside the panel. Needs a FIRMS key in Azimut's own Settings — without one the seat is greyed and says so — and stops at z14 where one mark stops meaning one detection. |
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.
+an open sweep all come back when you pick it up again. Reference windows and the
+fire layer are the exceptions: the windows are not on the map, and the fires are
+ground rather than drawing, so both stay while you measure over them.
+
+**Link the view** with the chain button in the panel's header. It puts this map on
+one camera with the other linked maps: other panels on other sites, and the app's
+own map tabs whose link is pressed. It is greyed until there is a second map to
+link to. Pressing it brings the others to this map; from then on a pan or a zoom
+here moves them, and one there moves this.
+
+A site's map is moved by writing the view into its address bar, so Google, Bing,
+Apple, Yandex, Earth and Copernicus reload to follow, and the panel comes back on
+its own once the page has loaded. OpenStreetMap, Zoom Earth and Satellites.pro take
+it without reloading. Only moving a map yourself leads: a map that arrived because
+it was sent stays quiet.
+
+A tab in the background waits. It keeps the last view it was sent and goes there
+when you come back to it, so a site reloads once instead of once per gesture on the
+map you are moving. A tab you can see follows straight away, including the front
+tab of a window you are not typing in.
+
+Each map follows as close as it goes. Zoom Earth stops at 11, Copernicus at 18,
+Google at 21, and the others are not asked to stop there with it: the status line
+says "as close as this map goes" instead. Street View and a tilted camera are left
+where they are. Apple opens no view nearer a pole than 70.5°, so a view past it
+stops there and the rest is a drag. A map already stopped at the limit is left
+alone by a view asking for the same ground again, rather than reloaded once per
+gesture on the map it follows. While an Apple place card is open the page
+hides where the map is, and the panel waits until the card is closed.
+
+On Firefox the panel may not come back after a reload on Apple, Earth or
+Copernicus, which the extension holds no host permission for. The other panels
+say so, and pressing the toolbar button on that tab puts it back.
**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.
@@ -132,53 +169,53 @@ 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
+Google's satellite view, a span in degrees for Apple, a camera distance and a field
+of view for Google Earth. Each of those was checked in a real browser before being
+believed (`docs/MAP_SITES.md`), and the drawing works from the first frame, with
+nothing to calibrate. Nothing is ever measured off a drag: a drag loses pixels to
+the site's own threshold and gains them to its glide, which is how Earth's marks
+once ended up four times too close together.
+
+**It starts placed, and a zoom places it better.** 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
+header. The app ships what its own calibration run measured, so a fresh install
+draws from the right pixel on the sites whose chrome does not move
+(`docs/MAP_SITES.md`). Apple's sidebar does move — it folds away in a narrow
+window — so Apple starts at the middle and is measured instead.
+
+Measuring it takes a zoom. A pan can never see the offset, because it slides along
+with the map; 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 status line says "zoom once to place it",
+and the tooltip on that line carries the offset being drawn from and where it came
+from — which is what to read when something lands somewhere the ground is not.
+
+**Google Earth is read like the others.** Its 2D map is Web Mercator, drawn about
+the middle of the window, and `d` and `y` in its address bar give the scale. A link
+written by hand, or the app's own "Open in Google Earth", has no ground height in
+it, and Earth draws it nearer than it says. So until you move the map once, which
+is when Earth writes the ground in, the panel shows "Move the map once so its
+address bar gives the scale" and draws nothing.
+
+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.
+Earth's 3D mode and Google's Earth 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 3D
+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. Earth's 2D map has no such problem.
**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",
+let go and ease into a zoom. A drag is followed exactly, because the map goes where
+the pointer goes; the glide and the zoom are not followed at all. The drawing comes
+back once the address bar has stopped changing, which on Earth is after the last of
+the several addresses it writes during one zoom. 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
@@ -204,18 +241,23 @@ 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.
+with it. Only tilting the camera switches the geometric tools off.
+
+Zoomed far out there are two cases and they get different answers. On a **flat
+map drawn small** — Google and Bing below level 8 — 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.
+
+On a **globe camera** (Earth's 3D mode more than 150 km out, and Google's Earth
+mode with it) nothing is drawn: no marks, no grid, no fire picture. That view is a
+perspective shot of a sphere, with no point the flat arithmetic is right about
+and no edge the error stays in, so the panel says "The camera is on a globe this
+far out, so zoom in" instead of dimming something nobody can judge. Come down and
+everything draws again. Earth's 2D map stays flat however far out you go, so it is
+never refused.
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
diff --git a/extension/background.js b/extension/background.js
index fbaff7b..de7171b 100644
--- a/extension/background.js
+++ b/extension/background.js
@@ -30,7 +30,12 @@ function captureActiveTab(windowId) {
/** Crop a captured frame (dataURL) to a viewport-CSS-px rect. The scale is
* measured (image width / viewport width), not assumed from devicePixelRatio,
- * so browser zoom can't silently shift the crop — same rule as the app. */
+ * so browser zoom can't silently shift the crop — same rule as the app.
+ *
+ * Returns the crop *and* that scale: the crop keeps the frame's own pixels, so
+ * the file holds `scale` of them per CSS pixel, and a zoom describes CSS
+ * pixels. Anything the app draws with a distance on it needs the ratio, or a
+ * scale bar on a 2× screen states twice the ground it covers. */
async function cropDataUrl(dataUrl, rect, viewportW) {
const blob = await (await fetch(dataUrl)).blob();
const bmp = await createImageBitmap(blob);
@@ -42,7 +47,7 @@ async function cropDataUrl(dataUrl, rect, viewportW) {
if (sw < 8 || sh < 8) throw new Error("selection too small");
const canvas = new OffscreenCanvas(sw, sh);
canvas.getContext("2d").drawImage(bmp, sx, sy, sw, sh, 0, 0, sw, sh);
- return canvas.convertToBlob({ type: "image/png" });
+ return { blob: await canvas.convertToBlob({ type: "image/png" }), scale };
}
/** File one screenshot with the backend (POST /api/ingest/screenshot). */
@@ -60,6 +65,10 @@ async function ingest(blob, meta) {
for (const k of ["lat", "lon", "zoom", "bearing"]) {
if (meta[k] !== null && meta[k] !== undefined && meta[k] !== "") form.append(k, String(meta[k]));
}
+ if (meta.marks) {
+ form.append("scale_north", "true");
+ form.append("device_scale", String(meta.deviceScale || 1));
+ }
form.append("captured_at", new Date().toISOString());
form.append("extension", api.runtime.getManifest().version);
let r;
@@ -420,8 +429,14 @@ const MAP_ROUTES = new Set([
"/api/ingest/grid/marks",
"/api/ingest/place",
"/api/ingest/media",
+ "/api/ingest/firms/sensors",
]);
+// …and the ones that answer with bytes. Separate because the relay above parses
+// what comes back as JSON, and because a route that hands over a picture is
+// worth listing where it can be seen rather than inferred from a content type.
+const MAP_IMAGE_ROUTES = new Set(["/api/ingest/firms"]);
+
//. Injected in this order: each one reads the globals the ones before it left.
const MAP_FILES = [
"mapmath.js",
@@ -429,6 +444,7 @@ const MAP_FILES = [
"maptools.js",
"mapdraw.js",
"mapref.js",
+ "maplink.js",
"mapoverlay.js",
];
@@ -473,6 +489,34 @@ async function mapApi(msg) {
return text ? JSON.parse(text) : null;
}
+/**
+ * A picture the app draws for the panel — today, NASA FIRMS over the view.
+ *
+ * Two reasons it is not `mapApi`: what comes back is bytes rather than JSON,
+ * and it is handed over as a data URL because a content script cannot hold the
+ * app's blob URL. The refusal is still read as the app's own sentence, since
+ * FIRMS says exactly what is wrong with a key and that is worth repeating.
+ */
+async function mapImage(msg) {
+ if (!MAP_IMAGE_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);
+ }
+ let r;
+ try {
+ r = await fetch(url, { 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 `data:${blob.type || "image/png"};base64,${await base64(blob)}`;
+}
+
/**
* One of the case's files, for a reference window (`extension/mapref.js`).
*
@@ -696,6 +740,269 @@ api.runtime.onConnect.addListener((port) => {
pumpEvents();
});
+// --- linked views --------------------------------------------------------------
+//
+// The app's Link button puts two of its map tabs on one camera over a
+// BroadcastChannel (`frontend/src/lib/map/link.js`). A panel on a site's map
+// cannot join that channel — it is another origin — so the worker is the hub for
+// everything the channel cannot reach: panel to panel, and panel to app, whose
+// bridge opens a port here for each map tab (`bridge.js`).
+//
+// A panel follows a view by writing it into its own address bar
+// (`maplink.js`), and most sites reload for that. A reload takes the panel with
+// it, so two facts have to outlive the page and live here: which tabs are linked,
+// and which one is on its way to a view it was sent. The second is what puts the
+// tools back once the page has loaded (`resumeFollow`), and what keeps a tab
+// counted as a peer while it reloads: without it the tab leading would see its
+// only peer vanish mid-follow and switch its own link off.
+//
+// Nothing here is written down beyond the session, and nothing reaches the
+// network: a camera is not case state.
+
+const LINK_PORT = "map-link";
+/** How long a tab that left to follow a view is waited for. Earth takes a
+ * dozen seconds to load on a machine without a GPU. */
+const FOLLOW_GRACE_MS = 30000;
+
+/** Every port on the link: `{ tabId, app }`, where `app` is one of the app's
+ * own map tabs rather than a panel. */
+const linkPorts = new Map();
+/** `{ linked: tabId[], following: { [tabId]: { at, view, pending } } }`,
+ * mirrored to storage.session because the worker may be evicted between two
+ * gestures. `pending` is a camera sent while that tab was away reloading. */
+let linkMemo = null;
+/** Tabs whose tools are being put back, so a page that reports "complete" twice
+ * is not injected twice — a second injection closes the panel. */
+const resuming = new Set();
+
+async function linkMemory() {
+ if (!linkMemo) {
+ const stored = (await api.storage.session.get({ mapLink: null }))?.mapLink;
+ linkMemo = { linked: stored?.linked ?? [], following: stored?.following ?? {} };
+ }
+ return linkMemo;
+}
+
+function rememberLinks() {
+ api.storage.session.set({ mapLink: linkMemo });
+}
+
+/** Tabs still waited for, the stale ones dropped on the way. */
+function waitedFor(memo) {
+ const now = Date.now();
+ for (const [tabId, follow] of Object.entries(memo.following)) {
+ if (now - follow.at >= FOLLOW_GRACE_MS) delete memo.following[tabId];
+ }
+ return memo.following;
+}
+
+/** Only the four numbers of a camera cross the hub, and only real ones. */
+function linkView(view) {
+ const ok =
+ view &&
+ Number.isFinite(view.lat) &&
+ Number.isFinite(view.lon) &&
+ Number.isFinite(view.zoom) &&
+ Math.abs(view.lat) <= 90 &&
+ Math.abs(view.lon) <= 180;
+ if (!ok) return null;
+ return { lat: view.lat, lon: view.lon, zoom: view.zoom, bearing: Number.isFinite(view.bearing) ? view.bearing : 0 };
+}
+
+function linkPost(port, message) {
+ try {
+ port.postMessage(message);
+ } catch {
+ // the tab went while this was in hand; its disconnect is already queued
+ }
+}
+
+/**
+ * Tell every port how many others it could link to.
+ *
+ * A panel counts everything else on the link. An app tab counts only panels,
+ * because it already counts the app's other tabs on its own channel. A tab
+ * reloading on its way to a view counts for both, for as long as it is waited
+ * for.
+ */
+function linkPeers() {
+ const panels = [...linkPorts.values()].filter((who) => !who.app);
+ const present = new Set(panels.map((who) => who.tabId));
+ const returning = linkMemo
+ ? Object.keys(waitedFor(linkMemo)).filter((tabId) => !present.has(Number(tabId))).length
+ : 0;
+ for (const [port, who] of linkPorts) {
+ const count = who.app ? panels.length + returning : linkPorts.size - 1 + returning;
+ linkPost(port, { type: "link-peers", count });
+ }
+}
+
+/**
+ * Keep a camera for every linked tab that is away reloading.
+ *
+ * A panel that left to follow one view is not connected while its page loads,
+ * and the analyst does not wait for it: the map being led goes on moving. Each
+ * of those cameras used to be dropped, and the tab landed on the first and stayed
+ * there. Only the last one matters, and the tab is handed it when it is back.
+ */
+function holdForReturning(memo, view, fromTabId) {
+ const present = new Set([...linkPorts.values()].filter((who) => !who.app).map((who) => who.tabId));
+ let held = false;
+ for (const [tabId, follow] of Object.entries(waitedFor(memo))) {
+ const id = Number(tabId);
+ if (id === fromTabId || present.has(id) || !memo.linked.includes(id)) continue;
+ follow.pending = view;
+ held = true;
+ }
+ if (held) rememberLinks();
+}
+
+async function onLinkMessage(port, msg) {
+ const who = linkPorts.get(port);
+ if (!who || !msg) return;
+ const memo = await linkMemory();
+ if (who.app) {
+ // An app tab only ever speaks a camera, and only to the panels: the app's
+ // other tabs heard it on their own channel.
+ const view = msg.type === "view" ? linkView(msg.view) : null;
+ if (!view) return;
+ for (const [other, them] of linkPorts) {
+ if (!them.app && memo.linked.includes(them.tabId)) linkPost(other, { type: "view", view });
+ }
+ holdForReturning(memo, view, null);
+ return;
+ }
+ if (msg.type === "link") {
+ memo.linked = memo.linked.filter((id) => id !== who.tabId);
+ if (msg.on) memo.linked.push(who.tabId);
+ else delete memo.following[who.tabId];
+ rememberLinks();
+ linkPost(port, { type: "link-state", linked: !!msg.on, asked: null });
+ return;
+ }
+ if (msg.type === "follow") {
+ memo.following[who.tabId] = { at: Date.now(), view: linkView(msg.view) };
+ rememberLinks();
+ // the count drops back once the wait is over, whether or not the tab came
+ setTimeout(linkPeers, FOLLOW_GRACE_MS + 50);
+ return;
+ }
+ if (msg.type === "landed") {
+ // a hash the site took without reloading: the panel never left
+ delete memo.following[who.tabId];
+ rememberLinks();
+ return;
+ }
+ if (msg.type === "view") {
+ const view = linkView(msg.view);
+ if (!view || !memo.linked.includes(who.tabId)) return;
+ for (const [other, them] of linkPorts) {
+ if (other === port) continue;
+ if (them.app || memo.linked.includes(them.tabId)) linkPost(other, { type: "view", view });
+ }
+ holdForReturning(memo, view, who.tabId);
+ }
+}
+
+async function openLink(port) {
+ const tab = port.sender?.tab;
+ if (!tab?.id && tab?.id !== 0) {
+ port.disconnect();
+ return;
+ }
+ const who = { tabId: tab.id, app: isAppUrl(tab.url) };
+ linkPorts.set(port, who);
+ // before anything is awaited, so nothing the port says first is missed
+ port.onMessage.addListener((msg) => onLinkMessage(port, msg));
+ port.onDisconnect.addListener(() => {
+ linkPorts.delete(port);
+ linkPeers();
+ });
+ const memo = await linkMemory();
+ if (!who.app) {
+ // A panel arriving where it was sent: it hears that it is linked, the view
+ // it was sent to (so it can say how close this map came), and whatever the
+ // map it follows did while it was loading. The wait itself stands until it
+ // runs out: a site may load a second document, and the tools go back on that
+ // one too.
+ const follow = waitedFor(memo)[tab.id];
+ const linked = memo.linked.includes(tab.id);
+ linkPost(port, { type: "link-state", linked, asked: follow?.view ?? null });
+ if (follow?.pending && linked) {
+ linkPost(port, { type: "view", view: follow.pending });
+ delete follow.pending;
+ rememberLinks();
+ }
+ }
+ linkPeers();
+}
+
+api.runtime.onConnect.addListener((port) => {
+ if (port.name === LINK_PORT) openLink(port);
+});
+
+/**
+ * Put the tools back on a tab that reloaded to follow a view.
+ *
+ * Only a tab that said it was leaving for one, and only while it is waited for:
+ * a linked tab the analyst reloads, or navigates somewhere else, loses its panel
+ * the way any tab does. The panel is looked for first because a site that takes
+ * the view in its hash reports "complete" without ever unloading it, and
+ * injecting an open panel again is what closes it.
+ *
+ * A browser may refuse, and that is the one real cost of following by address:
+ * where the extension holds no host permission, the tools were only ever allowed
+ * on the page that was open when the button was pressed. The other linked panels
+ * say so rather than leaving a tab that silently stopped following.
+ */
+/** How often, and how far apart, a refused injection is tried again. A page
+ * that reports "complete" can still be swapping its document, and the first
+ * refusal is often only that. */
+const RESUME_TRIES = 3;
+const RESUME_RETRY_MS = 1000;
+
+async function resumeFollow(tabId, attempt = 1) {
+ const memo = await linkMemory();
+ const follow = waitedFor(memo)[tabId];
+ if (!follow || resuming.has(tabId)) return;
+ resuming.add(tabId);
+ try {
+ const [probe] = await api.scripting.executeScript({
+ target: { tabId },
+ func: () => Boolean(window.__AZIMUT_MAP_TOOLS__),
+ });
+ if (!probe?.result) await api.scripting.executeScript({ target: { tabId }, files: MAP_FILES });
+ } catch {
+ if (attempt < RESUME_TRIES) {
+ setTimeout(() => resumeFollow(tabId, attempt + 1), RESUME_RETRY_MS);
+ return;
+ }
+ delete memo.following[tabId];
+ memo.linked = memo.linked.filter((id) => id !== tabId);
+ rememberLinks();
+ for (const [port, who] of linkPorts) {
+ if (!who.app) {
+ linkPost(port, { type: "link-note", note: "A linked tab reloaded and the browser kept its tools off. Open them there again" });
+ }
+ }
+ linkPeers();
+ } finally {
+ resuming.delete(tabId);
+ }
+}
+
+api.tabs.onUpdated.addListener((tabId, info) => {
+ if (info?.status === "complete") resumeFollow(tabId);
+});
+
+api.tabs.onRemoved?.addListener(async (tabId) => {
+ const memo = await linkMemory();
+ if (!memo.linked.includes(tabId) && !memo.following[tabId]) return;
+ memo.linked = memo.linked.filter((id) => id !== tabId);
+ delete memo.following[tabId];
+ rememberLinks();
+});
+
// --- message routes ------------------------------------------------------------
async function handle(msg, sender) {
@@ -737,8 +1044,8 @@ async function handle(msg, sender) {
if (msg.type === "area-cancelled" || !meta) return { ok: true };
try {
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);
+ const { blob, scale } = await cropDataUrl(dataUrl, msg.rect, msg.viewportW);
+ const body = await ingest(blob, { ...meta, deviceScale: scale });
notify("Capture filed into Azimut", body.title);
return { ok: true };
} catch (e) {
@@ -790,6 +1097,15 @@ async function handle(msg, sender) {
}
}
+ // The panel, asking for a picture to lay over the map.
+ if (msg.type === "map-image") {
+ try {
+ return { ok: true, src: await mapImage(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 {
diff --git a/extension/bridge.js b/extension/bridge.js
index 9464e67..25aa381 100644
--- a/extension/bridge.js
+++ b/extension/bridge.js
@@ -79,6 +79,55 @@
},
};
+ // A map tab's end of the linked views (`background.js`, "linked views"). The
+ // app opens it while its map is mounted: panels on other sites hand their
+ // cameras over it, and hear this tab's. A port rather than one message per
+ // camera, because the worker counts who is on the link by who is connected.
+ let link = null;
+ let linkWanted = false;
+ const LINK_RETRY_MS = 2000;
+
+ function openLink() {
+ if (link || !linkWanted || !current()) return;
+ try {
+ link = api.runtime.connect({ name: "map-link" });
+ } catch {
+ link = null;
+ return;
+ }
+ link.onMessage.addListener((msg) => {
+ if (!current()) return;
+ if (msg?.type === "view") post({ type: "map-link-event", kind: "view", view: msg.view });
+ if (msg?.type === "link-peers") post({ type: "map-link-event", kind: "peers", count: msg.count });
+ });
+ // an evicted worker takes the port with it; the next one is a retry away
+ link.onDisconnect.addListener(() => {
+ link = null;
+ if (linkWanted) setTimeout(openLink, LINK_RETRY_MS);
+ });
+ }
+
+ function onLink(msg) {
+ if (msg.kind === "open") {
+ linkWanted = true;
+ openLink();
+ } else if (msg.kind === "close") {
+ linkWanted = false;
+ try {
+ link?.disconnect();
+ } catch {
+ /* already gone */
+ }
+ link = null;
+ } else if (msg.kind === "view" && link) {
+ try {
+ link.postMessage({ type: "view", view: msg.view });
+ } catch {
+ // the port died between the check and the send; the retry reopens it
+ }
+ }
+ }
+
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;
@@ -89,6 +138,10 @@
post({ type: "pong", id: msg.id, version: VERSION });
return;
}
+ if (msg.type === "map-link") {
+ onLink(msg);
+ return;
+ }
const relay = RELAYS[msg.type];
if (!relay) return;
diff --git a/extension/maplink.js b/extension/maplink.js
new file mode 100644
index 0000000..836dc42
--- /dev/null
+++ b/extension/maplink.js
@@ -0,0 +1,345 @@
+/**
+ * One camera, written into someone else's address bar.
+ *
+ * The app links two of its own map tabs by handing a camera over a channel
+ * (`frontend/src/lib/map/link.js`) and calling `setView` with it. A site's map
+ * has no `setView` this extension may call. What it has is an address the site
+ * reads when it loads and, on a few of them, whenever its hash changes — so a
+ * view is followed by writing it there, and the site does the moving.
+ *
+ * Three rules come out of driving the sites in a browser (`docs/MAP_SITES.md`,
+ * "Following a linked view"):
+ *
+ * - **Only the camera is rewritten.** The layer, Copernicus's acquisition date,
+ * Zoom Earth's day, Earth's 2D or 3D mode and whatever place Google was
+ * showing all live in the same address, and a view that followed a peer by
+ * dropping them would be a different map at the same spot.
+ * - **The address has to be true the moment it lands**, because the tools read
+ * their scale from it. Google opens a `16.5z` (or the same view as metres) at
+ * level 16 and goes on saying 16.5 until the map is touched, so it is given
+ * whole levels; so is every site not measured taking a fraction. Bing takes one
+ * decimal, Apple's span and Earth's distance are read back as they land.
+ * - **Each map follows as close as it goes, and nothing asks the others to
+ * stop there.** Zoom Earth stops at 11 and Bing at 22, and both rewrite their
+ * address to say so. Google (21), OpenStreetMap (19) and Copernicus (18) keep
+ * a level they are not drawing until the map is touched, so what is *written*
+ * there is held to what they draw (`WRITE_CEILING`). The camera being followed
+ * is never touched.
+ *
+ * Classic script, no build step, like the rest of the panel. The camera
+ * comparison is `link.js`'s, copied; `extensionMapLink.test.js` runs both.
+ */
+(() => {
+ /** Metres of ground per pixel at the equator, zoom 0, on 256-pixel tiles. */
+ const EQUATOR_M_PER_PX = (2 * Math.PI * 6378137) / 256;
+ const MAX_LAT = 85.05112877980659;
+
+ /**
+ * The deepest level worth writing into a site that will not correct the
+ * address itself, measured over Paris.
+ *
+ * Opened past these, each one draws the level below and goes on quoting the
+ * one it was given until the map is moved: Google `23z` draws 21,
+ * OpenStreetMap `#map=20` draws 19, Copernicus `zoom=23` draws 18 (its wheel
+ * goes further, a link does not). The sites left out rewrite a level they
+ * cannot draw (Bing, Zoom Earth) or state a size the parser reads instead
+ * (Apple's span, Earth's distance). Yandex and Satellites.pro refuse a
+ * headless browser and are unmeasured.
+ */
+ const WRITE_CEILING = { "google-maps": 21, openstreetmap: 19, "copernicus-browser": 18 };
+
+ /**
+ * How near a pole a site will open a view, in degrees of latitude.
+ *
+ * Apple moves any address past ±70.4956° back to it on load, `?ll=` and
+ * `/frame` alike, at every zoom (measured over Svalbard and the Ross Sea).
+ * Dragged, its map goes on north and its address with it, so this is a limit
+ * on following and never on the drawing.
+ */
+ const OPEN_LAT_LIMIT = { "apple-maps": 70.495574 };
+
+ /** The closest Earth's camera comes to the ground, in metres. A nearer one
+ * is not a camera Earth placed (`engine/mapsites.py`, `EARTH_CLOSEST_M`). */
+ const EARTH_CLOSEST_M = 25;
+
+ /** Under a tenth of this and two cameras are pointed at the same thing
+ * (`link.js`, copied). */
+ const PLACES = 5;
+ const BEARING_EPSILON = 0.5;
+
+ /** How much shallower than asked a map may land and still count as there:
+ * a site given whole levels is up to half of one out by rounding alone. */
+ const SHORT_BY = 0.5;
+ /** How close to the view it was sent to a map has to be to count as having
+ * arrived: a few hundred metres, well inside any rounding a site does. */
+ const NEAR_DEG = 0.005;
+
+ function sameCamera(a, b) {
+ if (!a || !b) return false;
+ return (
+ a.lat.toFixed(PLACES) === b.lat.toFixed(PLACES) &&
+ a.lon.toFixed(PLACES) === b.lon.toFixed(PLACES) &&
+ Math.round(a.zoom) === Math.round(b.zoom) &&
+ Math.abs((a.bearing ?? 0) - (b.bearing ?? 0)) < BEARING_EPSILON
+ );
+ }
+
+ /** A camera worth sending or following: anything else moves a map to nowhere. */
+ function readable(view) {
+ return Boolean(
+ view &&
+ Number.isFinite(view.lat) &&
+ Number.isFinite(view.lon) &&
+ Number.isFinite(view.zoom) &&
+ Math.abs(view.lat) <= 90 &&
+ Math.abs(view.lon) <= 180
+ );
+ }
+
+ /**
+ * Whether this view can lead or follow at all.
+ *
+ * The same test the tools use for geometry: a flat map, looked at straight
+ * down, whose address states a scale. Street View, a pitched camera and a
+ * globe have no tile level to hand over, and moving one to a peer's level
+ * would throw away the view the analyst chose to be on.
+ */
+ function followable(parsed) {
+ return Boolean(
+ parsed?.site &&
+ parsed.view_kind === "map" &&
+ parsed.geometry &&
+ parsed.scale_source &&
+ readable({ lat: parsed.lat, lon: parsed.lon, zoom: parsed.zoom })
+ );
+ }
+
+ const fixed = (n, digits) => String(Number(n.toFixed(digits)));
+
+ /** Metres of ground one CSS pixel covers at this level and latitude. */
+ function metresPerPx(zoom, lat) {
+ return (EQUATOR_M_PER_PX * Math.cos((lat * Math.PI) / 180)) / 2 ** zoom;
+ }
+
+ /** The level actually worth writing into this site. */
+ function writableZoom(site, zoom) {
+ const ceiling = WRITE_CEILING[site];
+ return ceiling == null ? zoom : Math.min(zoom, ceiling);
+ }
+
+ /** The latitude this site will open, whatever it is handed. */
+ function openLat(site, lat) {
+ const limit = OPEN_LAT_LIMIT[site];
+ return limit == null ? lat : Math.max(-limit, Math.min(limit, lat));
+ }
+
+ /**
+ * The view this site really opens when it is sent this one.
+ *
+ * A site is written the camera it will honour rather than the one it was asked
+ * for, and the difference is not cosmetic. An address stating a view the site
+ * then moves away from is the address the tools take their ground from, so the
+ * drawing lands where the map is not until the site rewrites it — Apple past
+ * ±70.4956° did exactly that. And it is what a map already at its limit is
+ * compared against, so the next gesture on the map it follows does not reload
+ * it to put it back where it already was, on top of a drag the panel had just
+ * asked the analyst for.
+ */
+ function reachable(site, view) {
+ if (!readable(view)) return view;
+ return { ...view, lat: openLat(site, view.lat), zoom: writableZoom(site, view.zoom) };
+ }
+
+ /** The URL with one query parameter set, the rest left as the site wrote it. */
+ function withParams(url, params) {
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
+ return url.toString();
+ }
+
+ // --- one writer per site, each the inverse of its parser --------------------
+
+ const WRITERS = {
+ /**
+ * `@lat,lon,17z`, over the `,17z` or the satellite view's `,3231m` alike.
+ * Google turns a level into its own metres on arrival and keeps the layer,
+ * which lives after the camera block, so everything there stays.
+ */
+ "google-maps"(url, view) {
+ const camera = /@-?\d+(?:\.\d+)?,-?\d+(?:\.\d+)?,\d+(?:\.\d+)?[zm](?=\/|$)/;
+ if (!camera.test(url.pathname)) return null;
+ url.pathname = url.pathname.replace(
+ camera,
+ `@${fixed(view.lat, 7)},${fixed(view.lon, 7)},${Math.round(view.zoom)}z`
+ );
+ return url.toString();
+ },
+
+ /**
+ * `@lat,lon,Na,Nd,Ny,Nh,Nt,Nr`. The distance is worked out from the height
+ * the window covers, through the field of view the address already carries.
+ * Earth puts the camera `a + d` above sea level, and the ground under the new
+ * centre is not in any address, so `a` is left as it was: the scale is out by
+ * how far the ground rose or fell between the two places, over the distance,
+ * until Earth writes the real one in on the first gesture.
+ */
+ "google-earth"(url, view, height) {
+ const camera = /@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),([^/]*)/;
+ const found = url.pathname.match(camera);
+ if (!found || !(height > 0)) return null;
+ const fields = found[3].split(",");
+ const fov = Number((fields.find((f) => /y$/.test(f)) ?? "").slice(0, -1));
+ if (!(fov > 0 && fov < 180)) return null;
+ const tall = metresPerPx(view.zoom, view.lat) * height;
+ const distance = Math.max(EARTH_CLOSEST_M, tall / (2 * Math.tan((fov * Math.PI) / 360)));
+ // A view Earth never placed (`0a`, a typed link) stays one: a whole `d` next
+ // to it is what the parser reads as "not placed yet", and the panel asks
+ // for a gesture rather than drawing at a scale out by the ground's height.
+ const ground = Number((fields.find((f) => /a$/.test(f)) ?? "").slice(0, -1));
+ const size = ground === 0 ? String(Math.round(distance)) : fixed(distance, 2);
+ const rewritten = fields.map((f) => (/^-?\d+(?:\.\d+)?d$/.test(f) ? `${size}d` : f));
+ url.pathname = url.pathname.replace(
+ camera,
+ `@${fixed(view.lat, 8)},${fixed(view.lon, 8)},${rewritten.join(",")}`
+ );
+ return url.toString();
+ },
+
+ /** `?cp=lat~lon&lvl=17`, one decimal as Bing writes it. */
+ "bing-maps"(url, view) {
+ return withParams(url, { cp: `${fixed(view.lat, 6)}~${fixed(view.lon, 6)}`, lvl: fixed(view.zoom, 1) });
+ },
+
+ /** `?ll=lon,lat&z=17` — longitude first, and a whole level until a fraction
+ * is measured landing true. */
+ "yandex-maps"(url, view) {
+ return withParams(url, { ll: `${fixed(view.lon, 6)},${fixed(view.lat, 6)}`, z: String(Math.round(view.zoom)) });
+ },
+
+ /** `#map=17/lat/lon`. A whole level: the site's map snaps to one. */
+ openstreetmap(url, view) {
+ const hash = url.hash.replace(/^#/, "");
+ const camera = `map=${Math.round(view.zoom)}/${fixed(view.lat, 5)}/${fixed(view.lon, 5)}`;
+ url.hash = /map=[^&]*/.test(hash) ? hash.replace(/map=[^&]*/, camera) : camera;
+ return url.toString();
+ },
+
+ /**
+ * `/frame?center=lat,lon&z=17`, the form Apple redirects a link to. Its `z`
+ * is read when the page opens and never again, and a span in the same
+ * address outranks it, so only the layer is carried over. A page still on
+ * the link form (`?ll=`) is written in that form and redirected by Apple
+ * itself; a place card (`/place?…&coordinate=`) is closed by the move.
+ */
+ "apple-maps"(url, view) {
+ const linkForm = url.pathname === "/";
+ const next = new URL(linkForm ? "/" : "/frame", url);
+ for (const key of ["map", "t"]) {
+ if (url.searchParams.has(key)) next.searchParams.set(key, url.searchParams.get(key));
+ }
+ next.searchParams.set(linkForm ? "ll" : "center", `${fixed(view.lat, 6)},${fixed(view.lon, 6)}`);
+ next.searchParams.set("z", fixed(view.zoom, 2));
+ return next.toString();
+ },
+
+ /** `#view=lat,lon,11z`, whatever follows it (the day, the layer) kept. */
+ "zoom-earth"(url, view) {
+ const camera = `view=${fixed(view.lat, 6)},${fixed(view.lon, 6)},${Math.round(view.zoom)}z`;
+ const hash = url.hash.replace(/^#/, "");
+ if (!/view=[^/]*/.test(hash)) return null;
+ url.hash = hash.replace(/view=[^/]*/, camera);
+ return url.toString();
+ },
+
+ /** `#lat,lon,17`. */
+ "satellites-pro"(url, view) {
+ url.hash = `${fixed(view.lat, 6)},${fixed(view.lon, 6)},${Math.round(view.zoom)}`;
+ return url.toString();
+ },
+
+ /** `?zoom=17&lat=…&lng=…`, the acquisition and the layer left alone. */
+ "copernicus-browser"(url, view) {
+ return withParams(url, {
+ zoom: String(Math.round(view.zoom)),
+ lat: fixed(view.lat, 5),
+ lng: fixed(view.lon, 5),
+ });
+ },
+ };
+
+ /**
+ * The address that puts this site's map on `view`, or null where it cannot.
+ *
+ * `parsed` is the app's reading of the page as it is now. `height` is the
+ * map's height in CSS pixels, the number that reading was made against,
+ * because Earth's camera distance only means a level next to one.
+ */
+ function writeView(parsed, href, view, height) {
+ const writer = WRITERS[parsed?.site];
+ if (!writer || !readable(view) || Math.abs(view.lat) > MAX_LAT) return null;
+ let url;
+ try {
+ url = new URL(href);
+ } catch {
+ return null;
+ }
+ const written = writer(url, reachable(parsed.site, view), height);
+ return written && written !== href ? written : null;
+ }
+
+ /**
+ * The level this map stopped short at, or null when it went where it was sent.
+ *
+ * Said out loud in the panel rather than corrected, because nothing is wrong:
+ * the map is as close as it goes, and the one being followed is exactly where
+ * the analyst left it.
+ */
+ function shortOf(asked, view) {
+ if (!readable(asked) || !readable(view)) return null;
+ // Somewhere else is not short, it is still on its way: Earth flies in from
+ // space on every load, quoting a far camera over the Gulf of Guinea first.
+ const there = Math.abs(view.lat - asked.lat) < NEAR_DEG && Math.abs(view.lon - asked.lon) < NEAR_DEG;
+ return there && view.zoom < asked.zoom - SHORT_BY ? view.zoom : null;
+ }
+
+ /**
+ * Why a site's address carries no view right now, when the site says so.
+ *
+ * Apple swaps its address for `/place?…&coordinate=` while a place card is
+ * open — a click on a label, or a long press, which a drag held still before
+ * letting go also is — and the camera is not in it at all until the card is
+ * closed. Moving the map does not bring it back, so the panel says what does.
+ */
+ function hiddenBy(href) {
+ try {
+ const url = new URL(href);
+ if (url.hostname === "maps.apple.com" && url.pathname.startsWith("/place")) {
+ return "Apple hides the view while a place card is open. Close the card to go on";
+ }
+ } catch {
+ /* not an address */
+ }
+ return null;
+ }
+
+ /** The latitude this site stopped at, when the view it was sent to is nearer a
+ * pole than it will open one. */
+ function poleLimit(site, asked, view) {
+ const limit = OPEN_LAT_LIMIT[site];
+ if (limit == null || !readable(asked) || !readable(view)) return null;
+ const stopped = Math.abs(asked.lat) > limit && Math.abs(Math.abs(view.lat) - limit) < NEAR_DEG;
+ return stopped ? limit : null;
+ }
+
+ window.AzimutMapLink = {
+ WRITE_CEILING,
+ EARTH_CLOSEST_M,
+ followable,
+ hiddenBy,
+ poleLimit,
+ reachable,
+ readable,
+ sameCamera,
+ shortOf,
+ writeView,
+ };
+})();
diff --git a/extension/mapmath.js b/extension/mapmath.js
index 6d62fde..1ede6bb 100644
--- a/extension/mapmath.js
+++ b/extension/mapmath.js
@@ -16,14 +16,14 @@
* 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.
+ * **And nothing here is learned from a gesture.** How big the map is drawn is a
+ * number the site wrote (a level, a height in metres, a span, a camera
+ * distance), checked against a browser before it was believed
+ * (`docs/MAP_SITES.md`). Measuring it off a drag instead is what put Earth's
+ * drawing four times too small: a drag loses pixels to the site's threshold
+ * and gains them to its glide, and one bad reading lived on through every zoom.
+ * The one thing a gesture still says is *where* a site draws its centre, from a
+ * zoom about a held pixel, below.
*
* Loaded before `mapoverlay.js` and left on `window.AzimutMapMath`.
*/
@@ -114,80 +114,13 @@
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.
+ * The flattenings we can write down, named per site by the app
+ * (`engine/mapsites.py`). Unknown is a refusal rather than a default.
*/
const PROJECTIONS = {
webmercator: { project: projectSpherical, unproject: unprojectSpherical },
ellipsoidal: { project: projectEllipsoidal, unproject: unprojectEllipsoidal },
- equalearth: { project: projectEqualEarth, unproject: unprojectEqualEarth },
};
function flattening(view) {
@@ -220,8 +153,8 @@
* 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.
+ * centred on the area. `area` is that rectangle, `{ x, y, w, h }` — placed
+ * where this site draws its centre (`centreFromZoom`).
*/
function toScreen(point, view, area) {
const flat = flattening(view);
@@ -268,11 +201,9 @@
/**
* 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.
+ * The same turn `screenToOffset` applies, with no centre in it: a zoom
+ * anchor's offset is a vector rather than a point, and it is compared with
+ * coordinates, which run along the world's axes and not the screen's.
*/
function unturn(dx, dy, view) {
const turn = rad(view?.bearing || 0);
@@ -281,219 +212,9 @@
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 address bar says 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
@@ -561,6 +282,10 @@
return Number.isFinite(centre.x) && Number.isFinite(centre.y) ? centre : null;
}
+ /** How far from the centre the held point has to be before the division below
+ * says more than the address bar's own rounding does. */
+ const MIN_ANCHOR_PX = 80;
+
/**
* 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.
@@ -620,71 +345,6 @@
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). */
@@ -759,16 +419,9 @@
MIN_ZOOM_STEP,
toScreen,
toLatLon,
- toScreenMeasured,
- toLatLonMeasured,
- createCalibration,
turn,
unturn,
- identify,
- zoomFromScale,
- rescaleFromAnchor,
MIN_ANCHOR_PX,
- MIN_PAN_PX,
haversine,
pathLength,
polygonArea,
diff --git a/extension/mapoverlay.js b/extension/mapoverlay.js
index 7f5a354..f14b5ae 100644
--- a/extension/mapoverlay.js
+++ b/extension/mapoverlay.js
@@ -9,10 +9,10 @@
* 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.
+ * 2. **The view engine.** Where the camera is and how big the map is drawn,
+ * from the app's parse of the URL, carried between two URLs by the gesture
+ * in flight. A gesture moves the drawing and never re-measures it. This is
+ * what turns geometry on and off, and it says why in words when it does.
* 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
@@ -34,8 +34,9 @@
* 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.
+ * Injected after mapmath.js, maptheme.js, maptools.js, mapdraw.js, mapref.js and
+ * maplink.js. Injecting it a second time closes the panel, which is what the
+ * toolbar button does.
*/
(() => {
@@ -51,8 +52,9 @@
const T = window.AzimutMapTools;
const D = window.AzimutMapDraw;
const R = window.AzimutMapRefs;
+ const K = window.AzimutMapLink;
const THEME = window.AzimutMapTheme;
- if (!M || !T || !D || !R || !THEME) {
+ if (!M || !T || !D || !R || !K || !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.
@@ -65,9 +67,6 @@
/** 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;
@@ -75,6 +74,11 @@
/** 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 long the address bar has to stay the same before the map counts as
+ * landed. Earth writes its URL several times during one zoom, and ending the
+ * wait on the first of them drew the marks at a scale the map was only
+ * passing through. */
+ const SETTLE_QUIET_MS = 400;
/**
* How often the open sweep is re-read from the case, when nothing has said to.
*
@@ -125,8 +129,7 @@
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(),
+ view: null, // { lat, lon, zoom, bearing, projection }; zoom is null until the URL states a scale
// 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.
@@ -135,12 +138,18 @@
caseId: "",
cases: [],
tool: null, // which tool the panel is showing, or none
+ // `{ field, cursor }` while a date field has its calendar open. One at a
+ // time, and never remembered: it is a gesture, not a setting.
+ cal: null,
units: "metric",
note: "", // the last thing that went wrong, shown in the panel
pinTitle: "",
gridTitle: "",
grids: null,
collapsed: false,
+ // Following the other maps' camera (`linking` below). `asked` is the view
+ // this map was last sent to, kept to say how close it came.
+ link: { on: false, peers: 0, asked: null },
};
const tools = {
@@ -149,8 +158,9 @@
sky: T.createSky(),
grid: T.createGridTool(),
refs: T.createRefs(),
+ fires: T.createFires(),
};
- const ORDER = ["measure", "pins", "sky", "grid", "refs"];
+ const ORDER = ["measure", "pins", "sky", "grid", "refs", "fires"];
const current = () => (state.tool ? tools[state.tool] : null);
/**
@@ -170,63 +180,30 @@
};
}
- /**
- * 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);
+ /** Whether geometry is sound right now, and if not, why (maptools.js). */
+ const verdict = () => T.verdict(state.parsed);
// --- 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.
+ * The shape from the site table, the size from the address bar, and nothing
+ * from the gesture.
*
- * 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`).
+ * *Which* flattening a site draws in is a fact about the site, and the app's
+ * table (`engine/mapsites.py`) knows it. *How big* it is drawn is a number
+ * the site itself writes — a tile level, a viewport height in metres, a span
+ * in degrees, Earth's camera distance (`scale_source`) — and every one was
+ * checked against a browser before being believed.
*
- * 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.
+ * This used to fall back on a scale measured by panning where the URL said
+ * none. A drag loses a few pixels to the site's own threshold and gains some
+ * to its glide, the first reading was taken on trust, and every later one
+ * that disagreed was thrown away as a fling: on Earth that drew the marks
+ * four times too close together, for good. A view whose URL states no scale
+ * now draws nothing and says so.
*/
- 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());
+ return M.toScreen(point, state.view, area());
}
/**
@@ -243,9 +220,7 @@
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());
+ return M.toLatLon(point, state.view, area());
}
/** Metres across the shorter side of the window — what the sky arc is drawn
@@ -275,6 +250,14 @@
});
const root = host.attachShadow({ mode: "open" });
document.documentElement.appendChild(host);
+ // Ground first, so it is under the drawing: FIRMS is a picture of what was
+ // burning, and a measured path over it has to stay legible.
+ const ground = document.createElement("div");
+ Object.assign(ground.style, { position: "fixed", inset: "0", pointerEvents: "none", zIndex: "0" });
+ const groundImg = document.createElement("img");
+ Object.assign(groundImg.style, { position: "absolute", display: "none" });
+ ground.appendChild(groundImg);
+ root.appendChild(ground);
const layer = D.createDrawLayer(root);
let frame = 0;
@@ -317,10 +300,16 @@
/** 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
+ const moved = gesture
? `translate(${gesture.dx}px, ${gesture.dy}px) scale(${gesture.k})`
: "";
+ layer.canvas.style.transform = moved;
layer.canvas.style.transformOrigin = "0 0";
+ // The fire picture is ground, so it rides the same transform: it was drawn
+ // for a rectangle of the world, and that rectangle moved with everything
+ // else. Re-asking on every frame of a pan would be a request per frame.
+ ground.style.transform = moved;
+ ground.style.transformOrigin = "0 0";
}
function clearGesture() {
@@ -333,22 +322,28 @@
* 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.
+ * hundred milliseconds. 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".
+ * bar has said where the map landed and then stayed put for
+ * `SETTLE_QUIET_MS`. Each reading in between is drawn, dimmed, as it comes:
+ * Earth rewrites its URL several times in one zoom, and the first of those
+ * is a scale the map is only passing through.
*/
function beginSettle() {
+ lead();
settling = true;
+ settleMoved = 0;
layer.canvas.style.opacity = "0.25";
clearTimeout(settle);
clearTimeout(giveUp);
settle = setTimeout(function poll() {
readUrl();
+ if (settleMoved && Date.now() - settleMoved >= SETTLE_QUIET_MS) {
+ endSettle();
+ return;
+ }
if (settling) settle = setTimeout(poll, SETTLE_POLL_MS);
}, SETTLE_MS);
giveUp = setTimeout(endSettle, SETTLE_GIVE_UP_MS);
@@ -360,6 +355,7 @@
clearTimeout(settle);
clearTimeout(giveUp);
layer.canvas.style.opacity = confidence();
+ leadOn();
}
/**
@@ -385,6 +381,10 @@
function paint() {
const tool = current();
const say = verdict();
+ // The fire layer is not a tool being held: it stays on while something else
+ // is being measured over it, which is the whole reason to have it here.
+ placeFires();
+ refreshFires();
if (!tool || !state.view || !say.ok) {
layer.clear();
return;
@@ -401,6 +401,177 @@
layer.render(shapes, toScreen);
}
+ // --- the fire layer --------------------------------------------------------
+ //
+ // Not a drawing: FIRMS answers with a picture of the ground, so what is held
+ // is the rectangle of world that picture covers and where that rectangle is
+ // on screen now. One request per settled view — the panel has no tile grid to
+ // hang tiles on, and the FIRMS allowance is counted in requests.
+
+ /** The picture on screen: `{ src, bounds }`, or null when there is none. */
+ let fireImage = null;
+ let fireAsked = ""; // the view + question it was asked for, so a still map re-asks nothing
+ let fireTimer = 0;
+ let fireSeq = 0;
+ /** How long a settled view is given before the picture is asked for. Panning
+ * through three towns should not ask about all three. */
+ const FIRE_SETTLE_MS = 400;
+ /** The picture is asked for at the window's size, capped where the app caps
+ * it: past this it is a bigger bill for NASA rather than a sharper answer. */
+ const FIRE_MAX_PX = 2560;
+
+ /** The ground the window can see, as a rectangle of degrees. */
+ function visibleBounds() {
+ const a = area();
+ const corners = [
+ toLatLon({ x: 0, y: 0 }),
+ toLatLon({ x: a.w, y: 0 }),
+ toLatLon({ x: 0, y: a.h }),
+ toLatLon({ x: a.w, y: a.h }),
+ ];
+ const lats = corners.map((c) => c.lat);
+ const lons = corners.map((c) => c.lon);
+ // A view straddling the antimeridian would come back as a rectangle around
+ // the wrong side of the world. It is a degenerate case for a fire layer and
+ // is skipped rather than drawn wrong.
+ if (Math.max(...lons) - Math.min(...lons) > 180) return null;
+ return {
+ south: Math.max(-85, Math.min(...lats)),
+ north: Math.min(85, Math.max(...lats)),
+ west: Math.min(...lons),
+ east: Math.max(...lons),
+ };
+ }
+
+ /** Put the picture back where its own ground is now. */
+ function placeFires() {
+ if (!fireImage || !state.view || !verdict().ok) {
+ groundImg.style.display = "none";
+ return;
+ }
+ const { south, west, north, east } = fireImage.bounds;
+ const nw = toScreen({ lat: north, lon: west });
+ const ne = toScreen({ lat: north, lon: east });
+ const sw = toScreen({ lat: south, lon: west });
+ const se = toScreen({ lat: south, lon: east });
+ const wide = Math.hypot(ne.x - nw.x, ne.y - nw.y);
+ const tall = Math.hypot(sw.x - nw.x, sw.y - nw.y);
+ // The middle of the picture is the middle of its own corners, and never the
+ // coordinate halfway between its edges: Mercator stretches northwards, so
+ // the mean of two latitudes sits south of the point halfway down the
+ // screen between them. Placed there, the picture rode low — by nothing over
+ // a town and by a tenth of the window over a continent, which is why this
+ // only showed up zoomed out. A diagonal's midpoint survives a turned
+ // compass, which the edges' would not.
+ const middle = { x: (nw.x + se.x) / 2, y: (nw.y + se.y) / 2 };
+ if (!(wide > 0) || !(tall > 0)) {
+ groundImg.style.display = "none";
+ return;
+ }
+ // Out where the site draws a globe, the picture is the thing that drifts
+ // most: it is a flat rectangle of ground laid over a curve, and it covers
+ // the whole window rather than a mark near the middle. So it dims with the
+ // drawing beside it — same 0.55, same sentence in the status line.
+ ground.style.opacity = verdict().far ? "0.55" : "";
+ Object.assign(groundImg.style, {
+ display: "block",
+ left: `${middle.x}px`,
+ top: `${middle.y}px`,
+ width: `${wide}px`,
+ height: `${tall}px`,
+ // The picture is north-up ground; the map may not be. Same sign as the
+ // drawing's own turn: a map with east up points north to the left.
+ transform: `translate(-50%, -50%) rotate(${-(state.view?.bearing || 0)}deg)`,
+ });
+ }
+
+ /** Whether this view is deeper than a detection mark still means anything at. */
+ function firesTooDeep() {
+ const zoom = state.view?.zoom;
+ return zoom != null && zoom > T.FIRE_MAX_ZOOM;
+ }
+
+ /** Ask for the picture this view needs, once it has stopped moving. */
+ function refreshFires() {
+ const asking = tools.fires.query();
+ if (!asking || !state.view || !verdict().ok || gesture) {
+ if (!asking) {
+ fireImage = null;
+ fireAsked = "";
+ placeFires();
+ }
+ return;
+ }
+ // Past the ceiling the app's own map caps its tiles at, the last picture is
+ // kept and re-placed on its own ground — which is what the app does with a
+ // z14 tile at z18. Asking again would buy a bigger smear of the same marks.
+ if (firesTooDeep()) return;
+ const bounds = visibleBounds();
+ if (!bounds) return;
+ // Round the rectangle before it becomes an identity: a map that settles one
+ // metre from where it was is the same picture.
+ const key = JSON.stringify([
+ asking,
+ Object.values(bounds).map((n) => n.toFixed(3)),
+ ]);
+ if (key === fireAsked) return;
+ fireAsked = key;
+ clearTimeout(fireTimer);
+ fireTimer = setTimeout(() => void askFires(bounds, asking), FIRE_SETTLE_MS);
+ }
+
+ /**
+ * What the fire layer can be asked, and whether a key makes it askable.
+ *
+ * The app answers from a catalogue and its own settings file, so this is not
+ * a call to NASA — nothing reaches FIRMS until the layer is on. Asked again
+ * whenever FIRMS refuses, because the app files that refusal against the key
+ * and this is how the seat hears about it.
+ */
+ async function reofferFires() {
+ try {
+ tools.fires.offer(await call("GET", "/api/ingest/firms/sensors"));
+ } catch {
+ // an older app has no such route; the seat then says it needs a key
+ }
+ }
+
+ async function askFires(bounds, asking) {
+ const mine = ++fireSeq;
+ const a = area();
+ const answer = await api.runtime.sendMessage({
+ type: "map-image",
+ path: "/api/ingest/firms",
+ query: {
+ ...bounds,
+ ...asking,
+ width: Math.min(Math.round(a.w), FIRE_MAX_PX),
+ height: Math.min(Math.round(a.h), FIRE_MAX_PX),
+ },
+ });
+ if (mine !== fireSeq) return; // the map moved on while this was in flight
+ if (!answer?.ok) {
+ fireImage = null;
+ fireAsked = ""; // it failed, so the next settle is worth another try
+ state.note = answer?.error || "the app did not answer";
+ placeFires();
+ // FIRMS answers a key it will not take with a *picture* saying so, which
+ // the app recognises and files against the key. So the panel asks again
+ // who it is: a seat that keeps offering a layer the service has already
+ // refused is a seat that asks for the same refusal every time the map
+ // stops moving.
+ await reofferFires();
+ return render();
+ }
+ fireImage = { src: answer.src, bounds };
+ groundImg.src = answer.src;
+ placeFires();
+ if (state.note) {
+ state.note = "";
+ render();
+ }
+ }
+
/** The rectangle being dragged out, in the app's draft style. */
function boxShape() {
const a = toLatLon(box.from);
@@ -414,66 +585,62 @@
// --- 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.
+ // Two inputs, in order of authority. The address bar is the truth, and the
+ // app parses it: where the camera is and how far out. A gesture in flight
+ // carries the drawing between two truths; it is replaced, never merged, the
+ // moment the URL settles. What a finished gesture may still say is where the
+ // site draws its centre, from a zoom about a held pixel — never how big the
+ // map is.
/**
* 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.
+ * without rounding. A fraction written as a level 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. A zoom the app worked out from
+ * a size (a height in metres, a span, Earth's distance) is exact at any
+ * fraction, because the number it came from was written to the metre or
+ * finer. Nothing is measured off a view that is not exact, 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 exactLevel = (parsed, zoom) =>
+ zoom != null && (parsed?.scale_source !== "zoom" || wholeLevel(zoom));
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`.
+ //. The view a zoom about to happen started from, and the pixel it will hold
+ //. still — what `centreFromZoom` solves the site's centre from.
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
+ let settling = false; // a gesture has ended and the map has not settled
+ let settleMoved = 0; // when the address bar last changed while settling
/**
* 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.
+ * Three views state their scale as a size rather than as a level (Apple's
+ * span, Google satellite's metres, Earth's camera distance), 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
+ * centred by exactly half of what the chrome took, so the offset the panel is
+ * drawing from is the measurement of the header, whether it was solved here
+ * (`measureFrame`) or started from the app's table (`seedFrame`). 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
@@ -494,20 +661,21 @@
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.
+ // A URL read mid-gesture would replace the drawing the pointer is carrying
+ // 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;
+ if (settling && location.href !== lastUrl) settleMoved = Date.now();
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`).
+ // have and the parse needs: Apple states a span, Google's satellite view a
+ // height in metres and Earth a camera distance, and each is a scale only
+ // next to the number of pixels it was drawn in (`engine/mapsites.py`).
parsed = await call("GET", "/api/ingest/parse", {
query: { url: lastUrl, height },
});
@@ -517,16 +685,19 @@
return;
}
adopt(parsed);
+ takeWaitingView();
}
- /** Take the app's reading as the new truth, and score the prediction it just
- * settled. */
+ /** Take the app's reading as the new truth, and learn from the zoom that led
+ * to it where this site draws its centre. */
function adopt(parsed) {
const before = state.view;
state.parsed = parsed;
+ landedFollow();
if (!parsed?.site || parsed.lat == null || parsed.lon == null) {
state.view = null;
frameChain = null;
+ zoomAnchor = null;
dropHold();
clearGesture();
endSettle();
@@ -534,13 +705,12 @@
render();
return;
}
+ seedFrame(parsed);
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,
+ // null until the address bar states a scale, and nothing is drawn until then
+ zoom: parsed.zoom ?? null,
bearing: parsed.bearing || 0,
projection: parsed.projection || "webmercator",
};
@@ -551,45 +721,34 @@
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;
+ // A threshold, because a zoom worked out from a size moves a little when
+ // nothing has zoomed: a height in metres depends on the latitude it was
+ // quoted at, and Earth's distance on the ground under the new centre. The
+ // smallest real step any of these sites takes is a fifth of a level.
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);
+ const zoomed =
+ before?.zoom != null && view.zoom != null && Math.abs(before.zoom - view.zoom) > 0.02;
// 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.
+ // landed on. 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);
+ if (zoomAnchor && zoomed && near) {
+ const exact = exactLevel(parsed, view.zoom);
let solved = false;
- if (zoomAnchor.exact && whole) {
+ if (zoomAnchor.exact && exact) {
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;
+ const corrected = M.zoomFromAnchor(zoomAnchor.view, view, zoomAnchor, middleOf(area()));
+ if (corrected != null) {
+ view.zoom = corrected;
solved = true;
}
}
- zoomExact = whole || solved;
+ zoomExact = exact || 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
@@ -603,88 +762,32 @@
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
+ } else if (frameHold && !frameHold.touched && !turned) {
+ // the rest of the zoom that is being held: solved again from its anchor
+ if (zoomed) zoomExact = exactLevel(parsed, view.zoom);
reframe(view);
+ } else if (zoomed || before?.zoom == null) {
+ zoomExact = exactLevel(parsed, view.zoom);
+ if (!near) frameChain = null;
}
-
- 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
+ // a site still writing down where the analyst took it, after the wait gave up
+ if (leading) {
+ clearTimeout(leadQuiet);
+ leadQuiet = setTimeout(leadOn, SETTLE_QUIET_MS);
+ }
+ // the map has said where it is, so the canvas goes back to being untouched
+ // and everything is projected from there; the dimming lifts once the
+ // address bar stops moving (`beginSettle`)
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);
+ if (tools.sky.anchor && verdict().ok) tools.sky.fit(spanMetres());
+ // marks merge by how close together they are on screen, which needs a scale
+ if (view.zoom != null) tools.pins.atZoom(view.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.
*
@@ -735,6 +838,11 @@
*/
const FRAMES_KEPT = 4;
let frames = [];
+ /** Which way the offsets in storage were solved. Before 2, Earth's came out
+ * of a scale measured off a drag, and a stale one a few pixels out survived
+ * the zooms after it by being averaged in; they are dropped once, and each
+ * site measures its centre again on its first zoom. */
+ const FRAMES_VERSION = 2;
const sameWindow = (a, b) =>
Math.abs(a.w - b.w) <= WINDOW_SAME_PX && Math.abs(a.h - b.h) <= WINDOW_SAME_PX;
@@ -756,6 +864,9 @@
* actually moved does not, which is what the jump above is for. */
const FRAME_SAMPLES = 6;
let frameSamples = [];
+ /** Whether the offset being drawn from came from the app's site table rather
+ * than from a zoom on this machine — which is what the tooltip says. */
+ let seeded = false;
/** 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 }
@@ -785,9 +896,11 @@
/**
* 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.
+ * A moved centre, or a zoom that went on further, and nobody's hand on the
+ * map: that is the rest of the ease, not a new gesture, and the anchor still
+ * describes the map it started from. Earth writes a zoom several times over,
+ * Google writes the level first and the centre after. So the answer is solved
+ * again from the newer reading and the wait restarts.
*/
function reframe(view) {
if (!frameHold || frameHold.touched) return;
@@ -824,6 +937,7 @@
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;
+ seeded = false;
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
@@ -831,6 +945,40 @@
if (moved || first) save();
}
+ /**
+ * Where this site draws its centre before anything here has measured it.
+ *
+ * The middle of the window was never a neutral starting point — it is a
+ * table entry like any other, and the wrong one on four of these sites. A
+ * results panel or a header takes part of the window and the map is centred
+ * in what is left, which puts Yandex's camera 210 px right of the middle and
+ * Bing's 40 px down: at level 3 that is hundreds of kilometres of ground,
+ * with nothing on screen saying so. Every install started there and stayed
+ * there until the analyst happened to zoom.
+ *
+ * So the app's table hands over what its own calibration run measured
+ * (`engine/mapsites.py`, `_CAMERA_CENTRE`) and the panel starts from that. It
+ * is a starting offset and claims nothing more: it does not count as
+ * measured, the status line still asks for the zoom that would settle it, and
+ * the first solved answer replaces it. A site this machine has already
+ * measured keeps its own answer — a measurement here beats a measurement
+ * somewhere else, always.
+ */
+ function seedFrame(parsed) {
+ if (state.framed || frames.length || !parsed?.centre_hint) return;
+ // A sideways offset is a side panel, and a side panel is the thing that
+ // folds away when the window gets narrow. The table says the narrowest
+ // window each one was measured in; under that this site is centred
+ // horizontally and measured like any other. A header takes height, and a
+ // header is the same height in any window.
+ const wide = window.innerWidth >= (parsed.centre_hint.min_w || 0);
+ const hint = { x: wide ? parsed.centre_hint.x : 0, y: parsed.centre_hint.y };
+ if (!framePlausible(hint)) return;
+ if (hint.x === state.frame.x && hint.y === state.frame.y) return;
+ state.frame = hint;
+ seeded = true;
+ }
+
/** File the measurement under the window it was taken in. */
function rememberFrame() {
if (!state.framed) return;
@@ -838,32 +986,6 @@
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.
*
@@ -882,8 +1004,8 @@
/**
* 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.
+ * the drawing is carried by the pixels the pointer travelled, and nothing is
+ * learned from them.
*/
function onPointerDown(event) {
// From here the map moves for a reason the ease cannot account for, so the
@@ -896,7 +1018,6 @@
drag = {
x: event.clientX,
y: event.clientY,
- from: state.view,
moved: false,
base: gesture ?? { dx: 0, dy: 0, k: 1 },
};
@@ -911,27 +1032,14 @@
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) {
+ function onPointerUp() {
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
@@ -943,23 +1051,16 @@
* 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.
+ * zoom cannot: the site picks its own step and eases into it over a few
+ * hundred milliseconds. 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,
+ * and comes back at the scale the address bar states.
*
- * 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.
+ * What the zoom does leave behind is where this site draws its centre: every
+ * one of these maps zooms about a point it keeps still, the cursor for a
+ * wheel notch and the click for a double-click (`mapmath.js`,
+ * `centreFromZoom`).
*/
function beginZoom(at) {
// whatever a pan left the canvas offset by is kept rather than undone: it is
@@ -967,8 +1068,7 @@
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.
+ // solving for the site's centre needs where the camera was.
const sameSpot =
frameChain && Math.abs(frameChain.x - at.x) <= 6 && Math.abs(frameChain.y - at.y) <= 6;
zoomAnchor = {
@@ -989,16 +1089,7 @@
// 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();
}
@@ -1466,6 +1557,237 @@
}
}
+ // --- linking ---------------------------------------------------------------
+ //
+ // This map and the others on one camera: other panels, and the app's own map
+ // tabs. The worker is the hub (`background.js`, "linked views") and holds
+ // which tabs are linked, because following a view reloads most of these sites
+ // and takes this panel with it.
+ //
+ // A view is followed by writing it into the address bar (`maplink.js`), and a
+ // view is only ever *sent* after the analyst moved this map (`endSettle`). So a
+ // map that arrived somewhere because it was sent there is silent about it, and a
+ // map that stops short of a view — Zoom Earth at 11, Google at 21 — says so in
+ // its own panel instead of asking everything else to come back out to it.
+ //
+ // A map in a background tab is not moved where it stands: it keeps the last view
+ // and takes it when the analyst comes back to the tab. Writing the address bar
+ // reloads most of these sites, and a reload nobody is watching is a reload the
+ // analyst pays for twice — once per gesture on the map being led, and again in
+ // every race it opens: a page still loading has no panel to hand the next view
+ // to, and a browser that granted the tools for one page can refuse them on the
+ // next. One tab, one reload, at the moment its map is looked at.
+
+ let link = null; // the port to the hub, while it is up
+ let linkRetry = 0;
+ /** The view this map was just sent to, until the address bar shows it. Only a
+ * site that takes the view in its hash is still here to see that. */
+ let following = null;
+ let followedFrom = "";
+ /** A view that arrived while this map could not take it: before the address was
+ * first read, or with the tab in the background. Only the last one is kept —
+ * the analyst wants where the other map ended up, not the way it went. */
+ let waitingView = null;
+
+ /**
+ * How long after a gesture the address bar is still the analyst's motion.
+ *
+ * The settle gives up after a couple of seconds so the drawing is never left
+ * dimmed, but Earth writes a drag or a zoom down seconds after the pointer let
+ * go, in more than one go, and without a GPU up to twenty seconds later. A lead
+ * that ended with the settle sent nothing from Earth, or the first of its
+ * readings and never the one it stopped on.
+ */
+ const LEAD_WAIT_MS = 20000;
+ /** `{ until, sent }` while a gesture is leading: the last view handed over,
+ * or the one the gesture started from. */
+ let leading = null;
+ let leadQuiet = 0;
+
+ /** A gesture began: what the address bar says from here is the analyst's. */
+ function lead() {
+ leading = { until: Date.now() + LEAD_WAIT_MS, sent: leading ? leading.sent : state.view };
+ }
+
+ /**
+ * Hand the view over if the analyst's gesture moved it.
+ *
+ * Only a gesture leads. A view this map was sent to never gets here, which is
+ * what keeps two linked maps from pushing one camera back and forth, and a map
+ * that stopped short of one from dragging the rest back out to where it stopped.
+ */
+ function leadOn() {
+ clearTimeout(leadQuiet);
+ if (!leading || following || settling) return;
+ if (Date.now() > leading.until) {
+ leading = null;
+ return;
+ }
+ if (!state.view || K.sameCamera(state.view, leading.sent)) return;
+ leading.sent = state.view;
+ shareView();
+ }
+
+ function linkSend(message) {
+ try {
+ link?.postMessage(message);
+ } catch {
+ // the port died with the worker; `joinLink` is already opening another
+ }
+ }
+
+ function joinLink() {
+ clearTimeout(linkRetry);
+ if (!api.runtime?.connect) return;
+ try {
+ link = api.runtime.connect({ name: "map-link" });
+ } catch {
+ link = null;
+ linkRetry = setTimeout(joinLink, SYNC_RETRY_MS);
+ return;
+ }
+ link.onMessage.addListener(onLinkMessage);
+ link.onDisconnect.addListener(() => {
+ link = null;
+ linkRetry = setTimeout(joinLink, SYNC_RETRY_MS);
+ });
+ // a worker that was evicted forgot nothing it wrote down, but a panel that
+ // switched the link while it was gone has to say so again
+ if (state.link.on) linkSend({ type: "link", on: true });
+ }
+
+ function onLinkMessage(msg) {
+ if (msg?.type === "link-state") {
+ state.link.on = !!msg.linked;
+ if (msg.asked) state.link.asked = msg.asked;
+ return render();
+ }
+ if (msg?.type === "link-peers") {
+ if (state.link.peers === msg.count) return;
+ state.link.peers = msg.count;
+ return render();
+ }
+ if (msg?.type === "link-note") {
+ state.note = msg.note;
+ return render();
+ }
+ if (msg?.type === "view") followView(msg.view);
+ }
+
+ /** This map's camera, to the others. Pressing the button sends it too: the
+ * tab that switches the link on is the one the others come to. */
+ function shareView() {
+ if (!state.link.on || !K.followable(state.parsed) || !state.view) return;
+ const view = {
+ lat: state.view.lat,
+ lon: state.view.lon,
+ zoom: state.view.zoom,
+ bearing: state.view.bearing || 0,
+ };
+ if (!K.readable(view)) return;
+ linkSend({ type: "view", view });
+ if (state.link.asked) {
+ state.link.asked = null; // this map leads now, and is wherever the analyst put it
+ render();
+ }
+ }
+
+ /**
+ * Go where another map went.
+ *
+ * Not while the analyst is moving this one: the gesture in hand is the view
+ * that is about to lead, and yanking the map out from under it would read as
+ * the map fighting back. Not on a view that is not a flat map either — Street
+ * View, a pitched camera — because leaving it is the analyst's call, and the
+ * panel says it stayed.
+ */
+ function followView(view) {
+ if (!state.link.on || !K.readable(view) || drag || settling) return;
+ // A panel just put back after a reload hears the view it missed before it
+ // has read its own address, and a tab in the background would reload behind
+ // the analyst: either way the view waits.
+ if (!state.parsed || document.hidden) {
+ waitingView = view;
+ return;
+ }
+ // an Apple place card hides the camera, and the move closes the card
+ const hidden = K.hiddenBy(location.href);
+ if (!K.followable(state.parsed) && !hidden) {
+ state.note = "Linked view not followed: this is not a flat map";
+ return render();
+ }
+ // Against the view this site will really open, not the one it was asked for:
+ // a map held at a ceiling or at Apple's pole limit is already where the ask
+ // puts it, and reloading it to land it back there would undo the drag the
+ // panel just told the analyst to make.
+ if (K.sameCamera(K.reachable(state.parsed.site, view), state.view)) return;
+ const href = K.writeView(state.parsed, location.href, view, mapHeight());
+ if (!href) return;
+ // whatever this map was still writing down, another one leads now
+ leading = null;
+ clearTimeout(leadQuiet);
+ following = view;
+ followedFrom = location.href;
+ state.link.asked = view;
+ linkSend({ type: "follow", view });
+ location.assign(href);
+ }
+
+ /** Take up the view held while this map could not follow it. Dropped if the
+ * map cannot take it now either — the analyst is on this one, and where they
+ * put it is the view the others come to. */
+ function takeWaitingView() {
+ if (!waitingView) return;
+ const view = waitingView;
+ waitingView = null;
+ followView(view);
+ }
+
+ /**
+ * The analyst came back to this tab: catch the map up.
+ *
+ * Visibility, not the active tab, is what holds a view back — a tab that is the
+ * front one of a window the analyst is not typing in is still visible, and two
+ * maps side by side on two screens go on following each other the way they read
+ * as doing.
+ */
+ function onShown() {
+ if (!document.hidden) takeWaitingView();
+ }
+
+ /** A follow the site took without reloading has landed: nothing is on its way
+ * back to this tab any more. */
+ function landedFollow() {
+ if (!following || lastUrl === followedFrom) return;
+ following = null;
+ linkSend({ type: "landed" });
+ }
+
+ function toggleLink() {
+ if (!state.link.on && !state.link.peers) return;
+ state.link.on = !state.link.on;
+ linkSend({ type: "link", on: state.link.on });
+ if (state.link.on) shareView();
+ else state.link.asked = null;
+ render();
+ }
+
+ /** What the link button says, which is also why it may be greyed. */
+ function linkTitle() {
+ if (state.link.on) return "Stop following the other maps";
+ if (!state.link.peers) return "Open another map, here or in Azimut, to link the views";
+ return "Pan and zoom with the other maps";
+ }
+
+ /** The level this map stopped at, when a linked view asked for more. */
+ function linkShort() {
+ if (!state.link.on || !state.view) return "";
+ const pole = K.poleLimit(state.parsed.site, state.link.asked, state.view);
+ if (pole != null) return ` · this map opens no nearer the pole than ${pole.toFixed(1)}°, drag the rest of the way`;
+ const short = K.shortOf(state.link.asked, state.view);
+ return short == null ? "" : ` · as close as this map goes (linked view z${state.link.asked.zoom.toFixed(1)})`;
+ }
+
// --- the panel -------------------------------------------------------------
const panel = document.createElement("div");
@@ -1506,6 +1828,11 @@
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. */
+ .beta {
+ margin-left: 6px; padding: 1px 6px; border-radius: 999px;
+ font-size: 9.5px; letter-spacing: .06em; vertical-align: 1px;
+ color: ${t.warn}; border: 1px solid ${t.warn};
+ }
.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; }
@@ -1539,6 +1866,33 @@
border: 1px solid ${t.border};
}
.readout.small { font-size: 12.5px; }
+ /* the calendar: in flow, so the rows under it move down and no edge of this
+ panel — or of the window it floats in — can cut it */
+ .cal-row { display: flex; align-items: center; gap: 8px; }
+ .cal-label { flex: none; width: 34px; font-size: 11px; color: ${t.text3}; }
+ .cal-field {
+ flex: 1; min-width: 0; justify-content: space-between; padding: 4px 7px;
+ font-size: 12px; font-variant-numeric: tabular-nums;
+ }
+ .cal-field.empty { color: ${t.text3}; }
+ .cal {
+ display: flex; flex-direction: column; gap: 3px; padding: 6px;
+ background: ${t.bg2}; border: 1px solid ${t.border}; border-radius: 7px;
+ }
+ .cal-head { display: flex; align-items: center; justify-content: space-between; }
+ .cal-month { font-size: 11px; font-weight: 600; color: ${t.text1}; }
+ .cal-step { padding: 2px; width: 22px; background: none; border-color: transparent; color: ${t.text2}; }
+ .cal-week, .cal-days { display: grid; grid-template-columns: repeat(7, 1fr); gap: 1px; }
+ .cal-week span { text-align: center; font-size: 9.5px; color: ${t.text3}; }
+ .cal-day {
+ padding: 3px 0; font-size: 11px; font-variant-numeric: tabular-nums;
+ background: none; border-color: transparent; color: ${t.text2};
+ }
+ .cal-day.out { color: ${t.text3}; opacity: .55; }
+ .cal-day.today { border-color: ${t.borderStrong}; }
+ .cal-day.on { border-color: ${t.accent}; color: ${t.accent}; }
+ .cal-acts { display: flex; justify-content: flex-end; gap: 4px; }
+ .cal-act { padding: 3px 8px; font-size: 11px; }
/* 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; }
@@ -1582,6 +1936,72 @@
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>`;
+ /**
+ * One seat in the tab row.
+ *
+ * A tool with nothing behind it is greyed where it sits, wearing its own
+ * reason: the app's Layers panel does the same with the fire layer it has no
+ * key for, and a seat that opens on a paragraph about a missing key is a
+ * click spent learning there was nothing to click.
+ */
+ function tab(id) {
+ const tool = tools[id];
+ const usable = tool.offerable !== false;
+ const why = usable ? "" : ` disabled title="${esc(tool.readout(state.units) ?? "")}"`;
+ return button("tab", tool.icon, tool.label, state.tool === id, ` data-tab="${id}"${why}`);
+ }
+
+ /** Today, in the form every date in here is written in. */
+ const todayIso = () => new Date().toISOString().slice(0, 10);
+
+ /**
+ * One date, and the calendar it opens — drawn in the panel, never over it.
+ *
+ * `<input type="date">` came with a calendar of its own, and that calendar is
+ * the browser's: it opens at the size the browser wants, in the browser's
+ * locale, and over the page. On a panel floating at the edge of somebody
+ * else's map it was half outside the window, and read `12/09/2026` where
+ * everything else in here reads `2026-09-12`. So the month is ours, in flow,
+ * pushing the rows under it down.
+ */
+ function dayField(field, label, value, empty, min, max) {
+ const open = state.cal?.field === field;
+ const head = `
+ <button data-act="cal-open" data-field="${field}" class="cal-field${value ? "" : " empty"}"${open ? ' data-on="1"' : ""} aria-expanded="${open}">
+ <span>${esc(value || empty)}</span>${icon(open ? "chevronUp" : "chevronDown", 11)}
+ </button>`;
+ if (!open) return `<div class="cal-row"><span class="cal-label">${esc(label)}</span>${head}</div>`;
+
+ const cursor = state.cal.cursor || T.calMonthOf(value);
+ const back = !T.calMonthOutOfRange(T.calShiftMonth(cursor, -1), min, max);
+ const on = !T.calMonthOutOfRange(T.calShiftMonth(cursor, 1), min, max);
+ const today = todayIso();
+ const cells = T.calMonthDays(cursor)
+ .map((cell) => {
+ const refused = T.calOutOfRange(cell.iso, min, max);
+ const mark = [cell.inMonth ? "" : "out", cell.iso === value ? "on" : "", cell.iso === today ? "today" : ""]
+ .filter(Boolean)
+ .join(" ");
+ return `<button data-act="cal-day" data-day="${cell.iso}" class="cal-day ${mark}" title="${cell.iso}"${refused ? " disabled" : ""}>${cell.day}</button>`;
+ })
+ .join("");
+ return `
+ <div class="cal-row"><span class="cal-label">${esc(label)}</span>${head}</div>
+ <div class="cal">
+ <div class="cal-head">
+ <button data-act="cal-step" data-by="-1" class="cal-step" title="Previous month"${back ? "" : " disabled"}>${icon("chevronLeft", 12)}</button>
+ <span class="cal-month">${esc(T.calMonthLabel(cursor))}</span>
+ <button data-act="cal-step" data-by="1" class="cal-step" title="Next month"${on ? "" : " disabled"}>${icon("chevronRight", 12)}</button>
+ </div>
+ <div class="cal-week">${T.CAL_WEEKDAYS.map((day) => `<span>${day}</span>`).join("")}</div>
+ <div class="cal-days">${cells}</div>
+ <div class="cal-acts">
+ <button data-act="cal-day" data-day="${today}" class="cal-act"${T.calOutOfRange(today, min, max) ? " disabled" : ""}>Today</button>
+ ${field === "last" ? `<button data-act="cal-day" data-day="" class="cal-act"${value ? "" : " disabled"}>Clear</button>` : ""}
+ </div>
+ </div>`;
+ }
+
function toolBody() {
const tool = current();
if (!tool) return `<div class="hint">Pick a tool. The map stays yours until you do.</div>`;
@@ -1646,6 +2066,43 @@
: `<div class="hint">Hold a case image or video over the map while you pan. Nothing is filed or captured.</div>`}`;
}
+ if (state.tool === "fires") {
+ const fire = tool.state;
+ const dated = fire.window === T.FIRE_DATED;
+ if (!fire.keyed) {
+ return `<div class="hint">NASA FIRMS needs a key. Add one in Azimut Settings → Imagery, then reopen this panel.</div>`;
+ }
+ return `
+ ${button("fires-toggle", fire.on ? "eye" : "eyeOff", fire.on ? "Drawn" : "Draw fires", fire.on, off)}
+ <div class="readout small">${esc(readout)}</div>
+ ${fire.on ? `
+ <div class="row wrap">
+ ${fire.sensors
+ .map((entry) =>
+ button(
+ "fires-sensor",
+ "",
+ entry.label.replace(/\s*\(.*\)\s*$/, ""),
+ fire.sensor === entry.id,
+ ` data-sensor="${esc(entry.id)}" title="${esc(entry.label)}"`
+ )
+ )
+ .join("")}
+ </div>
+ <div class="row wrap">
+ ${T.FIRE_WINDOWS.map((entry) =>
+ button("fires-window", "", entry.label, fire.window === entry.id, ` data-window="${esc(entry.id)}" title="Detections from the last ${esc(entry.label.toLowerCase())}"`)
+ ).join("")}
+ ${button("fires-window", "", "Dates", dated, ` data-window="${T.FIRE_DATED}" title="Detections from a past day or range"`)}
+ </div>
+ ${dated ? `
+ ${dayField("first", "From", fire.first, "Pick a day", "", todayIso())}
+ ${dayField("last", "To", fire.last, "That day alone", fire.first, T.fireLastDay(fire.first))}
+ <div class="hint">Up to ${T.FIRE_MAX_RANGE_DAYS} days; blank draws the first day alone.</div>` : ""}
+ ${firesTooDeep() ? `<div class="hint">${fireImage ? `Past z${T.FIRE_MAX_ZOOM} the picture is held rather than asked again.` : `Zoom out to z${T.FIRE_MAX_ZOOM} to ask for detections.`}</div>` : ""}
+ ` : `<div class="hint">Thermal detections from NASA FIRMS, laid over this map.</div>`}`;
+ }
+
const cover = tool.coverage;
return `
${tool.grid ? "" : `
@@ -1705,19 +2162,20 @@
const seen = verdict();
panel.innerHTML = `
<header>
- <span class="name">Azimut</span>
+ <span class="name">Azimut${betaBadge()}</span>
+ ${button("link", "link", "", state.link.on, ` class="icon" title="${linkTitle()}"${state.link.on || state.link.peers ? "" : " disabled"}`)}
${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>
+ ${icon(seen.ok ? "satellite" : "alert", 14)}<span${frameTitle()}>${esc(seen.ok ? sound() : K.hiddenBy(location.href) ?? 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("")}
+ ${ORDER.map((id) => tab(id)).join("")}
</div>
${toolBody()}
${state.note ? `<div class="note">${esc(state.note)}</div>` : ""}
@@ -1726,29 +2184,32 @@
paint();
}
+ /** Google Earth is the site the tools keep up with worst: its camera and its
+ * 3D globe drift from what the URL says, so the panel owns up to it. */
+ function betaBadge() {
+ if (state.parsed?.site !== "google-earth") return "";
+ return ` <span class="beta" title="Drawings drift more on Google Earth than on other maps">Beta</span>`;
+ }
+
/** 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 { zoom } = state.view;
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}`;
+ return `${state.parsed.site} · z${zoom.toFixed(2)} · ${state.parsed.projection} (${state.parsed.scale_source} from the URL)${framed}${far}${linkShort()}`;
}
/** 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"`;
+ const at = `centre at ${x.toFixed(0)}, ${y.toFixed(0)}`;
+ if (state.framed) {
+ return ` title="${at} from the middle of a ${windowSize.w}×${windowSize.h} window"`;
+ }
+ return seeded ? ` title="${at}, from the site table until a zoom measures it"` : "";
}
// --- what the panel's controls do ------------------------------------------
@@ -1760,6 +2221,7 @@
state.note = "";
if (act === "close") return close();
+ if (act === "link") return toggleLink();
if (act === "collapse") {
state.collapsed = !state.collapsed;
save();
@@ -1769,6 +2231,7 @@
// 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;
+ state.cal = null; // an open calendar belongs to the panel it was opened in
// 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.
@@ -1826,6 +2289,47 @@
return render();
}
+ if (act === "fires-toggle") {
+ tools.fires.toggle();
+ redraw(); // the layer goes on or off without anything being clicked on the map
+ return render();
+ }
+ if (act === "cal-open") {
+ const field = target.dataset.field;
+ state.cal =
+ state.cal?.field === field
+ ? null
+ : { field, cursor: T.calMonthOf(tools.fires.state[field]) };
+ return render();
+ }
+ if (act === "cal-step" && state.cal) {
+ state.cal = { ...state.cal, cursor: T.calShiftMonth(state.cal.cursor, Number(target.dataset.by)) };
+ return render();
+ }
+ if (act === "cal-day" && state.cal) {
+ tools.fires.set(state.cal.field, target.dataset.day);
+ // A first day moved past the end of its own range takes the end with it,
+ // rather than leaving a question the service would refuse.
+ if (state.cal.field === "first" && T.calOutOfRange(tools.fires.state.last, target.dataset.day, T.fireLastDay(target.dataset.day))) {
+ tools.fires.set("last", "");
+ }
+ state.cal = null;
+ redraw();
+ return render();
+ }
+ if (act === "fires-sensor" || act === "fires-window") {
+ const field = act === "fires-sensor" ? "sensor" : "window";
+ tools.fires.set(field, target.dataset[field]);
+ if (field === "window") state.cal = null; // the fields it belonged to are gone
+ // Switching to Dates with nothing in them would draw nothing and say so;
+ // today is the day being asked about most of the time.
+ if (field === "window" && target.dataset.window === T.FIRE_DATED && !tools.fires.state.first) {
+ tools.fires.set("first", new Date().toISOString().slice(0, 10));
+ }
+ redraw();
+ return render();
+ }
+
if (act === "ref-add") {
refLayer.openPicker();
return render();
@@ -1960,6 +2464,7 @@
// each with the window it was measured in, because that is what makes
// it an answer rather than a number
frames,
+ framesVersion: FRAMES_VERSION,
},
});
}
@@ -1969,7 +2474,7 @@
if (!stored) return;
state.collapsed = !!stored.collapsed;
if (stored.tool && tools[stored.tool]) state.tool = stored.tool;
- if (Array.isArray(stored.frames)) {
+ if (Array.isArray(stored.frames) && stored.framesVersion === FRAMES_VERSION) {
// 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);
@@ -1983,6 +2488,7 @@
if (best) {
state.frame = { x: best.x, y: best.y };
state.framed = !!here;
+ seeded = false; // measured here once, which beats the app's table
frameSamples = here ? [state.frame] : [];
}
}
@@ -2042,6 +2548,11 @@
rememberFrame(); // file what was measured under the window it was measured in
windowSize = { w: window.innerWidth, h: window.innerHeight };
if (moved) {
+ // A window that changed width can have changed which half of the table's
+ // answer applies: a header is a header at any width and a side panel is
+ // not. Nothing measured here is touched — `seedFrame` stands aside for
+ // that, and `rememberFrame` has just filed it.
+ seedFrame(state.parsed);
// 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.
@@ -2072,6 +2583,7 @@
[window, "dblclick", onDoubleClick, true],
[window, "wheel", onWheel, { capture: true, passive: true }],
[window, "resize", onResize, false],
+ [document, "visibilitychange", onShown, false],
[layer.canvas, "pointerdown", canvasDown, false],
[layer.canvas, "pointermove", canvasMove, false],
[layer.canvas, "pointerup", canvasUp, false],
@@ -2081,6 +2593,7 @@
const gridPoll = setInterval(() => refreshGrid({ poll: true }), GRID_POLL_MS);
watch = setInterval(keepWatching, WATCH_MS);
listen();
+ joinLink();
function close() {
clearInterval(poll);
@@ -2093,6 +2606,17 @@
/* already gone */
}
sync = null;
+ clearTimeout(linkRetry);
+ clearTimeout(leadQuiet);
+ // closing the tools is leaving the link; a reload that follows a view is not
+ // a close, and never gets here
+ if (state.link.on) linkSend({ type: "link", on: false });
+ try {
+ link?.disconnect();
+ } catch {
+ /* already gone */
+ }
+ link = null;
clearTimeout(giveUp);
clearTimeout(settle);
clearTimeout(frameQuiet);
@@ -2116,6 +2640,7 @@
state.note = e.message;
}
await loadCases();
+ await reofferFires();
await readUrl(true);
})();
})();
diff --git a/extension/maptheme.js b/extension/maptheme.js
index a4b6a4c..c6645a3 100644
--- a/extension/maptheme.js
+++ b/extension/maptheme.js
@@ -65,12 +65,16 @@
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",
+ flame: "M12 3c3.2 3.4 5 6 5 8.6a5 5 0 0 1-10 0c0-1.6.6-3 1.9-4.3.1 1.2.6 2 1.4 2.6C10 7.6 10.6 5.3 12 3Z",
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",
+ link: "M10 14a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 10a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7",
chevronDown: "m6 9 6 6 6-6",
chevronUp: "m6 15 6-6 6 6",
+ chevronLeft: "m15 6-6 6 6 6",
+ chevronRight: "m9 6 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",
diff --git a/extension/maptools.js b/extension/maptools.js
index b97a955..93213ac 100644
--- a/extension/maptools.js
+++ b/extension/maptools.js
@@ -1,5 +1,5 @@
/**
- * The five tools, as state machines with no DOM and no network in them.
+ * The six 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
@@ -8,11 +8,13 @@
* 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.
+ * Two of them draw no shape and take no click on the map. `createRefs` holds
+ * the floating panes a reference is compared from (`mapref.js` paints them),
+ * and `createFires` holds the question NASA FIRMS is asked, whose answer is a
+ * picture of the ground laid under the drawing. Both live here because what
+ * they hold — where a pane sits, how far into the image it is zoomed, which
+ * stretch of time is being asked about — 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
@@ -38,12 +40,6 @@
* 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
@@ -52,25 +48,17 @@
const REFUSALS = {
streetview: "These tools work on the map, not in Street View",
tilted: "These tools work in 2D only, so turn 3D off",
+ globe: "The camera is on a globe this far out, so zoom in",
};
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";
+ /** What a map says while its address bar has not yet stated a scale — an
+ * Earth link typed with no ground in it, a satellite view before its height
+ * arrives. The site writes one as soon as the map is moved. */
+ const NO_SCALE = "Move the map once so its address bar gives the scale";
/** …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,
@@ -81,52 +69,39 @@
/**
* 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.
+ * `engine/mapsites.py` owns the URL formats and decides all of it: which
+ * camera this is, which flattening the site draws in, and which number in the
+ * URL says how big (`scale_source` — a tile level, a height in metres, a span
+ * in degrees, a camera distance). Every one of those was checked against a
+ * browser before being believed (`docs/MAP_SITES.md`). Nothing here second-
+ * guesses them from a gesture: that is what used to put Earth's drawing four
+ * times too small, and then keep it there.
*
- * 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.
+ * The answer carries `far` as well as `ok`, and the two globes it tells apart
+ * are not the same thing. A **flat map drawn far out** — Google and Bing
+ * below level 8 — still has a centre this arithmetic is right about, and
+ * drifts outward from it: that one draws, says so, and is dimmed, because a
+ * region's worth of marks is worth seeing at a glance. A **globe camera** —
+ * Earth's 3D mode past `LEVEL_CEILING_M`, and Google's Earth mode with it —
+ * is a perspective view of a sphere, where Mercator is not right at all.
+ * That one is refused outright and says to zoom in.
*
* @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) {
+ function verdict(parsed) {
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") {
+ if (parsed.view_kind && parsed.view_kind !== "map") {
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) {
+ if (!parsed.view_kind || !parsed.geometry) {
return { ok: false, why: "This view is not one Azimut can compute on" };
}
+ if (!parsed.scale_source) return { ok: false, why: NO_SCALE };
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 };
+ return { ok: true, why: far ? FAR : "", far };
}
// --- measure ---------------------------------------------------------------
@@ -1296,10 +1271,208 @@
};
}
+ // --- the calendar ----------------------------------------------------------
+ //
+ // `lib/calendar.js` a second time, for the same reason the fire question is:
+ // the panel is a classic script and cannot import the app's. A browser's own
+ // date picker was the first answer and the wrong one — it opens over the page
+ // at whatever size it likes, and this panel floats on somebody else's map with
+ // no room to spare. So the month is drawn inside the panel, and the days it
+ // draws are computed here and checked against the app's in
+ // `extensionMapTools.test.js`.
+
+ /** Monday first, two letters, so no two columns wear the same initial. */
+ const CAL_WEEKDAYS = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
+ const CAL_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+ /** The month a day belongs to, as the cursor a calendar is drawn from. */
+ function calMonthOf(iso, fallback = new Date().toISOString().slice(0, 10)) {
+ const day = String(iso ?? "");
+ if (/^\d{4}-\d{2}-\d{2}$/.test(day)) return day.slice(0, 7);
+ if (/^\d{4}-\d{2}$/.test(day)) return day;
+ return String(fallback).slice(0, 7);
+ }
+
+ /** That cursor, moved by whole months. */
+ function calShiftMonth(cursor, by) {
+ const [year, month] = calMonthOf(cursor).split("-").map(Number);
+ return new Date(Date.UTC(year, month - 1 + by, 1)).toISOString().slice(0, 7);
+ }
+
+ /** `Sep 2026`, the heading between the two arrows. */
+ function calMonthLabel(cursor) {
+ const [year, month] = calMonthOf(cursor).split("-").map(Number);
+ return `${CAL_MONTHS[month - 1]} ${year}`;
+ }
+
+ /** One month's cells, in whole weeks, with the days either side flagged. */
+ function calMonthDays(cursor) {
+ const [year, month] = calMonthOf(cursor).split("-").map(Number);
+ const lead = (new Date(Date.UTC(year, month - 1, 1)).getUTCDay() + 6) % 7;
+ const length = new Date(Date.UTC(year, month, 0)).getUTCDate();
+ const cells = [];
+ for (let i = 0; i < Math.ceil((lead + length) / 7) * 7; i += 1) {
+ const at = new Date(Date.UTC(year, month - 1, 1 - lead + i));
+ cells.push({
+ iso: at.toISOString().slice(0, 10),
+ day: at.getUTCDate(),
+ inMonth: at.getUTCMonth() === month - 1,
+ });
+ }
+ return cells;
+ }
+
+ /** Whether a day is outside what the field accepts; an empty bound is none. */
+ function calOutOfRange(iso, min = "", max = "") {
+ if (!asDay(iso)) return true;
+ if (asDay(min) && iso < min) return true;
+ return Boolean(asDay(max) && iso > max);
+ }
+
+ /** …and whether a whole month is, which is what greys an arrow. */
+ function calMonthOutOfRange(cursor, min = "", max = "") {
+ return calMonthDays(cursor)
+ .filter((cell) => cell.inMonth)
+ .every((cell) => calOutOfRange(cell.iso, min, max));
+ }
+
+ // --- fires -----------------------------------------------------------------
+
+ /** The rolling windows FIRMS keeps as layers of their own. Matches
+ * `lib/map/firms.js`; the cross-check runs both over the same input. */
+ const FIRE_WINDOWS = [
+ { id: "24h", label: "24 h" },
+ { id: "48h", label: "48 h" },
+ { id: "72h", label: "72 h" },
+ { id: "7d", label: "7 days" },
+ ];
+ /** Asking by date rather than by how recent. */
+ const FIRE_DATED = "dates";
+ /** FIRMS refuses a longer range, and counts a long one as several requests. */
+ const FIRE_MAX_RANGE_DAYS = 31;
+ /** …and the zoom past which it stops meaning anything: FIRMS draws a fixed
+ * symbol per detection and VIIRS resolves 375 m, so deeper is a screen of
+ * overlapping marks. The app's map caps its tile source at the same level
+ * (`lib/map/basemap.js`) and keeps showing that level, scaled; asking again
+ * from here would only buy a bigger version of the same smear. */
+ const FIRE_MAX_ZOOM = 14;
+
+ const asDay = (value) => (/^\d{4}-\d{2}-\d{2}$/.test(String(value ?? "")) ? String(value) : "");
+
+ /** The last day a range starting here may reach. */
+ function fireLastDay(first, maxDays = FIRE_MAX_RANGE_DAYS) {
+ const start = asDay(first);
+ if (!start) return "";
+ const end = new Date(`${start}T00:00:00Z`);
+ end.setUTCDate(end.getUTCDate() + maxDays - 1);
+ return end.toISOString().slice(0, 10);
+ }
+
+ /** Whether this choice is one the service can answer. */
+ function fireAskable({ window: win, first, last } = {}) {
+ if (win !== FIRE_DATED) return FIRE_WINDOWS.some((entry) => entry.id === win);
+ const start = asDay(first);
+ if (!start) return false;
+ const end = asDay(last) || start;
+ return end >= start && end <= fireLastDay(start);
+ }
+
+ /**
+ * NASA FIRMS over somebody else's map.
+ *
+ * It draws no shape and takes no click: what comes back is a picture of the
+ * ground, which `mapoverlay.js` lays under the drawing. What is held here is
+ * the question — which instrument, over what stretch of time — because that
+ * is arithmetic, and arithmetic is checked against the app's own.
+ */
+ function createFires() {
+ const state = {
+ on: false,
+ keyed: false,
+ sensors: [],
+ sensor: "viirs",
+ window: "24h",
+ first: "",
+ last: "",
+ };
+
+ return {
+ id: "fires",
+ label: "Fires",
+ icon: "flame",
+ needsGeometry: true,
+ /** Without a key there is nothing behind this seat, so the panel greys it
+ * rather than opening on a paragraph explaining the absence. */
+ get offerable() {
+ return state.keyed;
+ },
+ get armed() {
+ return false; // it never waits for a click on the map
+ },
+ get state() {
+ return state;
+ },
+ /** What it is asking for, or null while the question is unfinished. */
+ query() {
+ if (!state.on || !state.keyed || !fireAskable(state)) return null;
+ if (state.window !== FIRE_DATED) return { sensor: state.sensor, window: state.window };
+ const first = asDay(state.first);
+ return {
+ sensor: state.sensor,
+ window: FIRE_DATED,
+ first,
+ last: asDay(state.last) || first,
+ };
+ },
+ set(field, value) {
+ state[field] = value;
+ },
+ toggle() {
+ state.on = !state.on;
+ return state.on;
+ },
+ offer(catalogue) {
+ state.keyed = !!catalogue?.keyed;
+ state.sensors = catalogue?.sensors ?? [];
+ },
+ disarm() {},
+ shapes() {
+ return []; // it is a picture, not a drawing
+ },
+ readout() {
+ if (!state.keyed) return "Add a NASA FIRMS key in Azimut Settings";
+ if (!state.on) return "Detections are not being drawn";
+ if (!fireAskable(state)) return "Pick a date to draw the detections";
+ const name = state.sensors.find((entry) => entry.id === state.sensor)?.label ?? state.sensor;
+ const short = name.replace(/\s*\(.*\)\s*$/, "");
+ if (state.window !== FIRE_DATED) {
+ const win = FIRE_WINDOWS.find((entry) => entry.id === state.window)?.label ?? "";
+ return `${short} · last ${win}`;
+ }
+ const first = asDay(state.first);
+ const last = asDay(state.last);
+ return last && last !== first ? `${short} · ${first} → ${last}` : `${short} · ${first}`;
+ },
+ };
+ }
+
window.AzimutMapTools = {
MAX_CELLS,
- RESIDUAL_LIMIT,
- MEASURE_ME,
+ FIRE_WINDOWS,
+ FIRE_DATED,
+ FIRE_MAX_RANGE_DAYS,
+ FIRE_MAX_ZOOM,
+ fireAskable,
+ fireLastDay,
+ createFires,
+ CAL_WEEKDAYS,
+ calMonthOf,
+ calShiftMonth,
+ calMonthLabel,
+ calMonthDays,
+ calOutOfRange,
+ calMonthOutOfRange,
+ NO_SCALE,
verdict,
createMeasure,
createPins,
diff --git a/extension/popup.html b/extension/popup.html
index 611dc18..35534d7 100644
--- a/extension/popup.html
+++ b/extension/popup.html
@@ -61,6 +61,13 @@
<p id="coords-note" class="muted" hidden>
No coordinates found. Enter them now or add them later in Azimut.
</p>
+ <label class="check">
+ <input id="marks" type="checkbox" />
+ <span>Scale bar &amp; north arrow</span>
+ </label>
+ <p id="marks-note" class="muted indent" hidden>
+ The arrow needs a bearing. Type one above to get it.
+ </p>
<div class="actions stacked">
<button id="capture-area" class="primary">Select area to capture…</button>
<button id="save-place">Save this place</button>
diff --git a/extension/popup.js b/extension/popup.js
index c6ccf41..852fcf5 100644
--- a/extension/popup.js
+++ b/extension/popup.js
@@ -97,6 +97,11 @@ async function init() {
backendUrl: "http://127.0.0.1:8477",
token: "",
lastCaseId: "",
+ // The scale bar and north arrow tick. Kept here rather than read from the
+ // app: this popup opens on somebody else's tab and has to answer offline,
+ // and the app's own tick belongs to the map it draws itself. Off until
+ // asked for, then remembered — nobody wants to tick it per capture.
+ captureMarks: false,
});
stored.backendUrl = stored.backendUrl.replace(/\/+$/, "");
@@ -188,6 +193,22 @@ async function init() {
const paired = await loadCases($("case"), stored);
+ // The marks tick, and what it can honestly promise on this page. Neither mark
+ // is invented: the bar needs a zoom, the arrow a bearing, and most of these
+ // sites write no rotation into their URL — so the note points at the field
+ // that would fix it rather than drawing a needle pointing at a guess.
+ const marks = $("marks");
+ marks.checked = !!stored.captureMarks;
+ const syncMarksNote = () => {
+ $("marks-note").hidden = !marks.checked || numOrNull("bearing") !== null;
+ };
+ marks.addEventListener("change", () => {
+ api.storage.local.set({ captureMarks: marks.checked });
+ syncMarksNote();
+ });
+ $("bearing").addEventListener("input", syncMarksNote);
+ syncMarksNote();
+
// Saving the point needs no pixels — only a position. It stays out of reach
// until both coordinates are there, parsed from the URL or typed above.
const placeBtn = $("save-place");
@@ -247,6 +268,7 @@ async function init() {
lon: numOrNull("lon"),
zoom: numOrNull("zoom"),
bearing: numOrNull("bearing"),
+ marks: marks.checked,
},
});
if (r?.ok) window.close(); // the overlay takes over; a notification reports the result
diff --git a/extension/ui.css b/extension/ui.css
index 0eebb19..99acebc 100644
--- a/extension/ui.css
+++ b/extension/ui.css
@@ -54,6 +54,11 @@ p { margin: 6px 0; }
.row.coords input { width: 50%; }
.row input:focus, .row select:focus { outline: 1px solid var(--accent); }
+/* a switch among the fields above it, not another field: no label column */
+.check { display: flex; align-items: center; gap: 7px; margin: 9px 0 2px; font-size: 12px; }
+.check input { accent-color: var(--accent); }
+.indent { margin-left: 21px; }
+
.actions { display: flex; gap: 8px; margin-top: 12px; }
/* two full-width choices for the same page, stacked so neither label truncates */
.actions.stacked { flex-direction: column; }
diff --git a/frontend/calibration/earth.mjs b/frontend/calibration/earth.mjs
new file mode 100644
index 0000000..6c6b258
--- /dev/null
+++ b/frontend/calibration/earth.mjs
@@ -0,0 +1,179 @@
+/**
+ * Measure how big Google Earth draws its map, from its URL alone.
+ *
+ * npm run calibrate:earth # every case below, headless
+ * npm run calibrate:earth -- --cases cher-1600,chamonix
+ * python scripts/build_earth_fixture.py # registers the shots → tests/fixtures/earth-scale.json
+ *
+ * The map sites that state a tile level were measured by driving them
+ * (`record.mjs`). Earth states a camera distance and a field of view, and a
+ * drag is too blunt to check a formula against: it loses pixels to Earth's own
+ * threshold and gains them to its glide. So nothing here is dragged. Each case
+ * opens a URL, lets Earth place its camera on the ground with one wheel notch
+ * over the middle of the window, then opens the same camera again a known step
+ * east, a known step north, and at half the distance. The screenshots are
+ * registered against each other by `scripts/build_earth_fixture.py`, and how
+ * far the picture moved is the scale, with no gesture anywhere in it. The half
+ * distance says where Earth draws its camera: a picture scaled about any other
+ * pixel does not line up.
+ *
+ * Headless, because Earth puts up no consent wall, and on SwiftShader, because
+ * a headless browser has no GPU. Both only make it slow: each case takes a
+ * minute or so, most of it waiting for imagery to stop arriving.
+ */
+
+import { chromium } from '@playwright/test';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+/**
+ * Where, how far out, in which window. Flat country and a mountain range,
+ * three latitudes, three window shapes, two fields of view, and one case far
+ * enough out that Earth's 3D mode would be a globe: its 2D map is not.
+ */
+export const CASES = [
+ { id: 'cher-1600', lat: 47.388462, lon: 2.352785, d: 3000, w: 1600, h: 1000 },
+ { id: 'cher-1200', lat: 47.388462, lon: 2.352785, d: 3000, w: 1200, h: 760 },
+ { id: 'cher-square', lat: 47.388462, lon: 2.352785, d: 3000, w: 1000, h: 1000 },
+ { id: 'cher-60y', lat: 47.388462, lon: 2.352785, d: 3000, w: 1600, h: 1000, y: 60 },
+ { id: 'flevoland', lat: 52.455, lon: 5.59, d: 2000, w: 1600, h: 1000 },
+ { id: 'chamonix', lat: 45.9237, lon: 6.8694, d: 6000, w: 1600, h: 1000 },
+ { id: 'france-400km', lat: 47.388462, lon: 2.352785, d: 400000, w: 1600, h: 1000 },
+];
+
+/** How far each step moves the picture, in pixels: far enough that a tenth of
+ * a pixel of registration is a small share of it, near enough that most of
+ * the picture is in both shots. */
+const STEP_PX = 140;
+
+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
+
+const earthUrl = ({ lat, lon, a, d, y }) =>
+ `https://earth.google.com/web/@${lat.toFixed(8)},${lon.toFixed(8)},${a}a,${d}d,${y}y,0h,0t,0r`;
+
+/** The camera block of the URL Earth is showing, as numbers. */
+function cameraOf(url) {
+ const at = /@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+)a,([\d.]+)d,([\d.]+)y/.exec(url);
+ if (!at) throw new Error(`no camera in ${url}`);
+ return { lat: +at[1], lon: +at[2], a: at[3], d: at[4], y: at[5] };
+}
+
+/** The same camera, give or take the rounding of Earth's own eight decimals. */
+const sameCamera = (a, b) =>
+ ['lat', 'lon', 'a', 'd'].every((key) => Math.abs(Number(a[key]) - Number(b[key])) < 1e-6);
+
+/** Wait until the address bar and then the picture have both stopped moving. */
+async function still(page) {
+ let url = page.url();
+ let quiet = 0;
+ while (quiet < 2500) {
+ await sleep(250);
+ quiet = page.url() === url ? quiet + 250 : 0;
+ url = page.url();
+ }
+ let last = null;
+ for (let round = 0; round < 30; round += 1) {
+ await sleep(1500);
+ const shot = await page.screenshot();
+ if (last && shot.equals(last)) return;
+ last = shot;
+ }
+}
+
+async function shoot(page, url, path) {
+ await page.goto(url, { waitUntil: 'commit' });
+ await sleep(3000);
+ await page.mouse.move(2, 300); // off the map, so no hover label is in the picture
+ await still(page);
+ await page.screenshot({ path });
+ return page.url();
+}
+
+async function measure(browser, spec, out) {
+ const context = await browser.newContext({
+ viewport: { width: spec.w, height: spec.h },
+ locale: 'en-US',
+ });
+ const page = await context.newPage();
+ const say = (line) => process.stdout.write(` ${spec.id}: ${line}\n`);
+
+ say('opening');
+ await page.goto(earthUrl({ ...spec, a: 0, y: 35 }), { waitUntil: 'commit' });
+ await sleep(4000);
+ await still(page);
+ // One notch over the middle of the window: Earth writes the ground's height
+ // into `a` on any gesture, and a zoom about the camera leaves it in place.
+ await page.mouse.move(spec.w / 2, spec.h / 2);
+ await page.mouse.wheel(0, -120);
+ await sleep(1000);
+ await still(page);
+ const placed = { ...cameraOf(page.url()), y: String(spec.y ?? 35) };
+ say(`placed at ${placed.a} m, ${placed.d} m out`);
+
+ const halfFov = ((Number(placed.y) / 2) * Math.PI) / 180;
+ const metresPerPx = (2 * Number(placed.d) * Math.tan(halfFov)) / spec.h;
+ const dLat = (STEP_PX * metresPerPx) / 111320;
+ const dLon = dLat / Math.cos((placed.lat * Math.PI) / 180);
+ const file = (name) => join(out, `${spec.id}-${name}.png`);
+
+ const shots = {};
+ for (const [name, camera] of [
+ ['base', placed],
+ ['east', { ...placed, lon: placed.lon + dLon }],
+ ['north', { ...placed, lat: placed.lat + dLat }],
+ ['half', { ...placed, d: String(Number(placed.d) / 2) }],
+ ]) {
+ say(name);
+ const asked = earthUrl(camera);
+ const landed = await shoot(page, asked, file(name));
+ // Earth keeps the camera it was handed, to the eight decimals it writes; if
+ // it ever moves one, the shot is of some other view and measures nothing
+ if (!sameCamera(cameraOf(landed), cameraOf(asked))) {
+ throw new Error(`Earth rewrote ${asked} as ${landed}`);
+ }
+ shots[name] = { url: landed.split('/data=')[0], image: `${spec.id}-${name}.png` };
+ }
+ await context.close();
+ return { id: spec.id, window: { w: spec.w, h: spec.h }, dLat, dLon, shots };
+}
+
+function options(argv) {
+ const flags = {};
+ for (let i = 0; i < argv.length; i += 1) {
+ if (!argv[i].startsWith('--')) continue;
+ const next = argv[i + 1];
+ flags[argv[i].slice(2)] = next && !next.startsWith('--') ? next : 'yes';
+ }
+ return flags;
+}
+
+async function run() {
+ const flags = options(process.argv.slice(2));
+ const out = flags.out ?? join(tmpdir(), 'azimut-earth-calibration');
+ const wanted = flags.cases ? flags.cases.split(',') : null;
+ mkdirSync(out, { recursive: true });
+ const browser = await chromium.launch({
+ headless: true,
+ args: ['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
+ });
+ const measured = [];
+ const failed = [];
+ for (const spec of CASES.filter((c) => !wanted || wanted.includes(c.id))) {
+ try {
+ measured.push(await measure(browser, spec, out));
+ } catch (e) {
+ failed.push(`${spec.id}: ${e.message}`);
+ }
+ }
+ await browser.close();
+ writeFileSync(join(out, 'earth-shots.json'), `${JSON.stringify({ measured }, null, 1)}\n`);
+ process.stdout.write(`\n${measured.length} cases → ${out}\n`);
+ if (failed.length) process.stdout.write(`did not finish:\n${failed.map((f) => ` ${f}`).join('\n')}\n`);
+ process.stdout.write(`next: python scripts/build_earth_fixture.py ${out}\n`);
+}
+
+run().catch((e) => {
+ process.stderr.write(`${e.stack}\n`);
+ process.exit(1);
+});
diff --git a/frontend/calibration/protocol.mjs b/frontend/calibration/protocol.mjs
index 5d65af8..23236b3 100644
--- a/frontend/calibration/protocol.mjs
+++ b/frontend/calibration/protocol.mjs
@@ -52,14 +52,31 @@ export const VIEWPORTS = [
/** 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 };
+ * so it takes three to arrive somewhere its URL states exactly. Earth's moves
+ * about a third too, and states the fraction exactly, so three notches are
+ * simply a zoom big enough to solve from. 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, 'google-earth': 3 };
+
+/** How long the address bar has to hold still before a gesture counts as
+ * landed, per site, in milliseconds. Earth rewrites its URL more than once in
+ * one zoom, over a second or more on a machine without a GPU, and a shorter
+ * wait records a view it was only passing through. */
+const QUIET = { 'google-earth': 6000 };
+
+/** How long the address bar has to hold still after a site first opens, where
+ * that is longer than any other wait. Earth flies in from space on every load
+ * and pauses on the way down, and a drag started before it lands is ignored. */
+const OPEN_QUIET = { 'google-earth': 8000 };
+
+/** Sites whose address bar can take far longer than any quiet wait to answer a
+ * gesture, so the run waits for it to change before it waits for it to stop.
+ * Earth without a GPU wrote a pan twenty seconds after the drag. */
+const SLOW_TO_WRITE = new Set(['google-earth']);
/** 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. */
+ * the recording is called. */
const FROM_LINKS = [
['google', 'google-maps', 'google-maps'],
['google_sat', 'google-maps', 'google-maps satellite'],
@@ -92,7 +109,13 @@ export function sites() {
return [
...FROM_LINKS.map(([id, site, label]) => ({ id, site, label, url: links.get(id).url })),
...EXTRA,
- ].map((site) => ({ ...site, notches: NOTCHES[site.site] ?? 1 }));
+ ].map((site) => ({
+ ...site,
+ notches: NOTCHES[site.site] ?? 1,
+ quiet: QUIET[site.site],
+ openQuiet: OPEN_QUIET[site.site],
+ slow: SLOW_TO_WRITE.has(site.site),
+ }));
}
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
@@ -110,8 +133,12 @@ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
* 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 } = {}) {
+export async function settle(page, { quiet = 900, timeout = 120_000, say, changedFrom } = {}) {
const started = Date.now();
+ // a site slow to write is given the chance to say anything at all first
+ while (changedFrom && page.url() === changedFrom && Date.now() - started < 60_000) {
+ await sleep(150);
+ }
let last = page.url();
let still = 0;
let warned = false;
@@ -231,19 +258,21 @@ async function canvasRect(page) {
* 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 } = {}) {
+export async function drive(page, site, { say = () => {}, quiet = site.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 }));
+ record(await settle(page, { say, quiet: site.openQuiet ?? 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}`);
+ const changedFrom = () => (site.slow ? page.url() : undefined);
+ let from = changedFrom();
await panBy(page, { x: Math.round(view.width * 0.62), y: Math.round(view.height * 0.55) }, by);
- record(await settle(page, { say, quiet }));
+ record(await settle(page, { say, quiet, changedFrom: from }));
// 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
@@ -257,10 +286,11 @@ export async function drive(page, site, { say = () => {}, quiet } = {}) {
]) {
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}`);
+ from = changedFrom();
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 });
+ const before = steps.length - 1;
+ record(await settle(page, { say, quiet, changedFrom: from }));
+ zooms.push({ from: before, to: steps.length - 1, at });
}
return {
diff --git a/frontend/calibration/record.mjs b/frontend/calibration/record.mjs
index 1e96b0b..d197f81 100644
--- a/frontend/calibration/record.mjs
+++ b/frontend/calibration/record.mjs
@@ -104,7 +104,14 @@ async function run() {
headless: wanted.headless,
viewport: { width, height },
deviceScaleFactor: viewport.pageZoom,
- args: browser === 'chromium' ? [`--window-size=${viewport.w},${viewport.h}`] : [],
+ // A headless Chromium has no GPU, and Earth draws nothing without WebGL.
+ args:
+ browser === 'chromium'
+ ? [
+ `--window-size=${viewport.w},${viewport.h}`,
+ ...(wanted.headless ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : []),
+ ]
+ : [],
});
const page = context.pages()[0] ?? (await context.newPage());
if (wanted.rounding) {
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index c3f1775..13fc98f 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -489,7 +489,18 @@ const entityTypes = [
},
{ type: 'media', label: 'Media', family: 'collected', icon: 'image', manual: false, group: '', hint: 'a file the case collected', family_reads: 'bytes gathered into the case rather than written', attrs: [] },
{ type: 'capture', label: 'Capture', family: 'collected', icon: 'satellite', manual: false, group: '', hint: 'a map screenshot', family_reads: 'bytes gathered into the case rather than written', attrs: [] },
- { type: 'place', label: 'Place', family: 'place', icon: 'pin', manual: false, group: 'How precise', hint: 'a saved point', family_reads: 'a point on the map, never a thing standing on it', attrs: [] },
+ {
+ type: 'place', label: 'Place', family: 'place', icon: 'pin', manual: false, group: '',
+ hint: 'a saved point', family_reads: 'a point on the map, never a thing standing on it',
+ // the precision fields, as `engine/entities.py` declares them: a place edited from
+ // the map opens the same panel as the sidebar, and these are what it is opened for
+ attrs: [
+ { key: 'radius_m', label: 'Uncertainty radius (m)', kind: 'number', group: 'How precise', rungs: [{ value: 500, label: 'This neighbourhood' }], options: [], minimum: 1, maximum: 5000000 },
+ { key: 'footprint', label: 'Footprint', kind: 'geojson', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'verbatim', label: 'As the source put it', kind: 'longtext', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'method', label: 'How this point was found', kind: 'longtext', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
{ type: 'note', label: 'Note', family: 'document', icon: 'note', manual: false, group: '', hint: 'a Markdown page in the case notebook', family_reads: 'something read rather than gathered', attrs: [] },
{
type: 'bookmark', label: 'Bookmark', family: 'document', icon: 'globe', manual: false, group: '',
@@ -1775,6 +1786,17 @@ export async function installAppFixture(page, options = {}) {
return json(route, { entity: fixtureLookupEntities[url.searchParams.get('value')] ?? null });
}
if (path === '/api/satellite/providers') return json(route, fixtureProviders);
+ if (path === '/api/firms/sensors') {
+ return json(route, {
+ keyed: false,
+ sensors: [
+ { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'viirs_noaa20', label: 'VIIRS NOAA-20' },
+ { id: 'modis', label: 'MODIS' },
+ ],
+ max_zoom: 10,
+ });
+ }
// one billed map load, counted where it happens: the tile proxy cannot see
// the Maps JS widget, so the tool reports it itself
if (path.startsWith('/api/satellite/usage/') && request.method() === 'POST') {
diff --git a/frontend/e2e/place-precision.spec.js b/frontend/e2e/place-precision.spec.js
new file mode 100644
index 0000000..f357db2
--- /dev/null
+++ b/frontend/e2e/place-precision.spec.js
@@ -0,0 +1,151 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+/**
+ * How tightly a place is pinned, driven in a real browser.
+ *
+ * Tracing is a gesture on the map and nothing else can stand in for it: the
+ * corners are clicks on the ground, and what makes a shape wrong is where those
+ * clicks landed relative to a pin somewhere else on screen. Two rules are under
+ * test, and both were things the app let happen without a word — a shape traced
+ * beside its own point, and a radius that quietly stopped being drawn the moment
+ * a shape existed.
+ */
+
+// The point the fixture's home view opens on, so the pin sits dead centre.
+const HOME = { lat: 48.8584, lon: 2.2945 };
+
+const quay = {
+ id: 'place-1',
+ key: 'place-1',
+ kind: 'place',
+ title: 'checkpoint north',
+ lat: HOME.lat,
+ lon: HOME.lon,
+ zoom: 16,
+ radius_m: 500,
+ footprint: null,
+ relations: 0,
+ status: 'confirmed',
+ fetched_at: '2026-09-10T09:00:00Z',
+ geo: { state: 'ok', country_code: 'fr', country: 'France' },
+ continent: 'Europe',
+ country_en: 'France',
+};
+
+const chain = {
+ entity: {
+ id: 'place-1',
+ type: 'place',
+ label: 'checkpoint north',
+ attrs: { ...HOME, radius_m: 500, method: 'roofline match' },
+ provenance: { by: 'user', at: '2026-09-10T09:00:00Z', status: 'confirmed' },
+ },
+ sources: [],
+ lost: [],
+ dependents: [],
+ relations: [],
+ empty: true,
+};
+
+async function openCard(page) {
+ const fixture = await installAppFixture(page, {
+ savedIndex: [quay],
+ chains: { 'place-1': chain },
+ });
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+ await page.getByRole('button', { name: 'Saved work' }).click();
+ await page.locator('.saved-mark').click();
+ return fixture;
+}
+
+/** Arm tracing from the place's own card, which is the only way in. */
+async function armTrace(page) {
+ const fixture = await openCard(page);
+ await page.locator('.saved-popup').getByText('Trace footprint').click();
+ const panel = page.locator('.footprint-panel');
+ await expect(panel).toContainText('checkpoint north');
+ // it says what it is about to take the place of, before anything is written
+ await expect(panel).toContainText('replaces its 500 m circle');
+ return fixture;
+}
+
+/** Click corners at offsets from the middle of the map, where the pin is. */
+async function corners(page, points) {
+ const box = await page.locator('.map').boundingBox();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+ for (const [dx, dy] of points) await page.mouse.click(cx + dx, cy + dy);
+}
+
+const saveShape = (page) => page.locator('.footprint-panel').getByRole('button', { name: 'Save' });
+
+test('refuses a shape traced beside the place it belongs to', async ({ page }) => {
+ const fixture = await armTrace(page);
+
+ // three corners, all of them off to one side of the pin
+ await corners(page, [[140, -150], [260, -150], [260, -40]]);
+
+ const panel = page.locator('.footprint-panel');
+ await expect(panel).toContainText('The shape has to contain the pin it belongs to.');
+ await expect(saveShape(page)).toBeDisabled();
+ expect(fixture.entityWrites).toEqual([]);
+});
+
+test('writes a shape around the pin, and drops the circle it replaces', async ({ page }) => {
+ const fixture = await armTrace(page);
+
+ await corners(page, [[-130, -120], [130, -120], [130, 120], [-130, 120]]);
+
+ await expect(page.locator('.footprint-panel')).toContainText('4 corners');
+ await saveShape(page).click();
+
+ await expect.poll(() => fixture.entityWrites.length).toBe(1);
+ const written = fixture.entityWrites[0];
+ expect(written.method).toBe('PATCH');
+ expect(written.id).toBe('place-1');
+ expect(written.body.attrs.footprint.type).toBe('Polygon');
+ // the pin is inside what was drawn…
+ const ring = written.body.attrs.footprint.coordinates[0];
+ expect(Math.min(...ring.map(([lon]) => lon))).toBeLessThan(HOME.lon);
+ expect(Math.max(...ring.map(([lon]) => lon))).toBeGreaterThan(HOME.lon);
+ // …and the radius goes with the shape that replaced it: one precision, one form
+ expect(written.body.attrs.radius_m).toBe(null);
+ await expect(page.locator('.footprint-panel')).toBeHidden();
+});
+
+test('opens the full editor on a place from the map', async ({ page }) => {
+ await openCard(page);
+ await page.locator('.saved-popup').getByText('Edit', { exact: true }).click();
+
+ const dialog = page.getByRole('dialog', { name: 'Edit place' });
+ await expect(dialog).toBeVisible();
+ // the short form asks what an analyst fills at the moment of saving…
+ await expect(dialog.getByLabel('Title')).toHaveValue('checkpoint north');
+ await expect(dialog).not.toContainText('Uncertainty radius');
+
+ await dialog.getByRole('button', { name: 'Edit more details' }).click();
+
+ // …and the rest is the panel every other surface opens, on what the case holds
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await expect(details).toBeVisible();
+ await expect(details.getByLabel('Uncertainty radius (m)')).toHaveValue('500');
+ await expect(details.getByLabel('How this point was found')).toHaveValue('roofline match');
+});
+
+test('asks before handing over would drop what the short form holds', async ({ page }) => {
+ await openCard(page);
+ await page.locator('.saved-popup').getByText('Edit', { exact: true }).click();
+ const dialog = page.getByRole('dialog', { name: 'Edit place' });
+ await dialog.getByLabel('Title').fill('checkpoint north, gate');
+
+ await dialog.getByRole('button', { name: 'Edit more details' }).click();
+
+ await expect(page.getByText('This place has edits that Save has not taken.')).toBeVisible();
+ await expect(page.getByRole('dialog', { name: 'Details' })).toBeHidden();
+
+ await page.getByRole('button', { name: 'Discard' }).click();
+
+ await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+});
diff --git a/frontend/e2e/satellite-overlays.spec.js b/frontend/e2e/satellite-overlays.spec.js
index 67e2e5a..2e3154a 100644
--- a/frontend/e2e/satellite-overlays.spec.js
+++ b/frontend/e2e/satellite-overlays.spec.js
@@ -30,8 +30,12 @@ async function openGrid(page) {
* builds a layer's features off the main thread — so a click fired in the same
* tick can land before there is anything under it to hit. An analyst never
* moves that fast; a spec does.
+ *
+ * It starts clear of the map's top-left corner on purpose: the rail is a
+ * column, so the armed tool's panel opens beside it over roughly the first
+ * 280 px, and a drag begun under the panel never reaches the map at all.
*/
-async function dragBox(page, from = [140, 130], to = [420, 330]) {
+async function dragBox(page, from = [300, 130], to = [580, 330]) {
const bare = await mapPicture(page);
const box = await page.locator('.map').boundingBox();
await page.mouse.move(box.x + from[0], box.y + from[1]);
@@ -65,7 +69,7 @@ test('marks a cell where it was clicked, and files that mark', async ({ page })
await expect(coverage(page)).toContainText('0/');
const box = await page.locator('.map').boundingBox();
- await page.mouse.click(box.x + 200, box.y + 200);
+ await page.mouse.click(box.x + 360, box.y + 200);
// one cell cleared: the click reached the shape on the canvas, and only it
await expect(coverage(page)).toContainText('1/');
@@ -81,7 +85,7 @@ test('flags a cell on a right-click without cycling it', async ({ page }) => {
await dragBox(page);
const box = await page.locator('.map').boundingBox();
- await page.mouse.click(box.x + 200, box.y + 200, { button: 'right' });
+ await page.mouse.click(box.x + 360, box.y + 200, { button: 'right' });
await expect(coverage(page)).toContainText('flagged');
await expect.poll(() => {
@@ -205,8 +209,11 @@ test('carries the coordinates on a dragged pin, and drops it on exit', async ({
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByTitle('Marker style').selectOption('pin');
- await page.getByTitle('Move the marker (coordinates follow it)').click();
+ // both answers are behind the one square in the strip: what marks the point,
+ // and whether the point is the centre or a pin you drop
+ await page.getByRole('button', { name: 'Marker' }).click();
+ await page.getByRole('radio', { name: 'Pin', exact: true }).click();
+ await page.getByRole('radio', { name: 'Dropped' }).click();
const pin = page.locator('.sat-marker');
await expect(pin).toHaveCount(1);
@@ -221,7 +228,9 @@ test('carries the coordinates on a dragged pin, and drops it on exit', async ({
// the readout is what a capture files, so it follows the pin, not the centre
await expect.poll(async () => (await readout.innerText()) !== before).toBe(true);
- await page.getByTitle('Move the marker (coordinates follow it)').click();
+ // dragging on the map closed the menu, which is what a click anywhere else does
+ await page.getByRole('button', { name: 'Marker' }).click();
+ await page.getByRole('radio', { name: 'Centre' }).click();
await expect(pin).toHaveCount(0);
});
@@ -236,7 +245,8 @@ test('lays the OSM labels over the imagery, and lifts them off again', async ({
});
await page.goto('/#satellite');
await awaitMapReady(page);
- const labels = page.getByLabel('Toggle OSM labels overlay');
+ // the labels are a layer, listed with the others in the panel on the right
+ const labels = page.getByLabel('OSM labels');
expect(fixture.labelTiles).toEqual([]);
await labels.click();
diff --git a/frontend/e2e/satellite-widget.spec.js b/frontend/e2e/satellite-widget.spec.js
index 16c8763..d689eaf 100644
--- a/frontend/e2e/satellite-widget.spec.js
+++ b/frontend/e2e/satellite-widget.spec.js
@@ -12,12 +12,23 @@ import { awaitMapReady, fakeGoogleMaps, installAppFixture, mapPicture } from './
* and whether it is ever built twice.
*/
+/**
+ * Pick a basemap from the surface's own chip.
+ *
+ * It is a chip and a list rather than a `<select>`: the provider belongs to the
+ * surface, not to the tool, and two compared surfaces each carry their own.
+ */
+async function pickProvider(page, label) {
+ await page.getByRole('button', { name: 'Imagery provider' }).click();
+ await page.getByRole('option', { name: label }).click();
+}
+
async function openWidget(page) {
await fakeGoogleMaps(page);
const fixture = await installAppFixture(page, { widget: true });
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByTitle('Imagery provider').selectOption('google-js');
+ await pickProvider(page, 'Google Satellite (Maps JS)');
await expect(page.locator('.map-glass')).toBeAttached();
return fixture;
}
@@ -88,9 +99,9 @@ test('is built once and counted once, however often it is shown', async ({ page
expect(await maps(page)).toBe(1);
await expect.poll(() => fixture.widgetLoads).toEqual(['google_js']);
- await page.getByTitle('Imagery provider').selectOption('esri-world-imagery');
+ await pickProvider(page, 'Esri World Imagery');
await expect(page.locator('.map-glass')).toHaveAttribute('hidden', '');
- await page.getByTitle('Imagery provider').selectOption('google-js');
+ await pickProvider(page, 'Google Satellite (Maps JS)');
await expect(page.locator('.map-glass')).not.toHaveAttribute('hidden', '');
expect(await maps(page)).toBe(1);
diff --git a/frontend/e2e/satellite-windows.spec.js b/frontend/e2e/satellite-windows.spec.js
new file mode 100644
index 0000000..bf4d868
--- /dev/null
+++ b/frontend/e2e/satellite-windows.spec.js
@@ -0,0 +1,172 @@
+import { test, expect } from '@playwright/test';
+import { awaitMapReady, installAppFixture } from './app.fixture.js';
+
+/**
+ * One map, several windows — driven in a real browser, because every part of
+ * this is the browser's: the address bar, `window.open`, and whether a second
+ * window is allowed at all. None of it can be asserted from a source string.
+ *
+ * It runs on both engines. Firefox and Chromium disagree about what a window
+ * opened with features is, and about how a hash written with `replaceState`
+ * reads back, which is exactly why it is here rather than in a unit test.
+ */
+
+const readout = (page) => page.locator('.hud-coords');
+
+test('opens on the view its address carries, not the saved home view', async ({ page }) => {
+ await installAppFixture(page);
+ // the fixture's home view is 48.8584, 2.2945 at z16 — this is somewhere else
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13');
+ await awaitMapReady(page);
+
+ await expect(readout(page)).toContainText('50.450');
+ await expect(readout(page)).toContainText('30.523');
+ await expect(readout(page)).toContainText('z13');
+});
+
+test('leaves the map where it was when the address says something impossible', async ({ page }) => {
+ await installAppFixture(page);
+ // an address is typed by hand, and a map that flies to NaN is unrecoverable
+ await page.goto('/#satellite?ll=nowhere&z=900');
+ await awaitMapReady(page);
+
+ await expect(readout(page)).toContainText('48.858');
+ await expect(readout(page)).toContainText('z16');
+});
+
+test('keeps this window\'s view in this window\'s address', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite');
+ await awaitMapReady(page);
+
+ await expect.poll(() => page.evaluate(() => location.hash)).toContain('ll=48.8584');
+
+ const box = await page.locator('.map').boundingBox();
+ await page.mouse.move(box.x + 500, box.y + 300);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 300, box.y + 180, { steps: 8 });
+ await page.mouse.up();
+
+ // the pan moved the address with it…
+ await expect
+ .poll(() => page.evaluate(() => location.hash))
+ .not.toContain('ll=48.8584,2.2945');
+ // …and did not fill the back button on the way
+ expect(await page.evaluate(() => history.length)).toBeLessThan(4);
+});
+
+test('hands a second window the view the first one is showing', async ({ page, context }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13');
+ await awaitMapReady(page);
+
+ // the popup carries the fixture with it: it is the same origin, but a new page
+ const opening = context.waitForEvent('page');
+ await page.getByRole('button', { name: 'Open in a new tab' }).click();
+ const second = await opening;
+ await installAppFixture(second);
+ await second.reload();
+ await awaitMapReady(second);
+
+ // same ground…
+ await expect(second.locator('.hud-coords')).toContainText('50.450');
+ // …and it says which window it is, since two of them look identical
+ await expect(second.getByRole('heading', { name: 'Satellite · 2' })).toBeVisible();
+ // the first one stays unnumbered and keeps its own view
+ await expect(page.getByRole('heading', { name: 'Satellite', exact: true })).toBeVisible();
+
+ // two windows, two cameras: moving one leaves the other alone
+ const box = await second.locator('.map').boundingBox();
+ await second.mouse.move(box.x + 500, box.y + 300);
+ await second.mouse.down();
+ await second.mouse.move(box.x + 260, box.y + 160, { steps: 8 });
+ await second.mouse.up();
+ await expect.poll(() => second.evaluate(() => location.hash)).not.toContain('ll=50.4501');
+ await expect(readout(page)).toContainText('50.450');
+
+ await second.close();
+});
+
+test('opens the detached tab on the map, without the app around it', async ({ page, context }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13');
+ await awaitMapReady(page);
+
+ const opening = context.waitForEvent('page');
+ await page.getByRole('button', { name: 'Open in a new tab' }).click();
+ const second = await opening;
+ await installAppFixture(second);
+ await second.reload();
+ await awaitMapReady(second);
+
+ // the rail, the case bar and the tab strip are how you get somewhere else,
+ // and a second screen showing one map is already somewhere
+ await expect(second.locator('nav.rail')).toHaveCount(0);
+ await expect(second.locator('.topbar')).toHaveCount(0);
+ await expect(second.locator('.tabstrip')).toHaveCount(0);
+ // …and it is still a whole map
+ await expect(second.locator('.map')).toBeVisible();
+ await expect(second.locator('.hud-coords')).toContainText('50.450');
+
+ // the first window keeps all of its own
+ await expect(page.locator('nav.rail')).toHaveCount(1);
+
+ await second.close();
+});
+
+test('keeps the tab on the map alone after it has been panned and reloaded', async ({ page }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13&w=2&solo=1');
+ await awaitMapReady(page);
+ await expect(page.locator('nav.rail')).toHaveCount(0);
+
+ const box = await page.locator('.map').boundingBox();
+ await page.mouse.move(box.x + 500, box.y + 300);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 300, box.y + 180, { steps: 8 });
+ await page.mouse.up();
+
+ // the pan rewrites the address, and what the tab *is* has to ride along
+ await expect.poll(() => page.evaluate(() => location.hash)).toContain('solo=1');
+ await page.reload();
+ await awaitMapReady(page);
+ await expect(page.locator('nav.rail')).toHaveCount(0);
+});
+
+test('links two tabs onto one camera, and unlinks them again', async ({ page, context }) => {
+ await installAppFixture(page);
+ await page.goto('/#satellite?ll=50.4501,30.5234&z=13');
+ await awaitMapReady(page);
+
+ const second = await context.newPage();
+ await installAppFixture(second);
+ await second.goto('/#satellite?ll=48.8584,2.2945&z=13');
+ await awaitMapReady(second);
+
+ const link = (target) => target.getByRole('button', { name: 'Link the view to the other maps' });
+ await link(page).click();
+ await link(second).click();
+
+ // pressing it hands the others this tab's camera, so the last one pressed wins
+ await expect(readout(page)).toContainText('48.858');
+
+ // …and from then on a pan in either carries the other with it
+ const box = await page.locator('.map').boundingBox();
+ await page.mouse.move(box.x + 500, box.y + 300);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 280, box.y + 160, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(async () => (await readout(second).innerText()).includes('48.858')).toBe(false);
+
+ // unlinked, the two go their own ways again
+ await link(second).click();
+ const parked = await readout(second).innerText();
+ await page.mouse.move(box.x + 500, box.y + 300);
+ await page.mouse.down();
+ await page.mouse.move(box.x + 700, box.y + 420, { steps: 8 });
+ await page.mouse.up();
+ await expect.poll(async () => (await readout(page).innerText()) !== parked).toBe(true);
+ expect(await readout(second).innerText()).toBe(parked);
+
+ await second.close();
+});
diff --git a/frontend/e2e/saved-linked-posts.spec.js b/frontend/e2e/saved-linked-posts.spec.js
index c37f667..53deb9a 100644
--- a/frontend/e2e/saved-linked-posts.spec.js
+++ b/frontend/e2e/saved-linked-posts.spec.js
@@ -55,7 +55,7 @@ test('shows every linked post from a proof popup and opens the selected draft',
await page.getByRole('button', { name: 'Proofs', exact: true }).click();
await expect(page.getByText('Panorama autostitch test')).toBeVisible();
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark-proof').click();
const popup = page.locator('.saved-popup');
@@ -91,7 +91,7 @@ test('clears capture rows before a different case index arrives', async ({ page
await awaitMapReady(page); // the rows are read beside a map, and one mark is on it
const savedPanel = page.locator('.captures');
await expect(savedPanel.getByText('Capture A', { exact: true })).toBeVisible();
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await expect(page.locator('.saved-mark-capture')).toHaveCount(1);
await page.getByTitle('Switch case').click();
await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.js
index 8132934..d678847 100644
--- a/frontend/e2e/saved-relations.spec.js
+++ b/frontend/e2e/saved-relations.spec.js
@@ -73,7 +73,7 @@ test('opens a stacked row’s relations without closing the card', async ({ page
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -98,7 +98,7 @@ test('corrects the reading of a relation in place, and takes one back', async ({
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -125,7 +125,7 @@ test('settles a suggested relation from the card, which survives the click', asy
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
@@ -169,7 +169,7 @@ test('shows the findings on the card and leaves the pointers out', async ({ page
await page.goto('/#satellite');
await awaitMapReady(page);
- await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.getByRole('button', { name: 'Saved work', exact: true }).click();
await page.locator('.saved-mark').click();
const popup = page.locator('.saved-popup');
diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.js
index cba9d63..e892198 100644
--- a/frontend/e2e/timeline.spec.js
+++ b/frontend/e2e/timeline.spec.js
@@ -775,16 +775,23 @@ async function openTimelineOverJune(page, options = {}) {
return fixture;
}
+function timelineMapLayer(page) {
+ return page.getByRole('listitem').filter({
+ has: page.getByRole('button', { name: 'Timeline points', exact: true }),
+ });
+}
+
test('hands one window from the Timeline to the Map, the Board and back', async ({ page }) => {
const fixture = await openTimelineOverJune(page);
await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
- const layer = page.getByLabel('Timeline map layer');
- await expect(layer).toContainText('1 Jun – 21 Jun 2026');
+ const layer = timelineMapLayer(page);
+ await expect(layer.getByRole('button', { name: 'Timeline points' }))
+ .toHaveAttribute('title', '1 Jun – 21 Jun 2026');
// What the window holds, and how much of it the map can show: the layer reads
- // every category the Timeline was reading, so the count is the whole window.
- await expect(layer).toContainText('1 placed of 12 dated');
+ // every category the Timeline was reading, so the compact count is the whole window.
+ await expect(layer).toContainText('1 of 12');
await expect(page.locator('.temporal-mark')).toHaveCount(1);
await layer.getByRole('button', { name: 'Board' }).click();
@@ -836,7 +843,8 @@ test('draws the window and nothing else, framed on what it holds', async ({ page
await expect(page.locator('.temporal-mark')).toHaveCount(1);
await expect(page.locator('.saved-mark-place')).toHaveCount(0);
- await expect(page.getByRole('button', { name: 'Show saved work on the map' })).not.toHaveClass(/on/);
+ await expect(page.getByRole('button', { name: 'Saved work', exact: true }))
+ .toHaveAttribute('aria-pressed', 'false');
const framed = await page.evaluate(() => {
const map = document.querySelector('.map').getBoundingClientRect();
@@ -864,8 +872,8 @@ test('says a window holds nothing placed instead of pulling the map out to say i
await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
await awaitMapReady(page); // the marks are drawn on it, so it has to be up
- const layer = page.getByLabel('Timeline map layer');
- await expect(layer).toContainText('None of the 10 dated here carries a place.');
+ const layer = timelineMapLayer(page);
+ await expect(layer).toContainText('0 of 10');
// Nothing to draw is said in words, not by pulling the view out to two continents
// of unrelated pins, which is what a map showing everything looks like.
await expect(page.locator('.temporal-mark')).toHaveCount(0);
diff --git a/frontend/package.json b/frontend/package.json
index b3988d2..684036f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -11,6 +11,7 @@
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
"calibrate:maps": "node calibration/record.mjs",
+ "calibrate:earth": "node calibration/earth.mjs",
"check": "svelte-check --output human --threshold warning"
},
"devDependencies": {
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 939eb1f..9530455 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -22,6 +22,7 @@
workspaceOf,
toolFromHash,
} from './lib/workspaces.js';
+ import { readSolo, splitHash } from './lib/hash.js';
import { guideFor } from './lib/guide.js';
import { openGuide } from './lib/navigate.js';
import { createToolLoader } from './lib/toolLoader.js';
@@ -81,9 +82,32 @@
// (#compose, #compose/post) — see lib/workspaces.js
const fromHash = toolFromHash(location.hash, TOOL_IDS);
if (fromHash) uiState.tool = fromHash;
+ // The app owns the route; a tool may keep its own state in the query after it
+ // (the map writes the view its window is on, lib/map/view.js). So this writes
+ // only when the route is not already the open tool — otherwise switching back
+ // and forth would wipe what that tool had put there.
$effect(() => {
+ if (splitHash(location.hash).route === uiState.tool) return;
history.replaceState(null, '', `#${uiState.tool}`);
});
+ /**
+ * A tab opened to hold one tool and nothing else (`lib/hash.js`).
+ *
+ * Read once, at load, because it describes the tab rather than a state the
+ * app moves through: the way out of it is the address, which is the same way
+ * in. Everything it takes away belongs to getting *somewhere else* — the
+ * workspace rail, the case bar, the tab strip, the case sidebar — and a
+ * second screen showing one map is already somewhere.
+ */
+ const solo = readSolo(splitHash(location.hash).params);
+ // Map windows are numbered per window, and the one that opened the app is the
+ // first: a window that was detached carries its own number in the address and
+ // leaves the count alone (tools/Satellite.svelte).
+ if (!splitHash(location.hash).params.has('w')) {
+ try {
+ localStorage.setItem('azimut:mapWindows', '1');
+ } catch { /* a locked-down profile only loses the numbering */ }
+ }
// A frozen reading belongs to the surface that captured it. Carrying a Graph
// snapshot into Board made the capture look like an incomplete second case and
@@ -196,6 +220,7 @@
</script>
<div class="shell">
+ {#if !solo}
<header class="topbar">
<!-- 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
@@ -256,8 +281,10 @@
<Icon name="panelRight" size={16} />
</button>
</header>
+ {/if}
<div class="main">
+ {#if !solo}
<nav class="rail">
{#each WORKSPACES as ws (ws.id)}
<button
@@ -279,9 +306,10 @@
<span>{uiState.theme === 'light' ? 'Dark' : 'Light'}</span>
</button>
</nav>
+ {/if}
<main class="canvas">
- {#if activeWs && activeWs.tools.length > 1}
+ {#if !solo && activeWs && activeWs.tools.length > 1}
<div class="tabstrip">
{#each activeWs.tools as toolId (toolId)}
<button
@@ -315,7 +343,7 @@
</div>
</main>
- {#if uiState.sidebarOpen}
+ {#if uiState.sidebarOpen && !solo}
<CaseSidebar />
{/if}
</div>
diff --git a/frontend/src/app.css b/frontend/src/app.css
index dac2126..af19487 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -736,6 +736,36 @@ a:hover {
font-style: italic;
}
+/* A section heading inside a side panel, foldable: a chevron, an icon, the name
+ in the panel's small caps, and what it holds counted on the right. Global
+ because the sections of one panel are not all written in the same component —
+ the map's Layers list is its own — and a scoped copy is a heading that drifts
+ out of the voice of the one above it. */
+.sub-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 12px 2px 6px;
+ background: none;
+ border: none;
+ font: inherit;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-2);
+ text-align: left;
+ cursor: pointer;
+}
+.sub-head:hover {
+ color: var(--accent);
+}
+.sub-head .count {
+ margin-left: auto;
+ text-transform: none;
+}
+
/* Row and value marks, from the annotation palette. Global because three components
paint with them — the grid's rows and chips, the cell editor's offers, the column
panel's vocabulary — and a scoped copy per component is three lists that drift. The
diff --git a/frontend/src/components/AttrFields.svelte b/frontend/src/components/AttrFields.svelte
index 5eff98b..c3e3450 100644
--- a/frontend/src/components/AttrFields.svelte
+++ b/frontend/src/components/AttrFields.svelte
@@ -19,11 +19,10 @@
const fields = $derived(entityFields(type));
/**
- * A shape can only be traced on a map, and no map offers that gesture yet. So an
- * empty footprint shows nothing at all: a label over a hint reads as a control
- * that has stopped working, where absence reads as what it is. It appears the
- * moment a shape exists — set through the API, or by the drawing tool when it
- * lands — carrying the summary and the Clear that drops it.
+ * A shape is traced on the map, never typed here. So an empty footprint shows
+ * nothing at all: a label over a hint reads as a control that has stopped working,
+ * where absence reads as what it is. It appears the moment a shape exists, carrying
+ * the summary and the Clear that drops it.
*/
const shown = $derived(withHeadings(fields.filter((field) => {
if (exclude.includes(field.key)) return false;
diff --git a/frontend/src/components/DayPicker.render.test.js b/frontend/src/components/DayPicker.render.test.js
new file mode 100644
index 0000000..7ce4ca6
--- /dev/null
+++ b/frontend/src/components/DayPicker.render.test.js
@@ -0,0 +1,114 @@
+// @vitest-environment happy-dom
+/**
+ * The calendar, actually mounted.
+ *
+ * What it replaced was a browser's own picker, and the failures that made it
+ * worth replacing are all in the DOM rather than in the source: a calendar that
+ * opens over the panel instead of inside it, a day the bounds should have
+ * refused, a month arrow that walks into years the service cannot answer for.
+ */
+import { describe, expect, it, afterEach, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const { default: DayPicker } = await import('./DayPicker.svelte');
+
+const live = [];
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live.push(mount(DayPicker, { target, props }));
+ flushSync();
+ return target;
+}
+
+const field = (root) => root.querySelector('.field');
+const days = (root) => [...root.querySelectorAll('.day')];
+const dayNamed = (root, iso) => days(root).find((b) => b.title === iso);
+
+afterEach(() => {
+ while (live.length) unmount(live.pop());
+ document.body.innerHTML = '';
+});
+
+describe('the field', () => {
+ it('reads the day the way the rest of the app writes one', () => {
+ const root = open({ value: '2026-09-12' });
+ expect(field(root).textContent).toContain('2026-09-12');
+ expect(field(root).getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('says what an empty one means rather than showing a blank box', () => {
+ const root = open({ value: '', placeholder: 'That day alone' });
+ expect(field(root).textContent).toContain('That day alone');
+ });
+});
+
+describe('the calendar it opens', () => {
+ it('is drawn in the panel, not over it', () => {
+ const root = open({ value: '2026-09-12' });
+ field(root).click();
+ flushSync();
+ const cal = root.querySelector('.cal');
+ expect(cal).not.toBe(null);
+ // the whole reason it exists: nothing here is positioned out of the flow,
+ // so no edge of any panel can cut it
+ expect(getComputedStyle(cal).position).not.toBe('absolute');
+ expect(getComputedStyle(cal).position).not.toBe('fixed');
+ });
+
+ it('opens on the month of the day it holds, and walks whole months', () => {
+ const root = open({ value: '2026-09-12' });
+ field(root).click();
+ flushSync();
+ expect(root.querySelector('.month').textContent).toBe('Sep 2026');
+ root.querySelector('[aria-label="Previous month"]').click();
+ flushSync();
+ expect(root.querySelector('.month').textContent).toBe('Aug 2026');
+ });
+
+ it('hands the day back in the one form the services take, and closes', () => {
+ const onpick = vi.fn();
+ const root = open({ value: '2026-09-12', onpick });
+ field(root).click();
+ flushSync();
+ dayNamed(root, '2026-09-03').click();
+ flushSync();
+ expect(onpick).toHaveBeenCalledWith('2026-09-03');
+ expect(root.querySelector('.cal')).toBe(null);
+ });
+
+ it('marks the day it holds, and refuses the ones outside its bounds', () => {
+ const root = open({ value: '2026-09-12', min: '2026-09-10', max: '2026-09-20' });
+ field(root).click();
+ flushSync();
+ expect(dayNamed(root, '2026-09-12').classList.contains('on')).toBe(true);
+ expect(dayNamed(root, '2026-09-09').disabled).toBe(true);
+ expect(dayNamed(root, '2026-09-21').disabled).toBe(true);
+ expect(dayNamed(root, '2026-09-15').disabled).toBe(false);
+ });
+
+ it('greys the arrow into a month every day of which is refused', () => {
+ const root = open({ value: '2026-09-12', min: '2026-09-01', max: '2026-09-30' });
+ field(root).click();
+ flushSync();
+ expect(root.querySelector('[aria-label="Next month"]').disabled).toBe(true);
+ expect(root.querySelector('[aria-label="Previous month"]').disabled).toBe(true);
+ });
+
+ it('takes the day back out only where an empty field means something', () => {
+ const onpick = vi.fn();
+ const plain = open({ value: '2026-09-12', onpick });
+ field(plain).click();
+ flushSync();
+ expect([...plain.querySelectorAll('.act')].map((b) => b.textContent.trim())).toEqual(['Today']);
+
+ const ranged = open({ value: '2026-09-12', clearable: true, onpick });
+ field(ranged).click();
+ flushSync();
+ const clear = [...ranged.querySelectorAll('.act')].find((b) => b.textContent.trim() === 'Clear');
+ clear.click();
+ flushSync();
+ expect(onpick).toHaveBeenCalledWith('');
+ });
+});
diff --git a/frontend/src/components/DayPicker.svelte b/frontend/src/components/DayPicker.svelte
new file mode 100644
index 0000000..16baab6
--- /dev/null
+++ b/frontend/src/components/DayPicker.svelte
@@ -0,0 +1,268 @@
+<script>
+ /**
+ * A day, picked from a calendar drawn inside the panel it belongs to.
+ *
+ * `<input type="date">` was the obvious answer and the wrong one here: its
+ * calendar is browser chrome, so it opens at the browser's size, in the
+ * browser's locale, and *over* the page — which in a panel docked to the
+ * right edge of the window means half of it outside the window, and a date
+ * reading `12/09/2026` in an app that writes `2026-09-12` everywhere else.
+ *
+ * So the month is drawn here, in flow: it pushes the rows under it down
+ * rather than floating over them, which is the whole of why it cannot be
+ * clipped. The arithmetic is `lib/calendar.js`, and the extension's panel
+ * draws the same grid from its own copy of it.
+ */
+ import Icon from './Icon.svelte';
+ import {
+ WEEKDAYS,
+ monthDays,
+ monthLabel,
+ monthOf,
+ monthOutOfRange,
+ outOfRange,
+ shiftMonth,
+ today as todayOf,
+ } from '../lib/calendar.js';
+
+ let {
+ /** The day being shown, `YYYY-MM-DD`, or '' for none. */
+ value = '',
+ /** What the field says when there is no day yet. */
+ placeholder = 'Any day',
+ /** Bounds, either of which may be empty for "no bound". */
+ min = '',
+ max = '',
+ /** Names the field for a reader that cannot see the label beside it. */
+ label = 'Date',
+ /** Whether the day can be taken back out, for a field that means "and no
+ * further" as much as it means a date. */
+ clearable = false,
+ /** Called with the chosen day, or '' when it is cleared. */
+ onpick,
+ } = $props();
+
+ let open = $state(false);
+ let cursor = $state('');
+
+ const today = $derived(todayOf());
+ const month = $derived(cursor || monthOf(value));
+ const cells = $derived(monthDays(month));
+ const canGoBack = $derived(!monthOutOfRange(shiftMonth(month, -1), min, max));
+ const canGoOn = $derived(!monthOutOfRange(shiftMonth(month, 1), min, max));
+
+ function toggle() {
+ open = !open;
+ if (open) cursor = monthOf(value); // reopened on the day it holds, not where it was left
+ }
+
+ function pick(iso) {
+ onpick?.(iso);
+ open = false;
+ }
+</script>
+
+<div class="day-picker">
+ <button
+ type="button"
+ class="field"
+ class:empty={!value}
+ aria-expanded={open}
+ aria-label={label}
+ onclick={toggle}
+ >
+ <span>{value || placeholder}</span>
+ <Icon name={open ? 'chevronUp' : 'chevronDown'} size={11} />
+ </button>
+
+ {#if open}
+ <div class="cal" role="group" aria-label="{label} calendar">
+ <div class="head">
+ <button
+ type="button"
+ class="step"
+ disabled={!canGoBack}
+ aria-label="Previous month"
+ onclick={() => (cursor = shiftMonth(month, -1))}
+ >
+ <Icon name="chevronLeft" size={12} />
+ </button>
+ <span class="month">{monthLabel(month)}</span>
+ <button
+ type="button"
+ class="step"
+ disabled={!canGoOn}
+ aria-label="Next month"
+ onclick={() => (cursor = shiftMonth(month, 1))}
+ >
+ <Icon name="chevronRight" size={12} />
+ </button>
+ </div>
+
+ <div class="week">
+ {#each WEEKDAYS as day, i (i)}<span>{day}</span>{/each}
+ </div>
+
+ <div class="days">
+ {#each cells as cell (cell.iso)}
+ <button
+ type="button"
+ class="day"
+ class:out={!cell.inMonth}
+ class:on={cell.iso === value}
+ class:today={cell.iso === today}
+ disabled={outOfRange(cell.iso, min, max)}
+ aria-current={cell.iso === value ? 'date' : undefined}
+ title={cell.iso}
+ onclick={() => pick(cell.iso)}
+ >{cell.day}</button>
+ {/each}
+ </div>
+
+ <div class="acts">
+ <button
+ type="button"
+ class="act"
+ disabled={outOfRange(today, min, max)}
+ onclick={() => pick(today)}
+ >Today</button>
+ {#if clearable}
+ <button type="button" class="act" disabled={!value} onclick={() => pick('')}>Clear</button>
+ {/if}
+ </div>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .day-picker {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .field {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 3px 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-1);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ cursor: pointer;
+ }
+ .field:hover {
+ border-color: var(--border-strong);
+ }
+ .field.empty {
+ color: var(--text-3);
+ }
+ .field[aria-expanded='true'] {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ /* in flow, never over: the row under it moves down, and nothing can push it
+ past an edge it would be cut at */
+ .cal {
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+ .month {
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-1);
+ }
+ .step {
+ display: grid;
+ place-items: center;
+ width: 18px;
+ height: 18px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .step:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .step:disabled {
+ opacity: 0.3;
+ cursor: default;
+ }
+ .week,
+ .days {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 1px;
+ }
+ .week span {
+ text-align: center;
+ font-size: 9px;
+ color: var(--text-3);
+ }
+ .day {
+ padding: 2px 0;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ cursor: pointer;
+ }
+ .day:hover:not(:disabled) {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .day.out {
+ color: var(--text-3);
+ opacity: 0.5;
+ }
+ .day.today {
+ box-shadow: inset 0 0 0 1px var(--border-strong);
+ }
+ .day.on {
+ background: var(--accent-soft);
+ color: var(--accent);
+ box-shadow: inset 0 0 0 1px var(--accent);
+ }
+ .day:disabled {
+ opacity: 0.25;
+ cursor: default;
+ }
+ .acts {
+ display: flex;
+ justify-content: flex-end;
+ gap: 4px;
+ }
+ .act {
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: 10px;
+ cursor: pointer;
+ }
+ .act:hover:not(:disabled) {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .act:disabled {
+ opacity: 0.4;
+ cursor: default;
+ }
+</style>
diff --git a/frontend/src/components/EntityDetails.render.test.js b/frontend/src/components/EntityDetails.render.test.js
index d6595c2..84cb6af 100644
--- a/frontend/src/components/EntityDetails.render.test.js
+++ b/frontend/src/components/EntityDetails.render.test.js
@@ -28,6 +28,7 @@ const REGISTRY = [
group: '',
attrs: [
{ key: 'radius_m', label: 'Uncertainty radius (m)', kind: 'number', rungs: [], minimum: 1 },
+ { key: 'footprint', label: 'Footprint', kind: 'geojson', rungs: [] },
{ key: 'method', label: 'How this point was found', kind: 'longtext', rungs: [] },
],
},
@@ -221,3 +222,63 @@ describe('the source of a file the analyst brought in', () => {
expect(rows).toContain('Source');
});
});
+
+describe('a place states its precision once', () => {
+ const PLACE = { ...entity, attrs: { ...entity.attrs } };
+ const SHAPE = { type: 'Polygon', coordinates: [[[2, 1], [3, 1], [3, 2], [2, 1]]] };
+
+ afterEach(() => {
+ Object.assign(entity, PLACE, { attrs: { ...PLACE.attrs } });
+ patch.mockClear();
+ });
+
+ const save = (target) =>
+ [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Save');
+
+ it('asks before a typed radius drops the shape somebody traced', async () => {
+ Object.assign(entity, { attrs: { ...PLACE.attrs, radius_m: null, footprint: SHAPE } });
+ const target = await open();
+ await land();
+ const field = target.querySelector('#attr-radius_m');
+ field.value = '500';
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+
+ save(target).click();
+ await Promise.resolve();
+ flushSync();
+
+ expect(patch).not.toHaveBeenCalled();
+ expect(document.body.textContent).toContain('Drop the traced shape?');
+
+ [...document.body.querySelectorAll('button')]
+ .find((b) => b.textContent.trim() === 'Drop the shape')
+ .click();
+ await Promise.resolve();
+
+ expect(patch).toHaveBeenCalledWith(
+ '/api/cases/c1/entities/e1',
+ expect.objectContaining({
+ attrs: expect.objectContaining({ radius_m: 500, footprint: null }),
+ })
+ );
+ });
+
+ it('says nothing when a place written earlier holds both and neither is touched', async () => {
+ // The store judges the patch, not the stored result: saving the notes of a point
+ // written before the rule must not make anybody choose.
+ Object.assign(entity, { attrs: { ...PLACE.attrs, radius_m: 500, footprint: SHAPE } });
+ const target = await open();
+ await land();
+ const notes = target.querySelector('#ed-notes');
+ notes.value = 'two vehicles at the gate';
+ notes.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+
+ save(target).click();
+ await Promise.resolve();
+
+ expect(document.body.textContent).not.toContain('Drop the traced shape?');
+ expect(patch).toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index a121b10..a4e6e68 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -506,6 +506,32 @@
}
}
+ /**
+ * A place says how tightly it is pinned once (ONTOLOGY §2).
+ *
+ * A radius is a circle and a footprint is the shape itself, the map draws one of
+ * them, and the store refuses to hold both — so a radius typed over a traced shape
+ * is a request to drop the shape. It is somebody's traced work, so it is asked for
+ * rather than quietly overwritten on the way past.
+ *
+ * Only when this panel is what changed one of them, which is the same reading the
+ * store takes: a place written before the rule holds both, and saving its notes is
+ * not the moment to make anyone choose.
+ */
+ const precisionClash = $derived(
+ entity?.type === 'place' &&
+ Boolean(infoAttrs.radius_m) &&
+ Boolean(infoAttrs.footprint) &&
+ (infoAttrs.radius_m !== baseline?.attrs?.radius_m ||
+ infoAttrs.footprint !== baseline?.attrs?.footprint)
+ );
+ let dropping = $state(false);
+
+ function askSave() {
+ if (precisionClash) dropping = true;
+ else saveInfo();
+ }
+
async function saveInfo() {
if (!entity || infoSaving) return;
infoSaving = true;
@@ -1127,7 +1153,7 @@
{#if sourceIssue}<span class="save-problem">{sourceIssue}</span>{/if}
<button
class="btn btn-primary btn-sm"
- onclick={saveInfo}
+ onclick={askSave}
disabled={infoSaving || Boolean(sourceIssue)}
>
{infoSaving ? 'Saving…' : 'Save'}
@@ -1136,6 +1162,22 @@
</div>
{/if}
+{#if dropping}
+ <ConfirmDialog
+ title="Drop the traced shape?"
+ message="A place holds either a radius or a footprint, and the radius draws a circle."
+ detail="The shape traced on the map is removed."
+ confirmLabel="Drop the shape"
+ icon="alert"
+ onconfirm={() => {
+ dropping = false;
+ infoAttrs = { ...infoAttrs, footprint: null };
+ saveInfo();
+ }}
+ oncancel={() => (dropping = false)}
+ />
+{/if}
+
{#if pendingWalk}
<ConfirmDialog
title="Discard changes?"
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index de38ed0..ed1e2d5 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -116,7 +116,12 @@
reset: 'M4 9a8 8 0 1 1-1.6 4.7M4 9H1m3 0V6',
undo: 'M8 5 4 9l4 4M4 9h10a6 6 0 0 1 0 12h-4',
redo: 'm16 5 4 4-4 4m4-4H10a6 6 0 0 0 0 12h4',
- ghost: 'M5 20V10a7 7 0 0 1 14 0v10l-2.3-2-2.4 2-2.3-2-2.3 2-2.4-2-2.3 2ZM10 10h.01M14 10h.01',
+ // no mark at the point: the crosshair's ring, struck through
+ noMark: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM5.6 5.6l12.8 12.8',
+ // the point held at the middle of the frame
+ centre: 'M4 8V5a1 1 0 0 1 1-1h3m8 0h3a1 1 0 0 1 1 1v3m0 8v3a1 1 0 0 1-1 1h-3m-8 0H5a1 1 0 0 1-1-1v-3m8-4.5v1m-.5-.5h1',
+ // free to be moved anywhere
+ move: 'M12 3v18M3 12h18M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3',
sliders: 'M4 6h9m4 0h3M4 12h3m4 0h9M4 18h13m4 0h3M13 4v4m0 6v4m4-12v4',
wand: 'M4 20 13 11M15 3l1.1 3 3 1.1-3 1.1L15 11.3l-1.1-3-3-1.1 3-1.1L15 3ZM19.5 11.5l.6 1.8 1.8.6-1.8.6-.6 1.8-.6-1.8-1.8-.6 1.8-.6.6-1.8Z',
maximize: 'M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3M3 16v3a2 2 0 0 0 2 2h3m8 0h3a2 2 0 0 0 2-2v-3',
@@ -126,6 +131,9 @@
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',
+ // Active fires. A flame rather than the warning triangle it borrowed at
+ // first: a detection is a thing seen, not an alarm raised.
+ flame: 'M12 3c3.2 3.4 5 6 5 8.6a5 5 0 0 1-10 0c0-1.6.6-3 1.9-4.3.1 1.2.6 2 1.4 2.6C10 7.6 10.6 5.3 12 3Z',
// 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',
diff --git a/frontend/src/lib/calendar.js b/frontend/src/lib/calendar.js
new file mode 100644
index 0000000..ec622ba
--- /dev/null
+++ b/frontend/src/lib/calendar.js
@@ -0,0 +1,102 @@
+/**
+ * A month, as a grid of days — the arithmetic behind a calendar that is drawn
+ * rather than asked of the browser.
+ *
+ * `<input type="date">` brings its own calendar, and that calendar is browser
+ * chrome: it opens at whatever size the browser wants, in the browser's own
+ * locale, and it is laid over the page rather than inside it. In a panel docked
+ * to the right edge of the window, or floated over somebody else's map, it
+ * opens half outside what it belongs to and reads `12/09/2026` in an app whose
+ * every other date is written `2026-09-12`.
+ *
+ * So the days are computed here and drawn in the panel, where they can fit.
+ * Everything is UTC, which is the clock `map/firms.js` already keeps: a day is
+ * the name of a day, not an instant, and reading it locally would move it by
+ * one either side of midnight.
+ */
+
+/** Monday first: the week the rest of the world starts on, two letters so no
+ * two columns wear the same initial. */
+export const WEEKDAYS = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
+
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+const MONTH = /^\d{4}-\d{2}$/;
+
+/** A `YYYY-MM-DD` as a UTC date, or null — the same strictness as the service
+ * routes, so a half-typed field never becomes a request. */
+export function parseDay(iso) {
+ if (!DAY.test(String(iso ?? ''))) return null;
+ const at = new Date(`${iso}T00:00:00Z`);
+ // '2026-02-31' parses to March 3rd, which is not the day that was typed
+ return Number.isNaN(at.getTime()) || dayOf(at) !== iso ? null : at;
+}
+
+/** …and back. */
+export function dayOf(at) {
+ return at.toISOString().slice(0, 10);
+}
+
+/** Today, in the same form. */
+export function today(now = new Date()) {
+ return dayOf(now);
+}
+
+/** The month a day belongs to, as the cursor a calendar is drawn from. */
+export function monthOf(iso, fallback = today()) {
+ const day = String(iso ?? '');
+ if (DAY.test(day)) return day.slice(0, 7);
+ if (MONTH.test(day)) return day;
+ return String(fallback).slice(0, 7);
+}
+
+/** That cursor, moved by whole months — what `‹` and `›` press. */
+export function shiftMonth(cursor, by) {
+ const [year, month] = monthOf(cursor).split('-').map(Number);
+ const at = new Date(Date.UTC(year, month - 1 + by, 1));
+ return at.toISOString().slice(0, 7);
+}
+
+/** `Sep 2026`, the heading between the two arrows. */
+export function monthLabel(cursor) {
+ const [year, month] = monthOf(cursor).split('-').map(Number);
+ return `${MONTHS[month - 1]} ${year}`;
+}
+
+/**
+ * The cells of one month, in rows of seven.
+ *
+ * The days either side are included so a week is always seven boxes, and
+ * flagged `inMonth: false` so they can be drawn faintly. The number of rows
+ * follows the month rather than always being six: a trailing empty week is a
+ * panel that jumps by 28 px between February and March.
+ */
+export function monthDays(cursor) {
+ const [year, month] = monthOf(cursor).split('-').map(Number);
+ const first = new Date(Date.UTC(year, month - 1, 1));
+ const lead = (first.getUTCDay() + 6) % 7; // Sunday is 0 in JS, and last here
+ const length = new Date(Date.UTC(year, month, 0)).getUTCDate();
+ const weeks = Math.ceil((lead + length) / 7);
+ const cells = [];
+ for (let i = 0; i < weeks * 7; i += 1) {
+ const at = new Date(Date.UTC(year, month - 1, 1 - lead + i));
+ cells.push({ iso: dayOf(at), day: at.getUTCDate(), inMonth: at.getUTCMonth() === month - 1 });
+ }
+ return cells;
+}
+
+/** Whether a day is outside what the field accepts — an empty bound is no
+ * bound, which is how a range with no end is stated. */
+export function outOfRange(iso, min = '', max = '') {
+ if (!DAY.test(String(iso ?? ''))) return true;
+ if (DAY.test(String(min)) && iso < min) return true;
+ return Boolean(DAY.test(String(max)) && iso > max);
+}
+
+/** Whether a whole month is, which is what greys an arrow rather than letting
+ * it walk into years the service cannot answer for. */
+export function monthOutOfRange(cursor, min = '', max = '') {
+ const cells = monthDays(cursor).filter((cell) => cell.inMonth);
+ return cells.every((cell) => outOfRange(cell.iso, min, max));
+}
diff --git a/frontend/src/lib/calendar.test.js b/frontend/src/lib/calendar.test.js
new file mode 100644
index 0000000..0aae8c6
--- /dev/null
+++ b/frontend/src/lib/calendar.test.js
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import {
+ WEEKDAYS,
+ monthDays,
+ monthLabel,
+ monthOf,
+ monthOutOfRange,
+ outOfRange,
+ parseDay,
+ shiftMonth,
+ today,
+} from './calendar.js';
+
+describe('reading a day', () => {
+ it('takes the one form the services and the fields agree on', () => {
+ expect(parseDay('2026-09-12')?.toISOString()).toBe('2026-09-12T00:00:00.000Z');
+ for (const bad of ['', null, '12/09/2026', '2026-9-1', '2026-09-12T10:00']) {
+ expect(parseDay(bad), String(bad)).toBe(null);
+ }
+ });
+
+ it('refuses a day that does not exist, rather than sliding into the next month', () => {
+ // `new Date('2026-02-31')` is March 3rd, which is not the day that was typed
+ expect(parseDay('2026-02-31')).toBe(null);
+ expect(parseDay('2024-02-29')).not.toBe(null); // …and a leap day does exist
+ });
+
+ it('reads today in UTC, the clock the fire layer keeps', () => {
+ expect(today(new Date('2026-09-12T23:30:00Z'))).toBe('2026-09-12');
+ });
+});
+
+describe('the month a calendar opens on', () => {
+ it('is the day’s own, and today’s when there is no day yet', () => {
+ expect(monthOf('2026-03-04')).toBe('2026-03');
+ expect(monthOf('', '2026-09-12')).toBe('2026-09');
+ expect(monthOf('nonsense', '2026-09-12')).toBe('2026-09');
+ });
+
+ it('walks whole months, across a year', () => {
+ expect(shiftMonth('2026-01', -1)).toBe('2025-12');
+ expect(shiftMonth('2026-12', 1)).toBe('2027-01');
+ expect(shiftMonth('2026-03-31', -1)).toBe('2026-02'); // a day is a cursor too
+ });
+
+ it('names itself the way the heading reads it', () => {
+ expect(monthLabel('2026-09')).toBe('Sep 2026');
+ });
+});
+
+describe('the grid', () => {
+ it('starts on Monday and fills every week to seven', () => {
+ expect(WEEKDAYS).toHaveLength(7);
+ const cells = monthDays('2026-09');
+ expect(cells.length % 7).toBe(0);
+ // 1 September 2026 is a Tuesday, so the row before it carries 31 August
+ expect(cells[0].iso).toBe('2026-08-31');
+ expect(cells[1]).toEqual({ iso: '2026-09-01', day: 1, inMonth: true });
+ expect(cells[0].inMonth).toBe(false);
+ });
+
+ it('keeps the month whole, and no more rows than it needs', () => {
+ const days = monthDays('2026-09').filter((cell) => cell.inMonth);
+ expect(days).toHaveLength(30);
+ // February 2027 starts on a Monday and runs 28 days: exactly four rows, and
+ // a fifth would make the panel jump by a row between two months
+ expect(monthDays('2027-02')).toHaveLength(28);
+ expect(monthDays('2026-08')).toHaveLength(42); // …and one that does need six
+ });
+
+ it('carries a leap day', () => {
+ expect(monthDays('2024-02').filter((cell) => cell.inMonth)).toHaveLength(29);
+ });
+});
+
+describe('what the field will not accept', () => {
+ it('is either side of the bounds it was given', () => {
+ expect(outOfRange('2026-09-12', '2026-09-01', '2026-09-30')).toBe(false);
+ expect(outOfRange('2026-08-31', '2026-09-01', '')).toBe(true);
+ expect(outOfRange('2026-10-01', '', '2026-09-30')).toBe(true);
+ expect(outOfRange('', '', '')).toBe(true);
+ });
+
+ it('takes an empty bound as no bound, which is how an open range is stated', () => {
+ expect(outOfRange('1999-01-01', '', '')).toBe(false);
+ });
+
+ it('greys the arrow rather than walking into a month nothing can answer for', () => {
+ expect(monthOutOfRange('2026-10', '', '2026-09-30')).toBe(true);
+ expect(monthOutOfRange('2026-09', '', '2026-09-30')).toBe(false);
+ // the bounds fall inside the month: it is reachable, and only some of its
+ // days are not
+ expect(monthOutOfRange('2026-09', '2026-09-20', '2026-09-30')).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/extBridge.js b/frontend/src/lib/extBridge.js
index 479cb12..91fa1d6 100644
--- a/frontend/src/lib/extBridge.js
+++ b/frontend/src/lib/extBridge.js
@@ -185,6 +185,53 @@ export function onBridgeHello(cb, win = window) {
return () => win.removeEventListener('message', onMessage);
}
+/**
+ * This map tab's end of the extension's linked views, or null without one.
+ *
+ * The extension's map tools panel follows a camera on sites outside the app, and
+ * its worker is the hub between those panels and the app's map tabs
+ * (`background.js`, "linked views"). The bridge holds this tab's port to it;
+ * this is the app side of that, in the shape `map/link.js` takes as a `relay`.
+ *
+ * Two message types rather than one, because the page hears its own
+ * postMessage: `map-link` goes to the bridge and `map-link-event` comes back,
+ * so a camera this tab sends is never mistaken for one it was handed.
+ *
+ * Nothing leaves the machine. The bridge relays to the extension's worker, which
+ * relays to panels in other tabs of the same browser.
+ */
+export function mapLinkRelay({ win = window, doc = document } = {}) {
+ if (!extensionVersion(doc)) return null;
+ let heard = null;
+ const post = (kind, extra) =>
+ win.postMessage({ channel: CHANNEL, type: 'map-link', kind, ...extra }, win.location.origin);
+ function onMessage(event) {
+ if (event.origin !== win.location.origin || !heard) return;
+ const msg = event.data;
+ if (!msg || msg.channel !== CHANNEL) return;
+ // an extension that restarted brought a bridge with no port: ask again
+ if (msg.type === 'bridge-hello') return post('open');
+ if (msg.type !== 'map-link-event') return;
+ if (msg.kind === 'view') heard.view(msg.view);
+ if (msg.kind === 'peers') heard.peers(msg.count);
+ }
+ return {
+ listen(handlers) {
+ heard = handlers;
+ win.addEventListener('message', onMessage);
+ post('open');
+ },
+ send(view) {
+ post('view', { view });
+ },
+ close() {
+ post('close');
+ win.removeEventListener('message', onMessage);
+ heard = null;
+ },
+ };
+}
+
/**
* Every live bridge on this tab, as `[{version}]`.
*
diff --git a/frontend/src/lib/extBridge.test.js b/frontend/src/lib/extBridge.test.js
index b492e7f..82195b3 100644
--- a/frontend/src/lib/extBridge.test.js
+++ b/frontend/src/lib/extBridge.test.js
@@ -2,7 +2,7 @@
import { describe, it, expect, afterEach } from 'vitest';
import {
extensionVersion, extensionOutdated, captureTab, handOffPost, handOffReverse, onActivated,
- extensionState, pingExtensions, reloadExtension, onBridgeHello,
+ extensionState, pingExtensions, reloadExtension, onBridgeHello, mapLinkRelay,
} from './extBridge.js';
// The bridge protocol is the app's only path to widget pixels, so what these
@@ -341,3 +341,80 @@ describe('pingExtensions', () => {
off();
});
});
+
+describe('mapLinkRelay', () => {
+ // The app's map tab on the extension's linked views: panels on other sites
+ // hand their cameras over it. Two message types, because the page hears its
+ // own postMessage and must never take the camera it sent for one it was handed.
+ const wait = () => new Promise((r) => setTimeout(r, 10));
+ const fromBridge = (message) =>
+ window.postMessage({ channel: 'azimut-capture-ext', ...message }, window.location.origin);
+
+ function watchPage() {
+ const posted = [];
+ const onMessage = (event) => {
+ if (event.data?.type === 'map-link') posted.push(event.data);
+ };
+ window.addEventListener('message', onMessage);
+ return { posted, stop: () => window.removeEventListener('message', onMessage) };
+ }
+
+ it('is nothing without the extension', () => {
+ expect(mapLinkRelay()).toBe(null);
+ });
+
+ it('asks the bridge to open the link, and hands it this tab’s camera', async () => {
+ document.documentElement.dataset.azimutCaptureExtension = '0.3.0';
+ const page = watchPage();
+ const relay = mapLinkRelay();
+ relay.listen({ view() {}, peers() {} });
+ relay.send({ lat: 1, lon: 2, zoom: 3, bearing: 0 });
+ await wait();
+ expect(page.posted.map((m) => m.kind)).toEqual(['open', 'view']);
+ expect(page.posted[1].view).toEqual({ lat: 1, lon: 2, zoom: 3, bearing: 0 });
+ relay.close();
+ page.stop();
+ });
+
+ it('hears panels’ cameras and their count, never its own camera', async () => {
+ document.documentElement.dataset.azimutCaptureExtension = '0.3.0';
+ const views = [];
+ const counts = [];
+ const relay = mapLinkRelay();
+ relay.listen({ view: (v) => views.push(v), peers: (n) => counts.push(n) });
+ relay.send({ lat: 9, lon: 9, zoom: 9 });
+ fromBridge({ type: 'map-link-event', kind: 'view', view: { lat: 1, lon: 2, zoom: 3 } });
+ fromBridge({ type: 'map-link-event', kind: 'peers', count: 2 });
+ await wait();
+ expect(views).toEqual([{ lat: 1, lon: 2, zoom: 3 }]);
+ expect(counts).toEqual([2]);
+ relay.close();
+ });
+
+ it('opens the link again when a restarted extension brings a new bridge', async () => {
+ document.documentElement.dataset.azimutCaptureExtension = '0.3.0';
+ const relay = mapLinkRelay();
+ relay.listen({ view() {}, peers() {} });
+ await wait();
+ const page = watchPage();
+ fromBridge({ type: 'bridge-hello', version: '0.3.1' });
+ await wait();
+ expect(page.posted.map((m) => m.kind)).toEqual(['open']);
+ relay.close();
+ page.stop();
+ });
+
+ it('says goodbye and stops listening when the map closes', async () => {
+ document.documentElement.dataset.azimutCaptureExtension = '0.3.0';
+ const views = [];
+ const page = watchPage();
+ const relay = mapLinkRelay();
+ relay.listen({ view: (v) => views.push(v), peers() {} });
+ relay.close();
+ fromBridge({ type: 'map-link-event', kind: 'view', view: { lat: 1, lon: 2, zoom: 3 } });
+ await wait();
+ expect(views).toEqual([]);
+ expect(page.posted.at(-1).kind).toBe('close');
+ page.stop();
+ });
+});
diff --git a/frontend/src/lib/extension.test.js b/frontend/src/lib/extension.test.js
index 0fe0733..24cb42c 100644
--- a/frontend/src/lib/extension.test.js
+++ b/frontend/src/lib/extension.test.js
@@ -4,7 +4,7 @@
// source with a stubbed `chrome` global and exercises the internals it returns.
// 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 { describe, it, expect, vi, beforeEach, onTestFinished } from 'vitest';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
@@ -75,7 +75,7 @@ function load({ chrome = makeChrome(), fetchImpl, imageBitmap, canvasLog } = {})
'createImageBitmap',
'OffscreenCanvas',
'btoa',
- `${source}\n;return { cropDataUrl, ingest, handle, settings, handOff, handOffReverse, loadedStamp, reattachBridge, frameEvent, panels, pumpEvents, stopEvents };`
+ `${source}\n;return { cropDataUrl, ingest, handle, settings, handOff, handOffReverse, loadedStamp, reattachBridge, frameEvent, panels, pumpEvents, stopEvents, resumeFollow };`
);
return factory(
chrome,
@@ -98,12 +98,20 @@ describe('cropDataUrl', () => {
it('scales the CSS-px rect by the measured image/viewport ratio', async () => {
const { cropDataUrl } = load({ fetchImpl, canvasLog });
// image 2000 px wide over a 1000 px viewport → scale 2
- const blob = await cropDataUrl('data:x', { x: 10, y: 20, w: 100, h: 50 }, 1000);
+ const { blob } = await cropDataUrl('data:x', { x: 10, y: 20, w: 100, h: 50 }, 1000);
expect(blob.type).toBe('image/png');
expect(canvasLog).toContainEqual({ canvas: [200, 100] });
expect(canvasLog).toContainEqual({ drawImage: [20, 40, 200, 100, 0, 0, 200, 100] });
});
+ it('hands back the ratio it measured, since a scale bar is drawn from it', async () => {
+ // the crop keeps the frame's own pixels, and a zoom describes CSS pixels:
+ // without this the app would state twice the ground a 2× screen covers
+ const { cropDataUrl } = load({ fetchImpl, canvasLog });
+ const { scale } = await cropDataUrl('data:x', { x: 10, y: 20, w: 100, h: 50 }, 1000);
+ expect(scale).toBe(2);
+ });
+
it('clamps the crop to the captured frame', async () => {
const { cropDataUrl } = load({ fetchImpl, canvasLog });
// rect runs past the right edge: sw shrinks to what the image has left
@@ -834,3 +842,297 @@ describe('the nudge stream', () => {
w.leave(p);
});
});
+
+describe('linked views: the hub', () => {
+ /**
+ * Panels on sites' maps and the app's map tabs, all on one camera. The worker
+ * is the hub because a panel cannot hear the app's BroadcastChannel from
+ * another origin — and because following a view reloads most sites, which
+ * takes the panel with it, so which tabs are linked has to live here.
+ */
+ const APP = 'http://127.0.0.1:8477/#satellite';
+ const MAP = 'https://www.google.com/maps/@1,2,15z';
+ const VIEW = { lat: 48.85, lon: 2.29, zoom: 17, bearing: 0 };
+
+ function port(tabId, url = MAP, name = 'map-link') {
+ const p = {
+ name,
+ sender: { tab: { id: tabId, url } },
+ heard: [],
+ listeners: [],
+ gone: [],
+ onMessage: { addListener: (cb) => p.listeners.push(cb) },
+ onDisconnect: { addListener: (cb) => p.gone.push(cb) },
+ postMessage: vi.fn((msg) => p.heard.push(msg)),
+ disconnect: vi.fn(),
+ };
+ return p;
+ }
+
+ // microtasks only, so it works the same under a faked clock
+ const flush = async () => {
+ for (let i = 0; i < 20; i += 1) await Promise.resolve();
+ };
+
+ function hub(chrome = makeChrome()) {
+ const worker = load({ chrome });
+ const listeners = chrome.runtime.onConnect.addListener.mock.calls.map((call) => call[0]);
+ return {
+ ...worker,
+ chrome,
+ async connect(p) {
+ for (const cb of listeners) cb(p);
+ await flush();
+ return p;
+ },
+ async say(p, msg) {
+ for (const cb of p.listeners) cb(msg);
+ await flush();
+ },
+ leave(p) {
+ for (const cb of p.gone) cb();
+ },
+ };
+ }
+
+ const last = (p, type) => p.heard.filter((m) => m.type === type).at(-1);
+
+ it('tells a panel whether it is linked, and how many others it could link to', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ expect(last(a, 'link-state')).toEqual({ type: 'link-state', linked: false, asked: null });
+ expect(last(a, 'link-peers').count).toBe(0);
+ const b = await h.connect(port(2));
+ expect(last(a, 'link-peers').count).toBe(1);
+ expect(last(b, 'link-peers').count).toBe(1);
+ });
+
+ it('counts only panels for an app tab, which hears its own tabs on its channel', async () => {
+ const h = hub();
+ const app = await h.connect(port(9, APP));
+ const other = await h.connect(port(10, APP));
+ expect(last(app, 'link-peers').count).toBe(0);
+ const a = await h.connect(port(1));
+ expect(last(app, 'link-peers').count).toBe(1);
+ expect(last(other, 'link-peers').count).toBe(1);
+ expect(last(a, 'link-peers').count).toBe(2);
+ // …and an app tab is never told whether it is linked: that is the app's
+ expect(app.heard.some((m) => m.type === 'link-state')).toBe(false);
+ });
+
+ it('writes the link down for the session, since a worker can be evicted between gestures', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ await h.say(a, { type: 'link', on: true });
+ expect(last(a, 'link-state').linked).toBe(true);
+ expect(h.chrome.storage.session.set).toHaveBeenLastCalledWith({
+ mapLink: { linked: [1], following: {} },
+ });
+ });
+
+ it('reads it back after a restart', async () => {
+ const chrome = makeChrome();
+ chrome.storage.session.get = vi.fn(async () => ({ mapLink: { linked: [1], following: {} } }));
+ const h = hub(chrome);
+ const a = await h.connect(port(1));
+ expect(last(a, 'link-state').linked).toBe(true);
+ });
+
+ it('hands a linked panel’s camera to the other linked panels and the app, and to nobody else', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ const idle = await h.connect(port(3));
+ const app = await h.connect(port(9, APP));
+ await h.say(a, { type: 'link', on: true });
+ await h.say(b, { type: 'link', on: true });
+ await h.say(a, { type: 'view', view: VIEW });
+ expect(last(b, 'view')).toEqual({ type: 'view', view: VIEW });
+ expect(last(app, 'view')).toEqual({ type: 'view', view: VIEW });
+ expect(last(idle, 'view')).toBeUndefined();
+ expect(last(a, 'view')).toBeUndefined();
+ });
+
+ it('drops a camera from a panel that is not linked', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const app = await h.connect(port(9, APP));
+ await h.say(a, { type: 'view', view: VIEW });
+ expect(last(app, 'view')).toBeUndefined();
+ });
+
+ it('hands an app tab’s camera to the linked panels only', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const app = await h.connect(port(9, APP));
+ const other = await h.connect(port(10, APP));
+ await h.say(a, { type: 'link', on: true });
+ await h.say(app, { type: 'view', view: VIEW });
+ expect(last(a, 'view')).toEqual({ type: 'view', view: VIEW });
+ expect(last(other, 'view')).toBeUndefined();
+ });
+
+ it('carries the four numbers of a camera and nothing else', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(a, { type: 'link', on: true });
+ await h.say(b, { type: 'link', on: true });
+ await h.say(a, { type: 'view', view: { ...VIEW, extra: '<script>' } });
+ expect(last(b, 'view').view).toEqual(VIEW);
+ await h.say(a, { type: 'view', view: { lat: 200, lon: 2, zoom: 3 } });
+ expect(b.heard.filter((m) => m.type === 'view')).toHaveLength(1);
+ });
+
+ it('keeps counting a tab that left to follow a view, and tells it where it was sent', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(b, { type: 'link', on: true });
+ await h.say(b, { type: 'follow', view: VIEW });
+ h.leave(b); // the site reloads
+ expect(last(a, 'link-peers').count).toBe(1);
+ const back = await h.connect(port(2));
+ expect(last(back, 'link-state')).toEqual({ type: 'link-state', linked: true, asked: VIEW });
+ });
+
+ it('stops waiting once the wait runs out', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(b, { type: 'follow', view: VIEW });
+ h.leave(b);
+ expect(last(a, 'link-peers').count).toBe(1);
+ await vi.advanceTimersByTimeAsync(31000);
+ expect(last(a, 'link-peers').count).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('hands a tab back the last camera the analyst moved to while it was reloading', async () => {
+ // the map being led does not wait for its followers: every camera sent while
+ // one was loading used to be dropped, and it stayed on the first
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(a, { type: 'link', on: true });
+ await h.say(b, { type: 'link', on: true });
+ await h.say(b, { type: 'follow', view: VIEW });
+ h.leave(b);
+ await h.say(a, { type: 'view', view: { ...VIEW, lat: 48.9 } });
+ await h.say(a, { type: 'view', view: { ...VIEW, lat: 49 } });
+ const back = await h.connect(port(2));
+ expect(back.heard.filter((m) => m.type === 'view')).toEqual([{ type: 'view', view: { ...VIEW, lat: 49 } }]);
+ // …once
+ const again = await h.connect(port(2));
+ expect(again.heard.some((m) => m.type === 'view')).toBe(false);
+ });
+
+ it('holds nothing for a tab that switched its link off', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(a, { type: 'link', on: true });
+ await h.say(b, { type: 'link', on: true });
+ await h.say(b, { type: 'follow', view: VIEW });
+ await h.say(b, { type: 'link', on: false });
+ h.leave(b);
+ expect(last(a, 'link-peers').count).toBe(0);
+ });
+
+ it('forgets a follow that a site took in its hash without reloading', async () => {
+ const h = hub();
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(b, { type: 'follow', view: VIEW });
+ await h.say(b, { type: 'landed' });
+ h.leave(b);
+ expect(last(a, 'link-peers').count).toBe(0);
+ });
+
+ describe('putting the tools back after a reload', () => {
+ async function following(chrome) {
+ const h = hub(chrome);
+ const b = await h.connect(port(2));
+ await h.say(b, { type: 'link', on: true });
+ await h.say(b, { type: 'follow', view: VIEW });
+ h.leave(b);
+ return h;
+ }
+
+ it('injects the panel into a tab that reloaded on its way to a view', async () => {
+ const chrome = makeChrome();
+ chrome.scripting.executeScript = vi.fn(async ({ func }) => (func ? [{ result: false }] : []));
+ const h = await following(chrome);
+ await h.resumeFollow(2);
+ // the bridge is re-attached to the app's own tabs on every worker start
+ const files = chrome.scripting.executeScript.mock.calls
+ .map((c) => c[0].files)
+ .filter((f) => f?.includes('mapoverlay.js'));
+ expect(files).toHaveLength(1);
+ expect(files[0].at(-1)).toBe('mapoverlay.js');
+ expect(files[0]).toContain('maplink.js');
+ });
+
+ it('leaves a panel that is still there alone, since injecting it again closes it', async () => {
+ const chrome = makeChrome();
+ chrome.scripting.executeScript = vi.fn(async ({ func }) => (func ? [{ result: true }] : []));
+ const h = await following(chrome);
+ await h.resumeFollow(2);
+ expect(chrome.scripting.executeScript.mock.calls.some((c) => c[0].files?.includes('mapoverlay.js'))).toBe(
+ false
+ );
+ });
+
+ it('touches no tab that did not leave to follow a view', async () => {
+ const chrome = makeChrome();
+ const h = hub(chrome);
+ await h.resumeFollow(5);
+ expect(chrome.scripting.executeScript.mock.calls.some((c) => c[0].target.tabId === 5)).toBe(false);
+ });
+
+ it('tries again when a page that said it was loaded was still swapping documents', async () => {
+ vi.useFakeTimers();
+ try {
+ const chrome = makeChrome();
+ let refusals = 1;
+ chrome.scripting.executeScript = vi.fn(async ({ func }) => {
+ if (func && refusals-- > 0) throw new Error('Frame with ID 0 was removed');
+ return func ? [{ result: false }] : [];
+ });
+ const h = await following(chrome);
+ await h.resumeFollow(2);
+ await vi.advanceTimersByTimeAsync(1100);
+ const files = chrome.scripting.executeScript.mock.calls.filter((c) => c[0].files?.includes('mapoverlay.js'));
+ expect(files).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('unlinks a tab the browser will not put the tools back on, and says so', async () => {
+ vi.useFakeTimers();
+ onTestFinished(() => vi.useRealTimers());
+ const chrome = makeChrome();
+ chrome.scripting.executeScript = vi.fn(async () => {
+ throw new Error('Cannot access contents of the page');
+ });
+ const h = hub(chrome);
+ const a = await h.connect(port(1));
+ const b = await h.connect(port(2));
+ await h.say(b, { type: 'link', on: true });
+ await h.say(b, { type: 'follow', view: VIEW });
+ h.leave(b);
+ await h.resumeFollow(2);
+ await vi.advanceTimersByTimeAsync(2500); // every try refused
+ vi.useRealTimers();
+ expect(last(a, 'link-note').note).toContain('kept its tools off');
+ expect(last(a, 'link-peers').count).toBe(0);
+ const back = await h.connect(port(2));
+ expect(last(back, 'link-state').linked).toBe(false);
+ });
+ });
+});
diff --git a/frontend/src/lib/extensionBridge.test.js b/frontend/src/lib/extensionBridge.test.js
index 04f7263..b747237 100644
--- a/frontend/src/lib/extensionBridge.test.js
+++ b/frontend/src/lib/extensionBridge.test.js
@@ -182,3 +182,89 @@ describe('two instances in one tab', () => {
expect(posted).toHaveLength(0);
});
});
+
+describe('a map tab on the linked views', () => {
+ // The app's map opens a port to the worker's hub through here while it is
+ // mounted, so panels on other sites can hand it their cameras.
+ function linkChrome() {
+ const ports = [];
+ const chrome = makeChrome();
+ chrome.runtime.connect = vi.fn(({ name }) => {
+ const port = {
+ name,
+ listeners: [],
+ gone: [],
+ onMessage: { addListener: (cb) => port.listeners.push(cb) },
+ onDisconnect: { addListener: (cb) => port.gone.push(cb) },
+ postMessage: vi.fn(),
+ disconnect: vi.fn(),
+ };
+ ports.push(port);
+ return port;
+ });
+ return { chrome, ports };
+ }
+
+ it('opens the port only when the app asks', async () => {
+ const { chrome, ports } = linkChrome();
+ inject(chrome);
+ expect(ports).toHaveLength(0);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ expect(ports.map((p) => p.name)).toEqual(['map-link']);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ expect(ports).toHaveLength(1); // one port however often it is asked
+ });
+
+ it('carries the app’s camera to the worker', async () => {
+ const { chrome, ports } = linkChrome();
+ inject(chrome);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ await fromPage({ type: 'map-link', kind: 'view', view: { lat: 1, lon: 2, zoom: 3 } });
+ expect(ports[0].postMessage).toHaveBeenCalledWith({ type: 'view', view: { lat: 1, lon: 2, zoom: 3 } });
+ });
+
+ it('hands the worker’s cameras and counts to the app, under a type the app does not send', async () => {
+ const { chrome, ports } = linkChrome();
+ inject(chrome);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ const posted = [];
+ const spy = vi.spyOn(window, 'postMessage').mockImplementation((d) => posted.push(d));
+ for (const cb of ports[0].listeners) cb({ type: 'view', view: { lat: 1, lon: 2, zoom: 3 } });
+ for (const cb of ports[0].listeners) cb({ type: 'link-peers', count: 2 });
+ spy.mockRestore();
+ expect(posted).toEqual([
+ { channel: CHANNEL, type: 'map-link-event', kind: 'view', view: { lat: 1, lon: 2, zoom: 3 } },
+ { channel: CHANNEL, type: 'map-link-event', kind: 'peers', count: 2 },
+ ]);
+ });
+
+ it('lets the port go when the map closes, and does not reopen it', async () => {
+ const { chrome, ports } = linkChrome();
+ inject(chrome);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ await fromPage({ type: 'map-link', kind: 'close' });
+ expect(ports[0].disconnect).toHaveBeenCalled();
+ vi.useFakeTimers(); // the page's own messages are delivered on real ones
+ try {
+ for (const cb of ports[0].gone) cb();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(ports).toHaveLength(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('opens it again when the worker is evicted while the map is open', async () => {
+ const { chrome, ports } = linkChrome();
+ inject(chrome);
+ await fromPage({ type: 'map-link', kind: 'open' });
+ vi.useFakeTimers();
+ try {
+ for (const cb of ports[0].gone) cb();
+ await vi.advanceTimersByTimeAsync(2500);
+ expect(ports).toHaveLength(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/frontend/src/lib/extensionMapEngine.test.js b/frontend/src/lib/extensionMapEngine.test.js
index 16906e7..62cab04 100644
--- a/frontend/src/lib/extensionMapEngine.test.js
+++ b/frontend/src/lib/extensionMapEngine.test.js
@@ -30,7 +30,7 @@ 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'];
+const PARTS = ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapdraw.js', 'mapref.js', 'maplink.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
@@ -68,14 +68,13 @@ beforeAll(() => {
*/
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);
+ const sized = ['span', 'height_m', 'distance'].includes(step.scale_source);
return {
site: step.site,
label: step.site,
lat: view.lat,
lon: view.lon,
- zoom: sized ? view.zoom + Math.log2(height / drawnIn) : view.zoom,
+ zoom: sized && view.zoom != null ? view.zoom + Math.log2(height / drawnIn) : view.zoom,
bearing: view.bearing,
projection: view.projection,
view_kind: 'map',
@@ -83,8 +82,6 @@ function parseOf(step, height, drawnIn, extra = {}) {
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,
@@ -100,7 +97,7 @@ function parseOf(step, height, drawnIn, extra = {}) {
* 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 } = {}) {
+function open({ recording, size, ratio = 1, parse, storage = {}, firefox = false, answers = {} } = {}) {
const win = size ?? recording?.window ?? { w: 1600, h: 1000 };
window.happyDOM.setViewport({ width: win.w, height: win.h });
window.devicePixelRatio = ratio;
@@ -119,7 +116,16 @@ function open({ recording, size, ratio = 1, parse, storage = {}, firefox = false
onMessage: { addListener: vi.fn(), removeListener: vi.fn() },
sendMessage: vi.fn(async (message) => {
sent.push(message);
+ // A picture route answers with bytes, which the worker hands over as a
+ // data URL — one pixel of it is enough to place.
+ if (message.type === 'map-image') {
+ return { ok: true, src: 'data:image/png;base64,iVBORw0KGgo=' };
+ }
if (message.type !== 'map-api') return { ok: true, data: {} };
+ // What the app answers a given route with, when a test cares — the
+ // catalogue behind the fire layer is read on open, and whether a key is
+ // saved is the whole of what it says.
+ if (message.path in answers) return { ok: true, data: answers[message.path] };
if (message.path === '/api/ingest/parse') {
return { ok: true, data: parse(message.query) };
}
@@ -276,6 +282,153 @@ describe('measuring where a site draws its centre', () => {
expect(kept.w).toBe(recording.window.w);
expect(kept.h).toBe(recording.window.h);
});
+
+ it('drops an offset saved before the scale stopped being measured off a drag', async () => {
+ // Earth's offsets used to be solved through that scale, and one a few pixels
+ // out was averaged into every zoom after it rather than replaced
+ const recording = fixture.recordings.find((r) => r.site === 'google-earth');
+ const stale = { ...recording.window, x: 14, y: -9 };
+ const drawnIn = recording.map_height ?? recording.window.h;
+ for (const [stored, framed] of [
+ [{ frames: [stale] }, false],
+ [{ frames: [stale], framesVersion: 2 }, true],
+ ]) {
+ panel?.close();
+ panel = open({
+ recording,
+ storage: { 'mapTools:example.invalid': stored },
+ parse: (query) => parseOf(recording.steps.at(-1), Number(query.height), drawnIn),
+ });
+ panel.location.href = recording.steps.at(-1).url;
+ await tick();
+ expect(panel.state.framed).toBe(framed);
+ expect(panel.state.frame).toEqual(framed ? { x: 14, y: -9 } : { x: 0, y: 0 });
+ }
+ });
+});
+
+/**
+ * What the drawing is placed with before anybody has gestured at anything.
+ *
+ * The middle of the window was never a neutral starting point: four of these
+ * sites keep a results panel or a header and centre the map in what is left, so
+ * an install that starts at the middle starts 210 px out on Yandex and stays
+ * there until the analyst happens to zoom. Nothing on screen says so, and at
+ * level 3 Bing's 40 px is 450 km of ground.
+ *
+ * So the app's table hands over what its own calibration run measured and the
+ * panel starts there (`engine/mapsites.py`, `_CAMERA_CENTRE`). The numbers come
+ * from the fixture rather than from a copy here, and `tests/test_mapsites.py`
+ * is what holds them to the recording; what is asserted here is the other half
+ * — that a fresh install draws from them, and that they lose to anything
+ * measured on the machine in front of the analyst.
+ */
+describe('the offset a fresh install starts from', () => {
+ const hints = fixture.hints ?? {};
+ const hinted = fixture.recordings.filter((r) => hints[r.site]);
+
+ /** The panel opened on a recording and then left alone: no wheel, no drag,
+ * which is every install's first minute on a map. */
+ async function opened(recording, options = {}) {
+ const drawnIn = recording.map_height ?? recording.window.h;
+ const live = open({
+ recording,
+ parse: (query) => {
+ const found = recording.steps.find((s) => s.url === query.url);
+ return found
+ ? parseOf(found, Number(query.height), drawnIn, { centre_hint: hints[recording.site] })
+ : null;
+ },
+ ...options,
+ });
+ live.location.href = recording.steps[0].url;
+ await tick();
+ return live;
+ }
+
+ it('has an answer for every site whose chrome moves the camera', () => {
+ // the drift gate's other end: a site the recording shows off-centre and the
+ // table says nothing about is a site that starts wrong
+ const unplaced = fixture.recordings
+ .filter((r) => !hints[r.site] && Math.hypot(offset(r).x, offset(r).y) >= 4)
+ .map((r) => r.site);
+ // Apple is the one, and on purpose: its sidebar folds away below a width
+ // its URL never states, so its offset is 67 px in a wide window and nothing
+ // in a narrow one. That one is measured on the machine or not at all.
+ expect([...new Set(unplaced)]).toEqual(['apple-maps']);
+ });
+
+ it.each(hinted.map((r) => [r.label, r]))('draws from it on %s, ungestured', async (_l, recording) => {
+ panel = await opened(recording);
+ expect(panel.state.frame.x).toBeCloseTo(hints[recording.site].x, 6);
+ expect(panel.state.frame.y).toBeCloseTo(hints[recording.site].y, 6);
+ // and it is a starting point, not an answer: the panel still asks for the
+ // zoom that would settle it, and says where the number came from
+ expect(panel.state.framed).toBe(false);
+ expect(panel.status()).toContain('zoom once to place it');
+ expect(panel.statusTitle()).toContain('from the site table');
+ });
+
+ it('is replaced by the first zoom that measures one', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const live = await replay(recording, { extra: { centre_hint: { x: 40, y: 40 } } });
+ panel = live;
+ const want = offset(recording);
+ expect(live.state.framed).toBe(true);
+ expect(Math.abs(live.state.frame.x - want.x)).toBeLessThan(1.5);
+ expect(live.statusTitle()).not.toContain('site table');
+ });
+
+ it('loses to an offset this machine measured for itself', async () => {
+ // a table written somewhere else against a browser that is not this one,
+ // versus a measurement taken in this window — the measurement wins
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ const mine = { ...recording.window, x: 188, y: 3 };
+ const drawnIn = recording.map_height ?? recording.window.h;
+ panel = open({
+ recording,
+ storage: { 'mapTools:example.invalid': { frames: [mine], framesVersion: 2 } },
+ parse: (query) =>
+ parseOf(recording.steps[0], Number(query.height), drawnIn, {
+ centre_hint: hints['yandex-maps'],
+ }),
+ });
+ panel.location.href = recording.steps[0].url;
+ await tick();
+ expect(panel.state.frame).toEqual({ x: mine.x, y: mine.y });
+ expect(panel.state.framed).toBe(true);
+ expect(panel.statusTitle()).not.toContain('site table');
+ });
+
+ it('keeps the header and drops the panel in a window narrower than one measured', async () => {
+ // A header takes height and is the same height in any window. A side panel
+ // takes width, and a side panel is the thing that folds away — which is the
+ // whole of Apple's 67 px becoming nothing at 1200. So the sideways half is
+ // claimed only at or above a width the site was recorded in.
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ panel = await opened(recording, { size: { w: 1100, h: 900 } });
+ expect(panel.state.frame).toEqual({ x: 0, y: hints['yandex-maps'].y });
+ expect(panel.state.framed).toBe(false);
+ });
+
+ it('drops the panel half when the window is dragged below a measured width', async () => {
+ const recording = fixture.recordings.find((r) => r.site === 'yandex-maps');
+ panel = await opened(recording, { size: { w: 1600, h: 1000 } });
+ expect(panel.state.frame.x).toBeCloseTo(hints['yandex-maps'].x, 6);
+ window.happyDOM.setViewport({ width: 1100, height: 1000 });
+ window.dispatchEvent(new window.Event('resize'));
+ await tick();
+ expect(panel.state.frame).toEqual({ x: 0, y: hints['yandex-maps'].y });
+ });
+
+ it('is refused outright when it could not fit the window it opened in', async () => {
+ // the same rule a remembered offset is held to: a header taller than half
+ // the window is not a header, it is a layout that is gone
+ const recording = fixture.recordings.find((r) => r.site === 'bing-maps');
+ panel = await opened(recording, { size: { w: 1600, h: 70 } });
+ expect(panel.state.frame).toEqual({ x: 0, y: 0 });
+ expect(panel.statusTitle()).toBe('');
+ });
});
/**
@@ -460,7 +613,11 @@ describe('how tall the map is, which is not how tall the window is', () => {
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 },
+ 'mapTools:example.invalid': {
+ frames: [{ x: 210, y: 10, w: 380, h: 700 }],
+ framesVersion: 2,
+ panel: null,
+ },
};
// the same 420 px panel, in a window narrower than the offset it implies
panel = open({
@@ -712,129 +869,210 @@ describe('zoomed out', () => {
});
});
-// --- the compass ---------------------------------------------------------------
-
/**
- * A free camera that has been turned.
+ * The other globe, and not the one above.
*
- * 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.
+ * A flat map drawn far out still has a centre this arithmetic is right about,
+ * and edges that drift away from it — so it draws, dimmed, and says so. A
+ * perspective camera on a sphere has nothing Mercator is right about: Earth past
+ * its ceiling, and Google's Earth mode with it. Dimming a drawing that is simply
+ * wrong asks the analyst to judge how wrong it is, and nothing on screen tells
+ * them — so out there the panel refuses and says what to do instead.
+ */
+describe('a globe camera, which is not a map', () => {
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+ const google = () => fixture.recordings.find((r) => r.site === 'google-maps');
+ const keyed = {
+ '/api/ingest/firms/sensors': { keyed: true, sensors: [{ id: 'viirs', label: 'VIIRS' }] },
+ };
+ const globe = { extra: { view_kind: 'globe', geometry: false, far: true }, answers: keyed };
+
+ it('says what to do instead of drawing', async () => {
+ panel = await replay(google(), globe);
+ expect(panel.status()).toBe('The camera is on a globe this far out, so zoom in');
+ expect(panel.canvas().style.opacity).toBe('');
+ });
+
+ it('puts no fire picture on the ground, and asks NASA for none', async () => {
+ panel = await replay(google(), globe);
+ panel.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]')?.click();
+ await tick();
+ expect(panel.asks('/api/ingest/firms')).toEqual([]);
+ expect(root().querySelector('img').style.display).toBe('none');
+ });
+
+ it('picks the drawing back up as soon as the camera comes down', async () => {
+ // which is the whole point of saying "zoom in" rather than "not a map"
+ const recording = google();
+ const drawnIn = recording.map_height ?? recording.window.h;
+ let kind = 'globe';
+ panel = open({
+ recording,
+ answers: keyed,
+ parse: (query) => {
+ const found = recording.steps.find((s) => s.url === query.url);
+ return found
+ ? parseOf(found, Number(query.height), drawnIn, {
+ view_kind: kind,
+ geometry: kind === 'map',
+ far: kind === 'globe',
+ })
+ : null;
+ },
+ });
+ panel.location.href = recording.steps[0].url;
+ await tick();
+ expect(panel.status()).toContain('zoom in');
+
+ kind = 'map';
+ panel.location.href = recording.steps[1].url;
+ await tick();
+ expect(panel.status()).not.toContain('zoom in');
+ expect(panel.status()).toContain('google-maps');
+ });
+});
+
+// --- Google Earth --------------------------------------------------------------
+
+/**
+ * Earth, which states its scale as a camera distance.
*
- * 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.
+ * The panel used to think Earth stated none, and measured one off a drag
+ * instead. A drag loses pixels to Earth's threshold and gains them to its
+ * glide; the first reading was taken on trust, every later one that disagreed
+ * was thrown away as a fling, and each zoom carried the error along with it. On
+ * a real case that drew the marks four times too close together until the tab
+ * was closed. The app now reads the scale out of `d` and `y`
+ * (`engine/mapsites.py`), and a gesture moves the drawing and teaches it
+ * nothing.
*/
-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;
+describe('Google Earth', () => {
+ const HOME = { lat: 10.4806, lon: -66.9036 };
+ const SETTLE_QUIET_MS = 400;
- const url = ({ h = 0, lat = HOME.lat, lon = HOME.lon } = {}) =>
- `https://earth.google.com/web/@${lat},${lon},146a,666d,35y,${h}h,0t,0r`;
+ const url = ({ lat = HOME.lat, lon = HOME.lon, a = '903.25', d = 1000, h = 0 } = {}) =>
+ `https://earth.google.com/web/@${lat},${lon},${a}a,${d}d,35y,${h}h,0t,0r`;
- /** Earth's own reading: a position, a heading, and no scale of any kind. */
+ /**
+ * The app's reading, in the shape `engine/mapsites.py` gives it: Web
+ * Mercator, a zoom one level in for every halving of the distance and a
+ * little further out in a shorter window — or no scale at all for a link
+ * typed as `0a`, which Earth has not placed on the ground yet.
+ */
function earthParse(query) {
- const at = /@([\d.-]+),([\d.-]+),[^/]*?([\d.-]+)h/.exec(query.url);
+ const at = /@([\d.-]+),([\d.-]+),([\d.-]+)a,([\d.-]+)d,35y,([\d.-]+)h/.exec(query.url);
if (!at) return { site: null };
+ const placed = at[3] !== '0';
return {
site: 'google-earth',
label: 'Google Earth',
lat: Number(at[1]),
lon: Number(at[2]),
- zoom: null,
- bearing: Number(at[3]),
- projection: null,
+ zoom: placed
+ ? 15 + Math.log2(1000 / Number(at[4])) + Math.log2(Number(query.height) / 1000)
+ : null,
+ bearing: Number(at[5]),
+ projection: 'webmercator',
view_kind: 'map',
- geometry: false,
- scale_source: null,
+ geometry: true,
far: false,
+ globe_below: null,
+ scale_source: placed ? 'distance' : null,
};
}
- /** 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 });
+ async function onEarth(first = url()) {
+ panel = open({ parse: earthParse });
+ panel.location.href = first;
await tick();
- return live;
+ return panel;
}
- it('asks for a pan before it will draw, like any view with no scale in its URL', async () => {
+ it('draws from the first address it reads, with no drag asked for', async () => {
const live = await onEarth();
- panel = live;
- expect(live.status()).toContain('Drag the map across and down');
+ expect(live.state.view.zoom).toBe(15);
+ expect(live.status()).toContain('google-earth · z15.00 · webmercator (distance from the URL)');
});
- 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);
+ it('waits on a typed link until Earth has put its camera on the ground', async () => {
+ // `0a` is how a link is written, and over land 200 m up Earth draws it 7%
+ // nearer than its `d` says; the first gesture writes the ground in
+ const live = await onEarth(url({ a: '0' }));
+ expect(live.status()).toBe('Move the map once so its address bar gives the scale');
+ live.location.href = url({ d: 1000.25 });
+ await tick();
+ expect(live.status()).toContain('google-earth · z');
+ });
- live.location.href = url({ h: 45 }); // the same view, turned
+ it('learns nothing from a drag, however far the map glided on after it', async () => {
+ const live = await onEarth();
+ const send = (type, x, y) =>
+ window.dispatchEvent(new window.MouseEvent(type, { clientX: x, clientY: y, bubbles: true, button: 0 }));
+ send('pointerdown', 800, 500);
+ send('pointermove', 1000, 350);
+ // the canvas goes where the pointer went while the finger is down…
+ expect(live.canvas().style.transform).toBe('translate(200px, -150px) scale(1)');
+ send('pointerup', 1000, 350);
+ // …and Earth lands four drags further on, over a hill that moved `d`
+ live.location.href = url({ lat: HOME.lat + 0.02, lon: HOME.lon - 0.04, a: '1210.5', d: 693.6 });
await tick();
+ expect(live.canvas().style.transform).toBe('');
+ expect(live.state.view.zoom).toBeCloseTo(15 + Math.log2(1000 / 693.6), 9);
+ expect(live.state).not.toHaveProperty('calibration');
+ });
- 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('keeps the drawing dimmed until Earth stops rewriting a zoom', async () => {
+ // Earth writes its address several times during one zoom. Ending the wait on
+ // the first of them drew the marks at a scale the map was passing through.
+ const live = await onEarth();
+ wheel(1200, 300);
+ live.location.href = url({ d: 780 });
+ await tick(SETTLE_MS + 50);
+ live.location.href = url({ d: 500 });
+ await tick(POLL_MS);
+ expect(live.canvas().style.opacity).toBe('0.25');
+ expect(live.state.view.zoom).toBeCloseTo(16, 9);
+ await tick(SETTLE_QUIET_MS + 2 * POLL_MS);
+ expect(live.canvas().style.opacity).toBe('');
+ expect(live.state.view.zoom).toBeCloseTo(16, 9);
});
- 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('places its camera from a zoom, since a distance is exact at any fraction', async () => {
+ // A fractional level is only a rounding on a site that writes levels. Earth
+ // writes a distance to the hundredth of a millimetre, so a zoom of 1.4
+ // levels about one pixel says where it draws its centre as well as a whole
+ // one does. Synthesised here; `tests/fixtures/map-sites.json` carries Earth
+ // driven in a browser, which the recordings suite replays.
+ const FRAME = { x: 60, y: -20 };
+ const live = await onEarth();
+ const M = window.AzimutMapMath;
+ const middle = { x: window.innerWidth / 2 + FRAME.x, y: window.innerHeight / 2 + FRAME.y };
+ const at = { x: 1240, y: 290 };
+ const z0 = 15;
+ const d1 = 380;
+ const z1 = 15 + Math.log2(1000 / d1);
+ const c0 = M.project(HOME.lat, HOME.lon, z0);
+ const held = M.unproject(c0.x + at.x - middle.x, c0.y + at.y - middle.y, z0);
+ const p1 = M.project(held.lat, held.lon, z1);
+ const after = M.unproject(p1.x - (at.x - middle.x), p1.y - (at.y - middle.y), z1);
+
+ wheel(at.x, at.y);
+ live.location.href = url({ lat: after.lat, lon: after.lon, d: d1 });
+ await tick();
+ await tick(FRAME_QUIET_MS);
+ expect(live.state.framed).toBe(true);
+ expect(live.state.frame.x).toBeCloseTo(FRAME.x, 1);
+ expect(live.state.frame.y).toBeCloseTo(FRAME.y, 1);
+ expect(live.status()).not.toContain('zoom once to place it');
});
- 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.
+ it('keeps its scale when the compass turns', async () => {
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);
+ expect(live.state.view).toMatchObject({ zoom: 15, bearing: 45 });
+ expect(live.status()).toContain('distance from the URL');
});
});
@@ -916,120 +1154,153 @@ describe('the sky tool, zoomed out', () => {
});
/**
- * The first measurement on Google Earth, over ground that is not flat.
+ * The fire layer's seat, with and without the key behind it.
*
- * 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.
+ * The app greys its Active fires row when no FIRMS key is saved and says why on
+ * the row itself. The panel owes the same answer: a seat that opens on a
+ * paragraph about a missing key is a click spent learning there was nothing to
+ * click.
*/
-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,
- };
- }
+describe('the fire layer in the panel', () => {
+ const root = () => document.getElementById('azimut-map-tools').shadowRoot;
+ const seat = () => root().querySelector('[data-tab="fires"]');
+ const google = () => fixture.recordings.find((r) => r.site === 'google-maps');
- /**
- * 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);
- }
+ it('is greyed until a key is saved, and carries the reason', async () => {
+ await replay(google(), { answers: { '/api/ingest/firms/sensors': { keyed: false, sensors: [] } } });
+ expect(seat().disabled).toBe(true);
+ expect(seat().getAttribute('title')).toContain('FIRMS key');
+ });
- /** 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 });
+ const keyed = {
+ '/api/ingest/firms/sensors': {
+ keyed: true,
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ },
+ };
- async function onEarth() {
- const live = open({ parse: earthParse });
- live.location.href = url();
+ it('asks for nothing past the zoom where one mark stops meaning one detection', async () => {
+ // the recording ends at z17, which is deeper than the app's own map asks
+ // FIRMS at — it caps its tile source at z14 and scales what it has
+ const live = await replay(google(), { answers: keyed });
+ live.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]').click();
await tick();
- return live;
- }
+ expect(live.asks('/api/ingest/firms')).toEqual([]);
+ expect(root().textContent).toContain('Zoom out to z14');
+ });
- 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');
+ it('asks once the view is one it can answer for', async () => {
+ const live = await replay(google(), { answers: keyed, extra: { zoom: 10 } });
+ live.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]').click();
+ await tick();
+ const asked = live.asks('/api/ingest/firms');
+ expect(asked).toHaveLength(1);
+ expect(asked[0]).toMatchObject({ sensor: 'viirs', window: '24h' });
+ expect(asked[0].north).toBeGreaterThan(asked[0].south);
+ });
- 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);
+ /**
+ * Where the picture lands, zoomed out and away from the equator.
+ *
+ * FIRMS answers with one picture of a rectangle of ground, and that rectangle
+ * is drawn in Web Mercator — where the coordinate halfway between two
+ * latitudes is *not* the pixel halfway between them. Centred on the mean
+ * latitude, the picture rode low: nothing over a town, a tenth of the window
+ * over a continent, which is exactly the complaint about a zoomed-out map.
+ */
+ it('lands on its own ground, where Mercator stretches the north', async () => {
+ const live = await replay(google(), {
+ answers: keyed,
+ extra: { zoom: 4, lat: 55, lon: 10 },
+ });
+ live.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]').click();
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');
+ const asked = live.asks('/api/ingest/firms')[0];
+ const M = window.AzimutMapMath;
+ const view = live.state.view;
+ const area = { ...live.state.frame, w: window.innerWidth, h: window.innerHeight };
+ const nw = M.toScreen({ lat: asked.north, lon: asked.west }, view, area);
+ const se = M.toScreen({ lat: asked.south, lon: asked.east }, view, area);
+
+ const img = document.getElementById('azimut-map-tools').shadowRoot.querySelector('img');
+ const px = (name) => Number.parseFloat(img.style[name]);
+ // the box is centred and pulled back by half itself, so its north edge is
+ // the top of the ground it was drawn for
+ expect(px('top') - px('height') / 2).toBeCloseTo(nw.y, 1);
+ expect(px('left') - px('width') / 2).toBeCloseTo(nw.x, 1);
+ expect(px('top') + px('height') / 2).toBeCloseTo(se.y, 1);
+
+ // …and the placement it replaced is wrong by enough to see: the mean of the
+ // two latitudes is a different pixel from the middle of the two corners
+ const mean = M.toScreen({ lat: (asked.north + asked.south) / 2, lon: (asked.west + asked.east) / 2 }, view, area);
+ expect(Math.abs(mean.y - (nw.y + se.y) / 2)).toBeGreaterThan(5);
});
- 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);
+ it('dims out where the site draws a globe, as the drawing beside it does', async () => {
+ const live = await replay(google(), {
+ answers: keyed,
+ extra: { zoom: 4, lat: 55, lon: 10, far: true },
+ });
+ live.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]').click();
await tick();
- const measured = live.state.calibration.scale.pxPerLon;
+ const img = root().querySelector('img');
+ // a flat rectangle of ground laid over a curve, covering the whole window:
+ // the picture drifts further out there than any mark does
+ expect(img.parentElement.style.opacity).toBe('0.55');
+ expect(live.canvas().style.opacity).toBe('0.55');
+ });
- 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('asks a date with a calendar drawn in the panel, never over it', async () => {
+ const live = await replay(google(), {
+ answers: {
+ '/api/ingest/firms/sensors': {
+ keyed: true,
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ },
+ },
+ });
+ live.pick('fires');
+ root().querySelector('[data-act="fires-toggle"]').click();
+ root().querySelector('[data-window="dates"]').click();
+
+ // the browser's own picker is what this replaced: it opened over the page,
+ // at the browser's size, in the browser's locale
+ expect(root().querySelector('input[type="date"]')).toBe(null);
+ expect(root().querySelector('.cal')).toBe(null);
+
+ root().querySelector('[data-act="cal-open"][data-field="first"]').click();
+ expect(root().querySelector('.cal')).not.toBe(null);
+ root().querySelector('[data-act="cal-step"][data-by="-1"]').click();
+
+ const day = [...root().querySelectorAll('.cal-day')].find(
+ (b) => !b.disabled && !b.classList.contains('out')
+ );
+ const picked = day.dataset.day;
+ day.click();
+ expect(live.tools.fires.state.first).toBe(picked);
+ expect(root().querySelector('.cal')).toBe(null); // picked, so it is done
+ expect(root().querySelector('[data-act="cal-open"][data-field="first"]').textContent).toContain(
+ picked
+ );
});
- 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');
+ it('opens once one is, and none of the other seats was greyed with it', async () => {
+ const live = await replay(google(), {
+ answers: {
+ '/api/ingest/firms/sensors': {
+ keyed: true,
+ sensors: [{ id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' }],
+ },
+ },
+ });
+ expect(seat().disabled).toBe(false);
+ expect([...root().querySelectorAll('.tabs button')].filter((b) => b.disabled)).toEqual([]);
+ live.pick('fires');
+ expect(live.state.tool).toBe('fires');
});
});
diff --git a/frontend/src/lib/extensionMapFrame.test.js b/frontend/src/lib/extensionMapFrame.test.js
index e88b424..05f0ca1 100644
--- a/frontend/src/lib/extensionMapFrame.test.js
+++ b/frontend/src/lib/extensionMapFrame.test.js
@@ -50,6 +50,7 @@ describe('where each site draws its own centre', () => {
'apple-maps',
'bing-maps',
'copernicus-browser',
+ 'google-earth',
'google-maps',
'openstreetmap',
'satellites-pro',
@@ -126,7 +127,7 @@ describe('where each site draws its own centre', () => {
expect(off * METRES_PER_PIXEL(lat, 17)).toBeLessThan(2);
});
- it('is not the middle of the window on five of the eight', () => {
+ it('is not the middle of the window on five of the nine', () => {
// 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.
@@ -162,9 +163,10 @@ describe('where each site draws its own centre', () => {
.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', () => {
+ it('was driven at more than one window size on four of the sites', () => {
expect(twice.map(([site]) => site).sort()).toEqual([
'apple-maps',
+ 'google-earth',
'openstreetmap',
'yandex-maps',
]);
@@ -217,7 +219,7 @@ describe('where each site draws its own centre', () => {
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 });
+ expect(moved).toEqual({ 'apple-maps': 70, 'google-earth': 0, openstreetmap: 0, 'yandex-maps': 0 });
});
it('refuses to answer from a zoom too small to divide by', () => {
@@ -276,6 +278,9 @@ describe('the drawing follows a drag', () => {
// 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;
+ // Earth opens on a link with no ground in it, which states no scale to
+ // draw the drag through until the drag itself has placed the camera
+ if (before.zoom == null) return;
const area = {
x: recording.centre.x - recording.window.w / 2,
y: recording.centre.y - recording.window.h / 2,
diff --git a/frontend/src/lib/extensionMapLink.test.js b/frontend/src/lib/extensionMapLink.test.js
new file mode 100644
index 0000000..5da9d7b
--- /dev/null
+++ b/frontend/src/lib/extensionMapLink.test.js
@@ -0,0 +1,611 @@
+// @vitest-environment happy-dom
+/**
+ * Linked views over someone else's map (extension/maplink.js, and the panel's
+ * link button in extension/mapoverlay.js).
+ *
+ * The app puts two of its own tabs on one camera with `setView`. A site's map
+ * has nothing like it the extension may call, so a panel follows by writing the
+ * camera into the site's address bar, and only ever leads after the analyst
+ * moved its own map. Three things here are easy to get wrong and quiet when
+ * wrong:
+ *
+ * - **The written address has to read back as the view.** The tools take their
+ * scale from it. `tests/fixtures/map-link-writes.json` is checked from both
+ * sides: here the writer produces those URLs, and `test_map_link_writes.py`
+ * has the app's parser read them.
+ * - **A map that arrived because it was sent is silent.** Otherwise two linked
+ * maps push one camera back and forth for ever, and a map stopped at its own
+ * ceiling pulls the one it follows back out to it.
+ * - **The camera comparison is `link.js`'s.** The panel and the app decide
+ * "same view" on each side of the hub, and a disagreement is an echo.
+ */
+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';
+
+import { sameView } from './map/link.js';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const read = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
+const WRITES = JSON.parse(
+ readFileSync(join(here, '../../../tests/fixtures/map-link-writes.json'), 'utf8')
+).writes;
+
+let L;
+
+beforeAll(() => {
+ const scope = {};
+ new Function('window', read('maplink.js'))(scope);
+ L = scope.AzimutMapLink;
+});
+
+// --- the writer ------------------------------------------------------------------
+
+describe('a view written into a site’s address', () => {
+ it.each(WRITES.map((w) => [`${w.site}: ${w.name}`, w]))('%s', (_, w) => {
+ expect(L.writeView({ site: w.site }, w.from, w.view, w.height)).toBe(w.url);
+ });
+
+ it('holds a site that keeps a level it cannot draw to the level it draws', () => {
+ const deep = { lat: 48.85837, lon: 2.294481, zoom: 23, bearing: 0 };
+ const google = L.writeView({ site: 'google-maps' }, 'https://www.google.com/maps/@1,2,15z', deep, 1000);
+ expect(google).toContain(',21z');
+ const osm = L.writeView({ site: 'openstreetmap' }, 'https://www.openstreetmap.org/#map=15/1/2', deep, 1000);
+ expect(osm).toContain('map=19/');
+ });
+
+ it('leaves a site that corrects itself to do so', () => {
+ // Zoom Earth rewrites an 11-level ceiling into its own address, and Bing its
+ // 22: writing their ceiling here would be a second, staler copy of it
+ const deep = { lat: 48.85837, lon: 2.294481, zoom: 20, bearing: 0 };
+ const zoomEarth = L.writeView(
+ { site: 'zoom-earth' },
+ 'https://zoom.earth/maps/satellite/#view=1,2,11z',
+ deep,
+ 1000
+ );
+ expect(zoomEarth).toContain(',20z');
+ expect(L.writeView({ site: 'bing-maps' }, 'https://www.bing.com/maps?cp=1~2&lvl=15', deep, 1000)).toContain(
+ 'lvl=20'
+ );
+ });
+
+ it('refuses what it cannot write rather than guessing', () => {
+ const view = { lat: 1, lon: 2, zoom: 15, bearing: 0 };
+ // a site it does not know, a Street View camera, a view with no number in it
+ expect(L.writeView({ site: 'somewhere' }, 'https://example.com/', view, 1000)).toBeNull();
+ expect(
+ L.writeView({ site: 'google-maps' }, 'https://www.google.com/maps/@1,2,3a,75y,90h/data=!3m1', view, 1000)
+ ).toBeNull();
+ expect(L.writeView({ site: 'bing-maps' }, 'https://www.bing.com/maps', { lat: NaN, lon: 2, zoom: 3 }, 1000)).toBeNull();
+ // Earth's distance only means a level next to the height it is drawn in
+ expect(
+ L.writeView({ site: 'google-earth' }, 'https://earth.google.com/web/@1,2,10a,500d,35y,0h,0t,0r', view, 0)
+ ).toBeNull();
+ });
+
+ it('holds Apple to the latitude it opens, so its address is true when it lands', () => {
+ // written past the limit, Apple moves back to it and the address says the
+ // pole for as long as it takes the site to rewrite it — which is the address
+ // the tools take their ground from
+ const far = { lat: 78.223, lon: 15.6, zoom: 12, bearing: 0 };
+ const href = 'https://maps.apple.com/frame?center=70.1,15.6&z=12';
+ expect(L.writeView({ site: 'apple-maps' }, href, far, 1000)).toContain('center=70.495574%2C15.6');
+ expect(L.writeView({ site: 'apple-maps' }, href, { ...far, lat: -78.223 }, 1000)).toContain('-70.495574');
+ // and nowhere else: only Apple was measured refusing to open one
+ expect(L.writeView({ site: 'bing-maps' }, 'https://www.bing.com/maps?cp=1~2&lvl=15', far, 1000)).toContain(
+ 'cp=78.223%7E15.6'
+ );
+ });
+
+ it('writes nothing where the address already says it', () => {
+ const href = 'https://satellites.pro/#1,2,15';
+ expect(L.writeView({ site: 'satellites-pro' }, href, { lat: 1, lon: 2, zoom: 15 }, 1000)).toBeNull();
+ });
+});
+
+describe('where a site will not go, or will not say', () => {
+ it('names an Apple place card, which hides the camera until it is closed', () => {
+ expect(L.hiddenBy('https://maps.apple.com/place?map=satellite&coordinate=47.38,2.35&name=x')).toContain(
+ 'Close the card'
+ );
+ expect(L.hiddenBy('https://maps.apple.com/frame?center=47.38,2.35&z=16')).toBeNull();
+ expect(L.hiddenBy('not a url')).toBeNull();
+ });
+
+ it('says Apple stopped at the latitude it opens no view past', () => {
+ // opened past ±70.4956° Apple lands on it, and dragging goes the rest
+ const asked = { lat: 78.22, lon: 15.6, zoom: 12 };
+ expect(L.poleLimit('apple-maps', asked, { lat: 70.495574, lon: 15.6, zoom: 12 })).toBeCloseTo(70.4956, 3);
+ expect(L.poleLimit('apple-maps', { ...asked, lat: -78 }, { lat: -70.495574, lon: 15.6, zoom: 12 })).not.toBeNull();
+ expect(L.poleLimit('apple-maps', { ...asked, lat: 69 }, { lat: 69, lon: 15.6, zoom: 12 })).toBeNull();
+ expect(L.poleLimit('bing-maps', asked, { lat: 70.495574, lon: 15.6, zoom: 12 })).toBeNull();
+ });
+});
+
+describe('which views may lead or follow', () => {
+ const map = {
+ site: 'openstreetmap',
+ lat: 50.45,
+ lon: 30.52,
+ zoom: 17,
+ view_kind: 'map',
+ geometry: true,
+ scale_source: 'zoom',
+ };
+
+ it('takes a flat map whose address states a scale', () => {
+ expect(L.followable(map)).toBe(true);
+ });
+
+ it('leaves Street View, a pitched camera and an unscaled view where they are', () => {
+ expect(L.followable({ ...map, view_kind: 'streetview' })).toBe(false);
+ expect(L.followable({ ...map, view_kind: 'tilted' })).toBe(false);
+ expect(L.followable({ ...map, scale_source: null, zoom: null })).toBe(false);
+ expect(L.followable(null)).toBe(false);
+ });
+});
+
+describe('saying how close a map came', () => {
+ const asked = { lat: 1, lon: 2, zoom: 21 };
+
+ it('names the level a map stopped at', () => {
+ expect(L.shortOf(asked, { lat: 1, lon: 2, zoom: 11 })).toBe(11);
+ });
+
+ it('says nothing while a map is still on its way', () => {
+ // Earth flies in from space on every load, and its first address is not short
+ expect(L.shortOf(asked, { lat: 0, lon: -0.25, zoom: 3.3 })).toBeNull();
+ });
+
+ it('says nothing about half a level of rounding', () => {
+ expect(L.shortOf({ ...asked, zoom: 16.4 }, { lat: 1, lon: 2, zoom: 16 })).toBeNull();
+ expect(L.shortOf(asked, { lat: 1, lon: 2, zoom: 21 })).toBeNull();
+ expect(L.shortOf(null, { lat: 1, lon: 2, zoom: 21 })).toBeNull();
+ });
+});
+
+describe('the two copies of "the same camera" agree', () => {
+ const base = { lat: 48.8566, lon: 2.3522, zoom: 17, bearing: 0 };
+ const pairs = [
+ [base, base],
+ [base, { ...base, lat: base.lat + 0.0000001 }],
+ [base, { ...base, lat: 48.86 }],
+ [base, { ...base, zoom: 16 }],
+ [base, { ...base, zoom: 17.4 }],
+ [base, { ...base, bearing: 90 }],
+ [{ lat: 1, lon: 2, zoom: 5 }, { lat: 1, lon: 2, zoom: 5, bearing: 0 }],
+ [base, null],
+ ];
+
+ it('on every pair', () => {
+ for (const [a, b] of pairs) expect(L.sameCamera(a, b), JSON.stringify([a, b])).toBe(sameView(a, b));
+ });
+});
+
+// --- the panel ---------------------------------------------------------------------
+
+/** 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', 'maplink.js'];
+const POLL_MS = 300;
+
+beforeAll(() => {
+ globalThis.Path2D = class {
+ constructor(d) {
+ this.d = d;
+ }
+ };
+ window.HTMLCanvasElement.prototype.getContext = () => {
+ const noop = () => {};
+ return new Proxy({ measureText: () => ({ width: 20 }) }, { get: (t, n) => t[n] ?? noop });
+ };
+});
+
+/** The app's reading of an OpenStreetMap address: `#map=z/lat/lon`. A stand-in
+ * for the parser, which `test_map_link_writes.py` holds to the writer. */
+function osmParse(url, extra = {}) {
+ const m = /map=([\d.]+)\/(-?[\d.]+)\/(-?[\d.]+)/.exec(url);
+ return {
+ site: 'openstreetmap',
+ label: 'OpenStreetMap',
+ lat: Number(m[2]),
+ lon: Number(m[3]),
+ zoom: Number(m[1]),
+ bearing: 0,
+ projection: 'webmercator',
+ view_kind: 'map',
+ geometry: true,
+ far: false,
+ scale_source: 'zoom',
+ ...extra,
+ };
+}
+
+/**
+ * A panel on OpenStreetMap, the port it opens to the hub, and an address bar
+ * that takes a new hash the way that site does: in place, without a reload.
+ */
+function open({ extra = {}, href = 'https://www.openstreetmap.org/#map=17/50.45/30.52', parse = osmParse } = {}) {
+ window.happyDOM.setViewport({ width: 1400, height: 900 });
+ const location = {
+ href,
+ host: new URL(href).host,
+ assign: vi.fn((url) => {
+ location.href = url;
+ }),
+ };
+ const links = [];
+ const api = {
+ storage: { local: { get: vi.fn(async (d) => ({ ...d })), 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: {} };
+ if (message.path === '/api/ingest/parse') return { ok: true, data: parse(message.query.url, extra) };
+ if (message.path === '/api/ingest/ping') return { ok: true, data: { units: 'metric' } };
+ if (message.path === '/api/ingest/cases') return { ok: true, data: [{ id: 'c', name: 'Case' }] };
+ return { ok: true, data: [] };
+ }),
+ connect: vi.fn((info) => {
+ const port = {
+ name: info.name,
+ heard: [],
+ listeners: [],
+ onMessage: { addListener: (cb) => port.listeners.push(cb) },
+ onDisconnect: { addListener: () => {} },
+ postMessage: vi.fn((msg) => port.heard.push(msg)),
+ disconnect: vi.fn(),
+ };
+ if (info.name === 'map-link') links.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;
+ const link = () => links.at(-1);
+ return {
+ ...panel,
+ location,
+ link,
+ /** The hub, saying something to this panel. */
+ hub: (msg) => {
+ for (const cb of link().listeners) cb(msg);
+ },
+ said: (type) => link().heard.filter((m) => m.type === type),
+ button: () => root().querySelector('[data-act="link"]'),
+ /** This tab going behind another, and being come back to. */
+ hide: () => showTab(false),
+ show: () => showTab(true),
+ status: () => root().querySelector('.status')?.textContent ?? '',
+ note: () => root().querySelector('.note')?.textContent ?? '',
+ };
+}
+
+/** Whether this tab is the one being looked at, which is what the panel reads to
+ * decide between following a view now and keeping it for later. */
+function showTab(on) {
+ Object.defineProperty(document, 'hidden', { value: !on, configurable: true });
+ document.dispatchEvent(new window.Event('visibilitychange'));
+}
+
+const tick = (ms = POLL_MS) => vi.advanceTimersByTimeAsync(ms);
+const at = (type, x, y) =>
+ window.dispatchEvent(new window.MouseEvent(type, { clientX: x, clientY: y, bubbles: true, button: 0 }));
+
+let panel = null;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ panel?.close();
+ panel = null;
+ showTab(true);
+ vi.useRealTimers();
+ document.documentElement.querySelectorAll('#azimut-map-tools').forEach((node) => node.remove());
+});
+
+/** A panel that has read its address and been told it is linked with one peer. */
+async function linked(options) {
+ const live = open(options);
+ await tick();
+ live.hub({ type: 'link-peers', count: 1 });
+ live.hub({ type: 'link-state', linked: true, asked: null });
+ return live;
+}
+
+describe('the link button', () => {
+ it('opens the port the hub counts it by', async () => {
+ panel = open();
+ await tick();
+ expect(panel.link().name).toBe('map-link');
+ });
+
+ it('is greyed while there is no other map to link to', async () => {
+ panel = open();
+ await tick();
+ expect(panel.button().disabled).toBe(true);
+ expect(panel.button().title).toBe('Open another map, here or in Azimut, to link the views');
+ panel.hub({ type: 'link-peers', count: 1 });
+ expect(panel.button().disabled).toBe(false);
+ });
+
+ it('links, and brings the other maps to this one', async () => {
+ panel = open();
+ await tick();
+ panel.hub({ type: 'link-peers', count: 1 });
+ panel.button().click();
+ expect(panel.said('link')).toEqual([{ type: 'link', on: true }]);
+ expect(panel.said('view')).toEqual([{ type: 'view', view: { lat: 50.45, lon: 30.52, zoom: 17, bearing: 0 } }]);
+ expect(panel.button().dataset.on).toBe('1');
+ });
+
+ it('stays lit while a linked tab it follows is away reloading', async () => {
+ // the hub counts a tab on its way to a view, but a panel told nobody is left
+ // must not switch its own link off: that is the worker's to decide
+ panel = await linked();
+ panel.hub({ type: 'link-peers', count: 0 });
+ expect(panel.button().disabled).toBe(false);
+ expect(panel.button().dataset.on).toBe('1');
+ });
+
+ it('leaves the link when the tools are closed', async () => {
+ panel = await linked();
+ const port = panel.link();
+ panel.close();
+ panel = null;
+ expect(port.heard).toContainEqual({ type: 'link', on: false });
+ });
+});
+
+describe('following a view', () => {
+ const there = { lat: 50.47, lon: 30.6, zoom: 15, bearing: 0 };
+
+ it('writes it into the address bar, having told the hub it is on its way', async () => {
+ panel = await linked();
+ panel.hub({ type: 'view', view: there });
+ expect(panel.said('follow')).toEqual([{ type: 'follow', view: there }]);
+ expect(panel.location.assign).toHaveBeenCalledWith('https://www.openstreetmap.org/#map=15/50.47/30.6');
+ });
+
+ it('holds a view that arrives before the panel has read its own address', async () => {
+ // a panel put back after a reload hears what it missed straight away
+ panel = open();
+ panel.hub({ type: 'link-state', linked: true, asked: null });
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ await tick();
+ expect(panel.location.assign).toHaveBeenCalledWith('https://www.openstreetmap.org/#map=15/50.47/30.6');
+ expect(panel.note()).toBe('');
+ });
+
+ it('ignores views while it is not linked', async () => {
+ panel = open();
+ await tick();
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ });
+
+ it('does not move a map that is already there', async () => {
+ panel = await linked();
+ panel.hub({ type: 'view', view: { lat: 50.45, lon: 30.52, zoom: 17, bearing: 0 } });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ });
+
+ it('stays on a view that is not a flat map, and says so', async () => {
+ panel = await linked({ extra: { view_kind: 'streetview' } });
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ expect(panel.note()).toBe('Linked view not followed: this is not a flat map');
+ });
+
+ it('lands in silence, so the map it follows is not sent back its own view', async () => {
+ panel = await linked();
+ panel.hub({ type: 'view', view: there });
+ await tick();
+ expect(panel.state.view.zoom).toBe(15);
+ // the site took it in its hash: the panel never left, and says it arrived
+ expect(panel.said('landed')).toHaveLength(1);
+ await tick(3000);
+ expect(panel.said('view')).toEqual([]);
+ });
+
+ it('says it went as close as this map goes', async () => {
+ // Zoom Earth stops at 11 while the map it follows is at 21: said here, never
+ // corrected, because nothing is wrong with either
+ panel = open();
+ await tick();
+ panel.hub({ type: 'link-state', linked: true, asked: { lat: 50.45, lon: 30.52, zoom: 21, bearing: 0 } });
+ expect(panel.status()).toContain('as close as this map goes (linked view z21.0)');
+ });
+
+ it('follows from an Apple place card, which hides the camera, and says what to do meanwhile', async () => {
+ const place =
+ 'https://maps.apple.com/place?map=satellite&z=16&address=2+Route&coordinate=47.387736,2.353482&name=2+Route';
+ const appleNoView = () => ({ site: 'apple-maps', label: 'Apple Maps', lat: null, lon: null, zoom: null });
+ panel = await linked({ href: place, parse: appleNoView });
+ expect(panel.status()).toContain('Close the card to go on');
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).toHaveBeenCalledWith(
+ 'https://maps.apple.com/frame?map=satellite&center=50.47%2C30.6&z=15'
+ );
+ });
+
+ it('says Apple stopped at the latitude it will open, and to drag the rest', async () => {
+ const frame = 'https://maps.apple.com/frame?map=satellite&center=70.495574,15.6&z=12';
+ const apple = () => ({
+ site: 'apple-maps',
+ label: 'Apple Maps',
+ lat: 70.495574,
+ lon: 15.6,
+ zoom: 12,
+ bearing: 0,
+ projection: 'webmercator',
+ view_kind: 'map',
+ geometry: true,
+ far: false,
+ scale_source: 'span',
+ });
+ panel = open({ href: frame, parse: apple });
+ await tick();
+ panel.hub({ type: 'link-state', linked: true, asked: { lat: 78.22, lon: 15.6, zoom: 12, bearing: 0 } });
+ expect(panel.status()).toContain('opens no nearer the pole than 70.5°, drag the rest of the way');
+ });
+
+ it('keeps a view for a tab in the background, and takes it when it is looked at', async () => {
+ panel = await linked();
+ panel.hide();
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ // and the hub is not told a tab is on its way anywhere, because none is
+ expect(panel.said('follow')).toEqual([]);
+ panel.show();
+ expect(panel.location.assign).toHaveBeenCalledWith('https://www.openstreetmap.org/#map=15/50.47/30.6');
+ expect(panel.said('follow')).toEqual([{ type: 'follow', view: there }]);
+ });
+
+ it('keeps only the last of the views it missed, not the way the other map went', async () => {
+ panel = await linked();
+ panel.hide();
+ for (const zoom of [16, 14, 12]) panel.hub({ type: 'view', view: { ...there, zoom } });
+ panel.show();
+ expect(panel.location.assign).toHaveBeenCalledTimes(1);
+ expect(panel.location.assign).toHaveBeenCalledWith('https://www.openstreetmap.org/#map=12/50.47/30.6');
+ });
+
+ it('goes on following a tab that is only unfocused, which is still one being read', async () => {
+ // two maps side by side on two screens: neither is hidden, and a view held
+ // back until one of them is clicked would read as the link having dropped
+ panel = await linked();
+ panel.show();
+ panel.hub({ type: 'view', view: there });
+ expect(panel.location.assign).toHaveBeenCalledWith('https://www.openstreetmap.org/#map=15/50.47/30.6');
+ });
+
+ it('drops a view kept for a background tab that the analyst moves on arriving', async () => {
+ // coming back to a map and dragging it makes this one the map that leads:
+ // the view it missed would pull it off the ground the analyst just chose
+ panel = await linked();
+ panel.hide();
+ panel.hub({ type: 'view', view: there });
+ at('pointerdown', 700, 450);
+ panel.show();
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ at('pointerup', 700, 450);
+ await tick(3000);
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ });
+
+ it('leaves a map stopped at Apple’s pole where it is, gesture after gesture', async () => {
+ // it is already as far north as it opens, so every view past the limit asks
+ // for the ground it is on: reloading for each of them puts it back where it
+ // was, on top of the drag the panel had just asked for
+ const stopped = { lat: 70.495574, lon: 15.6, zoom: 12, bearing: 0 };
+ const apple = () => ({
+ site: 'apple-maps',
+ label: 'Apple Maps',
+ ...stopped,
+ projection: 'webmercator',
+ view_kind: 'map',
+ geometry: true,
+ far: false,
+ scale_source: 'span',
+ });
+ panel = await linked({ href: 'https://maps.apple.com/frame?center=70.495574,15.6&z=12', parse: apple });
+ for (const lat of [78.2, 79.1, 80]) panel.hub({ type: 'view', view: { ...stopped, lat } });
+ expect(panel.location.assign).not.toHaveBeenCalled();
+ // and it still goes where it can: the limit is on the latitude, not the view
+ panel.hub({ type: 'view', view: { lat: 79.1, lon: 20, zoom: 12, bearing: 0 } });
+ expect(panel.location.assign).toHaveBeenCalledWith('https://maps.apple.com/frame?center=70.495574%2C20&z=12');
+ });
+
+ it('passes on what the hub could not do', async () => {
+ panel = await linked();
+ panel.hub({ type: 'link-note', note: 'A linked tab reloaded and the browser kept its tools off. Open them there again' });
+ expect(panel.note()).toContain('kept its tools off');
+ });
+});
+
+describe('leading', () => {
+ it('sends the view once the analyst has moved this map and it has settled', async () => {
+ panel = await linked();
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.6';
+ await tick(1500);
+ expect(panel.said('view')).toEqual([{ type: 'view', view: { lat: 50.45, lon: 30.6, zoom: 17, bearing: 0 } }]);
+ });
+
+ it('sends nothing for a gesture that left the map where it was', async () => {
+ // Copernicus does not rewrite its address on a pan: there is no new view to
+ // hand over, and the old one would move the others back
+ panel = await linked();
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ await tick(3000);
+ expect(panel.said('view')).toEqual([]);
+ });
+
+ it('sends what a slow site writes down after the settle gave up waiting', async () => {
+ // Earth writes a drag seconds after the pointer let go, and again as it
+ // glides: the lead is the view it stops on, not the first nor none
+ panel = await linked();
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ await tick(3000); // the settle gives up with the address bar unchanged
+ expect(panel.said('view')).toEqual([]);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.55';
+ await tick(300);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.6';
+ await tick(1200);
+ expect(panel.said('view')).toEqual([{ type: 'view', view: { lat: 50.45, lon: 30.6, zoom: 17, bearing: 0 } }]);
+ });
+
+ it('stops counting the address bar as the analyst’s long after the gesture', async () => {
+ panel = await linked();
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ await tick(25000);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.6';
+ await tick(1500);
+ expect(panel.said('view')).toEqual([]);
+ });
+
+ it('sends nothing while it is not linked', async () => {
+ panel = open();
+ await tick();
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.6';
+ await tick(1500);
+ expect(panel.said('view')).toEqual([]);
+ });
+
+ it('stops saying how close it came once the analyst takes this map somewhere', async () => {
+ panel = open();
+ await tick();
+ panel.hub({ type: 'link-state', linked: true, asked: { lat: 50.45, lon: 30.52, zoom: 21, bearing: 0 } });
+ at('pointerdown', 700, 450);
+ at('pointermove', 600, 450);
+ at('pointerup', 600, 450);
+ panel.location.href = 'https://www.openstreetmap.org/#map=17/50.45/30.6';
+ await tick(1500);
+ expect(panel.status()).not.toContain('as close as this map goes');
+ });
+});
diff --git a/frontend/src/lib/extensionMapMath.test.js b/frontend/src/lib/extensionMapMath.test.js
index b1bd166..9fe7ef2 100644
--- a/frontend/src/lib/extensionMapMath.test.js
+++ b/frontend/src/lib/extensionMapMath.test.js
@@ -177,384 +177,29 @@ describe('the two flattenings are not interchangeable', () => {
});
});
-/**
- * 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');
+describe('what the arithmetic will not do', () => {
+ it('offers nothing that learns a scale from a gesture', () => {
+ // How big a map is drawn comes from its URL (`engine/mapsites.py`). The
+ // pan-measured scale that used to sit here put Earth's drawing four times
+ // too small and kept it there, so it went, and this keeps it gone.
+ expect(Object.keys(ext).sort()).toEqual(
+ [
+ 'MIN_ANCHOR_PX',
+ 'MIN_ZOOM_STEP',
+ 'centreFromZoom',
+ 'formatArea',
+ 'formatDistance',
+ 'haversine',
+ 'pathLength',
+ 'polygonArea',
+ 'project',
+ 'toLatLon',
+ 'toScreen',
+ 'turn',
+ 'unproject',
+ 'unturn',
+ 'zoomFromAnchor',
+ ].sort()
+ );
});
});
-
-/** 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/extensionMapSync.test.js b/frontend/src/lib/extensionMapSync.test.js
index cdd034d..d374a9d 100644
--- a/frontend/src/lib/extensionMapSync.test.js
+++ b/frontend/src/lib/extensionMapSync.test.js
@@ -26,7 +26,7 @@ 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 PARTS = ['mapmath.js', 'maptheme.js', 'maptools.js', 'mapdraw.js', 'mapref.js', 'maplink.js'];
const CASE = 'case-1';
const OTHER = 'case-2';
@@ -98,6 +98,7 @@ function open({ answers } = {}) {
};
const ports = [];
+ const links = []; // the linked-views port (extensionMapLink.test.js covers it)
const api = {
storage: {
local: { get: vi.fn(async (defaults) => ({ ...defaults })), set: vi.fn() },
@@ -121,7 +122,7 @@ function open({ answers } = {}) {
postMessage: vi.fn((msg) => port.heard.push(msg)),
disconnect: vi.fn(() => (port.gone = true)),
};
- ports.push(port);
+ (info.name === 'map-sync' ? ports : links).push(port);
return port;
}),
},
@@ -315,3 +316,35 @@ describe('an open sweep', () => {
expect(panel.asks()).not.toContain('/api/ingest/grids');
});
});
+
+describe('the beta badge', () => {
+ const badge = () =>
+ document.getElementById('azimut-map-tools').shadowRoot.querySelector('header .beta');
+
+ it('marks Google Earth, where the tools drift the most', async () => {
+ panel = open({
+ answers: {
+ '/api/ingest/parse': {
+ site: 'google-earth',
+ label: 'Google Earth',
+ lat: 50.45,
+ lon: 30.52,
+ zoom: 17,
+ bearing: 0,
+ projection: 'webmercator',
+ view_kind: 'satellite',
+ geometry: true,
+ scale_source: 'distance',
+ },
+ },
+ });
+ await settle();
+ await vi.waitFor(() => expect(badge()?.textContent).toBe('Beta'));
+ });
+
+ it('stays off every other map', async () => {
+ panel = open();
+ await settle();
+ expect(badge()).toBeNull();
+ });
+});
diff --git a/frontend/src/lib/extensionMapTheme.test.js b/frontend/src/lib/extensionMapTheme.test.js
index fee1b16..bb471cd 100644
--- a/frontend/src/lib/extensionMapTheme.test.js
+++ b/frontend/src/lib/extensionMapTheme.test.js
@@ -64,13 +64,24 @@ describe('the icons', () => {
}
});
+ /**
+ * Read off the panel's own source rather than listed by hand.
+ *
+ * A hand-kept list only covers the glyphs somebody remembered to add to it,
+ * and `icon()` falls back to the warning triangle for a name it does not
+ * know — so a missing glyph does not break, it draws an alarm where an arrow
+ * belongs, and nothing fails. Which is exactly what the calendar's `‹ ›`
+ * did. Asking the files which names they pass is the gate that would have
+ * caught it.
+ */
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',
- ];
+ const used = new Set(Object.values(theme.SAVED_GLYPH));
+ for (const file of ['mapoverlay.js', 'maptools.js', 'mapdraw.js', 'mapref.js']) {
+ const src = read(`../../../extension/${file}`);
+ for (const [, name] of src.matchAll(/\bicon\(\s*["']([A-Za-z]+)["']/g)) used.add(name);
+ for (const [, name] of src.matchAll(/icon:\s*["']([A-Za-z]+)["']/g)) used.add(name);
+ }
+ expect(used.size).toBeGreaterThan(15); // the scan found the calls, not nothing
for (const name of used) expect(theme.ICONS, name).toHaveProperty(name);
});
diff --git a/frontend/src/lib/extensionMapTools.test.js b/frontend/src/lib/extensionMapTools.test.js
index c313739..6479bb7 100644
--- a/frontend/src/lib/extensionMapTools.test.js
+++ b/frontend/src/lib/extensionMapTools.test.js
@@ -26,6 +26,8 @@ import * as app from './gridSearch.js';
import * as appSky from './skyOverlay.js';
import * as appMarkers from './savedMarkers.js';
import * as appRefs from './refViewers.js';
+import * as appFires from './map/firms.js';
+import * as appCal from './calendar.js';
const here = dirname(fileURLToPath(import.meta.url));
const load = (name) => readFileSync(join(here, `../../../extension/${name}`), 'utf8');
@@ -179,12 +181,11 @@ describe('grouping saved work into marks, on both sides', () => {
});
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;
+ /** The line a view with no stated scale shows. 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 noScale = () => ext.NO_SCALE;
const MAP = {
site: 'google-maps',
@@ -198,38 +199,49 @@ describe('the geometry verdict', () => {
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('asks for the one thing that makes the address bar state a scale', () => {
+ // every site writes its scale again as soon as the map moves, and Earth
+ // writes the ground's height into it, which is what a typed link lacks
+ expect(noScale()).toBe('Move the map once so its address bar gives the scale');
});
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 });
+ expect(ext.verdict(MAP)).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('draws from every scale the app can read out of a URL', () => {
+ // a tile level, Apple's span, Google satellite's height in metres, and
+ // Earth's camera distance through its field of view — each checked against
+ // a browser before it was believed (docs/MAP_SITES.md)
+ for (const [site, source] of [
+ ['google-maps', 'zoom'],
+ ['apple-maps', 'span'],
+ ['google-maps', 'height_m'],
+ ['google-earth', 'distance'],
+ ]) {
+ expect(ext.verdict({ ...MAP, site, zoom: 15.37, scale_source: source })).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('draws nothing where the URL states no scale, and learns none from a gesture', () => {
+ // There is no second argument any more. A scale measured off a drag is how
+ // Earth's marks ended up four times too close together, and stayed there.
+ const mute = { ...MAP, zoom: null, scale_source: null };
+ expect(ext.verdict(mute)).toEqual({ ok: false, why: noScale() });
+ expect(ext.verdict.length).toBe(1);
});
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);
+ expect(ext.verdict({ site: null }).why).toMatch(/not a map Azimut can read/);
+ expect(ext.verdict(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/);
+ expect(ext.verdict({ ...MAP, lat: null, lon: null }).why).toMatch(/move the map once/);
});
it('names the way out of every view it refuses', () => {
@@ -238,9 +250,9 @@ describe('the geometry verdict', () => {
['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: kind, geometry: false }).why).toBe(why);
}
- expect(ext.verdict({ ...MAP, view_kind: 'hologram', geometry: false }, null).why)
+ expect(ext.verdict({ ...MAP, view_kind: 'hologram', geometry: false }).why)
.toBe('This view is not a map to measure on');
});
@@ -249,71 +261,41 @@ describe('the geometry verdict', () => {
// 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)
+ expect(ext.verdict(tilted).why).toBe('These tools work in 2D only, so turn 3D off');
+ expect(ext.verdict({ ...tilted, tilt: 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);
+ const wide = ext.verdict({ ...MAP, zoom: 3, far: true });
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,
- });
+ expect(ext.verdict({ ...MAP, far: false })).toEqual({ ok: true, why: '', far: false });
+ });
+
+ it('refuses a globe camera outright, with a scale or without, and says to zoom in', () => {
+ // The other globe, and not the same thing at all. Above is a flat map drawn
+ // far out, whose centre this arithmetic is still right about. This is a
+ // perspective camera on a sphere — Earth's 3D mode past its ceiling, and
+ // Google's Earth mode with it — where Mercator is not right at all.
+ const earth = { ...MAP, site: 'google-earth', view_kind: 'globe', geometry: false, far: true };
+ for (const source of ['distance', null]) {
+ const said = ext.verdict({ ...earth, scale_source: source });
+ expect(said.ok).toBe(false);
+ expect(said.why).toBe('The camera is on a globe this far out, so zoom in');
+ }
});
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)
+ expect(ext.verdict({ ...MAP, view_kind: null, geometry: false, globe_below: 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', () => {
@@ -905,3 +887,159 @@ describe('the reference windows', () => {
expect(refs.open).toEqual([]);
});
});
+
+describe('the fire layer, on both sides of the boundary', () => {
+ const SENSORS = [
+ { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'modis', label: 'MODIS (Terra + Aqua)' },
+ ];
+
+ it('offers the same windows and the same limit as the app', () => {
+ expect(ext.FIRE_WINDOWS).toEqual(appFires.WINDOWS);
+ expect(ext.FIRE_DATED).toBe(appFires.DATED);
+ expect(ext.FIRE_MAX_RANGE_DAYS).toBe(appFires.MAX_RANGE_DAYS);
+ });
+
+ it('agrees with the app about what FIRMS will answer', () => {
+ const asked = [
+ { window: '24h' },
+ { window: '7d' },
+ { window: 'dates' },
+ { window: 'dates', first: '2026-08-01' },
+ { window: 'dates', first: '2026-08-01', last: '2026-08-09' },
+ { window: 'dates', first: '2026-08-09', last: '2026-08-01' },
+ { window: 'dates', first: '2026-01-01', last: '2026-03-01' },
+ { window: 'dates', first: 'soon' },
+ ];
+ for (const choice of asked) {
+ expect(ext.fireAskable(choice)).toBe(appFires.askable(choice));
+ }
+ });
+
+ it('stops a range on the same day the app does', () => {
+ for (const first of ['2026-01-01', '2026-02-10', '2026-12-20', '']) {
+ expect(ext.fireLastDay(first)).toBe(appFires.lastDayOf(first));
+ }
+ });
+
+ it('asks for the same thing the app asks for', () => {
+ const fires = ext.createFires();
+ fires.offer({ keyed: true, sensors: SENSORS });
+ fires.toggle();
+ expect(fires.query()).toEqual(appFires.tileParams({ sensor: 'viirs', window: '24h' }));
+
+ fires.set('sensor', 'modis');
+ fires.set('window', 'dates');
+ fires.set('first', '2026-08-01');
+ expect(fires.query()).toEqual(
+ appFires.tileParams({ sensor: 'modis', window: 'dates', first: '2026-08-01' })
+ );
+ });
+
+ it('asks for nothing until the layer is on, keyed and answerable', () => {
+ const fires = ext.createFires();
+ expect(fires.query()).toBe(null); // no key yet
+ fires.offer({ keyed: true, sensors: SENSORS });
+ expect(fires.query()).toBe(null); // …and not switched on
+ fires.toggle();
+ expect(fires.query()).not.toBe(null);
+ fires.set('window', 'dates');
+ expect(fires.query()).toBe(null); // …and waiting for a date
+ });
+
+ it('draws nothing and takes no click, whatever else is being measured', () => {
+ const fires = ext.createFires();
+ fires.offer({ keyed: true, sensors: SENSORS });
+ fires.toggle();
+ expect(fires.armed).toBe(false);
+ expect(fires.shapes()).toEqual([]);
+ fires.disarm();
+ expect(fires.state.on).toBe(true); // putting a tool down is not hiding a layer
+ });
+
+ it('says what it is showing, in the words the app uses', () => {
+ const fires = ext.createFires();
+ expect(fires.readout()).toBe('Add a NASA FIRMS key in Azimut Settings');
+ fires.offer({ keyed: true, sensors: SENSORS });
+ expect(fires.readout()).toBe('Detections are not being drawn');
+ fires.toggle();
+ expect(fires.readout()).toBe('VIIRS · last 24 h');
+ fires.set('window', 'dates');
+ expect(fires.readout()).toBe('Pick a date to draw the detections');
+ fires.set('first', '2026-08-01');
+ expect(fires.readout()).toBe('VIIRS · 2026-08-01');
+ });
+
+ it('stops asking at the zoom the app’s own map stops at', () => {
+ // the app caps the tile source rather than refusing to draw: past this it
+ // keeps showing that level, scaled. The panel holds its one picture the
+ // same way, and neither asks again.
+ const basemap = readFileSync(join(here, './map/basemap.js'), 'utf8');
+ const firms = /id: 'firms',[\s\S]*?maxZoom: (\d+)/.exec(basemap);
+ expect(ext.FIRE_MAX_ZOOM).toBe(Number(firms[1]));
+ });
+
+ it('offers no seat at all until a key is behind it', () => {
+ const fires = ext.createFires();
+ expect(fires.offerable).toBe(false);
+ fires.offer({ keyed: true, sensors: SENSORS });
+ expect(fires.offerable).toBe(true);
+ });
+});
+
+/**
+ * The calendar, which is the sixth thing written twice.
+ *
+ * Both sides draw their own month because the browser's own picker opens over
+ * the page and outside the panel it belongs to. Two calendars is two chances to
+ * disagree about which day a box is, so they are run over the same months here
+ * — including the ones that catch an off-by-one: a month starting on a Sunday,
+ * a leap February, and a year boundary.
+ */
+describe('the calendar, on both sides of the boundary', () => {
+ const MONTHS = ['2026-09', '2026-08', '2027-02', '2024-02', '2026-01', '2026-12', '2026-11'];
+
+ it('starts its weeks on the same day, named the same way', () => {
+ expect(ext.CAL_WEEKDAYS).toEqual(appCal.WEEKDAYS);
+ });
+
+ it('cuts every month into the same boxes', () => {
+ for (const month of MONTHS) {
+ expect(ext.calMonthDays(month), month).toEqual(appCal.monthDays(month));
+ expect(ext.calMonthLabel(month), month).toBe(appCal.monthLabel(month));
+ }
+ });
+
+ it('opens on the same month, from a day or from nothing', () => {
+ for (const value of ['2026-03-04', '2026-03', '', 'soon']) {
+ expect(ext.calMonthOf(value, '2026-09-12'), value).toBe(appCal.monthOf(value, '2026-09-12'));
+ }
+ });
+
+ it('walks months the same way, across both year boundaries', () => {
+ for (const [cursor, by] of [['2026-01', -1], ['2026-12', 1], ['2026-03-31', -1], ['2026-06', 7]]) {
+ expect(ext.calShiftMonth(cursor, by), `${cursor}${by}`).toBe(appCal.shiftMonth(cursor, by));
+ }
+ });
+
+ it('refuses the same days, and greys the same arrows', () => {
+ const bounds = [
+ ['', ''],
+ ['2026-09-10', '2026-09-20'],
+ ['', '2026-09-12'],
+ ['2026-09-12', ''],
+ ];
+ for (const [min, max] of bounds) {
+ for (const day of ['2026-09-09', '2026-09-12', '2026-09-21', '']) {
+ expect(ext.calOutOfRange(day, min, max), `${day} in ${min}..${max}`).toBe(
+ appCal.outOfRange(day, min, max)
+ );
+ }
+ for (const month of MONTHS) {
+ expect(ext.calMonthOutOfRange(month, min, max), `${month} in ${min}..${max}`).toBe(
+ appCal.monthOutOfRange(month, min, max)
+ );
+ }
+ }
+ });
+});
diff --git a/frontend/src/lib/extensionPopup.test.js b/frontend/src/lib/extensionPopup.test.js
index 014f598..1e8941e 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, height = 940 }) {
+async function runPopup({ tabUrl, answers, height = 940, stored = {} }) {
// 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
@@ -48,6 +48,7 @@ async function runPopup({ tabUrl, answers, height = 940 }) {
...defaults,
backendUrl: 'http://127.0.0.1:8477',
token: 'tok-123',
+ ...stored,
})),
set: vi.fn(),
},
@@ -172,3 +173,56 @@ describe('how tall the map is drawn', () => {
expect(parse).not.toContain('height=');
});
});
+
+describe('the scale bar and north arrow tick', () => {
+ const googleMaps = (stored) => ({
+ tabUrl: 'https://www.google.fr/maps/@48.85,2.29,17z',
+ stored,
+ answers: {
+ '/parse': ok({ site: 'google-maps', label: 'Google Maps', lat: 48.85, lon: 2.29, zoom: 17 }),
+ '/cases': ok([{ id: 'c1', name: 'Case one' }]),
+ },
+ });
+
+ it('starts off, and a capture taken without it asks for no marks', async () => {
+ await runPopup(googleMaps());
+
+ expect($('marks').checked).toBe(false);
+ $('capture-area').click();
+ const [[msg]] = globalThis.chrome.runtime.sendMessage.mock.calls;
+ expect(msg.meta.marks).toBe(false);
+ });
+
+ it('is remembered the moment it is ticked, and rides with the capture', async () => {
+ await runPopup(googleMaps());
+
+ $('marks').checked = true;
+ $('marks').dispatchEvent(new Event('change'));
+ expect(globalThis.chrome.storage.local.set).toHaveBeenCalledWith({ captureMarks: true });
+
+ $('capture-area').click();
+ const [[msg]] = globalThis.chrome.runtime.sendMessage.mock.calls;
+ expect(msg.meta.marks).toBe(true);
+ });
+
+ it('comes back ticked next time it is opened', async () => {
+ await runPopup(googleMaps({ captureMarks: true }));
+
+ expect($('marks').checked).toBe(true);
+ });
+
+ it('points at the bearing field, since this URL states no rotation', async () => {
+ await runPopup(googleMaps({ captureMarks: true }));
+
+ expect($('marks-note').hidden).toBe(false);
+ $('bearing').value = '42';
+ $('bearing').dispatchEvent(new Event('input'));
+ expect($('marks-note').hidden).toBe(true);
+ });
+
+ it('says nothing about a heading when the marks are not wanted', async () => {
+ await runPopup(googleMaps());
+
+ expect($('marks-note').hidden).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/geoTree.js b/frontend/src/lib/geoTree.js
index fe463f3..39544b0 100644
--- a/frontend/src/lib/geoTree.js
+++ b/frontend/src/lib/geoTree.js
@@ -43,6 +43,38 @@ function matchesKind(row, kind) {
return true;
}
+/**
+ * The folder a row was filed under, against the one being asked for.
+ *
+ * `null` is every folder and `''` is the rows nobody filed, which are two
+ * different questions: "show me everything" and "show me what I have not put
+ * away yet".
+ */
+function matchesFolder(row, folder) {
+ if (folder == null) return true;
+ return (row.folder || '') === folder;
+}
+
+/**
+ * The folders the given rows are filed under, each with how many it holds.
+ *
+ * Read off the rows rather than off the case: a folder holding notes and no
+ * saved point would be a switch that hides nothing, and the map's own filter
+ * should only offer what is on the map.
+ */
+export function savedFolders(rows) {
+ const counts = new Map();
+ for (const row of rows ?? []) {
+ const key = row.folder || '';
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+ }
+ return [...counts]
+ .map(([id, count]) => ({ id, count }))
+ // named folders in their own order, and the unfiled rows last: they are a
+ // leftover, not a place
+ .sort((a, b) => (a.id === '' ? 1 : b.id === '' ? -1 : a.id.localeCompare(b.id)));
+}
+
/** Everything a search over saved work reads: what it is called, what was
* written about it, where it is, and who it came from. */
function savedText(row) {
@@ -81,8 +113,13 @@ export function oneEach(rows) {
}
/** The rows a kind + query select, in the index's own newest-first order. */
-export function filterSaved(rows, { kind = 'all', query = '' } = {}) {
- return (rows ?? []).filter((row) => matchesKind(row, kind) && matchesTerms(savedText(row), query));
+export function filterSaved(rows, { kind = 'all', query = '', folder = null } = {}) {
+ return (rows ?? []).filter(
+ (row) =>
+ matchesKind(row, kind) &&
+ matchesFolder(row, folder) &&
+ matchesTerms(savedText(row), query)
+ );
}
/** How the search modal can order results. The tree has no sort control: its
diff --git a/frontend/src/lib/geoTree.test.js b/frontend/src/lib/geoTree.test.js
index 76e39c2..d5838c1 100644
--- a/frontend/src/lib/geoTree.test.js
+++ b/frontend/src/lib/geoTree.test.js
@@ -9,6 +9,7 @@ import {
KINDS,
oneEach,
pendingLocate,
+ savedFolders,
} from './geoTree.js';
const ok = (country, code, region, extra = {}) => ({
@@ -313,3 +314,40 @@ describe('a proof of several points', () => {
expect(filterSaved(rows, { query: 'harbour' })).toHaveLength(2);
});
});
+
+describe('showing only the folders wanted on the map', () => {
+ const rows = [
+ UA('a', 'Donetsk Oblast', { kind: 'place', folder: 'Bridges' }),
+ UA('bb', 'Kyiv Oblast', { kind: 'capture', folder: 'Bridges' }),
+ UA('ccc', 'Kyiv Oblast', { kind: 'place', folder: 'Airfields' }),
+ UA('dddd', 'Kyiv Oblast', { kind: 'place' }),
+ ];
+
+ it('lists the folders the rows are actually filed under, with their tallies', () => {
+ expect(savedFolders(rows)).toEqual([
+ { id: 'Airfields', count: 1 },
+ { id: 'Bridges', count: 2 },
+ { id: '', count: 1 }, // what nobody filed, last
+ ]);
+ });
+
+ it('draws every folder until one is asked for', () => {
+ expect(filterSaved(rows, {})).toHaveLength(4);
+ expect(filterSaved(rows, { folder: null })).toHaveLength(4);
+ });
+
+ it('narrows to one folder, and to the unfiled as its own answer', () => {
+ expect(filterSaved(rows, { folder: 'Bridges' }).map((r) => r.id)).toEqual(['a', 'bb']);
+ expect(filterSaved(rows, { folder: '' }).map((r) => r.id)).toEqual(['dddd']);
+ });
+
+ it('narrows with the kind rather than instead of it', () => {
+ expect(filterSaved(rows, { folder: 'Bridges', kind: 'places' }).map((r) => r.id)).toEqual(['a']);
+ });
+
+ it('has nothing to offer for a case whose saved work is unfiled', () => {
+ expect(savedFolders([UA('a', 'Kyiv Oblast', { kind: 'place' })])).toEqual([
+ { id: '', count: 1 },
+ ]);
+ });
+});
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index 531946c..cb50dda 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -192,7 +192,15 @@ export const GUIDE = [
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.',
+ text: 'Esri, its Wayback archive of past releases, OSM and OpenTopoMap are built in. Sentinel-2 and the other keyed providers use your own key, and a custom XYZ template is accepted.',
+ },
+ {
+ label: 'Right-click the ground',
+ text: 'The menu acts on the point under the cursor: copy it in any format, save it, measure or read the sun from it, see its imagery history, or open it in another map.',
+ },
+ {
+ label: 'Layers cost nothing until they are on',
+ text: 'Borders, roads, railways, power lines, sea marks, GPS traces, fires and night lights are listed in the Saved panel, and none of them is fetched before its switch is pressed.',
},
{
label: 'The search bar answers before it asks',
diff --git a/frontend/src/lib/hash.js b/frontend/src/lib/hash.js
new file mode 100644
index 0000000..059fba1
--- /dev/null
+++ b/frontend/src/lib/hash.js
@@ -0,0 +1,46 @@
+/**
+ * The location hash: which tool is open, and what that tool wants remembered.
+ *
+ * It used to be one word (`#satellite`), written by `App.svelte` on every tool
+ * change. A tool that opens in more than one window needs more than that: a
+ * second map window is the same tool on a different view, and the view has to
+ * be in the address or the window cannot be reopened, duplicated, or even
+ * survive a reload.
+ *
+ * So the hash reads `#<route>?<the tool's own state>`, and the two halves have
+ * two owners. The app owns the route and never touches the query; a tool owns
+ * its query and never touches the route. Anything written here is a link the
+ * analyst could have typed, so a tool reading it back validates it.
+ */
+
+/** `#satellite?ll=48.8,2.3` → `{ route: 'satellite', params: URLSearchParams }`. */
+export function splitHash(hash = '') {
+ const bare = String(hash).replace(/^#/, '');
+ const cut = bare.indexOf('?');
+ if (cut === -1) return { route: bare, params: new URLSearchParams() };
+ return { route: bare.slice(0, cut), params: new URLSearchParams(bare.slice(cut + 1)) };
+}
+
+/**
+ * Is this tab the tool on its own, with the app taken away from around it?
+ *
+ * A detached map is opened onto a second screen to *be* a map: the workspace
+ * rail, the case bar and the tab strip are how you get somewhere in the first
+ * window, and they are chrome in the second. So a tool that opens a peer says
+ * so in the address — which also means the tab survives a reload as what it
+ * was, and that nothing else has to be stored anywhere.
+ *
+ * The app is what honours it, since the app owns everything being removed.
+ */
+export function readSolo(params) {
+ const raw = params instanceof URLSearchParams ? params.get('solo') : params?.solo;
+ return raw === '1';
+}
+
+/** …and back. An empty query leaves the plain `#route` the app has always written. */
+export function buildHash(route, params) {
+ const query =
+ params instanceof URLSearchParams ? params : new URLSearchParams(params ?? {});
+ const tail = query.toString();
+ return tail ? `#${route}?${tail}` : `#${route}`;
+}
diff --git a/frontend/src/lib/hash.test.js b/frontend/src/lib/hash.test.js
new file mode 100644
index 0000000..7caa28f
--- /dev/null
+++ b/frontend/src/lib/hash.test.js
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { buildHash, readSolo, splitHash } from './hash.js';
+
+describe('the location hash', () => {
+ it('reads a bare route, the way every tool link is written', () => {
+ const { route, params } = splitHash('#satellite');
+ expect(route).toBe('satellite');
+ expect([...params]).toEqual([]);
+ });
+
+ it('reads a route with the tool\'s own state after it', () => {
+ const { route, params } = splitHash('#satellite?ll=48.8,2.3&z=17');
+ expect(route).toBe('satellite');
+ expect(params.get('ll')).toBe('48.8,2.3');
+ expect(params.get('z')).toBe('17');
+ });
+
+ it('reads a workspace route the same way', () => {
+ expect(splitHash('#compose/post?x=1').route).toBe('compose/post');
+ });
+
+ it('survives an empty, missing or hash-less input', () => {
+ for (const input of ['', '#', undefined, 'satellite']) {
+ expect(() => splitHash(input)).not.toThrow();
+ }
+ expect(splitHash(undefined).route).toBe('');
+ });
+
+ it('writes the plain route back when the tool asked for nothing', () => {
+ expect(buildHash('satellite', {})).toBe('#satellite');
+ expect(buildHash('satellite')).toBe('#satellite');
+ expect(buildHash('satellite', new URLSearchParams())).toBe('#satellite');
+ });
+
+ it('round-trips what a tool put there', () => {
+ const written = buildHash('satellite', { ll: '48.8,2.3', z: '17' });
+ expect(written).toBe('#satellite?ll=48.8%2C2.3&z=17');
+ expect(splitHash(written).params.get('ll')).toBe('48.8,2.3');
+ });
+});
+
+describe('a tab holding one tool and nothing else', () => {
+ it('is what a detached window says it is', () => {
+ expect(readSolo(splitHash('#satellite?ll=48.8,2.3&w=2&solo=1').params)).toBe(true);
+ expect(readSolo({ solo: '1' })).toBe(true);
+ });
+
+ it('is not what an ordinary window is', () => {
+ expect(readSolo(splitHash('#satellite').params)).toBe(false);
+ expect(readSolo(splitHash('#satellite?ll=48.8,2.3').params)).toBe(false);
+ expect(readSolo(undefined)).toBe(false);
+ });
+
+ it('takes nothing else for a yes, since an address is typed by hand', () => {
+ // the app around the tool is not something to lose to a stray character
+ for (const raw of ['0', 'true', 'yes', '', 'solo']) {
+ expect(readSolo({ solo: raw })).toBe(false);
+ }
+ });
+});
diff --git a/frontend/src/lib/map/basemap.js b/frontend/src/lib/map/basemap.js
index 609019c..09dd4bb 100644
--- a/frontend/src/lib/map/basemap.js
+++ b/frontend/src/lib/map/basemap.js
@@ -18,23 +18,164 @@
* for. MapLibre overzooms what it already holds instead.
*/
import { createGoogleGlass, loadGoogleMaps } from './gmaps.js';
-
-// A labels-only layer laid over the imagery: roads and place names readable
-// without hiding the satellite view. Over a street basemap it would only
-// double its own labels, which is why the tool keeps it to imagery.
-const LABELS_URL =
- 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png';
-const LABELS_ATTRIBUTION = '© OpenStreetMap contributors © CARTO';
-const LABELS_MAX_ZOOM = 20;
+import { INFRASTRUCTURE } from './infrastructure.js';
+import { tileTemplate as nightTemplate } from './nightlights.js';
/** What a `{s}` template is served from when the provider names no hosts. */
const DEFAULT_SUBDOMAINS = ['a', 'b', 'c'];
-const LABELS_SUBDOMAINS = ['a', 'b', 'c', 'd'];
const IMAGERY = 'basemap-imagery';
-const LABELS = 'basemap-labels';
+
+/**
+ * What can be laid over the imagery, in the order they stack — first is
+ * lowest, and the imagery goes under all of them.
+ *
+ * Each is asked for only once the analyst switches it on: a map that is not
+ * showing railways fetches no railway tiles. The key-less ones are fetched
+ * straight from their own servers, which all answer cross-origin, and none of
+ * them is billed. FIRMS is the exception and goes through the app, which is
+ * where its key lives.
+ *
+ * Order matters on screen. The night picture is opaque, so it sits lowest and
+ * everything reads over it. Then lines over the picture, point marks over the
+ * lines, names over all of them (a station name under its own track is a name
+ * nobody reads), and the fires last, because when that layer is on it is the
+ * subject.
+ *
+ * `url` may be a function, for a layer whose address is a question rather than
+ * a constant: FIRMS answers for one sensor over one window, the night lights
+ * for one night, and changing either is a different set of tiles.
+ *
+ * `vector` is a layer drawn from vector tiles by a style of our own: several
+ * sources and several engine layers, switched on and off as one.
+ */
+const OVERLAYS = [
+ {
+ // One night photographed from orbit, or the 2016 baseline (nightlights.js).
+ // Key-less and public domain. Magnified past its 750 m pixels rather than
+ // cut off, because which district went dark is read zoomed in.
+ id: 'nightlights',
+ layer: 'basemap-nightlights',
+ url: nightTemplate,
+ attribution: 'Night lights: NASA EOSDIS GIBS, VIIRS',
+ maxZoom: 8,
+ viewMaxZoom: 13,
+ // just enough of the ground through it to tell which street is lit
+ opacity: 0.85,
+ },
+ {
+ // The raw GPS traces people uploaded to OSM: tracks nobody mapped yet, and
+ // how a site is really driven into.
+ id: 'gpstraces',
+ layer: 'basemap-gpstraces',
+ url: 'https://gps.tile.openstreetmap.org/lines/{z}/{x}/{y}.png',
+ attribution: 'GPS traces © OpenStreetMap contributors',
+ maxZoom: 20,
+ },
+ {
+ // Esri's road reference, drawn for imagery like the labels are.
+ id: 'roads',
+ layer: 'basemap-roads',
+ url: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer/tile/{z}/{y}/{x}',
+ attribution: 'Esri, HERE, Garmin, © OpenStreetMap contributors',
+ maxZoom: 19,
+ },
+ {
+ // Tracks, yards and stations, drawn as lines over whatever is underneath —
+ // the one OSM rendering that says which of two parallel strips is a railway.
+ id: 'railway',
+ layer: 'basemap-railway',
+ url: 'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png',
+ subdomains: ['a', 'b', 'c'],
+ attribution: '© OpenStreetMap contributors · style © OpenRailwayMap',
+ maxZoom: 19,
+ },
+ {
+ id: 'power',
+ layer: 'basemap-power',
+ vector: INFRASTRUCTURE,
+ attribution: '© OpenStreetMap contributors · Open Infrastructure Map (CC-BY)',
+ },
+ {
+ // Buoys, lights, harbours and fairways: the sea's own signage.
+ id: 'seamarks',
+ layer: 'basemap-seamarks',
+ url: 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png',
+ attribution: '© OpenSeaMap contributors',
+ maxZoom: 18,
+ },
+ {
+ // Country, region and district borders with their names. Esri's, under the
+ // same terms as the World Imagery the app already shows.
+ id: 'boundaries',
+ layer: 'basemap-boundaries',
+ url: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer/tile/{z}/{y}/{x}',
+ attribution: 'Esri, HERE, Garmin, © OpenStreetMap contributors, and the GIS user community',
+ maxZoom: 19,
+ },
+ {
+ // Roads and place names readable without hiding the satellite view. Over a
+ // street basemap it would only double its own labels, which is why the tool
+ // keeps it to imagery.
+ id: 'labels',
+ layer: 'basemap-labels',
+ url: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager_only_labels/{z}/{x}/{y}.png',
+ subdomains: ['a', 'b', 'c', 'd'],
+ attribution: '© OpenStreetMap contributors © CARTO',
+ maxZoom: 20,
+ },
+ {
+ // Active fire detections, live or from the archive (engine/firms.py). The
+ // key is NASA's and stays on the backend, so this one address is ours.
+ id: 'firms',
+ layer: 'basemap-firms',
+ url: (params) => `/api/firms/tiles/{z}/{x}/{y}?${new URLSearchParams(params)}`,
+ attribution: 'Active fire data: NASA FIRMS',
+ // FIRMS draws a fixed symbol per detection and VIIRS resolves 375 m: deeper
+ // than this is a screen of overlapping marks, and the route refuses it.
+ maxZoom: 14,
+ },
+];
+
+/** The ids a surface can be asked to show, so nothing hard-codes the list. */
+export const OVERLAY_IDS = OVERLAYS.map((overlay) => overlay.id);
+
+/**
+ * The engine layers one overlay is drawn as, lowest first. A raster overlay is
+ * one; a vector overlay is one per entry of its style.
+ */
+export function overlayLayers(overlay) {
+ if (!overlay.vector) return [overlay.layer];
+ return overlay.vector.layers.map((entry) => `${overlay.layer}-${entry.id}`);
+}
+
+/** …and the sources behind them, as `[id, spec]`. */
+export function overlaySources(overlay, params) {
+ const { attribution } = overlay;
+ if (overlay.vector) {
+ return Object.entries(overlay.vector.sources).map(([name, url]) => [
+ `${overlay.layer}-${name}`,
+ { type: 'vector', tiles: [url], minzoom: 0, maxzoom: overlay.vector.maxZoom, attribution },
+ ]);
+ }
+ const template = typeof overlay.url === 'function' ? overlay.url(params ?? {}) : overlay.url;
+ return [
+ [
+ overlay.layer,
+ {
+ type: 'raster',
+ tiles: tileUrls(template, overlay.subdomains),
+ tileSize: 256,
+ minzoom: 0,
+ maxzoom: overlay.maxZoom,
+ attribution,
+ },
+ ],
+ ];
+}
+
/** Ours, so the first layer that is not is where the basemap stops. */
-const OWNED = new Set([IMAGERY, LABELS]);
+const OWNED = new Set([IMAGERY, ...OVERLAYS.flatMap(overlayLayers)]);
/**
* Where a provider's tiles are fetched from.
@@ -129,16 +270,38 @@ export function createBasemaps(engine, hooks = {}) {
// hiding and showing the one we have costs nothing. Never destroyed until
// the map goes, for the same reason.
let glass = null;
- let labels = false;
+ // The overlays currently laid over the imagery, each against the question it
+ // was built to answer (null for the ones that are simply on or off).
+ const shown = new Map();
let wanted = null; // the provider id last asked for, so a slow load can tell
let metered = null; // the billed provider whose tiles we are counting
// Drawn shapes are appended by `surface.js`, so the first layer this module
- // does not own is where the basemap stops and the overlays begin.
+ // does not own is where the basemap stops and a tool's own marks begin.
function ceiling() {
return map.getLayersOrder().find((id) => !OWNED.has(id));
}
+ /** Whether an overlay is on the map, read off its lowest layer. */
+ function isUp(overlay) {
+ return Boolean(map.getLayer(overlayLayers(overlay)[0]));
+ }
+
+ /** The lowest overlay that is up, which is what the imagery goes under. */
+ function lowestOverlay() {
+ const up = OVERLAYS.find(isUp);
+ return up ? overlayLayers(up)[0] : ceiling();
+ }
+
+ /**
+ * Where one overlay is inserted: under the first overlay declared above it
+ * that is already up, so the stack holds however they are switched on.
+ */
+ function under(overlay) {
+ const above = OVERLAYS.slice(OVERLAYS.indexOf(overlay) + 1).find(isUp);
+ return above ? overlayLayers(above)[0] : ceiling();
+ }
+
function onSourceData(event) {
if (!metered || event.sourceId !== IMAGERY || !event.isSourceLoaded) return;
// every visible tile is in, so what the proxy counted is now final
@@ -168,10 +331,7 @@ export function createBasemaps(engine, hooks = {}) {
dropTiles();
capZoom(provider);
map.addSource(IMAGERY, rasterSource(provider, providerId, cell));
- map.addLayer(
- { id: IMAGERY, type: 'raster', source: IMAGERY },
- map.getLayer(LABELS) ? LABELS : ceiling()
- );
+ map.addLayer({ id: IMAGERY, type: 'raster', source: IMAGERY }, lowestOverlay());
live = `${providerId}@${cell}`;
if (provider.meter) {
metered = provider;
@@ -203,36 +363,41 @@ export function createBasemaps(engine, hooks = {}) {
glass.show();
}
- function addLabels() {
- if (map.getLayer(LABELS)) return;
- map.addSource(LABELS, {
- type: 'raster',
- tiles: tileUrls(LABELS_URL, LABELS_SUBDOMAINS),
- tileSize: 256,
- minzoom: 0,
- maxzoom: LABELS_MAX_ZOOM,
- attribution: LABELS_ATTRIBUTION,
- });
+ function addOverlay(overlay, params) {
+ if (isUp(overlay)) return;
+ for (const [id, spec] of overlaySources(overlay, params)) map.addSource(id, spec);
+ const before = under(overlay);
+ if (overlay.vector) {
+ for (const entry of overlay.vector.layers) {
+ map.addLayer(
+ { ...entry, id: `${overlay.layer}-${entry.id}`, source: `${overlay.layer}-${entry.source}` },
+ before
+ );
+ }
+ return;
+ }
map.addLayer(
{
- id: LABELS,
+ id: overlay.layer,
type: 'raster',
- source: LABELS,
+ source: overlay.layer,
// Past its own last level the overlay stops rather than being blown up:
// a road name upscaled four times over a rooftop is a smear, and this
// is what the map before it did. The two ceilings are the same number
// and different questions — the source's is the deepest tile, the
// layer's is the deepest view, which the engine counts one shallower.
- maxzoom: LABELS_MAX_ZOOM,
+ // A picture whose coarse pixels are still worth reading zoomed in
+ // states a deeper view of its own.
+ maxzoom: overlay.viewMaxZoom ?? overlay.maxZoom,
+ ...(overlay.opacity != null ? { paint: { 'raster-opacity': overlay.opacity } } : {}),
},
- // above the imagery, below anything a tool draws
- ceiling()
+ before
);
}
- function dropLabels() {
- if (map.getLayer(LABELS)) map.removeLayer(LABELS);
- if (map.getSource(LABELS)) map.removeSource(LABELS);
+ function dropOverlay(overlay) {
+ for (const id of overlayLayers(overlay)) if (map.getLayer(id)) map.removeLayer(id);
+ for (const [id] of overlaySources(overlay, {})) if (map.getSource(id)) map.removeSource(id);
}
return {
@@ -262,11 +427,30 @@ export function createBasemaps(engine, hooks = {}) {
showTiles(provider, providerId, cell);
},
- setLabels(on) {
- if (on === labels) return;
- labels = on;
- if (on) addLabels();
- else dropLabels();
+ /**
+ * Lay one overlay over the imagery, or take it off (`OVERLAY_IDS`).
+ *
+ * Idempotent, because the surface re-states every overlay whenever one of
+ * them changes: switching the railways on must not rebuild the labels, and
+ * a rebuilt raster layer is every visible tile refetched.
+ *
+ * `params` is for a layer that is a question — FIRMS's sensor and window.
+ * A different question is a different set of tiles, so that one *is*
+ * rebuilt, and only when the answer it was built with has changed.
+ */
+ setOverlay(id, on, params) {
+ const overlay = OVERLAYS.find((entry) => entry.id === id);
+ if (!overlay) return;
+ const asked = on ? JSON.stringify(params ?? null) : null;
+ if (asked === (shown.get(id) ?? null)) return;
+ if (shown.has(id)) {
+ shown.delete(id);
+ dropOverlay(overlay);
+ }
+ if (on) {
+ shown.set(id, asked);
+ addOverlay(overlay, params);
+ }
},
dispose() {
diff --git a/frontend/src/lib/map/basemap.test.js b/frontend/src/lib/map/basemap.test.js
index f60eb0a..4ca6048 100644
--- a/frontend/src/lib/map/basemap.test.js
+++ b/frontend/src/lib/map/basemap.test.js
@@ -331,10 +331,10 @@ describe('the layers on a map', () => {
});
});
- it('stops the labels at their own last level rather than blowing them up', async () => {
+ it('stops an overlay at its own last level rather than blowing it up', async () => {
await withStubbedGoogle(async ({ createBasemaps }) => {
const map = stubMap();
- createBasemaps(stubEngine(map)).setLabels(true);
+ createBasemaps(stubEngine(map)).setOverlay('labels', true);
// the deepest tile, and the deepest view, which the engine counts one
// shallower — the same number, two questions
expect(map.sources.get('basemap-labels').maxzoom).toBe(20);
@@ -343,36 +343,207 @@ describe('the layers on a map', () => {
});
});
- it('adds the labels layer once and takes it off when asked', async () => {
+ it('adds an overlay once and takes it off when asked', async () => {
await withStubbedGoogle(async ({ createBasemaps }) => {
const map = stubMap();
const basemaps = createBasemaps(stubEngine(map));
- basemaps.setLabels(true);
- basemaps.setLabels(true);
+ basemaps.setOverlay('labels', true);
+ basemaps.setOverlay('labels', true);
expect(map.layers.map((l) => l.id)).toEqual(['basemap-labels']);
- basemaps.setLabels(false);
+ basemaps.setOverlay('labels', false);
expect(map.layers).toEqual([]);
});
});
- it('keeps the labels over the imagery and both under what a tool draws', async () => {
+ it('ignores an overlay it does not have', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ createBasemaps(stubEngine(map)).setOverlay('weather', true);
+ expect(map.layers).toEqual([]);
+ });
+ });
+
+ it('builds a layer that is a question from the question it was asked', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ createBasemaps(stubEngine(map)).setOverlay('firms', true, {
+ sensor: 'modis',
+ window: '48h',
+ });
+ const [url] = map.sources.get('basemap-firms').tiles;
+ // through the app, because the key is NASA's and stays on the backend
+ expect(url).toContain('/api/firms/tiles/{z}/{x}/{y}?');
+ expect(url).toContain('sensor=modis');
+ expect(url).toContain('window=48h');
+ });
+ });
+
+ it('rebuilds that layer when the question changes, and only then', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ const params = { sensor: 'viirs', window: '24h' };
+ basemaps.setOverlay('firms', true, params);
+ const first = map.sources.get('basemap-firms');
+ // the same question again is the same tiles: rebuilding would refetch
+ // every one of them, which reads on screen as a reloading map
+ basemaps.setOverlay('firms', true, { ...params });
+ expect(map.sources.get('basemap-firms')).toBe(first);
+
+ basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '7d' });
+ expect(map.sources.get('basemap-firms')).not.toBe(first);
+ expect(map.sources.get('basemap-firms').tiles[0]).toContain('window=7d');
+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-firms']);
+ });
+ });
+
+ it('draws the fires over the names, because when it is on it is the subject', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('firms', true, { sensor: 'viirs', window: '24h' });
+ basemaps.setOverlay('labels', true);
+ basemaps.setOverlay('railway', true);
+ expect(map.layers.map((l) => l.id)).toEqual([
+ 'basemap-railway',
+ 'basemap-labels',
+ 'basemap-firms',
+ ]);
+ });
+ });
+
+ it('holds the overlay stack however they are switched on', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ // the names last, whichever order they arrive in: a station label under
+ // its own track is a label nobody can read
+ basemaps.setOverlay('labels', true);
+ basemaps.setOverlay('railway', true);
+ expect(map.layers.map((l) => l.id)).toEqual(['basemap-railway', 'basemap-labels']);
+ });
+ });
+
+ it('keeps every overlay over the imagery and all of them under what a tool draws', async () => {
await withStubbedGoogle(async ({ createBasemaps }) => {
const map = stubMap();
const basemaps = createBasemaps(stubEngine(map));
basemaps.show(ESRI, ESRI.id, 256);
- basemaps.setLabels(true);
- // a tool's own layer, appended above both
+ basemaps.setOverlay('railway', true);
+ basemaps.setOverlay('labels', true);
+ // a tool's own layer, appended above all three
map.addLayer({ id: 'sfc-1-fill' });
- // and now a different provider, which must not land on top of either
+ // and now a different provider, which must not land on top of any of them
basemaps.show(SENTINEL, 'sentinel2~a~~~CC100', 512);
expect(map.layers.map((l) => l.id)).toEqual([
'basemap-imagery',
+ 'basemap-railway',
'basemap-labels',
'sfc-1-fill',
]);
});
});
+ it('draws a vector overlay as all of its layers, and takes them all off together', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('power', true);
+ expect([...map.sources.keys()]).toEqual([
+ 'basemap-power-power',
+ 'basemap-power-telecoms',
+ 'basemap-power-petroleum',
+ ]);
+ expect(map.sources.get('basemap-power-power')).toMatchObject({
+ type: 'vector',
+ tiles: ['https://openinframap.org/map/power/{z}/{x}/{y}.pbf'],
+ });
+ const ids = map.layers.map((l) => l.id);
+ expect(ids[0]).toBe('basemap-power-pipeline');
+ expect(ids).toContain('basemap-power-tower');
+ // every layer reads the source it names, under this overlay's own prefix
+ expect(map.getLayer('basemap-power-mast').source).toBe('basemap-power-telecoms');
+ basemaps.setOverlay('power', false);
+ expect(map.layers).toEqual([]);
+ expect(map.sources.size).toBe(0);
+ });
+ });
+
+ it('slides a vector overlay into the stack as one block', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('labels', true);
+ basemaps.setOverlay('railway', true);
+ basemaps.setOverlay('power', true);
+ const ids = map.layers.map((l) => l.id);
+ // over the tracks, under the names
+ expect(ids[0]).toBe('basemap-railway');
+ expect(ids.at(-1)).toBe('basemap-labels');
+ expect(ids.slice(1, -1).every((id) => id.startsWith('basemap-power-'))).toBe(true);
+ });
+ });
+
+ it('holds the whole stack, lowest first, whatever order the switches were pressed in', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.show(ESRI, ESRI.id, 256);
+ for (const id of ['firms', 'labels', 'boundaries', 'seamarks', 'railway', 'roads', 'gpstraces']) {
+ basemaps.setOverlay(id, true, id === 'firms' ? { sensor: 'viirs', window: '24h' } : undefined);
+ }
+ basemaps.setOverlay('nightlights', true, { source: 'noaa20', day: '2026-09-12' });
+ expect(map.layers.map((l) => l.id)).toEqual([
+ 'basemap-imagery',
+ 'basemap-nightlights',
+ 'basemap-gpstraces',
+ 'basemap-roads',
+ 'basemap-railway',
+ 'basemap-seamarks',
+ 'basemap-boundaries',
+ 'basemap-labels',
+ 'basemap-firms',
+ ]);
+ });
+ });
+
+ it('asks GIBS for the night it was given, and lets its coarse pixels be read zoomed in', async () => {
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ basemaps.setOverlay('nightlights', true, { source: 'snpp', day: '2022-02-24' });
+ const source = map.sources.get('basemap-nightlights');
+ expect(source.tiles[0]).toContain('/VIIRS_SNPP_DayNightBand_At_Sensor_Radiance/default/2022-02-24/');
+ expect(source.maxzoom).toBe(8);
+ const layer = map.getLayer('basemap-nightlights');
+ expect(layer.maxzoom).toBe(13);
+ expect(layer.paint['raster-opacity']).toBeLessThan(1);
+
+ basemaps.setOverlay('nightlights', true, { source: 'snpp', day: '2022-02-25' });
+ expect(map.sources.get('basemap-nightlights').tiles[0]).toContain('/2022-02-25/');
+ });
+ });
+
+ it('fetches every key-less overlay straight from its own server, over https', async () => {
+ // none of them is keyed or billed, so none of them needs the app in between;
+ // FIRMS is the one whose key has to stay on the backend
+ await withStubbedGoogle(async ({ createBasemaps }) => {
+ const { OVERLAY_IDS } = await import('./basemap.js');
+ const params = {
+ firms: { sensor: 'viirs', window: '24h' },
+ nightlights: { source: 'noaa20', day: '2026-09-12' },
+ };
+ const map = stubMap();
+ const basemaps = createBasemaps(stubEngine(map));
+ for (const id of OVERLAY_IDS) basemaps.setOverlay(id, true, params[id]);
+ for (const [id, source] of map.sources) {
+ const expected = id === 'basemap-firms' ? /^\/api\/firms\/tiles\// : /^https:\/\//;
+ for (const url of source.tiles) expect(url, id).toMatch(expected);
+ expect(source.attribution, id).toBeTruthy();
+ }
+ });
+ });
+
it('stops listening when the map goes, and lets the widget go with it', async () => {
await withStubbedGoogle(async ({ createBasemaps, glasses }) => {
const map = stubMap();
diff --git a/frontend/src/lib/map/contextMenu.js b/frontend/src/lib/map/contextMenu.js
new file mode 100644
index 0000000..d26953b
--- /dev/null
+++ b/frontend/src/lib/map/contextMenu.js
@@ -0,0 +1,79 @@
+/**
+ * What a right-click on the ground offers, and where the menu opens.
+ *
+ * The menu answers for the point under the cursor rather than the map centre,
+ * which is the whole reason for it: every act here already exists somewhere
+ * (the status line copies the centre, the Saved panel links out from it, the
+ * rail arms the measure), but each one first asks the analyst to pan the point
+ * to the middle. Here the point is wherever they clicked.
+ *
+ * Only the list and the placement are here, so both are read off a test
+ * (`contextMenu.test.js`); the acts themselves are the tool's.
+ */
+import { COORD_FORMATS, formatCoords } from '../coords.js';
+import { mapLinks } from '../maplinks.js';
+
+const FORMAT_LABELS = { dd: 'DD', dms: 'DMS', mgrs: 'MGRS' };
+
+/**
+ * The coordinates of a point in every format the app writes, the analyst's own
+ * first. A format that cannot state the point (MGRS past the poles) is left out
+ * rather than offered as a copy of something else.
+ */
+export function copyRows(lat, lon, preferred = 'dd') {
+ const order = [preferred, ...COORD_FORMATS.filter((format) => format !== preferred)];
+ const rows = [];
+ for (const format of order) {
+ if (!COORD_FORMATS.includes(format)) continue;
+ const text = formatCoords(lat, lon, format);
+ if (!text || rows.some((row) => row.text === text)) continue;
+ rows.push({ id: `copy-${format}`, format: FORMAT_LABELS[format], text });
+ }
+ return rows;
+}
+
+/** The acts on the point, in the order an analyst reaches for them. */
+export const ACTIONS = [
+ { id: 'lookup', label: 'What is here?', icon: 'search' },
+ { id: 'place', label: 'Save place here…', icon: 'pin' },
+ { id: 'measure', label: 'Measure from here', icon: 'ruler' },
+ { id: 'sky', label: 'Sun and moon from here', icon: 'sun' },
+ { id: 'history', label: 'Imagery history here', icon: 'clock' },
+ { id: 'centre', label: 'Centre the map here', icon: 'crosshair' },
+];
+
+/** The external maps, opened on the clicked point at the current zoom. */
+export function openRows(lat, lon, zoom) {
+ const round = (value) => Number(value.toFixed(6));
+ return mapLinks(round(lat), round(lon), zoom);
+}
+
+/**
+ * Where the menu's top-left corner goes, inside the map.
+ *
+ * It opens down and to the right of the cursor, and flips to the other side of
+ * the cursor on whichever axis would run past the map's edge, then clamps, so a
+ * right-click in a corner still shows every row.
+ */
+export function placeMenu(point, menu, frame, margin = 8) {
+ let left = point.x;
+ let top = point.y;
+ if (left + menu.width + margin > frame.width) left = point.x - menu.width;
+ if (top + menu.height + margin > frame.height) top = point.y - menu.height;
+ left = Math.max(margin, Math.min(left, frame.width - menu.width - margin));
+ top = Math.max(margin, Math.min(top, frame.height - menu.height - margin));
+ return { left: Math.round(left), top: Math.round(top) };
+}
+
+/**
+ * The row focus moves to with an arrow key, wrapping at either end, skipping
+ * rows that are disabled.
+ */
+export function nextFocus(count, current, direction, disabled = () => false) {
+ if (!count) return -1;
+ for (let step = 1; step <= count; step += 1) {
+ const index = (((current + direction * step) % count) + count) % count;
+ if (!disabled(index)) return index;
+ }
+ return -1;
+}
diff --git a/frontend/src/lib/map/contextMenu.test.js b/frontend/src/lib/map/contextMenu.test.js
new file mode 100644
index 0000000..086df2c
--- /dev/null
+++ b/frontend/src/lib/map/contextMenu.test.js
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest';
+import { ACTIONS, copyRows, nextFocus, openRows, placeMenu } from './contextMenu.js';
+
+describe('copying the point', () => {
+ it('offers every format the app writes, the analyst’s own first', () => {
+ const rows = copyRows(50.4501, 30.5234, 'mgrs');
+ expect(rows.map((row) => row.format)).toEqual(['MGRS', 'DD', 'DMS']);
+ expect(rows[1].text).toBe('50.450100, 30.523400');
+ expect(rows[2].text).toContain('°');
+ });
+
+ it('leaves out a format that cannot state the point rather than copying another', () => {
+ // MGRS stops short of the poles, and would fall back to decimal degrees
+ const rows = copyRows(89.9, 10, 'dd');
+ expect(rows.map((row) => row.format)).toEqual(['DD', 'DMS']);
+ });
+
+ it('falls back to the app’s order for a format it does not know', () => {
+ expect(copyRows(1, 2, 'utm').map((row) => row.format)).toEqual(['DD', 'DMS', 'MGRS']);
+ });
+});
+
+describe('what the menu offers', () => {
+ it('acts on the point, and names each act for the point rather than the centre', () => {
+ expect(ACTIONS.map((action) => action.id)).toEqual([
+ 'lookup',
+ 'place',
+ 'measure',
+ 'sky',
+ 'history',
+ 'centre',
+ ]);
+ for (const action of ACTIONS.filter((entry) => entry.id !== 'lookup')) {
+ expect(action.label).toMatch(/here/);
+ }
+ });
+
+ it('opens the external maps on the clicked point, at the current zoom', () => {
+ const links = openRows(48.85837123456, 2.29448123456, 18);
+ const google = links.find((link) => link.id === 'google');
+ expect(google.url).toBe('https://www.google.com/maps/@48.858371,2.294481,18z');
+ });
+});
+
+describe('where the menu opens', () => {
+ const frame = { width: 1000, height: 600 };
+ const menu = { width: 240, height: 300 };
+
+ it('opens down and to the right of the cursor', () => {
+ expect(placeMenu({ x: 100, y: 80 }, menu, frame)).toEqual({ left: 100, top: 80 });
+ });
+
+ it('flips to the other side of the cursor near the right or bottom edge', () => {
+ expect(placeMenu({ x: 900, y: 500 }, menu, frame)).toEqual({ left: 660, top: 200 });
+ });
+
+ it('stays inside a map too small to flip in', () => {
+ const small = { width: 260, height: 200 };
+ const at = placeMenu({ x: 20, y: 190 }, menu, small);
+ expect(at.left).toBe(8);
+ expect(at.top).toBe(8);
+ });
+});
+
+describe('moving through the menu with arrows', () => {
+ it('wraps at either end', () => {
+ expect(nextFocus(4, 3, 1)).toBe(0);
+ expect(nextFocus(4, 0, -1)).toBe(3);
+ });
+
+ it('starts at the first row when nothing has focus yet', () => {
+ expect(nextFocus(4, -1, 1)).toBe(0);
+ });
+
+ it('skips rows that cannot be pressed, and gives up on a menu with none', () => {
+ expect(nextFocus(4, 0, 1, (index) => index === 1)).toBe(2);
+ expect(nextFocus(3, 0, 1, () => true)).toBe(-1);
+ expect(nextFocus(0, 0, 1)).toBe(-1);
+ });
+});
diff --git a/frontend/src/lib/map/engine.css b/frontend/src/lib/map/engine.css
index e28c1b6..e52cf52 100644
--- a/frontend/src/lib/map/engine.css
+++ b/frontend/src/lib/map/engine.css
@@ -84,7 +84,8 @@
border-width: 0 1.5px 1.5px;
background: transparent;
padding: 0 4px 1px;
- margin: 0 10px 10px 0;
+ /* aligned with the coordinates card above it, which a tool insets by 12 */
+ margin: 0 0 10px 12px;
color: #fff;
font-size: 10px;
font-weight: 600;
diff --git a/frontend/src/lib/map/engine.js b/frontend/src/lib/map/engine.js
index 48bd092..fcb040c 100644
--- a/frontend/src/lib/map/engine.js
+++ b/frontend/src/lib/map/engine.js
@@ -111,10 +111,13 @@ export async function createMapEngine(container, { view, imperial = false } = {}
// stacked below the top-left tool cluster (fullscreen/labels/measure) via a
// CSS offset, instead of the engine's default corner margin
map.addControl(new NavigationControl({ showCompass: false }), 'top-left');
- // judging feature sizes (buildings, roads) needs a scale reference
+ // Judging feature sizes (buildings, roads) needs a scale reference, and it
+ // reads under the coordinates rather than in the opposite corner: how far a
+ // pixel goes and where you are are one instrument, and the right-hand corner
+ // is where the acts sit, which used to land Capture on top of the bracket.
map.addControl(
new ScaleControl({ unit: imperial ? 'imperial' : 'metric' }),
- 'bottom-right'
+ 'bottom-left'
);
map.scrollZoom.setWheelZoomRate(WHEEL_ZOOM_RATE);
// A source cannot be added before the style is up, and `basemap.js` adds one
diff --git a/frontend/src/lib/map/facade.js b/frontend/src/lib/map/facade.js
index cbef77a..3e560f2 100644
--- a/frontend/src/lib/map/facade.js
+++ b/frontend/src/lib/map/facade.js
@@ -38,6 +38,9 @@ const EVENTS = {
'view-settled': ['moveend'],
rotate: ['rotate'],
click: ['click'],
+ // The engine only fires it for a right-click that did not drag, and stops
+ // the browser's own menu once anything listens for it.
+ contextmenu: ['contextmenu'],
};
/** The vocabulary `on()` accepts. */
@@ -240,11 +243,15 @@ export function mapFacade(map, container) {
*/
on(name, handler) {
const events = engineEvents(name);
+ // A pointer event hands over the point; a right-click also where it was
+ // pressed, since a menu opens there. A shape that answers its own click
+ // answers its own right-click too: a flagged grid cell is not also a menu.
const relay =
- name === 'click'
+ name === 'click' || name === 'contextmenu'
? (event) => {
if (shapeUnder(event.point)) return;
- handler({ lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) });
+ const at = { lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) };
+ handler(name === 'click' ? at : { ...at, x: event.point.x, y: event.point.y });
}
: () => handler(camera());
for (const event of events) map.on(event, relay);
diff --git a/frontend/src/lib/map/facade.test.js b/frontend/src/lib/map/facade.test.js
index 0428d83..ae86c61 100644
--- a/frontend/src/lib/map/facade.test.js
+++ b/frontend/src/lib/map/facade.test.js
@@ -254,7 +254,7 @@ describe('framing a set of points', () => {
describe('the event vocabulary', () => {
it('names what happened to the view, not what the engine calls it', () => {
- expect(MAP_EVENTS).toEqual(['view-settled', 'rotate', 'click']);
+ expect(MAP_EVENTS).toEqual(['view-settled', 'rotate', 'click', 'contextmenu']);
expect(engineEvents('view-settled')).toEqual(['moveend']);
});
@@ -281,6 +281,26 @@ describe('the event vocabulary', () => {
expect(seen).toHaveBeenCalledWith({ lat: 7, lon: -160 });
});
+ it('hands a right-click the point and where it was pressed, for a menu to open there', () => {
+ const map = stubMap();
+ const seen = vi.fn();
+ mapFacade(map).on('contextmenu', seen);
+ expect(map.calls.on[0][0]).toBe('contextmenu');
+ map.calls.on[0][1]({ point: { x: 120, y: 48 }, lngLat: { lat: 7, lng: 200 } });
+ expect(seen).toHaveBeenCalledWith({ lat: 7, lon: -160, x: 120, y: 48 });
+ });
+
+ it('leaves a right-click on a shape that claims its clicks to that shape', () => {
+ // right-click flags a search-grid cell; a menu opening over it too would be two answers
+ const map = stubMap({ queryRenderedFeatures: () => [{ id: 1 }] });
+ const facade = mapFacade(map);
+ const seen = vi.fn();
+ facade.claimClicks(['cells']);
+ facade.on('contextmenu', seen);
+ map.calls.on[0][1]({ point: { x: 5, y: 6 }, lngLat: { lat: 1, lng: 2 } });
+ expect(seen).not.toHaveBeenCalled();
+ });
+
it('returns the unsubscribe, so nobody can hold half the pair', () => {
const map = stubMap();
const off = mapFacade(map).on('rotate', () => {});
diff --git a/frontend/src/lib/map/firms.js b/frontend/src/lib/map/firms.js
new file mode 100644
index 0000000..0738319
--- /dev/null
+++ b/frontend/src/lib/map/firms.js
@@ -0,0 +1,93 @@
+/**
+ * What to ask NASA FIRMS for, as the Layers panel asks it.
+ *
+ * The layer answers two different questions with the same marks. **Live** is
+ * the last day, three days or week, which FIRMS keeps as layers of its own.
+ * **A date** is the archive, which is the same detections asked with a range —
+ * and it is the half a case actually needs: whether that field, that depot,
+ * that street was burning on the day in question.
+ *
+ * Everything here is arithmetic over the analyst's choice, so the range rules
+ * are read off a test rather than off a map (`firms.test.js`). The key, the
+ * WMS and the tiles are the backend's (`engine/firms.py`); the browser never
+ * sees any of them.
+ */
+
+/** The rolling windows, newest first — what "live" can mean. */
+export const WINDOWS = [
+ { id: '24h', label: '24 h' },
+ { id: '48h', label: '48 h' },
+ { id: '72h', label: '72 h' },
+ { id: '7d', label: '7 days' },
+];
+
+/** Asking by date rather than by how recent. Not a window: a question. */
+export const DATED = 'dates';
+
+/** FIRMS refuses a longer range, and counts a long one as several requests. */
+export const MAX_RANGE_DAYS = 31;
+
+/** `YYYY-MM-DD`, the only form the service and the input agree on. */
+export function asDay(value) {
+ return /^\d{4}-\d{2}-\d{2}$/.test(String(value ?? '')) ? String(value) : '';
+}
+
+/** Today, in the same form — what an empty date field opens on. */
+export function today(now = new Date()) {
+ return now.toISOString().slice(0, 10);
+}
+
+/**
+ * The end of a range the service will accept, given where it starts.
+ *
+ * Returned rather than enforced, so the panel can say what the limit is on the
+ * input itself instead of refusing a date after it was typed.
+ */
+export function lastDayOf(first, maxDays = MAX_RANGE_DAYS) {
+ const start = asDay(first);
+ if (!start) return '';
+ const end = new Date(`${start}T00:00:00Z`);
+ end.setUTCDate(end.getUTCDate() + maxDays - 1);
+ return end.toISOString().slice(0, 10);
+}
+
+/**
+ * Is this choice one the service can answer?
+ *
+ * A dated window with no date is the normal state of a panel someone has just
+ * switched to Dates, not an error — so the layer waits rather than asking for
+ * tiles that would come back as an exception report.
+ */
+export function askable({ window, first, last } = {}) {
+ if (window !== DATED) return WINDOWS.some((entry) => entry.id === window);
+ const start = asDay(first);
+ if (!start) return false;
+ const end = asDay(last) || start;
+ if (end < start) return false;
+ return end <= lastDayOf(start);
+}
+
+/**
+ * …and the query the tile route is asked with.
+ *
+ * A rolling window carries no dates: they would be two more things to keep in
+ * step with a layer that already means "the last 24 hours".
+ */
+export function tileParams({ sensor, window, first, last } = {}) {
+ if (window !== DATED) return { sensor, window };
+ const start = asDay(first);
+ return { sensor, window: DATED, first: start, last: asDay(last) || start };
+}
+
+/** How the row says what it is showing, in the space a layer row has. */
+export function summary({ sensor, window, first, last } = {}, sensors = []) {
+ const name = sensors.find((entry) => entry.id === sensor)?.label ?? sensor ?? '';
+ const short = name.replace(/\s*\(.*\)\s*$/, '');
+ if (window !== DATED) {
+ return [short, WINDOWS.find((entry) => entry.id === window)?.label].filter(Boolean).join(' · ');
+ }
+ const start = asDay(first);
+ if (!start) return [short, 'pick a date'].filter(Boolean).join(' · ');
+ const end = asDay(last);
+ return [short, end && end !== start ? `${start} → ${end}` : start].filter(Boolean).join(' · ');
+}
diff --git a/frontend/src/lib/map/firms.test.js b/frontend/src/lib/map/firms.test.js
new file mode 100644
index 0000000..a858afa
--- /dev/null
+++ b/frontend/src/lib/map/firms.test.js
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+import {
+ askable,
+ DATED,
+ lastDayOf,
+ MAX_RANGE_DAYS,
+ summary,
+ tileParams,
+ today,
+ WINDOWS,
+} from './firms.js';
+
+const SENSORS = [
+ { id: 'viirs', label: 'VIIRS (S-NPP + NOAA-20)' },
+ { id: 'modis', label: 'MODIS (Terra + Aqua)' },
+];
+
+describe('what to ask FIRMS for', () => {
+ it('asks by how recent, for the rolling windows', () => {
+ expect(tileParams({ sensor: 'viirs', window: '24h' })).toEqual({
+ sensor: 'viirs',
+ window: '24h',
+ });
+ });
+
+ it('leaves the dates out of a rolling window', () => {
+ // they would be two more things to keep in step with a layer that already
+ // means "the last 24 hours"
+ const params = tileParams({ sensor: 'viirs', window: '7d', first: '2026-01-01' });
+ expect(params.first).toBeUndefined();
+ });
+
+ it('asks by date for the archive, and reads one day as a range of itself', () => {
+ expect(tileParams({ sensor: 'modis', window: DATED, first: '2026-08-01' })).toEqual({
+ sensor: 'modis',
+ window: DATED,
+ first: '2026-08-01',
+ last: '2026-08-01',
+ });
+ });
+});
+
+describe('what the service will answer', () => {
+ it('accepts every window it offers', () => {
+ for (const entry of WINDOWS) expect(askable({ window: entry.id })).toBe(true);
+ });
+
+ it('waits rather than asking, while a dated window has no date', () => {
+ // switching to Dates is not an error, so the layer holds instead of
+ // fetching tiles that come back as an exception report
+ expect(askable({ window: DATED })).toBe(false);
+ expect(askable({ window: DATED, first: 'soon' })).toBe(false);
+ });
+
+ it('accepts a single day and a range inside the limit', () => {
+ expect(askable({ window: DATED, first: '2026-08-01' })).toBe(true);
+ expect(askable({ window: DATED, first: '2026-08-01', last: '2026-08-09' })).toBe(true);
+ });
+
+ it('refuses a range longer than FIRMS allows', () => {
+ expect(askable({ window: DATED, first: '2026-01-01', last: '2026-03-01' })).toBe(false);
+ });
+
+ it('refuses a range that ends before it starts', () => {
+ expect(askable({ window: DATED, first: '2026-08-09', last: '2026-08-01' })).toBe(false);
+ });
+
+ it('says where a range has to stop, so the input can say it too', () => {
+ expect(lastDayOf('2026-01-01')).toBe('2026-01-31');
+ expect(askable({ window: DATED, first: '2026-01-01', last: lastDayOf('2026-01-01') })).toBe(
+ true
+ );
+ expect(lastDayOf('')).toBe('');
+ });
+
+ it('counts the first day as one of the days', () => {
+ const first = '2026-05-10';
+ const days =
+ (new Date(`${lastDayOf(first)}T00:00:00Z`) - new Date(`${first}T00:00:00Z`)) / 86400000;
+ expect(days).toBe(MAX_RANGE_DAYS - 1);
+ });
+
+ it('opens on a day that exists', () => {
+ expect(today(new Date('2026-09-12T22:30:00Z'))).toBe('2026-09-12');
+ });
+});
+
+describe('what the row says it is showing', () => {
+ it('names the instrument without the satellites it is made of', () => {
+ // "VIIRS (S-NPP + NOAA-20) · 24 h" does not fit a layer row
+ expect(summary({ sensor: 'viirs', window: '24h' }, SENSORS)).toBe('VIIRS · 24 h');
+ });
+
+ it('names the day, or the range, when it is showing the archive', () => {
+ expect(summary({ sensor: 'modis', window: DATED, first: '2026-08-01' }, SENSORS)).toBe(
+ 'MODIS · 2026-08-01'
+ );
+ expect(
+ summary({ sensor: 'modis', window: DATED, first: '2026-08-01', last: '2026-08-09' }, SENSORS)
+ ).toBe('MODIS · 2026-08-01 → 2026-08-09');
+ });
+
+ it('asks for the date it is waiting on', () => {
+ expect(summary({ sensor: 'viirs', window: DATED }, SENSORS)).toBe('VIIRS · pick a date');
+ });
+});
diff --git a/frontend/src/lib/map/infrastructure.js b/frontend/src/lib/map/infrastructure.js
new file mode 100644
index 0000000..27a0310
--- /dev/null
+++ b/frontend/src/lib/map/infrastructure.js
@@ -0,0 +1,180 @@
+/**
+ * Power lines, towers and substations, with pipelines and telecom masts, drawn
+ * from Open Infrastructure Map's vector tiles.
+ *
+ * Pylons and the lines strung between them are among the steadiest clues in a
+ * photograph: a line's route survives decades of imagery, and its voltage
+ * shows in the size of the towers. OSM maps them in detail, and Open
+ * Infrastructure Map serves that as vector tiles (data ODbL, analysis CC-BY),
+ * which is what this style reads.
+ *
+ * The style is ours and deliberately small: lines coloured by voltage on Open
+ * Infrastructure Map's own scale, so a reader who knows that map reads this one,
+ * then towers, substations, plants, pipelines and masts. No labels, because
+ * the engine loads no glyphs (`engine.js` asks the network for tiles and
+ * nothing else). Zooms here are the engine's own, one shallower than the app's.
+ */
+
+const TILES = 'https://openinframap.org/map';
+
+const VOLTAGE = ['to-number', ['coalesce', ['get', 'voltage'], 0]];
+
+/** Open Infrastructure Map's voltage scale, in kV. */
+export const VOLTAGE_COLOUR = [
+ 'step',
+ VOLTAGE,
+ '#7A7A85',
+ 10,
+ '#6E97B8',
+ 25,
+ '#55B555',
+ 52,
+ '#B59F10',
+ 132,
+ '#B55D00',
+ 220,
+ '#C73030',
+ 310,
+ '#B54EB2',
+ 550,
+ '#00C1CF',
+];
+
+/** A line drawn in the air, which is the only kind a satellite picture shows. */
+const OVERHEAD = [
+ 'all',
+ ['!', ['in', ['get', 'location'], ['literal', ['underground', 'underwater']]]],
+ ['!=', ['get', 'tunnel'], true],
+];
+
+export const INFRASTRUCTURE = {
+ sources: {
+ power: `${TILES}/power/{z}/{x}/{y}.pbf`,
+ telecoms: `${TILES}/telecoms/{z}/{x}/{y}.pbf`,
+ petroleum: `${TILES}/petroleum/{z}/{x}/{y}.pbf`,
+ },
+ maxZoom: 17,
+ layers: [
+ {
+ id: 'pipeline',
+ type: 'line',
+ source: 'petroleum',
+ 'source-layer': 'petroleum_pipeline',
+ minzoom: 6,
+ paint: {
+ 'line-color': '#B37D3C',
+ 'line-width': ['interpolate', ['linear'], ['zoom'], 6, 0.6, 14, 2],
+ 'line-dasharray': [3, 2],
+ },
+ },
+ {
+ id: 'plant-area',
+ type: 'fill',
+ source: 'power',
+ 'source-layer': 'power_plant',
+ minzoom: 8,
+ paint: { 'fill-color': '#B59F10', 'fill-opacity': 0.18 },
+ },
+ {
+ id: 'substation-area',
+ type: 'fill',
+ source: 'power',
+ 'source-layer': 'power_substation',
+ minzoom: 12,
+ paint: { 'fill-color': VOLTAGE_COLOUR, 'fill-opacity': 0.22 },
+ },
+ {
+ id: 'line-buried',
+ type: 'line',
+ source: 'power',
+ 'source-layer': 'power_line',
+ minzoom: 11,
+ filter: ['!', OVERHEAD],
+ paint: {
+ 'line-color': VOLTAGE_COLOUR,
+ 'line-width': 1,
+ 'line-opacity': 0.6,
+ 'line-dasharray': [2, 2],
+ },
+ },
+ {
+ id: 'line-minor',
+ type: 'line',
+ source: 'power',
+ 'source-layer': 'power_line',
+ minzoom: 9,
+ filter: ['all', OVERHEAD, ['<', VOLTAGE, 100]],
+ paint: {
+ 'line-color': VOLTAGE_COLOUR,
+ 'line-width': ['interpolate', ['linear'], ['zoom'], 9, 0.6, 16, 2.2],
+ },
+ },
+ {
+ id: 'line-major',
+ type: 'line',
+ source: 'power',
+ 'source-layer': 'power_line',
+ minzoom: 3,
+ filter: ['all', OVERHEAD, ['>=', VOLTAGE, 100]],
+ paint: {
+ 'line-color': VOLTAGE_COLOUR,
+ 'line-width': ['interpolate', ['linear'], ['zoom'], 3, 0.5, 10, 1.6, 16, 3.4],
+ },
+ },
+ {
+ id: 'substation',
+ type: 'circle',
+ source: 'power',
+ 'source-layer': 'power_substation_point',
+ minzoom: 8,
+ // past this the substation is drawn as its own outline instead
+ maxzoom: 12,
+ paint: {
+ 'circle-color': VOLTAGE_COLOUR,
+ 'circle-radius': ['interpolate', ['linear'], ['zoom'], 8, 1.5, 12, 3.5],
+ 'circle-stroke-color': '#ffffff',
+ 'circle-stroke-width': 0.6,
+ },
+ },
+ {
+ id: 'plant',
+ type: 'circle',
+ source: 'power',
+ 'source-layer': 'power_plant_point',
+ minzoom: 5,
+ maxzoom: 11,
+ paint: {
+ 'circle-color': '#E0B040',
+ 'circle-radius': 3,
+ 'circle-stroke-color': '#1b1b1b',
+ 'circle-stroke-width': 0.8,
+ },
+ },
+ {
+ id: 'tower',
+ type: 'circle',
+ source: 'power',
+ 'source-layer': 'power_tower',
+ minzoom: 13,
+ paint: {
+ 'circle-color': '#C9CDD2',
+ 'circle-radius': ['interpolate', ['linear'], ['zoom'], 13, 1.4, 18, 4],
+ 'circle-stroke-color': '#1b1b1b',
+ 'circle-stroke-width': 0.8,
+ },
+ },
+ {
+ id: 'mast',
+ type: 'circle',
+ source: 'telecoms',
+ 'source-layer': 'telecoms_mast',
+ minzoom: 11,
+ paint: {
+ 'circle-color': '#7EC8E3',
+ 'circle-radius': ['interpolate', ['linear'], ['zoom'], 11, 1.6, 17, 4],
+ 'circle-stroke-color': '#0B2A36',
+ 'circle-stroke-width': 0.8,
+ },
+ },
+ ],
+};
diff --git a/frontend/src/lib/map/infrastructure.test.js b/frontend/src/lib/map/infrastructure.test.js
new file mode 100644
index 0000000..ec6a27c
--- /dev/null
+++ b/frontend/src/lib/map/infrastructure.test.js
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+// The engine's own style validator, which ships inside maplibre-gl. A layer the
+// engine refuses is not an error on screen: it simply draws nothing.
+import { validateStyleMin } from '@maplibre/maplibre-gl-style-spec';
+import { INFRASTRUCTURE, VOLTAGE_COLOUR } from './infrastructure.js';
+
+function asStyle(spec) {
+ return {
+ version: 8,
+ sources: Object.fromEntries(
+ Object.entries(spec.sources).map(([name, url]) => [
+ name,
+ { type: 'vector', tiles: [url], maxzoom: spec.maxZoom },
+ ])
+ ),
+ layers: spec.layers,
+ };
+}
+
+describe('the infrastructure style', () => {
+ it('is one the engine accepts, layer by layer', () => {
+ expect(validateStyleMin(asStyle(INFRASTRUCTURE))).toEqual([]);
+ });
+
+ it('reads only layers Open Infrastructure Map serves from the source it names', () => {
+ const served = {
+ power: ['power_line', 'power_tower', 'power_substation', 'power_substation_point', 'power_plant', 'power_plant_point'],
+ telecoms: ['telecoms_mast'],
+ petroleum: ['petroleum_pipeline'],
+ };
+ for (const layer of INFRASTRUCTURE.layers) {
+ expect(served[layer.source], layer.id).toContain(layer['source-layer']);
+ }
+ });
+
+ it('draws buried lines apart from the ones a picture can show', () => {
+ const lines = INFRASTRUCTURE.layers.filter((layer) => layer['source-layer'] === 'power_line');
+ const buried = lines.find((layer) => layer.id === 'line-buried');
+ expect(buried.paint['line-dasharray']).toBeTruthy();
+ expect(lines.filter((layer) => layer.id !== 'line-buried').every((layer) => !layer.paint['line-dasharray'])).toBe(true);
+ });
+
+ it('colours voltage on Open Infrastructure Map’s own scale, from grey to cyan', () => {
+ expect(VOLTAGE_COLOUR[2]).toBe('#7A7A85');
+ expect(VOLTAGE_COLOUR.at(-1)).toBe('#00C1CF');
+ expect(VOLTAGE_COLOUR.at(-2)).toBe(550);
+ });
+
+ it('asks for tiles from Open Infrastructure Map over https and nothing else', () => {
+ for (const url of Object.values(INFRASTRUCTURE.sources)) {
+ expect(url).toMatch(/^https:\/\/openinframap\.org\/map\/[a-z]+\/\{z\}\/\{x\}\/\{y\}\.pbf$/);
+ }
+ });
+});
diff --git a/frontend/src/lib/map/link.js b/frontend/src/lib/map/link.js
new file mode 100644
index 0000000..8db51f8
--- /dev/null
+++ b/frontend/src/lib/map/link.js
@@ -0,0 +1,198 @@
+/**
+ * Two map tabs pointed at the same ground.
+ *
+ * Once the view is in the address (`view.js`), making a second tab follow the
+ * first costs almost nothing — and it buys a first version of Compare without
+ * writing Compare: two tabs, two providers, two screens, one camera. That is
+ * what this is for.
+ *
+ * **It never touches the network.** A `BroadcastChannel` carries a camera
+ * between tabs of the same browser, which is exactly as far as this has to
+ * reach: the tabs are the same app on the same machine, and a view is not case
+ * state — nothing here is written down, and the app's own nudge channel stays
+ * for the things that are.
+ *
+ * The hard part is not the channel, it is the echo. A tab that applies a view
+ * settles, and a settle is what makes it send: two linked tabs would then push
+ * one camera back and forth for ever, each landing a rounding error from where
+ * the other put it. So a tab never sends back the view it was just given, which
+ * `sameView` is the whole of — a comparison loose enough to catch a camera that
+ * came back changed only by the projection it went through.
+ *
+ * The channel also answers "is there anybody else?", because a button offering
+ * to link one tab to nothing is a button that does nothing when pressed. Nobody
+ * can ask a `BroadcastChannel` who is listening, so each map tab says hello when
+ * it opens, answers somebody else's hello, and says goodbye when it goes — on
+ * teardown and on `pagehide`, since a closed tab runs no teardown. A tab killed
+ * outright leaves its name behind until the next hello, which costs a button
+ * that is lit with nothing behind it: exactly what it was before this existed.
+ *
+ * **Maps outside the app join through the extension.** Its map tools panel
+ * follows a camera on Google, Bing, Earth and the rest by writing it into their
+ * address bar, and it cannot hear this channel from another origin, so the
+ * extension's worker is the hub for those and the bridge on this page is this
+ * tab's end of it (`extBridge.js`, `mapLinkRelay`). What arrives that way is
+ * treated exactly like a peer tab's camera, and counted as a peer.
+ *
+ * **A map lands as close as it goes.** One tab's imagery stops at 19 while the
+ * one it follows is at 21: the view it settles on is not the one it was handed,
+ * and sending that back would pull the leader out to 19. So the first settle
+ * after a view arrives is taken as the landing whatever its zoom, as long as it
+ * is on the same spot.
+ */
+
+/** Under a tenth of this and two cameras are pointed at the same thing. */
+const PLACES = 5; // ~1 m
+const BEARING_EPSILON = 0.5; // degrees
+/** How long after a view arrives the map's settle is its landing. Long enough
+ * for an eased camera, short enough that a zoom the analyst makes on the same
+ * spot afterwards is theirs. */
+const LANDING_MS = 2000;
+
+/** The channel every map tab of this app speaks on. */
+export const CHANNEL = 'azimut:map-view';
+
+/** Is this the same camera, allowing for what a round trip does to it? */
+export function sameView(a, b) {
+ return samePlace(a, b) && Math.round(a.zoom) === Math.round(b.zoom);
+}
+
+/** The same spot and heading, whatever the zoom: where a map that stopped short
+ * of a view still is. */
+export function samePlace(a, b) {
+ if (!a || !b) return false;
+ return (
+ a.lat.toFixed(PLACES) === b.lat.toFixed(PLACES) &&
+ a.lon.toFixed(PLACES) === b.lon.toFixed(PLACES) &&
+ Math.abs((a.bearing ?? 0) - (b.bearing ?? 0)) < BEARING_EPSILON
+ );
+}
+
+/** A camera worth sending: anything else would move a peer to nowhere. */
+export function readable(view) {
+ return Boolean(
+ view &&
+ Number.isFinite(view.lat) &&
+ Number.isFinite(view.lon) &&
+ Number.isFinite(view.zoom) &&
+ Math.abs(view.lat) <= 90 &&
+ Math.abs(view.lon) <= 180
+ );
+}
+
+/** What a tab says on the channel: a camera, or which tabs are here. */
+const VIEW = 'view';
+const HELLO = 'hello'; // a tab opened and is asking who else is there
+const HERE = 'here'; // the answer to somebody else's hello
+const BYE = 'bye'; // that tab is going
+
+/**
+ * The link itself: send this tab's camera, hear the others', know they exist.
+ *
+ * `BroadcastChannel` does not deliver to the tab that posted, so a tab never
+ * hears itself — what it can hear is its own view coming back off a peer, which
+ * is what `sameView` stops.
+ *
+ * `onPeers` is called with how many other maps are open, whenever that
+ * changes, so the caller can grey a button that would link to nobody.
+ *
+ * `relay` is the extension's end, when there is one (`extBridge.js`): it is
+ * given `{ view, peers }` to call, and is sent this tab's camera. `peers` there
+ * reports the extension's panels, which the app's own tabs cannot see.
+ *
+ * Returns a link that is `alive: false` where the browser has no channel and no
+ * extension (an old build, a hardened profile). The caller then simply has a
+ * button that links nothing, which is better than a tool that will not mount.
+ */
+export function createViewLink(onView, { channel = CHANNEL, onPeers = null, relay = null } = {}) {
+ const bus = typeof BroadcastChannel === 'function' ? new BroadcastChannel(channel) : null;
+ if (!bus && !relay) {
+ return { alive: false, get peers() { return 0; }, send() {}, close() {} };
+ }
+ const me = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+ /** The other map tabs, by the name each of them announced itself under. */
+ const peers = new Set();
+ /** How many of the extension's map panels are open. */
+ let panels = 0;
+ /** The last camera this tab was handed, so it is never handed back. */
+ let given = null;
+ /** Until when a settle on `given`'s spot is this map landing there. */
+ let landingUntil = 0;
+
+ const count = () => peers.size + panels;
+ const say = (kind, extra) => bus?.postMessage({ from: me, kind, ...extra });
+
+ const receive = (view) => {
+ if (!readable(view)) return;
+ given = view;
+ landingUntil = Date.now() + LANDING_MS;
+ onView(view);
+ };
+
+ if (bus) {
+ bus.onmessage = (event) => {
+ const message = event.data;
+ if (!message?.from || message.from === me) return;
+ if (message.kind === BYE) {
+ if (peers.delete(message.from)) onPeers?.(count());
+ return;
+ }
+ // Anything a tab says proves it is there, which is what keeps this honest
+ // through a reload: the new tab's hello arrives under a new name.
+ if (!peers.has(message.from)) {
+ peers.add(message.from);
+ onPeers?.(count());
+ }
+ if (message.kind === HELLO) say(HERE); // so the newcomer can count this tab
+ if (message.kind === VIEW) receive(message.view);
+ };
+ }
+
+ relay?.listen({
+ view: receive,
+ peers: (n) => {
+ const next = Number.isInteger(n) && n > 0 ? n : 0;
+ if (next === panels) return;
+ panels = next;
+ onPeers?.(count());
+ },
+ });
+
+ const leave = () => say(BYE);
+ window.addEventListener('pagehide', leave);
+ say(HELLO);
+
+ return {
+ alive: true,
+ /** How many other maps are open right now, tabs and panels together. */
+ get peers() {
+ return count();
+ },
+ /** Tell the peers where this tab is now, unless they are why it is there. */
+ send(view) {
+ if (!readable(view)) return false;
+ if (Date.now() < landingUntil && samePlace(view, given)) {
+ // where it was sent, perhaps short of the zoom it was handed: not news
+ given = view;
+ landingUntil = 0;
+ return false;
+ }
+ if (sameView(view, given)) return false;
+ given = null; // the camera moved on its own; the next peer view is news
+ landingUntil = 0;
+ const out = { lat: view.lat, lon: view.lon, zoom: view.zoom, bearing: view.bearing ?? 0 };
+ say(VIEW, { view: out });
+ relay?.send(out);
+ return true;
+ },
+ close() {
+ window.removeEventListener('pagehide', leave);
+ leave();
+ relay?.close();
+ if (bus) {
+ bus.onmessage = null;
+ bus.close();
+ }
+ },
+ };
+}
diff --git a/frontend/src/lib/map/link.test.js b/frontend/src/lib/map/link.test.js
new file mode 100644
index 0000000..d9337b2
--- /dev/null
+++ b/frontend/src/lib/map/link.test.js
@@ -0,0 +1,307 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+import { CHANNEL, createViewLink, readable, sameView } from './link.js';
+
+const VIEW = { lat: 48.8566, lon: 2.3522, zoom: 17, bearing: 0 };
+
+describe('one camera worth sending', () => {
+ it('takes a real view', () => {
+ expect(readable(VIEW)).toBe(true);
+ });
+
+ it('refuses anything that would move a peer to nowhere', () => {
+ for (const bad of [
+ null,
+ {},
+ { ...VIEW, lat: NaN },
+ { ...VIEW, lon: Infinity },
+ { ...VIEW, zoom: undefined },
+ { ...VIEW, lat: 120 },
+ { ...VIEW, lon: -400 },
+ ]) {
+ expect(readable(bad)).toBe(false);
+ }
+ });
+});
+
+describe('the same camera, after a round trip', () => {
+ it('is the same within a metre', () => {
+ expect(sameView(VIEW, { ...VIEW, lat: VIEW.lat + 0.0000001 })).toBe(true);
+ });
+
+ it('is not the same once it has actually moved', () => {
+ expect(sameView(VIEW, { ...VIEW, lat: 48.86 })).toBe(false);
+ expect(sameView(VIEW, { ...VIEW, zoom: 16 })).toBe(false);
+ expect(sameView(VIEW, { ...VIEW, bearing: 90 })).toBe(false);
+ });
+
+ it('reads a missing bearing as north, which is what the map means by it', () => {
+ expect(sameView({ lat: 1, lon: 2, zoom: 5 }, { lat: 1, lon: 2, zoom: 5, bearing: 0 })).toBe(
+ true
+ );
+ });
+
+ it('is nothing at all when there is nothing to compare', () => {
+ expect(sameView(VIEW, null)).toBe(false);
+ expect(sameView(null, null)).toBe(false);
+ });
+});
+
+describe('the link between two tabs', () => {
+ let channels;
+
+ beforeEach(() => {
+ channels = [];
+ // A stand-in for the browser's own: it delivers to every *other* channel on
+ // the same name, which is the behaviour the echo rule is written against.
+ globalThis.BroadcastChannel = vi.fn(function (name) {
+ this.name = name;
+ this.onmessage = null;
+ this.closed = false;
+ this.postMessage = (data) => {
+ for (const peer of channels) {
+ if (peer !== this && peer.name === name && !peer.closed) peer.onmessage?.({ data });
+ }
+ };
+ this.close = () => (this.closed = true);
+ channels.push(this);
+ });
+ });
+
+ afterEach(() => {
+ delete globalThis.BroadcastChannel;
+ });
+
+ it('carries one tab\'s camera to the others', () => {
+ const heard = vi.fn();
+ createViewLink(heard);
+ const other = createViewLink(() => {});
+ other.send(VIEW);
+ expect(heard).toHaveBeenCalledWith(expect.objectContaining({ lat: 48.8566, zoom: 17 }));
+ });
+
+ it('speaks on the one channel every map tab listens to', () => {
+ createViewLink(() => {});
+ expect(channels[0].name).toBe(CHANNEL);
+ });
+
+ it('never hands a view straight back to the tab it came from', () => {
+ // the echo rule: a tab that applies a view settles, and a settle is what
+ // makes it send — two linked tabs would otherwise push one camera for ever
+ const a = createViewLink(() => {});
+ const b = createViewLink(() => {});
+ a.send(VIEW);
+ expect(b.send(VIEW)).toBe(false);
+ expect(b.send({ ...VIEW, lat: VIEW.lat + 0.0000001 })).toBe(false);
+ });
+
+ it('sends again as soon as that tab moves on its own', () => {
+ const a = createViewLink(() => {});
+ const b = createViewLink(() => {});
+ a.send(VIEW);
+ expect(b.send(VIEW)).toBe(false); // the landing
+ expect(b.send({ ...VIEW, zoom: 12 })).toBe(true);
+ // …and having moved, it is no longer echoing anything
+ expect(b.send(VIEW)).toBe(true);
+ });
+
+ it('lands short of a view without pulling the tab it follows back out', () => {
+ // this tab's imagery stops at 19 and the leader is at 21: the settle at 19 is
+ // where it was sent, and sending it would move the leader out to 19
+ const a = createViewLink(() => {});
+ const b = createViewLink(() => {});
+ a.send({ ...VIEW, zoom: 21 });
+ expect(b.send({ ...VIEW, zoom: 19 })).toBe(false);
+ // the analyst zooming that tab afterwards is theirs, and is sent
+ expect(b.send({ ...VIEW, zoom: 17 })).toBe(true);
+ });
+
+ it('takes only a settle on the same spot as the landing', () => {
+ const a = createViewLink(() => {});
+ const b = createViewLink(() => {});
+ a.send(VIEW);
+ expect(b.send({ ...VIEW, lat: 48.9 })).toBe(true);
+ });
+
+ it('stops taking a same-spot zoom as the landing once the map has had time to land', () => {
+ vi.useFakeTimers();
+ try {
+ const a = createViewLink(() => {});
+ const b = createViewLink(() => {});
+ a.send({ ...VIEW, zoom: 21 });
+ vi.advanceTimersByTime(2500);
+ expect(b.send({ ...VIEW, zoom: 19 })).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('drops a camera a peer could not have meant', () => {
+ const heard = vi.fn();
+ createViewLink(heard);
+ channels[0].onmessage({ data: { lat: 'somewhere', lon: 2, zoom: 4 } });
+ expect(heard).not.toHaveBeenCalled();
+ });
+
+ it('stops listening when the tab lets it go', () => {
+ const heard = vi.fn();
+ const mine = createViewLink(heard);
+ const other = createViewLink(() => {});
+ mine.close();
+ other.send(VIEW);
+ expect(heard).not.toHaveBeenCalled();
+ });
+
+ it('is a button that links nothing where the browser has no channel', () => {
+ delete globalThis.BroadcastChannel;
+ const link = createViewLink(() => {});
+ expect(link.alive).toBe(false);
+ expect(() => {
+ link.send(VIEW);
+ link.close();
+ }).not.toThrow();
+ });
+});
+
+describe('knowing whether there is anybody to link to', () => {
+ let channels;
+
+ beforeEach(() => {
+ channels = [];
+ globalThis.BroadcastChannel = vi.fn(function (name) {
+ this.name = name;
+ this.onmessage = null;
+ this.closed = false;
+ this.postMessage = (data) => {
+ for (const peer of channels) {
+ if (peer !== this && peer.name === name && !peer.closed) peer.onmessage?.({ data });
+ }
+ };
+ this.close = () => (this.closed = true);
+ channels.push(this);
+ });
+ });
+
+ afterEach(() => {
+ delete globalThis.BroadcastChannel;
+ });
+
+ it('counts nobody while a map tab is on its own', () => {
+ const alone = createViewLink(() => {});
+ expect(alone.peers).toBe(0);
+ });
+
+ it('tells the tab that was already open that a second one arrived', () => {
+ const first = createViewLink(() => {});
+ const heard = vi.fn();
+ createViewLink(() => {}, { onPeers: heard });
+ expect(first.peers).toBe(1);
+ expect(heard).toHaveBeenCalledWith(1); // …and the newcomer was answered
+ });
+
+ it('lets the newcomer count a tab that has said nothing since it opened', () => {
+ createViewLink(() => {});
+ const late = createViewLink(() => {});
+ expect(late.peers).toBe(1);
+ });
+
+ it('takes a tab off the count when it goes', () => {
+ const staying = createViewLink(() => {});
+ const leaving = createViewLink(() => {});
+ expect(staying.peers).toBe(1);
+ leaving.close();
+ expect(staying.peers).toBe(0);
+ });
+
+ it('says goodbye when the tab is closed rather than unmounted', () => {
+ const staying = createViewLink(() => {});
+ createViewLink(() => {});
+ expect(staying.peers).toBe(1);
+ window.dispatchEvent(new Event('pagehide'));
+ expect(staying.peers).toBe(0);
+ });
+
+ it('counts each tab once however much it says', () => {
+ const heard = vi.fn();
+ createViewLink(() => {}, { onPeers: heard });
+ const other = createViewLink(() => {});
+ other.send(VIEW);
+ other.send({ ...VIEW, zoom: 12 });
+ expect(heard.mock.calls).toEqual([[1]]);
+ });
+
+ it('counts nobody where the browser has no channel', () => {
+ delete globalThis.BroadcastChannel;
+ expect(createViewLink(() => {}).peers).toBe(0);
+ });
+});
+
+describe('maps outside the app, through the extension', () => {
+ /** A stand-in for `extBridge.js`'s relay: what the app hands it, and a way to
+ * speak as the extension's panels. */
+ function fakeRelay() {
+ const relay = {
+ handlers: null,
+ sent: [],
+ closed: false,
+ listen(handlers) {
+ relay.handlers = handlers;
+ },
+ send(view) {
+ relay.sent.push(view);
+ },
+ close() {
+ relay.closed = true;
+ },
+ };
+ return relay;
+ }
+
+ afterEach(() => {
+ delete globalThis.BroadcastChannel;
+ });
+
+ it('counts the extension’s panels as peers', () => {
+ const relay = fakeRelay();
+ const heard = vi.fn();
+ const link = createViewLink(() => {}, { relay, onPeers: heard });
+ relay.handlers.peers(2);
+ expect(link.peers).toBe(2);
+ expect(heard).toHaveBeenLastCalledWith(2);
+ relay.handlers.peers(0);
+ expect(link.peers).toBe(0);
+ });
+
+ it('follows a panel’s camera, and does not hand it back', () => {
+ const relay = fakeRelay();
+ const heard = vi.fn();
+ const link = createViewLink(heard, { relay });
+ relay.handlers.view(VIEW);
+ expect(heard).toHaveBeenCalledWith(VIEW);
+ expect(link.send(VIEW)).toBe(false);
+ expect(relay.sent).toEqual([]);
+ });
+
+ it('sends its own camera to the panels', () => {
+ const relay = fakeRelay();
+ const link = createViewLink(() => {}, { relay });
+ expect(link.send({ ...VIEW, bearing: undefined })).toBe(true);
+ expect(relay.sent).toEqual([{ ...VIEW, bearing: 0 }]);
+ });
+
+ it('works with the extension alone where the browser has no channel', () => {
+ delete globalThis.BroadcastChannel;
+ const relay = fakeRelay();
+ const link = createViewLink(() => {}, { relay });
+ expect(link.alive).toBe(true);
+ link.close();
+ expect(relay.closed).toBe(true);
+ });
+
+ it('ignores a count that is not one', () => {
+ const relay = fakeRelay();
+ const link = createViewLink(() => {}, { relay });
+ relay.handlers.peers('lots');
+ expect(link.peers).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/map/nightlights.js b/frontend/src/lib/map/nightlights.js
new file mode 100644
index 0000000..7649058
--- /dev/null
+++ b/frontend/src/lib/map/nightlights.js
@@ -0,0 +1,89 @@
+/**
+ * What to ask NASA GIBS for when the night lights layer is on.
+ *
+ * The Day/Night Band of VIIRS photographs the ground at night, once a night
+ * around 01:30 local time, and GIBS serves each night as its own tiles. A night
+ * is the question an analyst brings: whether a city was dark after a strike,
+ * whether a depot was lit. The 2016 composite is the other question, a
+ * cloud-free baseline to hold a night against.
+ *
+ * Key-less and public domain, so the browser asks GIBS directly. Each sensor's
+ * record starts on a different day (read off GIBS's capabilities, 2026-09), and
+ * the calendar is bounded by it rather than failing on a date already picked.
+ */
+
+export const GIBS = 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best';
+
+export const SENSORS = [
+ {
+ id: 'noaa20',
+ label: 'NOAA-20',
+ layer: 'VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance',
+ first: '2024-03-25',
+ },
+ {
+ id: 'snpp',
+ label: 'Suomi NPP',
+ layer: 'VIIRS_SNPP_DayNightBand_At_Sensor_Radiance',
+ first: '2020-11-18',
+ },
+];
+
+/** A year of cloud-free nights, as one picture. Not a sensor: a baseline. */
+export const COMPOSITE = {
+ id: 'composite',
+ label: '2016',
+ layer: 'VIIRS_Black_Marble',
+ day: '2016-01-01',
+};
+
+/** `YYYY-MM-DD` or ''. */
+function asDay(value) {
+ return /^\d{4}-\d{2}-\d{2}$/.test(String(value ?? '')) ? String(value) : '';
+}
+
+/**
+ * The last night GIBS can be expected to hold. Today's pass is still being
+ * processed for much of the day, and a blank night reads as an outage.
+ */
+export function lastNight(now = new Date()) {
+ const day = new Date(now.getTime());
+ day.setUTCDate(day.getUTCDate() - 1);
+ return day.toISOString().slice(0, 10);
+}
+
+/** The first night a source can answer, or '' for the composite. */
+export function firstNight(source) {
+ return SENSORS.find((sensor) => sensor.id === source)?.first ?? '';
+}
+
+/** Is this choice one GIBS can answer? A sensor needs a night inside its record. */
+export function askable({ source, day } = {}, now = new Date()) {
+ if (source === COMPOSITE.id) return true;
+ const sensor = SENSORS.find((entry) => entry.id === source);
+ const night = asDay(day);
+ if (!sensor || !night) return false;
+ return night >= sensor.first && night <= lastNight(now);
+}
+
+/** The question the tiles are built from. The composite has one date only. */
+export function tileParams({ source, day } = {}) {
+ if (source === COMPOSITE.id) return { source };
+ return { source, day: asDay(day) };
+}
+
+/** The XYZ template GIBS serves one night, or the composite, from. */
+export function tileTemplate({ source, day } = {}) {
+ const composite = source === COMPOSITE.id;
+ const layer = composite ? COMPOSITE.layer : SENSORS.find((entry) => entry.id === source)?.layer;
+ const night = composite ? COMPOSITE.day : asDay(day);
+ if (!layer || !night) return '';
+ return `${GIBS}/${layer}/default/${night}/GoogleMapsCompatible_Level8/{z}/{y}/{x}.png`;
+}
+
+/** How the row says what it is showing. */
+export function summary({ source, day } = {}) {
+ if (source === COMPOSITE.id) return 'composite · 2016';
+ const label = SENSORS.find((entry) => entry.id === source)?.label ?? '';
+ return [label, asDay(day) || 'pick a night'].filter(Boolean).join(' · ');
+}
diff --git a/frontend/src/lib/map/nightlights.test.js b/frontend/src/lib/map/nightlights.test.js
new file mode 100644
index 0000000..7581f15
--- /dev/null
+++ b/frontend/src/lib/map/nightlights.test.js
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import {
+ COMPOSITE,
+ askable,
+ firstNight,
+ lastNight,
+ summary,
+ tileParams,
+ tileTemplate,
+} from './nightlights.js';
+
+const NOW = new Date('2026-09-13T10:00:00Z');
+
+describe('which night can be asked for', () => {
+ it('ends the night before today, since today’s pass is still being processed', () => {
+ expect(lastNight(NOW)).toBe('2026-09-12');
+ });
+
+ it('starts where each sensor’s record does', () => {
+ expect(firstNight('noaa20')).toBe('2024-03-25');
+ expect(firstNight('snpp')).toBe('2020-11-18');
+ expect(firstNight(COMPOSITE.id)).toBe('');
+ });
+
+ it('answers a night inside the record and nothing outside it', () => {
+ expect(askable({ source: 'noaa20', day: '2026-09-12' }, NOW)).toBe(true);
+ expect(askable({ source: 'noaa20', day: '2024-03-24' }, NOW)).toBe(false);
+ expect(askable({ source: 'snpp', day: '2022-02-24' }, NOW)).toBe(true);
+ expect(askable({ source: 'snpp', day: '2026-09-13' }, NOW)).toBe(false);
+ });
+
+ it('waits for a night rather than asking for tiles without one', () => {
+ expect(askable({ source: 'noaa20', day: '' }, NOW)).toBe(false);
+ expect(askable({ source: 'noaa20', day: '12/09/2026' }, NOW)).toBe(false);
+ expect(askable({ source: 'landsat', day: '2026-09-12' }, NOW)).toBe(false);
+ });
+
+ it('always answers the composite, which has one date of its own', () => {
+ expect(askable({ source: COMPOSITE.id }, NOW)).toBe(true);
+ });
+});
+
+describe('what GIBS is asked', () => {
+ it('names the sensor’s layer and the night, on the Web Mercator grid', () => {
+ expect(tileTemplate({ source: 'noaa20', day: '2026-09-12' })).toBe(
+ 'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/' +
+ 'VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance/default/2026-09-12/' +
+ 'GoogleMapsCompatible_Level8/{z}/{y}/{x}.png'
+ );
+ });
+
+ it('asks the composite for its own year, whatever day is in the field', () => {
+ expect(tileTemplate({ source: COMPOSITE.id, day: '2026-09-12' })).toContain(
+ '/VIIRS_Black_Marble/default/2016-01-01/'
+ );
+ expect(tileParams({ source: COMPOSITE.id, day: '2026-09-12' })).toEqual({ source: 'composite' });
+ });
+
+ it('builds nothing from a question it cannot state', () => {
+ expect(tileTemplate({ source: 'noaa20', day: 'yesterday' })).toBe('');
+ expect(tileTemplate({ source: 'landsat', day: '2026-09-12' })).toBe('');
+ });
+});
+
+describe('how the row reads', () => {
+ it('names the sensor and the night, or asks for one', () => {
+ expect(summary({ source: 'snpp', day: '2022-02-24' })).toBe('Suomi NPP · 2022-02-24');
+ expect(summary({ source: 'noaa20', day: '' })).toBe('NOAA-20 · pick a night');
+ expect(summary({ source: COMPOSITE.id })).toBe('composite · 2016');
+ });
+});
diff --git a/frontend/src/lib/map/tools.js b/frontend/src/lib/map/tools.js
new file mode 100644
index 0000000..49c03d7
--- /dev/null
+++ b/frontend/src/lib/map/tools.js
@@ -0,0 +1,227 @@
+/**
+ * The map's tools, declared once.
+ *
+ * A map tool used to be three edits in three places: a button in a cluster, a
+ * panel floated somewhere beside it, and a line in whichever `toggle…` function
+ * happened to know about it. Twelve more tools are on the roadmap for this
+ * surface (3D, resection, compare, wayback, event layers, viewshed, tracks,
+ * boards), so the third one to arrive would have been the third rewrite of the
+ * same four-button cluster.
+ *
+ * So a tool declares itself here and the chrome is built from the declaration:
+ * the rail renders the entries, the surface takes its cursor from whichever is
+ * armed, and the panel slot shows that one's settings. Adding a tool is a
+ * descriptor plus its panel — no edit to the host.
+ *
+ * **Nothing in this file touches a store, a component or the DOM.** The
+ * descriptors are data and the three functions below are arithmetic over a
+ * handler map the host supplies, which is what lets the exclusion rule — the
+ * part that was previously spread over four `toggle…` functions calling each
+ * other — be tested without a browser (`tools.test.js`).
+ */
+
+/**
+ * The pointer modes, in rail order.
+ *
+ * `group` breaks the rail into sections: the separator between two groups is
+ * the whole of the rail's grammar, and keeping it in the data means a new tool
+ * files itself under an existing heading instead of growing a flat list of
+ * fifteen icons.
+ *
+ * `cursor` is the name the surface puts on itself while this mode is armed
+ * (`MapSurface`'s `armed`), which is what turns the pointer into a crosshair. A
+ * mode with no cursor changes what a click *means* without changing how the map
+ * is pointed at.
+ *
+ * `rail: false` declares a mode that is armed from somewhere else — the capture
+ * marquee is armed from the Capture button, because arming it is half of
+ * pressing Capture and nobody would look for it in a toolbox. It is still
+ * declared, because the exclusion rule has to know it exists.
+ */
+export const MAP_MODES = [
+ {
+ id: 'measure',
+ label: 'Measure tools',
+ icon: 'ruler',
+ group: 'work',
+ cursor: 'measuring',
+ panel: true,
+ },
+ {
+ id: 'grid',
+ label: 'Grid Search',
+ icon: 'grid',
+ group: 'work',
+ cursor: 'grid-drawing',
+ panel: true,
+ },
+ {
+ id: 'sky',
+ label: 'Sun and moon',
+ icon: 'sun',
+ group: 'read',
+ panel: true,
+ },
+ {
+ id: 'capture',
+ label: 'Select area',
+ icon: 'crop',
+ group: 'capture',
+ cursor: 'selecting',
+ panel: false,
+ rail: false,
+ },
+ {
+ // Armed from a saved place's own card, for the same reason the marquee is
+ // armed from Capture: a footprint is *this* place's shape, and a rail seat
+ // would offer to trace one for nobody.
+ id: 'footprint',
+ label: 'Trace footprint',
+ icon: 'polygon',
+ group: 'work',
+ cursor: 'tracing',
+ panel: true,
+ rail: false,
+ },
+];
+
+/**
+ * The rail's one-shot entries: they do something and arm nothing.
+ *
+ * Reference windows are the only one today. It sits in the rail rather than
+ * among the layers because opening one is an act — a picker, a choice, a window
+ * — while the layers panel lists things that are simply on or off.
+ */
+export const MAP_ACTIONS = [
+ {
+ id: 'reference',
+ label: 'Add reference',
+ icon: 'image',
+ group: 'read',
+ hint: 'Add a reference image or video over the map',
+ },
+];
+
+/**
+ * What can be drawn over the imagery.
+ *
+ * These never take a rail seat. That distinction is the point of the rework:
+ * the old cluster mixed "what I am doing" with "what is shown", and put OSM
+ * labels and saved pins in a toolbox.
+ *
+ * `handoff: true` marks a layer that only exists because another tool sent
+ * something here — a sheet's coordinate column, a Timeline window. It appears
+ * in the list when it arrives and leaves when it is closed, so it is never an
+ * empty switch.
+ */
+export const MAP_LAYERS = [
+ { id: 'labels', label: 'OSM labels', icon: 'text' },
+ { id: 'boundaries', label: 'Borders', icon: 'polygon' },
+ { id: 'roads', label: 'Roads', icon: 'line' },
+ { id: 'railway', label: 'OSM railways', icon: 'line' },
+ { id: 'power', label: 'Power lines', icon: 'network' },
+ { id: 'seamarks', label: 'Sea marks', icon: 'ship' },
+ { id: 'gpstraces', label: 'GPS traces', icon: 'freehand' },
+ { id: 'firms', label: 'Active fires', icon: 'flame' },
+ { id: 'nightlights', label: 'Night lights', icon: 'moon' },
+ { id: 'saved', label: 'Saved work', icon: 'pin' },
+ { id: 'sheet', label: 'Sheet points', icon: 'table', handoff: true },
+ { id: 'timeline', label: 'Timeline points', icon: 'clock', handoff: true },
+];
+
+/** The rail's entries, in order, with the one-shot actions filed in their group. */
+export function railEntries(modes = MAP_MODES, actions = MAP_ACTIONS) {
+ return [
+ ...modes.filter((mode) => mode.rail !== false).map((mode) => ({ ...mode, kind: 'mode' })),
+ ...actions.map((action) => ({ ...action, kind: 'action' })),
+ ];
+}
+
+/**
+ * Those entries cut into the sections the rail draws a hairline between.
+ *
+ * Group order follows first appearance rather than a second list to keep in
+ * step: moving a tool between groups is one edit to its descriptor.
+ */
+export function railSections(entries = railEntries()) {
+ const sections = [];
+ for (const entry of entries) {
+ const last = sections[sections.length - 1];
+ if (last && last.group === entry.group) last.entries.push(entry);
+ else sections.push({ group: entry.group, entries: [entry] });
+ }
+ return sections;
+}
+
+/**
+ * Which mode is armed, from the handler map the host supplies.
+ *
+ * A handler is `{ isOn, open, close }` closing over that tool's own store, so
+ * this file never learns that Grid Search keeps a boolean and the measure tools
+ * keep a sub-mode string.
+ */
+export function armedId(handlers) {
+ for (const [id, handler] of Object.entries(handlers)) {
+ if (handler?.isOn()) return id;
+ }
+ return null;
+}
+
+/**
+ * Arm one mode and only that one, or disarm it if it was already armed.
+ *
+ * This is the rule that used to live as pairwise calls between four `toggle…`
+ * functions — where "sun turns off capture, measure and grid" and "grid turns
+ * off capture and measure" were two separate pieces of knowledge, and a fifth
+ * tool would have had to be added to every one of them. Here, arming anything
+ * closes everything else by construction.
+ *
+ * @returns {string|null} what is armed afterwards.
+ */
+export function arm(handlers, id) {
+ const target = handlers[id];
+ if (!target) return armedId(handlers);
+ if (target.isOn()) {
+ target.close();
+ return armedId(handlers);
+ }
+ closeOthers(handlers, id);
+ target.open();
+ return armedId(handlers);
+}
+
+/**
+ * Everything except one mode, closed.
+ *
+ * What a mode armed from outside the rail owes the others: the capture marquee
+ * arms itself from the Capture button, and reports in here so that pressing it
+ * while Grid Search is drawing does not leave two modes waiting for the same
+ * left drag.
+ */
+export function closeOthers(handlers, id) {
+ for (const [key, handler] of Object.entries(handlers)) {
+ if (key !== id && handler?.isOn()) handler.close();
+ }
+}
+
+/** Close whatever is armed. What Escape does when no tool claimed the key first. */
+export function disarm(handlers) {
+ for (const handler of Object.values(handlers)) {
+ if (handler?.isOn()) handler.close();
+ }
+}
+
+/**
+ * The cursor name the surface wears for what is armed.
+ *
+ * Returned as null rather than an empty string when nothing is armed, because
+ * that is what `MapSurface` reads as "the map is just a map".
+ */
+export function cursorOf(id, modes = MAP_MODES) {
+ return modes.find((mode) => mode.id === id)?.cursor ?? null;
+}
+
+/** Whether the armed mode brings a panel with it, so the slot knows to open. */
+export function hasPanel(id, modes = MAP_MODES) {
+ return Boolean(modes.find((mode) => mode.id === id)?.panel);
+}
diff --git a/frontend/src/lib/map/tools.test.js b/frontend/src/lib/map/tools.test.js
new file mode 100644
index 0000000..16c5bc4
--- /dev/null
+++ b/frontend/src/lib/map/tools.test.js
@@ -0,0 +1,144 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAP_ACTIONS,
+ MAP_LAYERS,
+ MAP_MODES,
+ arm,
+ armedId,
+ cursorOf,
+ disarm,
+ hasPanel,
+ railEntries,
+ railSections,
+} from './tools.js';
+
+/**
+ * Handlers the way the host builds them, over a plain object instead of four
+ * Svelte stores. The exclusion rule is the whole reason this registry exists —
+ * it was previously spread over `toggleSunMode`, `toggleGridMode`,
+ * `setMeasureMode` and `toggleSelect`, each calling the others — so it is
+ * tested here, without a browser or a map.
+ */
+function stubHandlers(on = {}) {
+ const state = { measure: false, grid: false, sky: false, capture: false, ...on };
+ const handlers = {};
+ for (const id of Object.keys(state)) {
+ handlers[id] = {
+ isOn: () => state[id],
+ open: () => (state[id] = true),
+ close: () => (state[id] = false),
+ };
+ }
+ return { handlers, state };
+}
+
+describe('the rail', () => {
+ it('leaves out a mode that is armed from somewhere else', () => {
+ const ids = railEntries().map((entry) => entry.id);
+ expect(ids).toContain('measure');
+ // the capture marquee is armed from the Capture button, not from a toolbox
+ expect(ids).not.toContain('capture');
+ });
+
+ it('files one-shot actions among the modes, tagged by kind', () => {
+ const entries = railEntries();
+ const reference = entries.find((entry) => entry.id === 'reference');
+ expect(reference.kind).toBe('action');
+ expect(entries.find((entry) => entry.id === 'measure').kind).toBe('mode');
+ });
+
+ it('cuts the entries into the sections it draws a line between', () => {
+ const sections = railSections(railEntries());
+ expect(sections.map((section) => section.group)).toEqual(['work', 'read']);
+ expect(sections[0].entries.map((entry) => entry.id)).toEqual(['measure', 'grid']);
+ expect(sections[1].entries.map((entry) => entry.id)).toEqual(['sky', 'reference']);
+ });
+
+ it('keeps the rail short enough to read', () => {
+ // the survival rule from the design: past seven seats a tool joins a group
+ // with a flyout rather than taking the eighth
+ expect(railEntries().length).toBeLessThanOrEqual(7);
+ });
+});
+
+describe('arming', () => {
+ it('arms one mode', () => {
+ const { handlers, state } = stubHandlers();
+ expect(arm(handlers, 'grid')).toBe('grid');
+ expect(state.grid).toBe(true);
+ });
+
+ it('closes everything else, whatever was open', () => {
+ const { handlers, state } = stubHandlers({ measure: true, capture: true });
+ arm(handlers, 'sky');
+ expect(state).toEqual({ measure: false, grid: false, sky: true, capture: false });
+ });
+
+ it('disarms the mode that was already armed', () => {
+ const { handlers, state } = stubHandlers({ sky: true });
+ expect(arm(handlers, 'sky')).toBe(null);
+ expect(state.sky).toBe(false);
+ });
+
+ it('never opens a second mode, whichever order they are pressed', () => {
+ const { handlers, state } = stubHandlers();
+ for (const id of ['measure', 'grid', 'sky', 'capture', 'grid']) arm(handlers, id);
+ expect(Object.values(state).filter(Boolean).length).toBeLessThanOrEqual(1);
+ });
+
+ it('ignores a mode the host did not wire, and says what is still armed', () => {
+ const { handlers, state } = stubHandlers({ grid: true });
+ expect(arm(handlers, 'viewshed')).toBe('grid');
+ expect(state.grid).toBe(true);
+ });
+
+ it('reports nothing armed when nothing is', () => {
+ expect(armedId(stubHandlers().handlers)).toBe(null);
+ });
+
+ it('disarms everything', () => {
+ const { handlers, state } = stubHandlers({ measure: true, grid: true });
+ disarm(handlers);
+ expect(Object.values(state).some(Boolean)).toBe(false);
+ });
+});
+
+describe('what the armed mode says about the surface', () => {
+ it('hands the surface the cursor for the armed mode', () => {
+ expect(cursorOf('measure')).toBe('measuring');
+ expect(cursorOf('capture')).toBe('selecting');
+ });
+
+ it('says the map is just a map when nothing is armed', () => {
+ expect(cursorOf(null)).toBe(null);
+ // a mode can change what a click means without changing how it is pointed
+ expect(cursorOf('sky')).toBe(null);
+ });
+
+ it('opens the panel slot only for a mode that brings one', () => {
+ expect(hasPanel('grid')).toBe(true);
+ expect(hasPanel('capture')).toBe(false);
+ expect(hasPanel(null)).toBe(false);
+ });
+});
+
+describe('the declarations themselves', () => {
+ it('gives every entry an id, a label, an icon and a group', () => {
+ for (const entry of [...MAP_MODES, ...MAP_ACTIONS]) {
+ expect(entry.id).toBeTruthy();
+ expect(entry.label).toBeTruthy();
+ expect(entry.icon).toBeTruthy();
+ expect(entry.group).toBeTruthy();
+ }
+ });
+
+ it('keeps every id unique across modes, actions and layers', () => {
+ const ids = [...MAP_MODES, ...MAP_ACTIONS, ...MAP_LAYERS].map((entry) => entry.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('gives no layer a rail seat', () => {
+ const rail = new Set(railEntries().map((entry) => entry.id));
+ for (const layer of MAP_LAYERS) expect(rail.has(layer.id)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/map/view.js b/frontend/src/lib/map/view.js
new file mode 100644
index 0000000..d683428
--- /dev/null
+++ b/frontend/src/lib/map/view.js
@@ -0,0 +1,88 @@
+/**
+ * A map view, written into the address and read back out of it.
+ *
+ * This is what makes a second map window possible at all. The window the
+ * analyst detaches is the same app on the same case, and the only thing that
+ * distinguishes it is where its camera is pointed — so the camera goes in the
+ * hash. Four things follow for free: a reload comes back to the same ground, a
+ * view is a link worth keeping, a window can be duplicated, and two windows can
+ * later be told to follow each other without inventing a second channel.
+ *
+ * Everything here is a number a person could have typed into the address bar,
+ * which is why `readView` validates rather than parses: a hand-edited `z=900`
+ * or `ll=nowhere` must leave the map where it was, not fly it to NaN.
+ *
+ * Precision is six decimals, about 0.1 m — past what any imagery resolves and
+ * short enough to keep the address readable.
+ */
+
+const PLACES = 6;
+
+/** Is this a real number, inside the bounds the app states everywhere else? */
+function within(value, low, high) {
+ return Number.isFinite(value) && value >= low && value <= high;
+}
+
+/** The view as query parameters, for `buildHash`. */
+export function viewParams({ lat, lon, zoom, bearing = 0, provider = '' } = {}) {
+ const params = {};
+ if (within(lat, -90, 90) && within(lon, -180, 180)) {
+ params.ll = `${Number(lat.toFixed(PLACES))},${Number(lon.toFixed(PLACES))}`;
+ }
+ if (within(zoom, 0, 24)) params.z = String(Math.round(zoom));
+ // north-up is the default everywhere, so it is not worth an address
+ if (within(bearing, 0, 360) && Math.round(bearing) % 360 !== 0) {
+ params.b = String(Math.round(bearing) % 360);
+ }
+ if (provider) params.p = provider;
+ return params;
+}
+
+/**
+ * …and back, or null when there is no usable view in there.
+ *
+ * A partial address is honoured as far as it goes: `#satellite?p=sentinel2`
+ * names a basemap and no place, and the map opens where it would have anyway.
+ */
+export function readView(params) {
+ const get = (key) => (params instanceof URLSearchParams ? params.get(key) : params?.[key]);
+ const view = {};
+
+ const pair = String(get('ll') ?? '').split(',');
+ if (pair.length === 2) {
+ const lat = Number(pair[0]);
+ const lon = Number(pair[1]);
+ if (within(lat, -90, 90) && within(lon, -180, 180)) {
+ view.lat = lat;
+ view.lon = lon;
+ }
+ }
+
+ const zoom = Number(get('z'));
+ if (get('z') !== null && get('z') !== undefined && within(zoom, 0, 24)) {
+ view.zoom = Math.round(zoom);
+ }
+
+ const bearing = Number(get('b'));
+ if (get('b') !== null && get('b') !== undefined && within(bearing, 0, 360)) {
+ view.bearing = Math.round(bearing) % 360;
+ }
+
+ const provider = get('p');
+ if (provider) view.provider = String(provider);
+
+ return Object.keys(view).length ? view : null;
+}
+
+/**
+ * Which window this is, for the ones opened beside the first.
+ *
+ * The first window carries no number and says nothing; a detached one is told
+ * which it is, because two identical windows on a second screen are otherwise
+ * impossible to tell apart. Bounded, because it reaches a title and a badge.
+ */
+export function readWindowLabel(params) {
+ const raw = params instanceof URLSearchParams ? params.get('w') : params?.w;
+ const n = Number(raw);
+ return Number.isInteger(n) && n > 1 && n < 100 ? n : null;
+}
diff --git a/frontend/src/lib/map/view.test.js b/frontend/src/lib/map/view.test.js
new file mode 100644
index 0000000..2db0049
--- /dev/null
+++ b/frontend/src/lib/map/view.test.js
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+import { readView, readWindowLabel, viewParams } from './view.js';
+
+describe('a view written into the address', () => {
+ it('carries where the camera is, at a tenth of a metre', () => {
+ expect(viewParams({ lat: 48.85661234, lon: 2.35222987, zoom: 17 })).toEqual({
+ ll: '48.856612,2.35223',
+ z: '17',
+ });
+ });
+
+ it('leaves north-up out, because it is what every map opens on', () => {
+ expect(viewParams({ lat: 1, lon: 1, zoom: 5, bearing: 0 }).b).toBeUndefined();
+ expect(viewParams({ lat: 1, lon: 1, zoom: 5, bearing: 360 }).b).toBeUndefined();
+ expect(viewParams({ lat: 1, lon: 1, zoom: 5, bearing: 215 }).b).toBe('215');
+ });
+
+ it('names the basemap, which is the surface\'s own and not the tool\'s', () => {
+ expect(viewParams({ lat: 1, lon: 1, zoom: 5, provider: 'sentinel2' }).p).toBe('sentinel2');
+ });
+
+ it('writes nothing it cannot vouch for', () => {
+ expect(viewParams({ lat: NaN, lon: 2, zoom: 4 }).ll).toBeUndefined();
+ expect(viewParams({ lat: 91, lon: 2, zoom: 4 }).ll).toBeUndefined();
+ expect(viewParams({ lat: 1, lon: 2, zoom: 99 }).z).toBeUndefined();
+ expect(viewParams()).toEqual({});
+ });
+});
+
+describe('a view read back out of it', () => {
+ const read = (query) => readView(new URLSearchParams(query));
+
+ it('reads a whole view', () => {
+ expect(read('ll=48.8566,2.3522&z=17&b=215&p=esri')).toEqual({
+ lat: 48.8566,
+ lon: 2.3522,
+ zoom: 17,
+ bearing: 215,
+ provider: 'esri',
+ });
+ });
+
+ it('round-trips what was written', () => {
+ const view = { lat: 48.8566, lon: 2.3522, zoom: 17, bearing: 90, provider: 'sentinel2' };
+ expect(read(new URLSearchParams(viewParams(view)).toString())).toEqual(view);
+ });
+
+ it('honours a partial address as far as it goes', () => {
+ expect(read('p=sentinel2')).toEqual({ provider: 'sentinel2' });
+ expect(read('z=12')).toEqual({ zoom: 12 });
+ });
+
+ it('refuses what a hand-edited address can say', () => {
+ // the map must stay where it is rather than fly to NaN
+ expect(read('ll=nowhere')).toBe(null);
+ expect(read('ll=91,2')).toBe(null);
+ expect(read('ll=48.8,181')).toBe(null);
+ expect(read('z=900')).toBe(null);
+ expect(read('b=-4')).toBe(null);
+ expect(read('')).toBe(null);
+ });
+
+ it('drops half a coordinate rather than guessing the other half', () => {
+ expect(read('ll=48.8')).toBe(null);
+ });
+});
+
+describe('which window this is', () => {
+ const label = (query) => readWindowLabel(new URLSearchParams(query));
+
+ it('numbers a detached window', () => {
+ expect(label('w=2')).toBe(2);
+ });
+
+ it('says nothing about the first one', () => {
+ expect(label('')).toBe(null);
+ expect(label('w=1')).toBe(null);
+ });
+
+ it('refuses a number that would reach a title unread', () => {
+ expect(label('w=0')).toBe(null);
+ expect(label('w=-3')).toBe(null);
+ expect(label('w=2.5')).toBe(null);
+ expect(label('w=999')).toBe(null);
+ expect(label('w=<script>')).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/maplinks.js b/frontend/src/lib/maplinks.js
index aa54fcd..0a779da 100644
--- a/frontend/src/lib/maplinks.js
+++ b/frontend/src/lib/maplinks.js
@@ -30,13 +30,9 @@ export function mapLinks(lat, lon, zoom = 17) {
{
id: 'google_earth',
label: 'Google Earth',
- // 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`,
+ // Earth takes a camera distance and a field of view, not a zoom, and it
+ // honours both: `1y` here once opened every link 35 times too close.
+ url: `https://earth.google.com/web/@${lat},${lon},0a,${earthDistance(z, lat)}d,${EARTH_FOV}y,0h,0t,0r`,
},
{
id: 'apple',
@@ -69,16 +65,27 @@ export function mapLinks(lat, lon, zoom = 17) {
];
}
+/** Metres of ground per pixel at the equator, zoom 0, on 256-pixel tiles. */
+const EQUATOR_M_PER_PX = (2 * Math.PI * 6378137) / 256;
+
+/** The field of view Earth writes for itself, in degrees. */
+const EARTH_FOV = 35;
+
+/** The window height a link is sized for, in CSS pixels. Earth's view covers
+ * the same ground in any window, so a shorter one lands a little further out. */
+const EARTH_WINDOW_PX = 1000;
+
/**
* 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.
+ * Earth's 2D map covers `2·d·tan(y/2)` metres of ground across the window's
+ * height, measured in a browser (`engine/mapsites.py`, `_earth_height_m`), so a
+ * level `z` of Web Mercator in a 1000 px window is the `d` below. The ground's
+ * height is not in a link, so Earth draws it that much closer until the map is
+ * first moved.
*/
-function earthDistance(zoom) {
- return Math.round(78_600_000 / 2 ** Math.max(0, zoom));
+function earthDistance(zoom, lat) {
+ const metresPerPx = (EQUATOR_M_PER_PX * Math.cos((lat * Math.PI) / 180)) / 2 ** Math.max(0, zoom);
+ const halfFov = (EARTH_FOV * Math.PI) / 360;
+ return Math.max(25, Math.round((metresPerPx * EARTH_WINDOW_PX) / (2 * Math.tan(halfFov))));
}
diff --git a/frontend/src/lib/maplinks.test.js b/frontend/src/lib/maplinks.test.js
index 75f89bc..fbeb596 100644
--- a/frontend/src/lib/maplinks.test.js
+++ b/frontend/src/lib/maplinks.test.js
@@ -66,14 +66,21 @@ describe('mapLinks', () => {
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('gives Earth the camera that shows the same level in a 1000 px window', () => {
+ // Earth's view is 2·d·tan(y/2) metres tall, measured; z17 at 48.86° is
+ // 0.6 m a pixel, so 1000 px of it is 600 m and d is 600 / (2·tan 17.5°)
+ const earth = (zoom, lat = 48.8584) => mapLinks(lat, 2.2945, zoom).find((l) => l.id === 'google_earth');
+ const camera = (link) => /@[^/]*/.exec(link.url)[0].split(',');
+ const [, , a, d, y, h, t] = camera(earth(17));
+ expect([a, y, h, t]).toEqual(['0a', '35y', '0h', '0t']);
+ const metresPerPx = (156543.03392804097 * Math.cos((48.8584 * Math.PI) / 180)) / 2 ** 17;
+ expect(parseFloat(d)).toBeCloseTo((metresPerPx * 1000) / (2 * Math.tan((17.5 * Math.PI) / 180)), -1);
+ const distance = (link) => parseFloat(camera(link)[3]);
+ expect(distance(earth(16)) / distance(earth(17))).toBeCloseTo(2, 2);
+ // nearer the pole a level is less ground, so the camera comes down
+ expect(distance(earth(17, 70))).toBeLessThan(distance(earth(17, 10)));
+ // …and never under the 25 m Earth stops at
+ expect(distance(earth(23))).toBe(25);
});
it('never sends Google a viewport height where a zoom belongs', () => {
diff --git a/frontend/src/lib/measure.js b/frontend/src/lib/measure.js
index b1fbbc9..35031da 100644
--- a/frontend/src/lib/measure.js
+++ b/frontend/src/lib/measure.js
@@ -57,6 +57,27 @@ export function polygonArea(points) {
return Math.abs((sum * R * R) / 2);
}
+/**
+ * Is `point` inside the ring through `points`?
+ *
+ * Ray casting in degrees, which is what the analyst sees: the shape is judged as it
+ * is drawn on the map rather than on a sphere, and at the size of a traced footprint
+ * the two answers are the same. A point on the edge counts either way.
+ */
+export function containsPoint(points, point) {
+ if (!points || points.length < 3 || !point) return false;
+ let inside = false;
+ for (let i = 0; i < points.length; i++) {
+ const { lat: y1, lon: x1 } = points[i];
+ const { lat: y2, lon: x2 } = points[(i + 1) % points.length];
+ if (y1 > point.lat !== y2 > point.lat) {
+ const crossing = ((x2 - x1) * (point.lat - y1)) / (y2 - y1 || 1e-12) + x1;
+ if (point.lon < crossing) inside = !inside;
+ }
+ }
+ return inside;
+}
+
/** Interior angle at `vertex` between the rays to `a` and `b`, in degrees. */
export function angleAt(a, vertex, b) {
const cosLat = Math.cos(rad(vertex.lat));
diff --git a/frontend/src/lib/measure.test.js b/frontend/src/lib/measure.test.js
index 74c08b7..ddffd14 100644
--- a/frontend/src/lib/measure.test.js
+++ b/frontend/src/lib/measure.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
+ containsPoint,
haversine,
pathLength,
polygonArea,
@@ -152,3 +153,38 @@ describe('destination', () => {
expect(east.lon).toBeGreaterThan(-180);
});
});
+
+describe('containsPoint', () => {
+ // A traced footprint and the pin it belongs to: the shape has to hold the point,
+ // or the place claims an area it does not sit in.
+ const quay = [
+ { lat: 53.43, lon: 14.54 },
+ { lat: 53.43, lon: 14.56 },
+ { lat: 53.45, lon: 14.56 },
+ { lat: 53.45, lon: 14.54 },
+ ];
+
+ it('holds a point inside the ring and refuses one outside it', () => {
+ expect(containsPoint(quay, { lat: 53.44, lon: 14.55 })).toBe(true);
+ expect(containsPoint(quay, { lat: 53.5, lon: 14.6 })).toBe(false);
+ });
+
+ it('reads a concave shape as drawn rather than as its bounding box', () => {
+ // an L: the notch is inside the box and outside the shape
+ const bay = [
+ { lat: 0, lon: 0 },
+ { lat: 0, lon: 4 },
+ { lat: 2, lon: 4 },
+ { lat: 2, lon: 2 },
+ { lat: 4, lon: 2 },
+ { lat: 4, lon: 0 },
+ ];
+ expect(containsPoint(bay, { lat: 1, lon: 1 })).toBe(true);
+ expect(containsPoint(bay, { lat: 3, lon: 3 })).toBe(false);
+ });
+
+ it('is nothing at all without an area or a point', () => {
+ expect(containsPoint(quay.slice(0, 2), { lat: 53.44, lon: 14.55 })).toBe(false);
+ expect(containsPoint(quay, null)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 67844f8..9ed83a2 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -23,6 +23,7 @@ export const prefs = $state({
coordFormat: 'dd', // 'dd' | 'dms' | 'mgrs'
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
+ captureScaleNorth: false, // burn a scale bar and a north arrow into captures
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
postTarget: 'x', // social composer a fresh post draft starts with
postPrefill: true, // let the capture extension fill that composer on Publish
@@ -91,6 +92,7 @@ export function applyPrefs(s) {
if (s.coord_format) prefs.coordFormat = s.coord_format;
if (s.units) prefs.units = s.units;
if (s.home_view) prefs.homeView = s.home_view;
+ if (s.capture_scale_north !== undefined) prefs.captureScaleNorth = s.capture_scale_north;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
if (s.post_target !== undefined) prefs.postTarget = s.post_target;
if (s.post_prefill !== undefined) prefs.postPrefill = s.post_prefill;
diff --git a/frontend/src/lib/wayback.js b/frontend/src/lib/wayback.js
new file mode 100644
index 0000000..73d589f
--- /dev/null
+++ b/frontend/src/lib/wayback.js
@@ -0,0 +1,95 @@
+/**
+ * Esri World Imagery Wayback: which release of World Imagery a map is showing.
+ *
+ * A release rides on the provider id as a variant, `esri-wayback~64776`, the way
+ * a Sentinel-2 window does (`lib/sentinel.js`), and `engine/wayback.py` reads the
+ * same shape. The plain id means the newest release, which the backend names.
+ *
+ * Two dates must not be confused anywhere this is shown. A **release date** is
+ * when Esri published the mosaic. The **acquisition date** is when the pixels
+ * under a point were taken, which can be years earlier and differs from one
+ * point of a release to the next. The picker lists releases; the date pill under
+ * it (the imagery-date route) states the acquisition.
+ */
+
+export const WAYBACK_ID = 'esri-wayback';
+const SEP = '~';
+
+/** A release is a whole positive number, and nothing else reaches a URL. */
+export function validRelease(value) {
+ return Number.isInteger(value) && value > 0 && value < 1e9;
+}
+
+/** The provider id for one release, or the plain id for the newest. */
+export function waybackId(baseId, release) {
+ if (baseId !== WAYBACK_ID || !validRelease(release)) return baseId;
+ return `${baseId}${SEP}${release}`;
+}
+
+/** …and back: the release an id names, or null for the plain basemap. */
+export function releaseOf(providerId) {
+ const [base, spec] = String(providerId ?? '').split(SEP);
+ if (base !== WAYBACK_ID || !/^\d{1,9}$/.test(spec ?? '')) return null;
+ return Number(spec);
+}
+
+/**
+ * The releases the picker walks through, newest first.
+ *
+ * With `changesOnly`, only the releases whose pixels changed at the point; that
+ * list is a subset of the whole one, so the dates always come from the list.
+ */
+export function visibleReleases(releases, changes, changesOnly) {
+ if (!changesOnly || !changes) return releases;
+ const changed = new Set(changes);
+ return releases.filter((entry) => changed.has(entry.release));
+}
+
+/**
+ * Where a release sits in a list, counting the plain basemap as the newest.
+ *
+ * A release absent from the list (the analyst narrowed it to changes, and the
+ * one on screen changed nothing here) sits where its date would put it, so
+ * stepping from it moves to the neighbouring change rather than to the top.
+ */
+export function positionOf(list, releases, current) {
+ if (!list.length) return -1;
+ if (current == null) return 0;
+ const exact = list.findIndex((entry) => entry.release === current);
+ if (exact !== -1) return exact;
+ const date = releases.find((entry) => entry.release === current)?.date;
+ if (!date) return 0;
+ const older = list.findIndex((entry) => entry.date < date);
+ return older === -1 ? list.length - 0.5 : older - 0.5;
+}
+
+/**
+ * One step through the list: `-1` is newer, `+1` is older. Returns the release
+ * to show, or undefined when there is nowhere further to go.
+ */
+export function stepRelease(list, releases, current, direction) {
+ const at = positionOf(list, releases, current);
+ if (at === -1) return undefined;
+ const next = direction > 0 ? Math.floor(at + 1) : Math.ceil(at - 1);
+ return list[next]?.release;
+}
+
+/** The publication date of a release, or '' while the list is unknown. */
+export function releaseDate(releases, release) {
+ if (release == null) return releases[0]?.date ?? '';
+ return releases.find((entry) => entry.release === release)?.date ?? '';
+}
+
+/**
+ * The question the change list answers: one tile at the view zoom. A nudge that
+ * stays inside that tile has the same history, so it is not asked again.
+ */
+export function changesKey(lat, lon, zoom) {
+ const z = Math.max(0, Math.min(19, Math.round(zoom)));
+ const scale = 2 ** z;
+ const x = Math.floor(((lon + 180) / 360) * scale);
+ const clamped = Math.max(-85.05112878, Math.min(85.05112878, lat));
+ const sin = Math.sin((clamped * Math.PI) / 180);
+ const y = Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * scale);
+ return `${z}/${x}/${y}`;
+}
diff --git a/frontend/src/lib/wayback.test.js b/frontend/src/lib/wayback.test.js
new file mode 100644
index 0000000..6d010cc
--- /dev/null
+++ b/frontend/src/lib/wayback.test.js
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+import {
+ WAYBACK_ID,
+ changesKey,
+ positionOf,
+ releaseDate,
+ releaseOf,
+ stepRelease,
+ validRelease,
+ visibleReleases,
+ waybackId,
+} from './wayback.js';
+
+/** Newest first, with numbers out of date order, as Esri publishes them. */
+const RELEASES = [
+ { release: 26334, date: '2026-08-05' },
+ { release: 64776, date: '2023-08-31' },
+ { release: 25982, date: '2023-06-13' },
+ { release: 10, date: '2014-02-20' },
+];
+
+describe('the id a release rides on', () => {
+ it('names the release, and leaves the newest plain', () => {
+ expect(waybackId(WAYBACK_ID, 64776)).toBe('esri-wayback~64776');
+ expect(waybackId(WAYBACK_ID, null)).toBe('esri-wayback');
+ });
+
+ it('never decorates another basemap', () => {
+ expect(waybackId('esri-world-imagery', 64776)).toBe('esri-world-imagery');
+ });
+
+ it('refuses anything that is not a whole release number', () => {
+ for (const bad of [0, -3, 1.5, '64776', NaN, 1e9]) {
+ expect(validRelease(bad)).toBe(false);
+ expect(waybackId(WAYBACK_ID, bad)).toBe(WAYBACK_ID);
+ }
+ });
+
+ it('reads the release back out of an id', () => {
+ expect(releaseOf('esri-wayback~64776')).toBe(64776);
+ expect(releaseOf('esri-wayback')).toBeNull();
+ expect(releaseOf('sentinel2~SWIR')).toBeNull();
+ expect(releaseOf('esri-wayback~../x')).toBeNull();
+ });
+});
+
+describe('what the picker offers', () => {
+ it('is every release until the changes are known', () => {
+ expect(visibleReleases(RELEASES, null, true)).toBe(RELEASES);
+ });
+
+ it('narrows to the releases that changed the point, keeping their dates', () => {
+ expect(visibleReleases(RELEASES, [64776, 10], true)).toEqual([RELEASES[1], RELEASES[3]]);
+ });
+
+ it('shows everything when asked to, whatever the changes say', () => {
+ expect(visibleReleases(RELEASES, [10], false)).toBe(RELEASES);
+ });
+
+ it('dates the newest when no release is pinned, and nothing before the list', () => {
+ expect(releaseDate(RELEASES, null)).toBe('2026-08-05');
+ expect(releaseDate(RELEASES, 25982)).toBe('2023-06-13');
+ expect(releaseDate([], null)).toBe('');
+ });
+});
+
+describe('stepping through time', () => {
+ const changed = [RELEASES[1], RELEASES[3]]; // 2023-08-31, 2014-02-20
+
+ it('walks one release older or newer', () => {
+ expect(stepRelease(RELEASES, RELEASES, 64776, 1)).toBe(25982);
+ expect(stepRelease(RELEASES, RELEASES, 64776, -1)).toBe(26334);
+ });
+
+ it('starts from the newest when nothing is pinned', () => {
+ expect(positionOf(RELEASES, RELEASES, null)).toBe(0);
+ expect(stepRelease(RELEASES, RELEASES, null, 1)).toBe(64776);
+ });
+
+ it('stops at either end rather than wrapping', () => {
+ expect(stepRelease(RELEASES, RELEASES, 26334, -1)).toBeUndefined();
+ expect(stepRelease(RELEASES, RELEASES, 10, 1)).toBeUndefined();
+ });
+
+ it('steps from a release outside the narrowed list to its neighbouring change', () => {
+ // 25982 changed nothing here; older than it is 2014, newer is 2023-08-31
+ expect(stepRelease(changed, RELEASES, 25982, 1)).toBe(10);
+ expect(stepRelease(changed, RELEASES, 25982, -1)).toBe(64776);
+ });
+
+ it('has nowhere to go in an empty list', () => {
+ expect(stepRelease([], RELEASES, 10, 1)).toBeUndefined();
+ });
+});
+
+describe('the question a point history answers', () => {
+ it('is one tile at the view zoom, so a nudge inside it is the same question', () => {
+ expect(changesKey(50.45, 30.51, 15)).toBe(changesKey(50.4501, 30.5101, 15));
+ });
+
+ it('is a different question in the next tile or at another zoom', () => {
+ expect(changesKey(50.45, 30.51, 15)).not.toBe(changesKey(50.45, 30.53, 15));
+ expect(changesKey(50.45, 30.51, 15)).not.toBe(changesKey(50.45, 30.51, 16));
+ });
+
+ it('matches the tile the backend walks, and stops at the basemap ceiling', () => {
+ // engine/tiles.py project(50.45, 30.51, 15) → (19161.09, 11049.07)
+ expect(changesKey(50.45, 30.51, 15)).toBe('15/19161/11049');
+ expect(changesKey(50.45, 30.51, 22).startsWith('19/')).toBe(true);
+ });
+});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index 315be5e..d127e9c 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -13,6 +13,8 @@
* and the case is not a stage: it is what every stage files into. It hangs off
* the case switcher in the topbar instead, beside the name of the case it opens.
*/
+import { splitHash } from './hash.js';
+
export const CASE_WORKSPACE = {
id: 'case',
label: 'Case',
@@ -91,9 +93,12 @@ export function sidebarOpenForWorkspace(workspaceId, remembered = {}) {
* '#<tool>' — stable pre-workspace links (#media, #proof, …)
* '#<workspace>/<tool>' — a specific tab (#compose/post)
* '#<workspace>' — the workspace's first tool (#compose → proof)
+ * Any of them may carry the tool's own state as a query (`#satellite?ll=…`).
*/
export function toolFromHash(hash, allTools) {
- const [head, sub] = hash.replace(/^#/, '').split('/');
+ // A tool may keep its own state after the route (`#satellite?ll=…`, see
+ // lib/hash.js); the route is all that names a tool.
+ const [head, sub] = splitHash(hash).route.split('/');
if (allTools.includes(head)) return head;
const ws = ALL_WORKSPACES.find((w) => w.id === head);
if (!ws) return null;
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index e4b0362..88f4f18 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -3596,7 +3596,7 @@
<ProofCanvas
bind:containerEl
{tool}
- {textEdit}
+ bind:textEdit
{focusSelect}
{commitTextEdit}
{proofHasContent}
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index dae5dc3..d42d5e3 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -7,12 +7,14 @@
import { createSurface } from '../lib/map/surface.js';
import MapSurface from './satellite/MapSurface.svelte';
import { createSentinelState } from './satellite/state/sentinel.svelte.js';
+ import { createWaybackState } from './satellite/state/wayback.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 { createFootprintState } from './satellite/state/footprint.svelte.js';
import {
createCaptureState,
PRESETS,
@@ -22,7 +24,7 @@
import { setAnalysisPeriod } from '../lib/analysisSearch.svelte.js';
import { temporalMapQuery } from '../lib/temporalMap.js';
import { windowWords } from '../lib/timeline.js';
- import { isMode } from '../lib/geoTree.js';
+ import { isMode, KINDS } from '../lib/geoTree.js';
import {
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
} from '../lib/state.svelte.js';
@@ -35,22 +37,57 @@
import { saveRelation } from '../lib/relations.svelte.js';
import { openEntity } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
- import { extensionVersion, onActivated } from '../lib/extBridge.js';
+ import { extensionVersion, mapLinkRelay, onActivated } from '../lib/extBridge.js';
+ import { SENTINEL_ID } from '../lib/sentinel.js';
+ import { WAYBACK_ID } from '../lib/wayback.js';
+ import { buildHash, readSolo, splitHash } from '../lib/hash.js';
+ import { readView, readWindowLabel, viewParams } from '../lib/map/view.js';
+ import { createViewLink } from '../lib/map/link.js';
import {
- SENTINEL_ID,
- maxccLabel,
- cloudLabel,
- cloudClass,
- monthLabel,
- monthGrid,
- } from '../lib/sentinel.js';
+ askable,
+ DATED as FIRMS_DATED,
+ lastDayOf,
+ summary,
+ tileParams,
+ today,
+ WINDOWS as FIRMS_WINDOWS,
+ } from '../lib/map/firms.js';
+ import {
+ askable as nightCanAsk,
+ COMPOSITE as NIGHT_COMPOSITE,
+ firstNight,
+ lastNight,
+ SENSORS as NIGHT_SENSORS,
+ summary as nightSummary,
+ tileParams as nightParams,
+ } from '../lib/map/nightlights.js';
+ // The map's tools declare themselves once (lib/map/tools.js); the rail, the
+ // panel slot, the surface's cursor and the exclusion between modes are all
+ // read from that declaration rather than written out here per tool.
+ import {
+ arm,
+ armedId,
+ closeOthers,
+ cursorOf,
+ disarm,
+ hasPanel,
+ railEntries,
+ railSections,
+ } from '../lib/map/tools.js';
import Icon from '../components/Icon.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import Modal from '../components/Modal.svelte';
+ import EntityDetails from '../components/EntityDetails.svelte';
import RefViewer from './RefViewer.svelte';
- import MapToolCluster from './satellite/MapToolCluster.svelte';
+ import MapRail from './satellite/MapRail.svelte';
+ import MapLayers from './satellite/MapLayers.svelte';
+ import MapContextMenu from './satellite/MapContextMenu.svelte';
+ import MapStatusBar from './satellite/MapStatusBar.svelte';
+ import MarkerMenu from './satellite/MarkerMenu.svelte';
+ import MeasurePanel from './satellite/MeasurePanel.svelte';
import SunPanel from './satellite/SunPanel.svelte';
import GridSearchPanel from './satellite/GridSearchPanel.svelte';
- import SentinelPicker from './satellite/SentinelPicker.svelte';
+ import FootprintPanel from './satellite/FootprintPanel.svelte';
import ScreenshotDialog from './satellite/ScreenshotDialog.svelte';
import ExtensionGate from './satellite/ExtensionGate.svelte';
import RefPicker from './satellite/RefPicker.svelte';
@@ -63,6 +100,20 @@
import SheetPointsOverlay from './satellite/SheetPointsOverlay.svelte';
import TemporalMapOverlay from './satellite/TemporalMapOverlay.svelte';
+ /**
+ * This window, as its own address describes it.
+ *
+ * A second map window is the same app on the same case with its camera
+ * somewhere else, so the camera is what the address carries. Read once, at
+ * build: afterwards the map moves the address, never the other way round.
+ */
+ const opening = splitHash(location.hash);
+ const openingView = readView(opening.params);
+ const windowNumber = readWindowLabel(opening.params);
+ /** Whether this tab is the map on its own; `App.svelte` is what honours it,
+ * and the map is what has to keep saying so as it rewrites the address. */
+ const solo = readSolo(opening.params);
+
let toolEl; // Browser fullscreen target.
// 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
@@ -95,12 +146,14 @@
let savedSearchOpen = $state(false);
let savedOverlay = $state(false); // map layer: off by default, session only
let temporalMap = $state(null); // Timeline handoff, session-only
+ let temporalShown = $state(true); // …and whether its marks are drawn
let temporalMapLoading = $state(false);
let temporalMapError = $state('');
let temporalMapSeq = 0;
/** A sheet's coordinate column, handed over as points. Session-only, like the layer
* above it, and never part of a capture or a proof. */
let sheetPoints = $state(null); // { points, sheet, column }
+ let sheetShown = $state(true); // …and whether its marks are drawn
let hoveredSavedId = $state(null); // shared by the tree, the modal and the map
let revealSavedId = $state(null);
let capturesCollapsed = $state(false);
@@ -120,6 +173,155 @@
// OSM labels overlay: a transparent labels-only layer laid over the imagery so
// roads / place names are readable without hiding the satellite view (item 1).
let osmOverlay = $state(false);
+ // OpenRailwayMap over the same imagery: which of two parallel strips is a
+ // railway, where a siding ends, what a yard is made of. Unlike the labels it
+ // is worth having over a street base map too, which draws tracks as one
+ // undifferentiated line.
+ let railOverlay = $state(false);
+ /**
+ * The other key-less reference layers, each simply on or off: Esri's borders
+ * and roads, Open Infrastructure Map's power lines, OpenSeaMap's sea marks
+ * and OSM's raw GPS traces. Off by default, so none of them fetches a tile
+ * until its switch is pressed.
+ */
+ const refLayers = $state({
+ boundaries: false,
+ roads: false,
+ power: false,
+ seamarks: false,
+ gpstraces: false,
+ });
+ /**
+ * The night lights: one night's VIIRS pass from NASA GIBS, or the 2016
+ * composite. Key-less, and nothing is asked until the layer is on.
+ */
+ const night = $state({ on: false, source: 'noaa20', day: lastNight() });
+ const nightAskable = $derived(nightCanAsk(night));
+ /**
+ * NASA FIRMS: what was burning, live or on a given day.
+ *
+ * The catalogue is read once on mount from our own backend — it is a list of
+ * sensor names and whether a key is saved, and touches no network. Nothing
+ * is asked of NASA until the layer is switched on.
+ */
+ const fires = $state({
+ on: false,
+ keyed: false,
+ sensors: [],
+ sensor: 'viirs',
+ window: '24h',
+ first: '',
+ last: '',
+ });
+ const firmsAskable = $derived(askable(fires));
+ const firmsSummary = $derived(summary(fires, fires.sensors));
+
+ /**
+ * Which instruments are on offer, and whether the key for them is saved.
+ *
+ * Our own backend, reading a catalogue and a settings file: no network, so it
+ * is safe on mount. Failing quietly leaves the row disabled with its reason,
+ * which is the same state as no key — and is the truth either way.
+ */
+ async function loadFireSensors() {
+ try {
+ const answer = await api.get('/api/firms/sensors');
+ fires.sensors = answer.sensors ?? [];
+ fires.keyed = Boolean(answer.keyed);
+ } catch {
+ fires.keyed = false;
+ }
+ }
+
+ /** The two questions the fire layer asks, as rows under its switch. */
+ const firmsControls = $derived([
+ {
+ label: 'Sensor',
+ options: fires.sensors.map((entry) => ({
+ id: entry.id,
+ // "VIIRS (S-NPP + NOAA-20)" does not fit a panel this wide, and the
+ // instrument is the part being chosen between
+ label: entry.label.replace(/\s*\(.*\)\s*$/, ''),
+ title:
+ entry.id === 'modis'
+ ? `${entry.label} · 1 km, back to 2000`
+ : `${entry.label} · 375 m, back to 2012`,
+ })),
+ value: fires.sensor,
+ pick: (id) => (fires.sensor = id),
+ },
+ {
+ label: 'Showing',
+ options: [
+ ...FIRMS_WINDOWS.map((entry) => ({
+ ...entry,
+ title: `Detections from the last ${entry.label.toLowerCase()}`,
+ })),
+ { id: FIRMS_DATED, label: 'Dates', title: 'Detections from a past day or range' },
+ ],
+ value: fires.window,
+ pick: (id) => {
+ fires.window = id;
+ if (id === FIRMS_DATED && !fires.first) fires.first = today();
+ },
+ dates:
+ fires.window === FIRMS_DATED
+ ? {
+ first: fires.first,
+ last: fires.last,
+ today: today(),
+ // FIRMS refuses a longer range, so the input says so rather than
+ // the map failing on a date that was already typed
+ max: lastDayOf(fires.first),
+ setFirst: (value) => (fires.first = value),
+ setLast: (value) => (fires.last = value),
+ }
+ : null,
+ },
+ ]);
+
+ /** The night layer's question, asked in its row like the fires'. */
+ const nightControls = $derived([
+ {
+ label: 'Showing',
+ options: [
+ ...NIGHT_SENSORS.map((sensor) => ({
+ id: sensor.id,
+ label: sensor.label,
+ title: `${sensor.label} · one night, back to ${sensor.first}`,
+ })),
+ { id: NIGHT_COMPOSITE.id, label: NIGHT_COMPOSITE.label, title: 'Cloud-free composite of 2016' },
+ ],
+ value: night.source,
+ pick: (id) => (night.source = id),
+ day:
+ night.source === NIGHT_COMPOSITE.id
+ ? null
+ : {
+ label: 'Night of',
+ title: 'Night of the pass, around 01:30 local time',
+ value: night.day,
+ min: firstNight(night.source),
+ max: lastNight(),
+ set: (value) => (night.day = value),
+ },
+ },
+ ]);
+
+ /** What the surface is asked to lay over the picture (lib/map/basemap.js). */
+ const overlays = $derived(
+ [
+ osmOverlay && baseIsImagery && 'labels',
+ refLayers.boundaries && 'boundaries',
+ refLayers.roads && baseIsImagery && 'roads',
+ railOverlay && 'railway',
+ refLayers.power && 'power',
+ refLayers.seamarks && 'seamarks',
+ refLayers.gpstraces && 'gpstraces',
+ fires.on && fires.keyed && firmsAskable && { id: 'firms', params: tileParams(fires) },
+ night.on && nightAskable && { id: 'nightlights', params: nightParams(night) },
+ ].filter(Boolean)
+ );
// 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).
@@ -141,15 +343,23 @@
api,
});
const isSentinel = $derived(currentProvider?.id === SENTINEL_ID);
- let s2MenuEl = $state(); // bound to the popover wrapper — outside-click detection
+
+ // --- Esri Wayback: which release of World Imagery ---
+ // The release rides on the provider id like a Sentinel-2 window, and both
+ // questions it asks (the release list, a point's history) reach Esri, so
+ // neither is asked until the basemap is on screen or its picker is open.
+ const wb = createWaybackState({
+ api,
+ place: () => ({ lat: center.lat, lon: center.lon, zoom: center.zoom }),
+ });
// --- 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(imagery.pill(currentProvider));
+ const shown = $derived(
+ imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release })
+ );
// Fullscreen: the tool covers the whole viewport; SAVED stays collapsible (item 4).
let fullscreen = $state(false);
@@ -162,6 +372,9 @@
// External-maps quick links, in the SAVED panel (item 6).
let linksOpen = $state(false);
+ // …and the layers list above them, open by default: it is what the panel
+ // says about the map itself.
+ let layersOpen = $state(true);
// --- Grid Search (spec §5): overlay a metric grid on an area of interest and
// sweep it cell by cell, marking each cleared or flagged. The grids a case
@@ -190,6 +403,16 @@
setViewers: (windows) => (uiState.refViewers = windows),
});
+ // --- tracing a place's footprint: the shape it really is, rather than the
+ // circle a radius draws around it. Armed from that place's own card.
+ const footprint = createFootprintState({
+ api,
+ notify: toast,
+ caseId: () => caseState.current?.id,
+ engine: () => engine,
+ onSaved: reloadCase,
+ });
+
// Svelte only honours a cleanup returned from a *synchronous* onMount, and the
// setup below has to await the providers and the saved home view. So onMount
// stays synchronous and hands back a teardown that runs whatever the async
@@ -212,8 +435,34 @@
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 };
+ // The address wins over the saved home view: it is what a detached window,
+ // a reload and a kept link all carry. A basemap named there has to exist —
+ // the catalogue depends on which keys are configured, and an address can be
+ // typed by hand.
+ center = { ...openingHome };
+ if (openingView?.provider && imagery.find(openingView.provider)) {
+ providerId = openingView.provider;
+ }
+ if (windowNumber) document.title = `Azimut · Map ${windowNumber}`;
homeReady = true; // …and only now is there a view for the surface to open on
+ loadFireSensors();
+ // A peer moved. Applied whatever this tab was doing, because the analyst
+ // asked for that by pressing the link — but only while it is pressed.
+ viewLink = createViewLink(
+ (view) => {
+ if (!linked || !engine) return;
+ engine.setView(view, view.zoom);
+ setBearing(view.bearing);
+ },
+ {
+ onPeers: (count) => {
+ peerMaps = count;
+ if (!count) linked = false;
+ },
+ // the extension's map tools, following on Google, Bing, Earth and the rest
+ relay: mapLinkRelay(),
+ }
+ );
window.addEventListener('keydown', onKeydown);
document.addEventListener('fullscreenchange', onFullscreenChange);
// the user clicked the extension after a refused capture — close the loop
@@ -223,10 +472,13 @@
return () => {
window.removeEventListener('keydown', onKeydown);
document.removeEventListener('fullscreenchange', onFullscreenChange);
+ viewLink?.close();
+ viewLink = null;
offActivated();
measure.destroy();
sky.destroy();
grid.destroy();
+ footprint.destroy();
markerSurface?.destroy();
};
}
@@ -256,7 +508,7 @@
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 || refs.picking || deleteTarget) return;
+ if (notesItem || placeModal || detailsEntityId || 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
@@ -274,21 +526,27 @@
if (k === 'p') return void (e.preventDefault(), grid.reviewToPlace());
}
if (e.key !== 'Escape') return;
+ // A menu open over the map is the innermost thing of all.
+ if (pointMenu) return closePointMenu();
+ // Innermost first: what the armed mode is in the middle of, then the mode
+ // itself, then the tool's own frame. A mode no longer has to be named here
+ // to be closed — whatever is armed is what Escape disarms.
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);
+ if (capture.menuOpen && !capture.armed) return void (capture.menuOpen = false);
+ if (sky.placing) return sky.togglePlacing();
+ if (armedMode) return disarm(modes);
+ if (capture.menuOpen) return void (capture.menuOpen = false);
// native fullscreen already exits on Esc (handled by onFullscreenChange);
// only the CSS fallback needs an explicit toggle here
- else if (fullscreen && !document.fullscreenElement) toggleFullscreen();
+ if (fullscreen && !document.fullscreenElement) toggleFullscreen();
}
- // force the labels overlay off whenever the base isn't imagery (item 1)
+ // force the labels overlay off whenever the base isn't imagery (item 1), and
+ // the roads with it: a street map already draws both
$effect(() => {
if (!baseIsImagery && osmOverlay) osmOverlay = false;
+ if (!baseIsImagery && refLayers.roads) refLayers.roads = false;
});
// While the picker is open, a settled pan refreshes its dates. The stale
@@ -318,6 +576,23 @@
});
let s2LatestTimer;
+ // Wayback names its releases once it is on screen: the chip reads a date
+ // rather than "Newest", and the picker opens on a list already read.
+ $effect(() => {
+ if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();
+ });
+
+ // While its picker is open, a pan that settles in another tile reads that
+ // tile's history. Debounced, and answered from memory for a tile already read.
+ $effect(() => {
+ if (!wb.menuOpen || shown.provider?.id !== WAYBACK_ID) return;
+ if (!wb.stale) return;
+ clearTimeout(wbChangesTimer);
+ wbChangesTimer = setTimeout(() => wb.loadChanges(), 900);
+ return () => clearTimeout(wbChangesTimer);
+ });
+ let wbChangesTimer;
+
// --- 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
@@ -383,20 +658,493 @@
tick().then(() => engine?.resize());
}
+ // --- this window, and the next one ---------------------------------------
+ //
+ // The map is the first tool that opens in more than one window, because two
+ // areas side by side on two screens is what the work actually looks like.
+ // Everything that makes that possible is already here: the case is the one
+ // the workspace last opened, and a point saved or a cell swept reaches every
+ // window over the nudge channel. The only thing a second window needs of its
+ // own is where its camera is — so that goes in the address.
+
+ /**
+ * Where the surface opens: the address when it names a place, else the saved
+ * home view. The surface reads this once, at build — so it has to be the same
+ * answer the tool gave `center`, or the map opens on one and reports the
+ * other.
+ */
+ const openingHome = $derived(
+ openingView?.lat != null
+ ? {
+ lat: openingView.lat,
+ lon: openingView.lon,
+ zoom: openingView.zoom ?? prefs.homeView.zoom,
+ }
+ : prefs.homeView
+ );
+
+ /** The bearing the address asked for, applied once the map exists to turn. */
+ let bearingApplied = false;
+ $effect(() => {
+ if (!mapReady || bearingApplied) return;
+ bearingApplied = true;
+ if (openingView?.bearing) setBearing(openingView.bearing);
+ });
+
+ /**
+ * This window's view, kept in its own address.
+ *
+ * `replaceState`, never push: panning a map is not navigating, and a back
+ * button holding four hundred camera positions is worse than useless.
+ */
+ $effect(() => {
+ if (uiState.tool !== 'satellite' || !mapReady) return;
+ const params = viewParams({
+ lat: center.lat,
+ lon: center.lon,
+ zoom: center.zoom,
+ bearing,
+ provider: providerId,
+ });
+ if (windowNumber) params.w = String(windowNumber);
+ // What this tab *is* rides along with where it is pointed: rewritten
+ // without it, the first pan would turn a detached map back into the whole
+ // app on the next reload.
+ if (solo) params.solo = '1';
+ history.replaceState(null, '', buildHash('satellite', params));
+ });
+
+ /**
+ * This tab following the others, and them following it.
+ *
+ * Off by default and per tab, which is the point: two maps are worth linking
+ * when they are being compared, and in the way of each other the rest of the
+ * time. Nothing here is written down and nothing reaches the network — a
+ * camera is not case state (`lib/map/link.js`).
+ */
+ let linked = $state(false);
+ let viewLink = null;
+ /**
+ * How many other maps are open, the app's tabs and the extension's panels on
+ * other sites together, which is the whole of whether the button means
+ * anything. With none, linking would be pressing a control that pans
+ * nothing — so it greys out, and a link already on is dropped when the last
+ * peer goes rather than left lit over an empty channel.
+ */
+ let peerMaps = $state(0);
+
+ function toggleLink() {
+ if (!peerMaps) return;
+ linked = !linked;
+ if (linked) viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing });
+ }
+
+ $effect(() => {
+ if (!linked || !mapReady) return;
+ viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing });
+ });
+
+ const WINDOWS_KEY = 'azimut:mapWindows';
+
+ /** The number the next detached window wears. A label, not an identity. */
+ function nextWindowNumber() {
+ let count = 1;
+ try {
+ const seen = Number(localStorage.getItem(WINDOWS_KEY));
+ if (Number.isInteger(seen) && seen > 0) count = seen;
+ localStorage.setItem(WINDOWS_KEY, String(count + 1));
+ } catch { /* a locked-down profile only loses the numbering */ }
+ return count + 1;
+ }
+
+ /**
+ * Open this map again in a tab of its own, on the view it is showing.
+ *
+ * A peer and a whole map, but not a whole app: the tab opens `solo`
+ * (`lib/hash.js`), so the workspace rail, the case bar and the tab strip stay
+ * in the window they belong to. What is left is the map and the map's own
+ * chrome, which is what a second screen is for — the first window is still
+ * where you go somewhere else.
+ *
+ * An ordinary tab rather than a `popup=yes` window: a tab can be torn onto
+ * the second screen, put back, and is what a browser does not refuse.
+ */
+ function detachWindow() {
+ const params = viewParams({
+ lat: center.lat,
+ lon: center.lon,
+ zoom: center.zoom,
+ bearing,
+ provider: providerId,
+ });
+ params.w = String(nextWindowNumber());
+ params.solo = '1';
+ const url = `${location.pathname}${location.search}${buildHash('satellite', params)}`;
+ const opened = window.open(url, '_blank');
+ if (!opened) toast('The browser refused a second tab. Allow pop-ups for this page', 'warn', 8000);
+ }
+
+ // --- the right-click menu: acts on the point under the cursor -------------
+ //
+ // Every act here already exists for the map centre; the menu hands each one
+ // the clicked point instead (lib/map/contextMenu.js). Session chrome, never
+ // part of a capture.
+ let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup }
+ let pointLookupSeq = 0;
+
+ function onMapContextMenu(at) {
+ pointLookupSeq += 1;
+ pointMenu = {
+ ...at,
+ frame: { width: mapEl?.clientWidth ?? 0, height: mapEl?.clientHeight ?? 0 },
+ lookup: null,
+ };
+ }
+
+ function closePointMenu() {
+ pointLookupSeq += 1;
+ pointMenu = null;
+ }
+
+ async function onPointMenu(id, value) {
+ const at = pointMenu;
+ if (!at || !engine) return;
+ const point = { lat: at.lat, lon: at.lon };
+ if (id === 'lookup') return lookUpPoint(point);
+ closePointMenu();
+ if (id === 'copy') {
+ try {
+ await navigator.clipboard.writeText(value);
+ toast('Coordinates copied', 'ok', 1600);
+ } catch {
+ toast('The browser refused the clipboard', 'warn');
+ }
+ } else if (id === 'place') {
+ openNewPlaceAt(point);
+ } else if (id === 'centre') {
+ engine.setView(point, center.zoom);
+ } else if (id === 'measure') {
+ if (!modes.measure.isOn()) arm(modes, 'measure');
+ if (measure.mode !== 'distance') setMeasureMode('distance');
+ measure.addPoint(point);
+ } else if (id === 'sky') {
+ if (!sky.on) arm(modes, 'sky');
+ sky.handOff({ ...point, date: sky.day || undefined });
+ } else if (id === 'history') {
+ providerId = WAYBACK_ID;
+ engine.setView(point, Math.max(center.zoom, 15));
+ await tick();
+ if (!wb.menuOpen) wb.toggleMenu();
+ }
+ }
+
+ /** "What is here?": the geocoder's name for the point, shown in the menu itself. */
+ async function lookUpPoint(point) {
+ const mine = ++pointLookupSeq;
+ pointMenu = { ...pointMenu, lookup: { busy: true } };
+ try {
+ const answer = await api.get(`/api/geo/reverse?lat=${point.lat}&lon=${point.lon}`);
+ if (mine !== pointLookupSeq || !pointMenu) return;
+ pointMenu = {
+ ...pointMenu,
+ lookup: { text: answer.display_name || 'No name for this point' },
+ };
+ } catch (error) {
+ if (mine !== pointLookupSeq || !pointMenu) return;
+ pointMenu = { ...pointMenu, lookup: { error: `Lookup failed: ${error.message}` } };
+ }
+ }
+
+ // The menu is pinned to a screen point, so a zoom or a pan leaves it pointing
+ // at somewhere else. A drag already closes it by pressing outside; the wheel
+ // does not, so the settled view does.
+ $effect(() => {
+ if (!mapReady || !pointMenu) return;
+ return engine.on('view-settled', closePointMenu);
+ });
+
+ /** Arm tracing for one saved place, closing whatever else was armed. */
+ function startTrace(row) {
+ if (!footprint.start(row)) return;
+ closeOthers(modes, 'footprint');
+ toast('Click the corners, then Save', 'info', 4000);
+ }
+
// --- 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.
+ // One router, asked in the order the modes exclude each other: a shape being
+ // traced or 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) {
+ if (footprint.addPoint(at)) return;
if (grid.addVertex(at)) return;
if (sky.place(at)) return;
measure.addPoint(at);
}
+ /**
+ * The map's modes, each behind the three questions the registry asks.
+ *
+ * The stores keep what a mode *is* in whatever shape suits it — Grid Search a
+ * boolean, the measure tools a sub-mode string, the capture marquee an armed
+ * flag — and this is where each one answers "are you on", "open" and "close"
+ * in the same words. `lib/map/tools.js` then owns the rule that used to be
+ * written four times over, once in each `toggle…` function: arming anything
+ * closes everything else.
+ *
+ * Declared before `sky` and `capture` exist, which is safe because nothing
+ * here reads a store until a rail seat is pressed.
+ */
+ const modes = {
+ measure: {
+ isOn: () => measure.panelOpen || Boolean(measure.mode),
+ open: () => measure.togglePanel(),
+ close: () => {
+ measure.setMode(null);
+ if (measure.panelOpen) measure.togglePanel();
+ },
+ pointing: () => Boolean(measure.mode),
+ },
+ grid: {
+ isOn: () => grid.on,
+ open: () => grid.open(),
+ close: () => grid.exit(),
+ pointing: () => Boolean(grid.drawMode),
+ },
+ sky: {
+ isOn: () => sky.on,
+ // the planted anchor, or where the analyst is looking
+ open: () => sky.open(markerLatLng ?? { lat: center.lat, lon: center.lon }),
+ close: () => sky.close(),
+ },
+ capture: {
+ isOn: () => Boolean(capture.armed),
+ open: () => capture.toggleSelect(),
+ close: () => capture.disarm(),
+ pointing: () => Boolean(capture.armed),
+ },
+ footprint: {
+ isOn: () => footprint.on,
+ // opened by a place's card handing it the place, never by the rail: there
+ // is no such thing as tracing a footprint for nobody
+ open: () => {},
+ close: () => footprint.cancel(),
+ pointing: () => footprint.on,
+ },
+ };
+
+ /** Which mode is armed, if any — the panel slot, and the rail's amber edge. */
+ const armedMode = $derived.by(() => armedId(modes));
+ /**
+ * The cursor the surface wears.
+ *
+ * Armed is not the same as *pointing*: the measure panel can be open with no
+ * tool chosen in it, and Grid Search can be open on a saved grid nobody is
+ * redrawing. Either would otherwise put a crosshair over a map that has
+ * nothing to do with a click.
+ */
+ const armedCursor = $derived(modes[armedMode]?.pointing?.() ? cursorOf(armedMode) : null);
+ const RAIL = railSections(railEntries());
+ /** The rail's inset from the map's top-left corner, shared with the CSS. */
+ const RAIL_TOP = 12;
+ /** Its own height, so the engine's zoom buttons stack under it rather than
+ * behind it — and keep doing so when a tool is added to the rail. */
+ let railHeight = $state(0);
+ const railBottom = $derived(RAIL_TOP + railHeight + 8);
+
+ /**
+ * The saved layer's own two questions, asked where the layer is listed.
+ *
+ * The folder row appears only where there is a choice to make: a case whose
+ * saved work all sits in one place gets a control that could only ever be
+ * set back to where it already was.
+ */
+ const savedFilters = $derived.by(() => {
+ const folders = savedWork.folders;
+ const rows = [
+ {
+ label: 'Show',
+ value: savedWork.kind,
+ options: KINDS.map((entry) => ({ id: entry.id, label: entry.label })),
+ pick: (id) => (savedWork.kind = id),
+ },
+ ];
+ if (folders.length > 1) {
+ rows.push({
+ label: 'Folder',
+ value: savedWork.folder ?? 'all',
+ // folders are named by the analyst and there can be dozens, so this one
+ // is a list rather than the row of chips the fixed questions get
+ list: true,
+ options: [
+ { id: 'all', label: 'All', title: 'Every folder' },
+ ...folders.map((entry) => ({
+ id: entry.id,
+ label: entry.id || 'Unfiled',
+ title: `${entry.count} item${entry.count === 1 ? '' : 's'}`,
+ })),
+ ],
+ pick: (id) => (savedWork.folder = id === 'all' ? null : id),
+ });
+ }
+ return rows;
+ });
+
+ /**
+ * What is drawn over the imagery, as the panel on the right lists it.
+ *
+ * The two that arrive from another tool — a sheet's coordinate column, a
+ * Timeline window — are rows only while they are here, so the list never
+ * offers a switch for something that is not on the map. Each keeps a Close
+ * beside its switch, because hiding a layer and being done with it are two
+ * different intentions and used to be the same button.
+ */
+ const layerRows = $derived([
+ {
+ id: 'labels',
+ label: 'OSM labels',
+ on: osmOverlay,
+ disabled: !baseIsImagery,
+ title: baseIsImagery
+ ? 'Roads and place names over the imagery'
+ : 'Only useful over satellite imagery',
+ toggle: () => (osmOverlay = !osmOverlay),
+ },
+ {
+ id: 'railway',
+ label: 'OSM railways',
+ on: railOverlay,
+ title: 'Tracks, sidings and stations, from OpenRailwayMap',
+ toggle: () => (railOverlay = !railOverlay),
+ },
+ {
+ id: 'boundaries',
+ label: 'Borders',
+ on: refLayers.boundaries,
+ title: 'Country, region and district borders, from Esri',
+ toggle: () => (refLayers.boundaries = !refLayers.boundaries),
+ },
+ {
+ id: 'roads',
+ label: 'Roads',
+ on: refLayers.roads,
+ disabled: !baseIsImagery,
+ title: baseIsImagery ? 'Road network over the imagery, from Esri' : 'Only useful over satellite imagery',
+ toggle: () => (refLayers.roads = !refLayers.roads),
+ },
+ {
+ id: 'power',
+ label: 'Power lines',
+ on: refLayers.power,
+ title: 'Power lines by voltage, towers, substations, pipelines and masts, from Open Infrastructure Map',
+ toggle: () => (refLayers.power = !refLayers.power),
+ note: refLayers.power ? 'Towers appear from zoom 14.' : '',
+ },
+ {
+ id: 'seamarks',
+ label: 'Sea marks',
+ on: refLayers.seamarks,
+ title: 'Buoys, lights, harbours and fairways, from OpenSeaMap',
+ toggle: () => (refLayers.seamarks = !refLayers.seamarks),
+ },
+ {
+ id: 'gpstraces',
+ label: 'GPS traces',
+ on: refLayers.gpstraces,
+ title: 'Raw GPS tracks uploaded to OpenStreetMap, mapped or not',
+ toggle: () => (refLayers.gpstraces = !refLayers.gpstraces),
+ },
+ {
+ id: 'firms',
+ label: 'Active fires',
+ on: fires.on,
+ disabled: !fires.keyed,
+ detail: fires.keyed ? firmsSummary : '',
+ title: fires.keyed
+ ? 'Thermal detections from NASA FIRMS, live or from the archive'
+ : 'Add a NASA FIRMS key in Settings → Imagery',
+ toggle: () => (fires.on = !fires.on),
+ // its two questions — which instrument, and over what — are asked in the
+ // row rather than in a card of its own floating somewhere
+ controls: fires.on && fires.keyed ? firmsControls : null,
+ note: fires.on && !firmsAskable ? 'Pick a date to draw the detections.' : '',
+ },
+ {
+ id: 'nightlights',
+ label: 'Night lights',
+ on: night.on,
+ detail: night.on ? nightSummary(night) : '',
+ title: 'The ground at night, from NASA’s VIIRS passes',
+ toggle: () => (night.on = !night.on),
+ controls: night.on ? nightControls : null,
+ note: !night.on
+ ? ''
+ : nightAskable
+ ? 'Cloud hides lights too, so a dark night is not an outage on its own.'
+ : 'Pick a night inside this sensor’s record.',
+ },
+ {
+ id: 'saved',
+ label: 'Saved work',
+ on: savedOverlay,
+ disabled: !savedWork.rows.length,
+ detail: savedWork.shown.length ? String(savedWork.shown.length) : '',
+ title: savedWork.rows.length
+ ? "This case's saved places and captures"
+ : 'Nothing is saved in this case yet',
+ toggle: () => (savedOverlay = !savedOverlay),
+ // Which of them are drawn. The same two answers the Saved panel is asking
+ // — what kind, and which folder — so a map read here and a panel read
+ // beside it can never disagree about what is on the case.
+ controls: savedOverlay && savedWork.rows.length ? savedFilters : null,
+ },
+ ...(sheetPoints
+ ? [
+ {
+ id: 'sheet',
+ label: 'Sheet points',
+ on: sheetShown,
+ detail: `${sheetPoints.sheet} · ${sheetPoints.points.length}`,
+ title: `${sheetPoints.sheet} · ${sheetPoints.column}`,
+ toggle: () => (sheetShown = !sheetShown),
+ actions: [{ label: 'Close', quiet: true, run: () => (sheetPoints = null) }],
+ },
+ ]
+ : []),
+ ...(temporalMap
+ ? [
+ {
+ id: 'timeline',
+ label: 'Timeline points',
+ on: temporalShown,
+ detail: temporalMapLoading
+ ? 'loading…'
+ : temporalMapError
+ ? 'failed'
+ : `${temporalMap.mapped} of ${temporalMap.matched}${temporalMap.truncated ? ', partial' : ''}`,
+ title: windowWords(temporalMap.from, temporalMap.to, 'UTC'),
+ toggle: () => (temporalShown = !temporalShown),
+ actions: [
+ { label: 'Timeline', run: () => openTemporalTimeline() },
+ { label: 'Board', run: () => openTemporalCatalog('board') },
+ { label: 'Graph', run: () => openTemporalCatalog('graph') },
+ { label: 'Close', quiet: true, run: closeTemporalMap },
+ ],
+ },
+ ]
+ : []),
+ ]);
+
+ /** A rail seat was pressed: a mode is armed (and every other closed), an
+ * action just runs. */
+ function pickTool(id) {
+ if (id === 'reference') return refs.openPicker();
+ arm(modes, id);
+ }
+
function setMeasureMode(mode) {
- // measuring and the capture marquee can't both be armed
+ // the sub-mode inside the armed measure tool; arming it is the rail's
if (measure.setMode(mode)) capture.disarm();
}
@@ -442,11 +1190,15 @@
// re-sync providers + prefs when returning to this tab: Settings may have
// toggled a basemap off (it must vanish from the selector) or changed the
- // eco / override prefs meanwhile (tools stay mounted, so no fresh onMount)
+ // eco / override prefs meanwhile (tools stay mounted, so no fresh onMount).
+ // The fire layer's key is the same story and was the same bug — a key pasted
+ // into Settings is a key the map should have on the way back, not after a
+ // reload.
$effect(() => {
if (uiState.tool !== 'satellite' || !mapReady) return;
imagery.refreshUsage();
imagery.loadProviders();
+ loadFireSensors();
});
// A different case drops everything this one was holding: both indexes, the
@@ -463,6 +1215,7 @@
deleteTarget = null;
notesItem = null;
placeModal = null;
+ detailsEntityId = null;
temporalMapSeq += 1;
temporalMap = null;
temporalMapLoading = false;
@@ -529,6 +1282,7 @@
if (!mapReady || !handed?.points?.length) return;
uiState.mapSheetPoints = null;
sheetPoints = handed;
+ sheetShown = true;
tick().then(() => {
engine?.fitPoints(handed.points, { padding: [48, 48], maxZoom: 17 });
});
@@ -539,6 +1293,7 @@
const caseId = caseState.current?.id;
if (!mapReady || !handed || !caseId) return;
uiState.mapTimelineRange = null;
+ temporalShown = true;
const run = ++temporalMapSeq;
temporalMap = {
from: handed.from,
@@ -622,14 +1377,7 @@
const sky = createSkyState({ engine: () => engine, api, notify: toast });
function toggleSunMode() {
- 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 });
+ arm(modes, 'sky');
}
// Coords & Sky hands over a point, a date and a time: same mode, second way
@@ -730,7 +1478,10 @@
maxZoom: () => shown.provider?.max_zoom ?? 19,
provenance: () => surface.provenance(),
onRect: (rect) => (selRect = rect),
- onArm: () => setMeasureMode(null),
+ // The marquee is the one mode armed from outside the rail, so it reports in
+ // rather than being armed through it — otherwise pressing Capture while
+ // Grid Search is drawing leaves two modes waiting for the same left drag.
+ onArm: () => closeOthers(modes, 'capture'),
});
let sizeMenuEl = $state(); // bound to the popover wrapper — outside-click detection
// The live drag outline, in map-container px. Shared chrome: the capture
@@ -797,24 +1548,11 @@
return () => document.removeEventListener('mousedown', onDocMousedown, true);
});
- // …and the Sentinel-2 layer/date popover
- $effect(() => {
- if (!s2.menuOpen) return;
- const onDocMousedown = (e) => {
- if (s2MenuEl && !s2MenuEl.contains(e.target)) s2.menuOpen = false;
- };
- document.addEventListener('mousedown', onDocMousedown, true);
- return () => document.removeEventListener('mousedown', onDocMousedown, true);
- });
-
// --- 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() {
- capture.toggleSelect();
- }
-
+ // The frame, the ratio lock and the filing are the store's; arming it closes
+ // the other modes through the registry (`onArm` above). What stays here is
+ // the one thing the store cannot do: hand it a left-drag off the map element
+ // it does not own.
function onSelectDrag(e) {
capture.startSelect(e);
}
@@ -827,13 +1565,7 @@
// — the same gesture as the capture marquee, sharing its live outline.
function toggleGridMode() {
- if (grid.on) {
- grid.exit();
- return;
- }
- if (capture.armed) toggleSelect(); // exclusive with the capture marquee…
- setMeasureMode(null); // …and the measure tools
- grid.open();
+ arm(modes, 'grid');
}
// rectangle area: drag a box, mirroring the capture marquee and reusing
@@ -913,7 +1645,7 @@
/** The edit action, for whichever kind of row it was pressed on. */
function editSaved(row) {
if (row.kind === 'place') openEditPlace(row);
- else openNotes(row);
+ else notesItem = row;
}
/** Accept a point a tool proposed, from the panel the analyst is reading it in.
@@ -1058,14 +1790,38 @@
let placeModal = $state(null);
let placeSaving = $state(false);
+ // --- the full editor, reached from the place dialog ---------------------------
+ // The same body the case sidebar and the Media Library open, so everything a
+ // place holds is editable from the map without this tool keeping a second copy
+ // of that form. Its fields wait for Save, so Escape and the backdrop ask first.
+ let detailsEntityId = $state(null);
+ let detailsDirty = $state(false);
+ let detailsDiscarding = $state(false);
+
+ function closeDetails() {
+ if (detailsDirty) detailsDiscarding = true;
+ else detailsEntityId = null;
+ }
+
+ function openPlaceDetails() {
+ detailsDirty = false; // a fresh panel, whatever the last one was left holding
+ detailsEntityId = placeModal?.id ?? null;
+ placeModal = null;
+ }
+
function openNewPlace() {
+ openNewPlaceAt(displayCoords);
+ }
+
+ /** The same dialog for any point, such as one right-clicked away from the centre. */
+ function openNewPlaceAt({ lat, lon }) {
placeModal = {
id: null,
title: '',
notes: '',
folder: '',
- lat: displayCoords.lat,
- lon: displayCoords.lon,
+ lat,
+ lon,
zoom: center.zoom,
bearing,
relation: null, // collected by the gate, filed once the place exists
@@ -1149,7 +1905,9 @@
<div class="tool" class:fullscreen bind:this={toolEl}>
<div class="tool-header">
- <h2>Satellite</h2>
+ <!-- Two identical windows on a second screen are otherwise impossible to
+ tell apart; the first one needs no number and says nothing. -->
+ <h2>Satellite{windowNumber ? ` · ${windowNumber}` : ''}</h2>
<div class="spacer"></div>
<PlaceSearch
bind:value={coordsText}
@@ -1160,6 +1918,33 @@
onpick={goToSuggestion}
onsubmit={goTo}
/>
+ <!-- What the window does with the tool, not what the tool does with the
+ map: these sit with the title rather than among the map's own controls. -->
+ <button
+ class="btn btn-icon"
+ class:on={linked}
+ onclick={toggleLink}
+ disabled={!peerMaps}
+ title={!peerMaps
+ ? 'Open a second map tab or the extension map tools to link the views'
+ : linked
+ ? 'Stop following the other maps'
+ : 'Pan and zoom with the other maps'}
+ aria-label="Link the view to the other maps"
+ ><Icon name="link" size={15} /></button>
+ <button
+ class="btn btn-icon"
+ onclick={detachWindow}
+ title="Open this map in a tab of its own, on this view"
+ aria-label="Open in a new tab"
+ ><Icon name="external" size={15} /></button>
+ <button
+ class="btn btn-icon"
+ class:on={fullscreen}
+ onclick={toggleFullscreen}
+ title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
+ aria-label="Toggle fullscreen"
+ ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={15} /></button>
</div>
<div class="body">
@@ -1172,21 +1957,18 @@
bind:bearing
bind:ready={mapReady}
bind:refused={mapRefused}
+ bind:providerId
{imagery}
- {providerId}
{s2}
- home={prefs.homeView}
- labels={osmOverlay}
+ wayback={wb}
+ home={openingHome}
+ {overlays}
imperial={prefs.units === 'imperial'}
- armed={measure.mode
- ? 'measuring'
- : capture.armed
- ? 'selecting'
- : grid.drawMode
- ? 'grid-drawing'
- : null}
+ controlsTop={railBottom}
+ armed={armedCursor}
grabbing={capture.hiding}
onclick={onMapClick}
+ oncontextmenu={onMapContextMenu}
onusage={() => imagery.refreshUsage()}
onwidgetload={(meter) => imagery.countLoad(meter)}
onwidgetauthfailure={onWidgetAuthFailure}
@@ -1208,126 +1990,113 @@
onpost={openLinkedPost}
onshowproofs={() => (savedWork.kind = 'proofs')}
onrefresh={reloadCase}
+ ontrace={startTrace}
/>
{/if}
- {#if sheetPoints}
+ <!-- Both handoff layers can be on at once. Neither carries a card of its
+ own any more: what they are and what to do with them is a row in the
+ Layers list, with every other layer. -->
+ {#if sheetPoints && sheetShown}
<SheetPointsOverlay engine={mapReady ? engine : null} points={sheetPoints.points} />
- <!-- Both temporary layers can be on at once, so this one sits under the other
- rather than on top of it. -->
- <div class="temporal-layer-card" class:stacked={temporalMap} aria-label="Sheet map layer">
- <div>
- <strong>Sheet</strong>
- <span>{sheetPoints.sheet} · {sheetPoints.column}</span>
- </div>
- <p>{sheetPoints.points.length} point{sheetPoints.points.length === 1 ? '' : 's'} read from the column</p>
- <nav aria-label="Close the sheet layer">
- <button class="quiet" onclick={() => (sheetPoints = null)}>Close</button>
- </nav>
- </div>
{/if}
- {#if temporalMap}
+ {#if temporalMap && temporalShown}
<TemporalMapOverlay
engine={mapReady ? engine : null}
items={temporalMap.items}
caseId={caseState.current?.id}
onopen={openTemporalTimeline}
/>
- <div class="temporal-layer-card" aria-label="Timeline map layer">
- <div>
- <strong>Timeline</strong>
- <span>{windowWords(temporalMap.from, temporalMap.to, 'UTC')}</span>
- </div>
- {#if temporalMapLoading}
- <p>Loading placed statements…</p>
- {:else if temporalMapError}
- <p class="error">{temporalMapError}</p>
- {:else if !temporalMap.matched}
- <p>Nothing is dated in this window.</p>
- {:else if !temporalMap.mapped}
- <p>None of the {temporalMap.matched} dated here carries a place.</p>
- {:else}
- <p>{temporalMap.mapped} placed of {temporalMap.matched} dated{temporalMap.truncated ? ', partial' : ''}</p>
- {/if}
- <nav aria-label="Open Timeline range">
- <button onclick={() => openTemporalTimeline()}>Timeline</button>
- <button onclick={() => openTemporalCatalog('board')}>Board</button>
- <button onclick={() => openTemporalCatalog('graph')}>Graph</button>
- <button class="quiet" onclick={closeTemporalMap}>Close</button>
- </nav>
- </div>
{/if}
- <!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools -->
+ <!-- The map's toolbox, and the one slot the armed tool's settings open
+ in. Only verbs live here; what is *drawn* over the imagery is a layer
+ and is listed in the panel on the right. -->
<div class="map-tools">
- <MapToolCluster
- {fullscreen}
- {toggleFullscreen}
- bind:osmOverlay
- {baseIsImagery}
- toolsOpen={measure.panelOpen}
- measureMode={measure.mode}
- toggleTools={() => measure.togglePanel()}
- gridMode={grid.on}
- {toggleGridMode}
- bind:savedOverlay
- savedCount={savedWork.rows.length}
- referenceCount={refs.open.length}
- openRefPicker={() => refs.openPicker()}
- {setMeasureMode}
- measureReadout={measure.readout}
- measureHint={MEASURE_HINT}
- clearMeasure={() => measure.clear()}
- sunMode={sky.on}
- {toggleSunMode}
+ <MapRail
+ sections={RAIL}
+ bind:height={railHeight}
+ state={{
+ measure: { on: modes.measure.isOn() },
+ grid: { on: grid.on },
+ sky: { on: sky.on },
+ reference: {
+ on: refs.open.length > 0,
+ title: refs.open.length
+ ? `${refs.open.length} reference window${refs.open.length === 1 ? '' : 's'} open`
+ : undefined,
+ },
+ }}
+ onpick={pickTool}
/>
- {#if sky.on}
- <SunPanel
- 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 grid.on}
- <GridSearchPanel
- 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 hasPanel(armedMode)}
+ <!-- One slot, one panel: only one mode is ever armed, so the settings
+ for three tools cannot stack or cross each other any more. -->
+ <div class="mode-panel">
+ {#if armedMode === 'measure'}
+ <MeasurePanel
+ mode={measure.mode}
+ setMode={setMeasureMode}
+ clear={() => measure.clear()}
+ />
+ {:else if armedMode === 'sky'}
+ <SunPanel
+ 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}
+ />
+ {:else if armedMode === 'footprint'}
+ <FootprintPanel
+ place={footprint.place}
+ points={footprint.points.length}
+ complete={footprint.complete}
+ covers={footprint.covers}
+ saving={footprint.saving}
+ undo={() => footprint.undo()}
+ save={() => footprint.save()}
+ cancel={() => footprint.cancel()}
+ />
+ {:else if armedMode === 'grid'}
+ <GridSearchPanel
+ 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>
{/if}
</div>
@@ -1393,68 +2162,21 @@
</div>
{/if}
- <div class="hud card">
- <button class="hud-coords mono" onclick={copyCoords} title="Copy coordinates">
- <Icon name="crosshair" size={13} />
- {readout}
- <span class="z">z{center.zoom}</span>
- {#if moveMode && markerLatLng}<span class="pin-tag">pin</span>{/if}
- <Icon name="copy" size={12} />
- </button>
- </div>
-
- <div class="capture-bar card">
- <select class="select" bind:value={providerId} title="Imagery provider">
- {#each imagery.providers as p (p.id)}
- <option value={p.id} disabled={p.needs_key}>
- {p.label}{p.needs_key ? ' (needs API key)' : ''}
- </option>
- {/each}
- </select>
- {#if isSentinel}
- <SentinelPicker
- bind:menuEl={s2MenuEl}
- {s2}
- {maxccLabel}
- {monthLabel}
- {monthGrid}
- {cloudClass}
- {cloudLabel}
- />
- {/if}
- {#if usagePill}
- <span
- class="usage-pill mono"
- title="Requests to this billed provider this month"
- >{usagePill}</span>
- {/if}
- {#if shown.fallenBack}
- <span
- class="fallback-pill"
- 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={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">
- <option value="crosshair">✛ crosshair</option>
- <option value="pin">📍 pin</option>
- <option value="none">no marker</option>
- </select>
- <button
- class="btn btn-toggle"
- class:on={moveMode}
- onclick={toggleMoveMode}
- disabled={markerStyle === 'none'}
- title="Move the marker (coordinates follow it)"
- >
- <Icon name="crosshair" size={14} /> {moveMode ? 'Moving' : 'Move pin'}
- </button>
- <span class="bar-sep" aria-hidden="true"></span>
+ <!-- Where you are and what the armed tool is reading, then the two acts
+ that take something off the map. The imagery provider left this bar
+ for the surface's own corner: it describes the picture, not the
+ tool, and two compared surfaces each show their own. -->
+ <MapStatusBar
+ coords={readout}
+ zoom={center.zoom}
+ pinned={moveMode && !!markerLatLng}
+ copy={copyCoords}
+ reading={measure.mode ? (measure.readout ?? '') : ''}
+ hint={measure.mode && !measure.readout ? MEASURE_HINT[measure.mode] : ''}
+ >
+ <!-- What marks the point and whether it is the centre: one square, set
+ once, beside the two acts that are pressed all day. -->
+ <MarkerMenu bind:style={markerStyle} free={moveMode} toggleFree={toggleMoveMode} />
<div class="place-save">
<button
class="btn place-save-main"
@@ -1496,10 +2218,23 @@
bind:customWidth={capture.customW}
bind:customHeight={capture.customH}
bind:resolution={capture.resolution}
+ bind:scaleNorth={capture.scaleNorth}
openScreenshot={() => (capture.shotOpen = true)}
openExtensionGate={() => (capture.extGate = true)}
/>
- </div>
+ </MapStatusBar>
+ {#if pointMenu}
+ <MapContextMenu
+ at={pointMenu}
+ frame={pointMenu.frame}
+ zoom={center.zoom}
+ format={prefs.coordFormat}
+ {fullscreen}
+ lookup={pointMenu.lookup}
+ onpick={onPointMenu}
+ onclose={closePointMenu}
+ />
+ {/if}
<!-- floating reference-image windows (scratch aids over the map) -->
{#each refs.open as pane (pane.id)}
<RefViewer
@@ -1545,6 +2280,11 @@
<!-- collapsed: header acts as the toggle back to the list -->
{:else}
<div class="panel-scroll">
+ <!-- What is drawn over the imagery. One list, above the case's own
+ work: the labels and the saved pins used to be buttons in the
+ toolbox, and the handoffs floating cards over the map. -->
+ <MapLayers rows={layerRows} bind:open={layersOpen} />
+
<!-- External maps: quick jumps to maps we can't embed in-tool, at the
current target coordinates (item 6) -->
<button type="button" class="sub-head" onclick={() => (linksOpen = !linksOpen)}>
@@ -1688,7 +2428,7 @@
{#if placeModal}
<PlaceDialog
- draft={placeModal}
+ bind:draft={placeModal}
caseId={caseState.current?.id}
folders={caseState.current?.folders ?? []}
saving={placeSaving}
@@ -1703,6 +2443,33 @@
await loadPlaceRelations(placeModal?.id);
await reloadCase();
}}
+ ondetails={openPlaceDetails}
+ />
+{/if}
+
+{#if detailsEntityId}
+ <Modal title="Details" onclose={closeDetails} width="520px">
+ <EntityDetails
+ entityId={detailsEntityId}
+ bind:dirty={detailsDirty}
+ onclose={() => (detailsEntityId = null)}
+ ondeleted={() => (detailsEntityId = null)}
+ />
+ </Modal>
+{/if}
+
+{#if detailsDiscarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This place has edits that Save has not taken."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => {
+ detailsDiscarding = false;
+ detailsDirty = false;
+ detailsEntityId = null;
+ }}
+ oncancel={() => (detailsDiscarding = false)}
/>
{/if}
@@ -1725,45 +2492,6 @@
display: flex;
min-height: 0;
}
- .temporal-layer-card.stacked { top: 150px; }
- .temporal-layer-card {
- position: absolute;
- z-index: 720;
- top: 12px;
- right: 12px;
- width: min(330px, calc(100% - 90px));
- padding: 10px 12px;
- border: 1px solid var(--border-strong);
- border-radius: var(--r-md);
- background: color-mix(in srgb, var(--bg-1) 94%, transparent);
- box-shadow: var(--shadow-2);
- color: var(--text-2);
- font-size: var(--fs-xs);
- }
- .temporal-layer-card > div {
- display: flex;
- gap: 7px;
- min-width: 0;
- }
- .temporal-layer-card strong { color: var(--text-1); }
- .temporal-layer-card span {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- .temporal-layer-card p { margin: 6px 0 8px; color: var(--text-3); }
- .temporal-layer-card .error { color: var(--danger); }
- .temporal-layer-card nav { display: flex; gap: 9px; }
- .temporal-layer-card button {
- padding: 0;
- border: 0;
- background: none;
- color: var(--accent);
- font: inherit;
- cursor: pointer;
- }
- .temporal-layer-card button:hover { text-decoration: underline; }
- .temporal-layer-card .quiet { margin-left: auto; color: var(--text-3); }
.frame-overlay {
position: absolute;
top: 50%;
@@ -1815,41 +2543,6 @@
fill: currentColor;
opacity: 0.8;
}
- .pin-tag {
- font-size: 9px;
- font-weight: 700;
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--accent-text, #fff);
- background: var(--accent);
- border-radius: 3px;
- padding: 1px 4px;
- }
- .hud {
- position: absolute;
- top: 12px;
- left: 50%;
- transform: translateX(-50%);
- z-index: 600;
- display: flex;
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- }
- .hud-coords {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 7px 13px;
- font-size: var(--fs-sm);
- color: var(--text-1);
- }
- .hud-coords:hover {
- color: var(--accent);
- }
- .z {
- color: var(--text-3);
- font-size: var(--fs-xs);
- }
/* fullscreen: the whole tool covers the viewport, above the app chrome */
.tool.fullscreen {
@@ -1859,19 +2552,28 @@
background: var(--bg-0);
}
- /* top-left control cluster (fullscreen · OSM labels · measure) */
+ /* The rail, and the single slot its armed tool's settings open in. Above the
+ engine's own control corners, so a panel is never hidden behind the zoom
+ buttons — which the rail now stacks on top of rather than beside. */
.map-tools {
position: absolute;
top: 12px;
left: 12px;
- /* above the engine's own control corners so the measure panel is never
- hidden behind the zoom +/- buttons (item 7) */
z-index: 1100;
+ /* the rail sits in flow here, so this box is exactly rail-wide — which is
+ what the panel slot beside it measures its offset against */
display: flex;
flex-direction: column;
- gap: 8px;
align-items: flex-start;
}
+ /* The slot itself places; each panel dresses itself, because two of them
+ (the sun path, Grid Search) are draggable or collapsible cards of their
+ own and would have to be undressed to sit in a shared one. */
+ .mode-panel {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 8px);
+ }
/* draggable square handle for the area corners / polygon vertices */
:global(.grid-handle) {
@@ -1907,70 +2609,6 @@
white-space: nowrap;
}
- .capture-bar {
- position: absolute;
- bottom: 34px;
- /* Centred by auto margins across the full width, NOT by left:50% +
- translateX: an absolutely positioned box with `left: 50%` may only be as
- wide as the half it starts at, so the bar was being squeezed to half the
- map and cut off (or, once it could wrap, folded into a stack of rows).
- Spanning left:0/right:0 gives it the whole width to size against, and
- fit-content keeps it hugging its controls. */
- left: 0;
- right: 0;
- margin: 0 auto;
- width: fit-content;
- max-width: calc(100% - 20px);
- z-index: 600;
- display: flex;
- align-items: center;
- justify-content: center;
- /* only ever reached on a genuinely narrow map — a second row beats
- controls that are off-screen */
- flex-wrap: wrap;
- gap: 8px 10px;
- padding: 10px 12px;
- background: rgba(24, 24, 24, 0.92);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- }
- .capture-bar .select {
- width: auto;
- /* "OpenTopoMap (topographic · contour lines)" is not worth a row of bar */
- max-width: 190px;
- }
- /* billed-provider tile counter (IMAGERY_PROVIDERS.md) — full readout in Settings */
- .usage-pill {
- font-size: var(--fs-xs);
- color: var(--text-3);
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 3px 9px;
- white-space: nowrap;
- }
- .bar-sep {
- width: 1px;
- align-self: stretch;
- background: var(--border);
- margin: 0 2px;
- }
- /* eco / soft-block fallback: the billed basemap stepped aside for free imagery */
- .fallback-pill {
- display: inline-flex;
- align-items: center;
- gap: 5px;
- font-size: var(--fs-xs);
- color: var(--ok);
- background: var(--bg-2);
- border: 1px solid var(--border);
- border-radius: var(--r-sm);
- padding: 3px 9px;
- white-space: nowrap;
- }
- .fallback-pill.paused {
- color: var(--danger);
- }
.prov.dates {
display: flex;
align-items: center;
@@ -2004,7 +2642,8 @@
.btn-toggle {
white-space: nowrap;
}
- .btn-toggle.on {
+ .btn-toggle.on,
+ .btn-icon.on {
background: var(--accent);
color: var(--accent-text);
border-color: var(--accent);
@@ -2098,30 +2737,8 @@
display: flex;
flex-direction: column;
}
- .sub-head {
- display: flex;
- align-items: center;
- gap: 6px;
- width: 100%;
- padding: 12px 2px 6px;
- background: none;
- border: none;
- font: inherit;
- font-size: var(--fs-xs);
- font-weight: 600;
- letter-spacing: 0.04em;
- text-transform: uppercase;
- color: var(--text-2);
- text-align: left;
- cursor: pointer;
- }
- .sub-head:hover {
- color: var(--accent);
- }
- .sub-head .count {
- margin-left: auto;
- text-transform: none;
- }
+ /* `.sub-head` is in app.css: the Layers list writes its own heading, and the
+ two have to read as one panel. */
.links-grid {
display: grid;
grid-template-columns: 1fr 1fr;
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 94319b4..e95ae50 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -2,10 +2,8 @@ import { describe, expect, it } from 'vitest';
import { readdirSync, readFileSync } from 'node:fs';
const source = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');
-const cluster = readFileSync(
- new URL('./satellite/MapToolCluster.svelte', import.meta.url),
- 'utf8'
-);
+const rail = readFileSync(new URL('./satellite/MapRail.svelte', import.meta.url), 'utf8');
+const layers = readFileSync(new URL('./satellite/MapLayers.svelte', import.meta.url), 'utf8');
// The sky overlay's geometry moved to `lib/skyOverlay.js`, where it is exercised
// against real numbers (`skyOverlay.test.js`); the tool hands it to the map.
const sky = readFileSync(new URL('../lib/skyOverlay.js', import.meta.url), 'utf8');
@@ -39,6 +37,20 @@ describe('Satellite saved work', () => {
expect(source).not.toContain('items={savedWork.rows}');
});
+ it('opens the details dialog when a capture row is edited', () => {
+ // Edit on a capture, from the map popup or the panel, sets the row the
+ // dialog renders; a call to a helper that no longer exists fails silently.
+ const edit = source.slice(source.indexOf('function editSaved'));
+ const body = edit.slice(0, edit.indexOf('\n }'));
+ expect(body).toContain("row.kind === 'place'");
+ expect(body).toContain('notesItem = row');
+ for (const [, name] of body.matchAll(/\b(open\w+)\(/g)) {
+ expect(source, `${name} is called but never defined`).toMatch(
+ new RegExp(`function ${name}\\b|const ${name}\\b`)
+ );
+ }
+ });
+
it('loads and drops both indexes with the case, through the store', () => {
expect(source).toContain('return savedWork.load(id);');
expect(source).toContain('savedWork.loadProofs(caseState.current?.id, caseState.rev)');
@@ -68,8 +80,15 @@ describe('Satellite saved work', () => {
it('keeps the map overlay off by default and out of the case file', () => {
expect(source).toContain('let savedOverlay = $state(false)');
expect(source).toContain('{#if savedOverlay}');
- expect(cluster).toContain('savedOverlay = $bindable()');
- expect(cluster).toContain('onclick={() => (savedOverlay = !savedOverlay)}');
+ // it is a layer, listed with the other layers rather than sitting in the
+ // toolbox: nothing about it changes what the pointer does
+ expect(source).toContain('toggle: () => (savedOverlay = !savedOverlay)');
+ expect(layers).toContain('aria-pressed={Boolean(row.on)}');
+ // one eye for both states: only its colour says whether the layer is on
+ expect(layers).toContain('<Icon name="eye" size={13} />');
+ expect(layers).not.toContain("'ghost'");
+ expect(layers).toMatch(/\.eye\.on \{\s*color: var\(--accent\);/);
+ expect(rail).not.toContain('savedOverlay');
// nothing about the overlay is written back to the case — session only
expect(source).not.toContain('savedOverlay:');
});
@@ -142,10 +161,11 @@ describe('reference windows', () => {
// 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', () => {
+ it('hands one store to the rail, 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()}');
+ // a rail seat that runs rather than arms: it opens a picker and a window
+ expect(source).toContain("if (id === 'reference') return refs.openPicker();");
+ expect(source).toContain('on: refs.open.length > 0,');
expect(source).toContain('{#each refs.open as pane (pane.id)}');
expect(source).toContain('onpick={(item) => refs.add(item)}');
});
@@ -225,13 +245,16 @@ describe('sun and moon mode', () => {
// 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', () => {
+ it('is a map mode in the rail, exclusive with the others through the registry', () => {
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 (capture.armed) toggleSelect()');
- expect(source).toContain('if (grid.on) toggleGridMode()');
- expect(source).toContain('else if (sky.on) toggleSunMode()'); // the Esc cascade
+ // Exclusivity is declared once, not written out per pair: the mode says how
+ // to open and close itself and `arm()` closes whatever else was on.
+ expect(source).toContain("arm(modes, 'sky')");
+ expect(source).toContain('isOn: () => sky.on,');
+ expect(source).toContain('close: () => sky.close(),');
+ // the pairwise calls this replaced are gone, in both directions
+ expect(source).not.toContain('if (capture.armed) toggleSelect()');
+ expect(source).not.toContain('if (grid.on) toggleGridMode()');
});
it('opens on the moved pin when there is one, else on the view', () => {
@@ -286,10 +309,14 @@ describe('the capture button', () => {
expect(source).toContain('onChange: (rect) => (selRect = rect)');
});
- 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
+ it('cannot be armed at the same time as any other map mode', () => {
+ // The marquee is armed from the Capture button rather than from the rail,
+ // so it reports in to the registry instead of naming the one other mode it
+ // used to know about — which left Grid Search and the sun path open.
+ expect(source).toContain("onArm: () => closeOthers(modes, 'capture')");
+ expect(source).toContain('capture: {');
+ expect(source).toContain('close: () => capture.disarm(),');
+ // …and a measure sub-mode still puts the marquee away
expect(source).toContain('if (measure.setMode(mode)) capture.disarm()');
});
@@ -301,6 +328,170 @@ describe('the capture button', () => {
});
});
+describe('what is laid over the imagery', () => {
+ const surface = readFileSync(new URL('./satellite/MapSurface.svelte', import.meta.url), 'utf8');
+
+ it('hands the surface the list, not one flag per layer', () => {
+ // the surface puts overlays on; which are offered is the tool's business,
+ // and a second one used to mean a second prop through the same wall
+ expect(source).toContain('{overlays}');
+ expect(surface).toContain(
+ 'for (const id of OVERLAY_IDS) basemaps.setOverlay(id, asked.has(id), asked.get(id))'
+ );
+ });
+
+ it('offers the railways over any basemap and the labels only over imagery', () => {
+ // OSM's own street map already draws its labels twice; it draws a railway
+ // as one more line, which is the thing OpenRailwayMap is for
+ expect(source).toContain("osmOverlay && baseIsImagery && 'labels'");
+ expect(source).toContain("railOverlay && 'railway'");
+ const rows = source.slice(source.indexOf('const layerRows = $derived(['));
+ expect(rows.slice(0, 900)).toContain("label: 'OSM railways'");
+ expect(rows.slice(0, 900)).toContain('toggle: () => (railOverlay = !railOverlay)');
+ });
+
+ it('gives neither of them a rail seat', () => {
+ expect(rail).not.toContain('railOverlay');
+ expect(rail).not.toContain('osmOverlay');
+ });
+
+ it('fetches no railway tile until it is asked for', () => {
+ // local-first: a map that is not showing railways phones nobody
+ expect(source).toContain('let railOverlay = $state(false);');
+ });
+
+ it('reads what the fire layer can be asked without phoning NASA', () => {
+ // our own backend, reading a catalogue and a settings file: safe on mount
+ expect(source).toContain("await api.get('/api/firms/sensors')");
+ expect(source).toContain('on: false,');
+ });
+
+ it('hears about a key pasted into Settings on the way back to the tab', () => {
+ // tools stay mounted, so there is no fresh onMount to read it again — and
+ // a reload to see a layer light up is a reload nobody should need
+ const back = source.slice(source.indexOf('// re-sync providers + prefs when returning to this tab'));
+ expect(back.slice(0, 700)).toContain('loadFireSensors()');
+ });
+
+ it('offers the layer disabled, with the reason, when there is no key', () => {
+ const rows = source.slice(source.indexOf('const layerRows = $derived(['));
+ expect(rows).toContain('disabled: !fires.keyed');
+ expect(rows).toContain('Add a NASA FIRMS key in Settings → Imagery');
+ });
+
+ it('asks for no tile until the choice is one the service can answer', () => {
+ // a dated window with no date yet is the normal state of a panel someone
+ // just switched, not a request
+ expect(source).toContain("fires.on && fires.keyed && firmsAskable && { id: 'firms'");
+ expect(source).toContain('const firmsAskable = $derived(askable(fires))');
+ });
+
+ it('asks its two questions in the row rather than in a card over the map', () => {
+ expect(source).toContain('controls: fires.on && fires.keyed ? firmsControls : null');
+ const layersPanel = readFileSync(
+ new URL('./satellite/MapLayers.svelte', import.meta.url),
+ 'utf8'
+ );
+ expect(layersPanel).toContain('{#if row.controls?.length}');
+ expect(layersPanel).not.toContain('position: absolute');
+ });
+});
+
+describe('choosing which saved work is drawn', () => {
+ it('asks the layer\'s own two questions where the layer is listed', () => {
+ // the same state the Saved panel binds, so a map read here and a panel read
+ // beside it cannot disagree about what the case holds
+ expect(source).toContain('controls: savedOverlay && savedWork.rows.length ? savedFilters : null');
+ expect(source).toContain('pick: (id) => (savedWork.kind = id)');
+ expect(source).toContain("pick: (id) => (savedWork.folder = id === 'all' ? null : id)");
+ });
+
+ it('offers the folder control only where there is a choice to make', () => {
+ expect(source).toContain('if (folders.length > 1)');
+ });
+
+ it('picks folders from a list, since the analyst names them and there can be many', () => {
+ expect(source).toContain('list: true');
+ expect(layers).toContain('{#if control.list}');
+ expect(layers).toContain('onchange={(event) => control.pick(event.currentTarget.value)}');
+ });
+
+ it('stacks a setting\'s options under their label rather than trailing them', () => {
+ // right-aligned wrapping turned a handful of options into a staircase, one
+ // per line, in a panel this narrow
+ expect(layers).not.toContain('justify-content: flex-end');
+ expect(layers).not.toContain('justify-content: space-between');
+ });
+
+ it('counts what is drawn rather than what the case holds', () => {
+ expect(source).toContain('detail: savedWork.shown.length ? String(savedWork.shown.length)');
+ });
+});
+
+describe('tracing a place\'s footprint', () => {
+ it('is armed from that place\'s own card, never from the rail', () => {
+ expect(source).toContain('ontrace={startTrace}');
+ expect(source).toContain("closeOthers(modes, 'footprint')");
+ // the registry still has to know it exists, or arming it would leave a
+ // second mode waiting for the same click
+ expect(source).toContain('footprint: {');
+ });
+
+ it('owns the map click while it is tracing', () => {
+ expect(source).toContain('if (footprint.addPoint(at)) return;');
+ });
+
+ it('gives the panel slot the place it is tracing for', () => {
+ expect(source).toContain('<FootprintPanel');
+ expect(source).toContain('place={footprint.place}');
+ // and whether the shape holds that place's own pin, which is what the panel
+ // refuses on: a polygon traced beside the point describes somewhere else
+ expect(source).toContain('covers={footprint.covers}');
+ });
+});
+
+describe('the full editor, reached from the map', () => {
+ // The dialog that saves a place asks for what an analyst fills at that moment;
+ // everything else a place holds is edited in the panel every other surface opens,
+ // so the map hands over to it rather than keeping a second copy of that form.
+ const dialog = readFileSync(new URL('./satellite/PlaceDialog.svelte', import.meta.url), 'utf8');
+
+ it('is offered from the place dialog, for a place that exists', () => {
+ expect(dialog).toContain('{#if draft.id && ondetails}');
+ expect(dialog).toContain('Edit more details');
+ expect(source).toContain('ondetails={openPlaceDetails}');
+ });
+
+ it('asks before handing over would drop what was typed in the short form', () => {
+ expect(dialog).toContain('touched ? (discarding = true) : ondetails()');
+ expect(dialog).toContain('<ConfirmDialog');
+ });
+
+ it('is the same body the sidebar and the Media Library open', () => {
+ expect(source).toContain("import EntityDetails from '../components/EntityDetails.svelte'");
+ expect(source).toContain('entityId={detailsEntityId}');
+ // its fields wait for Save, so Escape and the backdrop ask first
+ expect(source).toContain('bind:dirty={detailsDirty}');
+ expect(source).toContain('onclose={closeDetails}');
+ });
+});
+
+describe('the two acts at the foot of the map', () => {
+ it('keeps the marker behind one square rather than across the strip', () => {
+ // a full-width select and a Move-pin toggle pushed Save place and Capture
+ // onto a second row, which sat on the engine's own scale bracket
+ expect(source).toContain('<MarkerMenu bind:style={markerStyle} free={moveMode}');
+ expect(source).not.toContain("title=\"Marker style\"");
+ expect(source).not.toContain('class="bar-sep"');
+ });
+
+ it('leaves the strip the two things that file something', () => {
+ const acts = source.slice(source.indexOf('<MapStatusBar'), source.indexOf('</MapStatusBar>'));
+ expect(acts).toContain('Save place');
+ expect(acts).toContain('<CaptureOptions');
+ });
+});
+
describe('accepting a proposed point from the Saved panel', () => {
it('offers it wherever the panel lists a row', () => {
// the tree and the search modal read the same index, so both offer it
@@ -397,3 +588,171 @@ describe('Satellite — the search bar', () => {
expect(source).toContain('engine.setView(item, item.zoom ?? Math.max(engine.getZoom(), 13));');
});
});
+
+describe('a map in more than one window', () => {
+ // The pure halves are `lib/hash.js` and `lib/map/view.js`, each with its own
+ // tests. What is this file's business is that the tool opens on what the
+ // address says, keeps it there, and can hand it to a second window.
+ it('opens on the view in the address rather than the saved home view', () => {
+ expect(source).toContain("const opening = splitHash(location.hash)");
+ expect(source).toContain('const openingView = readView(opening.params)');
+ expect(source).toContain('openingView?.lat != null');
+ expect(source).toContain('zoom: openingView.zoom ?? prefs.homeView.zoom,');
+ // the surface reads where it opens once, at build, so it has to be handed
+ // the same answer the tool gave `center`
+ expect(source).toContain('home={openingHome}');
+ expect(source).toContain('center = { ...openingHome };');
+ });
+
+ it('refuses a basemap the catalogue does not hold, since an address is typed', () => {
+ expect(source).toContain('if (openingView?.provider && imagery.find(openingView.provider))');
+ });
+
+ it('keeps this window\'s view in this window\'s address', () => {
+ expect(source).toContain("history.replaceState(null, '', buildHash('satellite', params))");
+ // panning is not navigating: a back button full of camera positions is worse
+ // than no history at all
+ expect(source).not.toContain('history.pushState');
+ });
+
+ it('writes nothing while another tool is open', () => {
+ const writer = source.slice(source.indexOf("if (uiState.tool !== 'satellite' || !mapReady) return;"));
+ expect(writer.slice(0, 400)).toContain('viewParams({');
+ });
+
+ it('opens a peer tab on the view it is showing, and says when refused', () => {
+ // a tab, not a popup window: it can be torn onto the second screen and put
+ // back, and it is what a browser does not refuse
+ expect(source).toContain("window.open(url, '_blank')");
+ expect(source).toContain('params.w = String(nextWindowNumber())');
+ expect(source).toContain('The browser refused a second tab');
+ });
+
+ it('greys the link until there is a second map to link to', () => {
+ // a lit button that links one tab to nothing is a button that does nothing
+ expect(source).toContain('disabled={!peerMaps}');
+ expect(source).toContain("'Open a second map tab or the extension map tools to link the views'");
+ // …and a link already on is dropped when the last peer goes
+ expect(source).toContain('if (!count) linked = false;');
+ });
+
+ it('opens that tab on the map alone', () => {
+ // the rail, the case bar and the tab strip are how you get somewhere else,
+ // and a second screen showing one map is already somewhere (lib/hash.js)
+ expect(source).toContain("params.solo = '1'");
+ });
+
+ it('numbers a detached window, and leaves the first one unnumbered', () => {
+ expect(source).toContain('const windowNumber = readWindowLabel(opening.params)');
+ expect(source).toContain('<h2>Satellite{windowNumber ? ` · ${windowNumber}` : \'\'}</h2>');
+ expect(source).toContain('if (windowNumber) document.title = `Azimut · Map ${windowNumber}`');
+ });
+
+ it('keeps saying what the tab is as it rewrites where it is pointed', () => {
+ // rewritten without it, the first pan would turn a detached map back into
+ // the whole app on the next reload
+ expect(source).toContain("if (solo) params.solo = '1';");
+ expect(source).toContain('const solo = readSolo(opening.params)');
+ });
+
+ it('follows the other tabs only while the link is pressed', () => {
+ expect(source).toContain('let linked = $state(false);');
+ expect(source).toContain('if (!linked || !engine) return;');
+ expect(source).toContain('viewLink?.send({ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing })');
+ });
+
+ it('links to the extension panels on other sites as well as to its own tabs', () => {
+ expect(source).toContain('relay: mapLinkRelay(),');
+ });
+
+ it('lets the channel go with the tool, so a closed map holds no listener', () => {
+ expect(source).toContain('viewLink?.close();');
+ });
+
+ it('survives a profile that refuses local storage', () => {
+ // the numbering is a label; losing it must not cost the window
+ const counter = source.slice(source.indexOf('function nextWindowNumber()'));
+ expect(counter.slice(0, 400)).toContain('} catch {');
+ });
+});
+
+describe('the key-less reference layers', () => {
+ it('fetches no tile from any of them until its switch is pressed', () => {
+ // local-first: a map not showing borders asks Esri nothing about borders
+ const state = source.slice(source.indexOf('const refLayers = $state({'));
+ expect(state.slice(0, 200)).not.toContain('true');
+ expect(source).toContain("const night = $state({ on: false, source: 'noaa20', day: lastNight() });");
+ });
+
+ it('asks for each by id, and the roads only over imagery like the labels', () => {
+ for (const id of ['boundaries', 'power', 'seamarks', 'gpstraces']) {
+ expect(source).toContain(`refLayers.${id} && '${id}'`);
+ }
+ expect(source).toContain("refLayers.roads && baseIsImagery && 'roads'");
+ expect(source).toContain('if (!baseIsImagery && refLayers.roads) refLayers.roads = false;');
+ });
+
+ it('asks GIBS for no night until the choice is one it can answer', () => {
+ expect(source).toContain("night.on && nightAskable && { id: 'nightlights', params: nightParams(night) }");
+ expect(source).toContain('controls: night.on ? nightControls : null');
+ });
+
+ it('warns that a dark night is not an outage by itself', () => {
+ expect(source).toContain('Cloud hides lights too, so a dark night is not an outage on its own.');
+ });
+
+ it('picks one night from a calendar bounded by the sensor’s record', () => {
+ expect(source).toContain('min: firstNight(night.source)');
+ expect(source).toContain('max: lastNight()');
+ expect(layers).toContain('{#if control.day}');
+ });
+});
+
+describe('Esri Wayback', () => {
+ it('reads the release list only once the basemap is on screen', () => {
+ // local-first: opening the tab names no release
+ expect(source).toContain('if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();');
+ });
+
+ it('reads a point’s history only while its picker is open', () => {
+ const effect = source.slice(source.indexOf('if (!wb.menuOpen || shown.provider?.id !== WAYBACK_ID) return;'));
+ expect(effect.slice(0, 300)).toContain('wb.loadChanges()');
+ });
+
+ it('puts the release on the id every tile and capture keys on', () => {
+ expect(source).toContain('imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release })');
+ expect(source).toContain('wayback={wb}');
+ });
+});
+
+describe('the right-click menu', () => {
+ it('opens on the surface’s own right-click, for the point under the cursor', () => {
+ expect(source).toContain('oncontextmenu={onMapContextMenu}');
+ expect(source).toContain('<MapContextMenu');
+ expect(source).toContain('onpick={onPointMenu}');
+ });
+
+ it('is the first thing Escape closes', () => {
+ const escape = source.slice(source.indexOf("if (e.key !== 'Escape') return;"));
+ expect(escape.slice(0, 200)).toContain('if (pointMenu) return closePointMenu();');
+ });
+
+ it('closes when the view moves out from under it', () => {
+ expect(source).toContain("return engine.on('view-settled', closePointMenu);");
+ });
+
+ it('hands each act the clicked point rather than the map centre', () => {
+ const acts = source.slice(source.indexOf('async function onPointMenu(id, value)'));
+ const body = acts.slice(0, acts.indexOf('async function lookUpPoint'));
+ expect(body).toContain('openNewPlaceAt(point)');
+ expect(body).toContain('measure.addPoint(point)');
+ expect(body).toContain('sky.handOff({ ...point');
+ expect(body).toContain('engine.setView(point');
+ expect(body).not.toContain('displayCoords');
+ });
+
+ it('drops a lookup answer that arrives after the menu moved on', () => {
+ const lookup = source.slice(source.indexOf('async function lookUpPoint(point)'));
+ expect(lookup.slice(0, 600)).toContain('if (mine !== pointLookupSeq || !pointMenu) return;');
+ });
+});
diff --git a/frontend/src/tools/Settings.render.test.js b/frontend/src/tools/Settings.render.test.js
index 25dac9f..e1ada6f 100644
--- a/frontend/src/tools/Settings.render.test.js
+++ b/frontend/src/tools/Settings.render.test.js
@@ -123,10 +123,13 @@ describe('each section', () => {
expect(text).toContain('Signature');
});
- it('Imagery draws one card per keyed provider', () => {
+ it('Imagery draws one card per key, basemap or layer', () => {
show('imagery');
- expect(pane().querySelectorAll('.cards .card').length).toBe(4);
+ // four basemaps and NASA FIRMS, which buys a layer over whichever one is
+ // showing rather than a basemap of its own
+ expect(pane().querySelectorAll('.cards .card').length).toBe(5);
expect(pane().textContent).toContain('Eco mode');
+ expect(pane().textContent).toContain('NASA FIRMS');
});
it('Templates says when there is nothing stored yet', () => {
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index b5c805b..ab8afe3 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -128,6 +128,26 @@
tierNote:
'Copernicus documents 10,000 but provisions 30,000, per account; check yours on the dashboard.',
},
+ {
+ id: 'firms',
+ label: 'NASA FIRMS',
+ gives: 'Active fire layer · live and archive',
+ cost: 'Never billed',
+ field: 'FIRMS MAP_KEY',
+ placeholder: '0123456789abcdef0123456789abcdef',
+ help: 'https://firms.modaps.eosdis.nasa.gov/api/map_key/',
+ // Not a basemap: it buys a layer laid over whichever one is showing, and
+ // nothing meters it. The card leaves out the meter, the allowance box and
+ // the eco threshold, all of which would be answering about tiles nobody
+ // is billed for.
+ metered: false,
+ steps: [
+ 'Ask for a MAP_KEY on the FIRMS page below; it arrives by email.',
+ 'One key serves both the global and the US/Canada service.',
+ ],
+ overage:
+ 'The limit is 5,000 requests per 10 minutes, which only a layer left on while panning could approach.',
+ },
];
/** Build the per-provider shape used by key and preference state. */
diff --git a/frontend/src/tools/proof/ProofCanvas.svelte b/frontend/src/tools/proof/ProofCanvas.svelte
index a195741..44ec9c6 100644
--- a/frontend/src/tools/proof/ProofCanvas.svelte
+++ b/frontend/src/tools/proof/ProofCanvas.svelte
@@ -4,7 +4,7 @@
let {
containerEl = $bindable(),
tool,
- textEdit,
+ textEdit = $bindable(),
focusSelect,
commitTextEdit,
proofHasContent,
diff --git a/frontend/src/tools/satellite/CaptureOptions.svelte b/frontend/src/tools/satellite/CaptureOptions.svelte
index 940fc41..ab4d514 100644
--- a/frontend/src/tools/satellite/CaptureOptions.svelte
+++ b/frontend/src/tools/satellite/CaptureOptions.svelte
@@ -20,6 +20,7 @@
customWidth = $bindable(),
customHeight = $bindable(),
resolution = $bindable(),
+ scaleNorth = $bindable(),
openScreenshot,
openExtensionGate,
} = $props();
@@ -157,6 +158,12 @@
</div>
<div class="menu-hint">Captures a deeper zoom for a sharper file.</div>
{/if}
+
+ <label class="menu-check">
+ <input type="checkbox" bind:checked={scaleNorth} />
+ <span>Scale bar & north arrow</span>
+ </label>
+ <div class="menu-hint last">Drawn into the capture, in your units.</div>
</div>
{/if}
</div>
@@ -229,5 +236,19 @@
.chip:hover { border-color: var(--border-strong); color: var(--text-1); }
.chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
.menu-hint { font-size: 10px; color: var(--text-3); margin: -1px 0 5px; }
+ .menu-hint.last { margin-bottom: 0; }
+ /* The one setting here that outlives the session, so it reads as a switch
+ rather than as one more chip to pick from. */
+ .menu-check {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding-top: 7px;
+ border-top: 1px solid var(--border);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .menu-check input { accent-color: var(--accent); cursor: pointer; }
.menu-row + .custom-size { justify-content: flex-end; padding: 2px 0; }
</style>
diff --git a/frontend/src/tools/satellite/FootprintPanel.svelte b/frontend/src/tools/satellite/FootprintPanel.svelte
new file mode 100644
index 0000000..56331e0
--- /dev/null
+++ b/frontend/src/tools/satellite/FootprintPanel.svelte
@@ -0,0 +1,81 @@
+<script>
+ /**
+ * Tracing a footprint, in the rail's one panel slot.
+ *
+ * It names the place the whole time it is open: the shape on the map belongs
+ * to a point somewhere else on the screen, and without the name this is a
+ * polygon being drawn for nobody.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let { place, points, complete, covers, saving, undo, save, cancel } = $props();
+
+ /** What this tracing takes the place of. A place states how tightly it is pinned
+ * once, so saving a shape drops the circle it had. */
+ const replaces = $derived.by(() => {
+ if (place?.footprint) return 'replaces its current shape';
+ const m = Number(place?.radius_m);
+ if (!(m > 0)) return '';
+ return `replaces its ${m >= 1000 ? `${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km` : `${Math.round(m)} m`} circle`;
+ });
+</script>
+
+<div class="footprint-panel card">
+ <p class="who">
+ Tracing <strong>{place?.title}</strong>
+ {#if replaces}<span class="over">{replaces}</span>{/if}
+ </p>
+ <p class="hint" class:warn={complete && !covers}>
+ {#if complete && !covers}
+ The shape has to contain the pin it belongs to.
+ {:else if complete}
+ {points} corners. Save closes the shape.
+ {:else}
+ Click the corners. {3 - points} more to make an area.
+ {/if}
+ </p>
+ <div class="acts">
+ <button class="btn btn-sm" onclick={undo} disabled={!points || saving}>
+ <Icon name="reset" size={13} /> Undo
+ </button>
+ <button class="btn btn-sm btn-primary" onclick={save} disabled={!complete || !covers || saving}>
+ {saving ? 'Saving…' : 'Save'}
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={cancel} disabled={saving}>Cancel</button>
+ </div>
+</div>
+
+<style>
+ .footprint-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ width: max-content;
+ max-width: 260px;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .who {
+ margin: 0;
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ }
+ .over {
+ display: block;
+ color: var(--text-3);
+ }
+ .hint {
+ margin: -4px 0 0;
+ font-size: 10px;
+ color: var(--text-3);
+ }
+ .hint.warn {
+ color: var(--warn);
+ }
+ .acts {
+ display: flex;
+ gap: 4px;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/GridSearchPanel.svelte b/frontend/src/tools/satellite/GridSearchPanel.svelte
index 86b1f28..53a06ac 100644
--- a/frontend/src/tools/satellite/GridSearchPanel.svelte
+++ b/frontend/src/tools/satellite/GridSearchPanel.svelte
@@ -192,9 +192,7 @@
<style>
.grid-panel {
- position: absolute;
- top: 0;
- left: calc(100% + 8px);
+ /* placed by the rail's panel slot */
width: 218px;
display: flex;
flex-direction: column;
diff --git a/frontend/src/tools/satellite/ImageryChip.svelte b/frontend/src/tools/satellite/ImageryChip.svelte
new file mode 100644
index 0000000..0e36bba
--- /dev/null
+++ b/frontend/src/tools/satellite/ImageryChip.svelte
@@ -0,0 +1,269 @@
+<script>
+ /**
+ * Which picture this surface is showing, in the surface's own corner.
+ *
+ * It used to be a native `<select>` in a bar at the foot of the tool, beside
+ * Save place and Capture — which put a property of the image in the same box
+ * as the acts that file things, and made the provider look like the tool's
+ * rather than this map's. It is the surface's: two surfaces compared side by
+ * side (SPEC v3) each show their own provider, and a chip in a shared bar
+ * could not say which was which.
+ *
+ * The eco and usage pills ride with it for the same reason. They describe the
+ * pixels being drawn here, and they are only ever true of one surface.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import SentinelPicker from './SentinelPicker.svelte';
+ import WaybackPicker from './WaybackPicker.svelte';
+ import { WAYBACK_ID } from '../../lib/wayback.js';
+ import {
+ SENTINEL_ID,
+ cloudClass,
+ cloudLabel,
+ maxccLabel,
+ monthGrid,
+ monthLabel,
+ } from '../../lib/sentinel.js';
+
+ let {
+ /** The shared catalogue and meter (state/imagery.svelte.js). */
+ imagery,
+ /** What this surface was asked to show. Changed from here. */
+ providerId = $bindable(),
+ /** This surface's Sentinel-2 choices, when that basemap is on it. */
+ s2 = null,
+ /** This surface's Wayback release, when that basemap is on it. */
+ wayback = null,
+ /** What it is actually showing — a billed base steps aside when paused. */
+ shown,
+ } = $props();
+
+ let menuOpen = $state(false);
+ let menuEl = $state();
+ let s2MenuEl = $state();
+ let wbMenuEl = $state();
+
+ const asked = $derived(imagery.find(providerId));
+ const isSentinel = $derived(asked?.id === SENTINEL_ID);
+ const isWayback = $derived(asked?.id === WAYBACK_ID);
+ const usagePill = $derived(imagery.pill(asked));
+
+ function pick(provider) {
+ if (provider.needs_key) return;
+ providerId = provider.id;
+ menuOpen = false;
+ }
+
+ // clicking outside either popover closes it
+ $effect(() => {
+ if (!menuOpen) return;
+ const outside = (e) => {
+ if (menuEl && !menuEl.contains(e.target)) menuOpen = false;
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
+
+ $effect(() => {
+ if (!s2?.menuOpen) return;
+ const outside = (e) => {
+ if (s2MenuEl && !s2MenuEl.contains(e.target)) s2.menuOpen = false;
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
+
+ $effect(() => {
+ if (!wayback?.menuOpen) return;
+ const outside = (e) => {
+ if (wbMenuEl && !wbMenuEl.contains(e.target)) wayback.menuOpen = false;
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
+</script>
+
+<div class="chip-row">
+ {#if usagePill}
+ <span class="pill mono" title="Requests to this billed provider this month">{usagePill}</span>
+ {/if}
+ {#if shown.fallenBack}
+ <span
+ class="pill fallback"
+ class:paused={shown.blocked}
+ title={shown.blocked
+ ? `${asked?.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 ${asked?.label} detail. Toggle in Settings.`}
+ >
+ <Icon name={shown.blocked ? 'alert' : 'leaf'} size={11} />
+ {shown.blocked ? 'paused · free imagery' : 'eco · free imagery'}
+ </span>
+ {/if}
+ {#if isSentinel && s2}
+ <SentinelPicker
+ bind:menuEl={s2MenuEl}
+ {s2}
+ {maxccLabel}
+ {monthLabel}
+ {monthGrid}
+ {cloudClass}
+ {cloudLabel}
+ />
+ {/if}
+ {#if isWayback && wayback}
+ <WaybackPicker bind:menuEl={wbMenuEl} wb={wayback} />
+ {/if}
+ <div class="chip-wrap" bind:this={menuEl}>
+ <button
+ class="chip"
+ class:on={menuOpen}
+ onclick={() => (menuOpen = !menuOpen)}
+ title="Imagery provider"
+ aria-label="Imagery provider"
+ aria-haspopup="listbox"
+ aria-expanded={menuOpen}
+ >
+ <Icon name="satellite" size={13} />
+ <span class="name">{asked?.label ?? '—'}</span>
+ <Icon name="more" size={12} />
+ </button>
+ {#if menuOpen}
+ <ul class="menu card" role="listbox" aria-label="Imagery provider">
+ {#each imagery.providers as provider (provider.id)}
+ <li>
+ <button
+ role="option"
+ aria-selected={provider.id === providerId}
+ class="row"
+ class:on={provider.id === providerId}
+ disabled={provider.needs_key}
+ onclick={() => pick(provider)}
+ title={provider.needs_key ? 'Add this provider’s API key in Settings' : undefined}
+ >
+ <span class="tick">
+ {#if provider.id === providerId}<Icon name="check" size={12} />{/if}
+ </span>
+ <!-- not `label`: that class is the app's form-label voice, in
+ small caps and letterspaced, and it turned every basemap name
+ into a heading three lines tall -->
+ <span class="name">{provider.label}</span>
+ {#if provider.needs_key}<span class="need">needs key</span>{/if}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .chip-row {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .chip-wrap {
+ position: relative;
+ }
+ .chip {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: 30px;
+ padding: 0 8px;
+ 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);
+ box-shadow: 0 0 0 1px var(--border);
+ cursor: pointer;
+ }
+ .chip:hover,
+ .chip.on {
+ color: var(--accent);
+ }
+ .chip .name {
+ max-width: 160px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .menu {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ z-index: 20;
+ /* wide enough for the longest basemap name on one line: the list is read
+ by shape as much as by word, and a wrapped row breaks the column */
+ min-width: 244px;
+ max-height: 60vh;
+ overflow-y: auto;
+ padding: 4px;
+ margin: 0;
+ list-style: none;
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 5px 8px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ text-align: left;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .row:hover:not(:disabled) {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .row.on {
+ color: var(--accent);
+ }
+ .row:disabled {
+ color: var(--text-3);
+ cursor: not-allowed;
+ }
+ /* one column, so the names line up whether or not a row is the live one */
+ .tick {
+ display: grid;
+ place-items: center;
+ width: 13px;
+ }
+ .row .name {
+ flex: 1;
+ }
+ .need {
+ padding: 1px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ font-size: 10px;
+ color: var(--text-3);
+ }
+ .pill {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ height: 22px;
+ padding: 0 7px;
+ border-radius: var(--r-sm, 4px);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ }
+ .pill.fallback {
+ color: var(--ok);
+ }
+ .pill.paused {
+ color: var(--warn);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapContextMenu.svelte b/frontend/src/tools/satellite/MapContextMenu.svelte
new file mode 100644
index 0000000..3b2401d
--- /dev/null
+++ b/frontend/src/tools/satellite/MapContextMenu.svelte
@@ -0,0 +1,225 @@
+<script>
+ /**
+ * The right-click menu: what can be done with the point under the cursor.
+ *
+ * It lives inside the map surface and is placed against it, so it travels
+ * with a detached window and is hidden with the rest of the chrome during a
+ * screen grab. The list and the placement are `lib/map/contextMenu.js`; the
+ * acts are the tool's, reported through `onpick`.
+ */
+ import { onMount } from 'svelte';
+ import Icon from '../../components/Icon.svelte';
+ import { ACTIONS, copyRows, nextFocus, openRows, placeMenu } from '../../lib/map/contextMenu.js';
+
+ let {
+ /** `{ lat, lon, x, y }`: the point, and where it was clicked in the map. */
+ at,
+ /** The map's own size, which the menu must stay inside. */
+ frame = { width: 0, height: 0 },
+ zoom = 17,
+ /** The analyst's coordinate format, offered first. */
+ format = 'dd',
+ /** A link out would drop the map out of fullscreen, so links are greyed. */
+ fullscreen = false,
+ /** `{ busy, text, error }` once "What is here?" was asked. */
+ lookup = null,
+ /** `(id, value)`: `copy` with the text, or an action id from `ACTIONS`. */
+ onpick,
+ onclose,
+ } = $props();
+
+ let menuEl = $state();
+ let width = $state(0);
+ let height = $state(0);
+ let linksOpen = $state(false);
+
+ const copies = $derived(copyRows(at.lat, at.lon, format));
+ const links = $derived(openRows(at.lat, at.lon, zoom));
+ // Measured once drawn; until then a typical size keeps the first frame inside.
+ const place = $derived(
+ placeMenu(at, { width: width || 236, height: height || 320 }, frame)
+ );
+
+ function items() {
+ return [...(menuEl?.querySelectorAll('[role="menuitem"]') ?? [])];
+ }
+
+ function onkeydown(event) {
+ const rows = items();
+ const current = rows.indexOf(document.activeElement);
+ const move = { ArrowDown: 1, ArrowUp: -1 }[event.key];
+ if (move) {
+ event.preventDefault();
+ const next = nextFocus(rows.length, current, move, (i) => rows[i].hasAttribute('disabled'));
+ rows[next]?.focus();
+ } else if (event.key === 'Home' || event.key === 'End') {
+ event.preventDefault();
+ (event.key === 'Home' ? rows[0] : rows.at(-1))?.focus();
+ } else if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ onclose();
+ } else if (event.key === 'Tab') {
+ // a menu is left, not tabbed through
+ onclose();
+ }
+ }
+
+ onMount(() => {
+ items()[0]?.focus();
+ const outside = (event) => {
+ if (menuEl && !menuEl.contains(event.target)) onclose();
+ };
+ document.addEventListener('mousedown', outside, true);
+ return () => document.removeEventListener('mousedown', outside, true);
+ });
+</script>
+
+<div
+ class="ctx card"
+ role="menu"
+ tabindex="-1"
+ aria-label="This point"
+ bind:this={menuEl}
+ bind:offsetWidth={width}
+ bind:offsetHeight={height}
+ style:left={`${place.left}px`}
+ style:top={`${place.top}px`}
+ {onkeydown}
+ oncontextmenu={(event) => event.preventDefault()}
+>
+ {#each copies as row (row.id)}
+ <button
+ class="item copy"
+ role="menuitem"
+ title="Copy {row.format}"
+ onclick={() => onpick('copy', row.text)}
+ >
+ <span class="fmt">{row.format}</span>
+ <span class="mono coords">{row.text}</span>
+ <Icon name="copy" size={12} />
+ </button>
+ {/each}
+
+ <div class="rule" role="separator"></div>
+
+ {#each ACTIONS as action (action.id)}
+ <button class="item" role="menuitem" onclick={() => onpick(action.id)}>
+ <Icon name={action.icon} size={13} />
+ <span>{action.label}</span>
+ </button>
+ {#if action.id === 'lookup' && lookup}
+ <p class="answer" class:dim={lookup.busy} class:warn={lookup.error} aria-live="polite">
+ {lookup.busy ? 'Looking it up…' : (lookup.error ?? lookup.text)}
+ </p>
+ {/if}
+ {/each}
+
+ <div class="rule" role="separator"></div>
+
+ <button
+ class="item"
+ role="menuitem"
+ aria-expanded={linksOpen}
+ onclick={() => (linksOpen = !linksOpen)}
+ >
+ <Icon name="external" size={13} />
+ <span>Open in…</span>
+ <Icon name={linksOpen ? 'chevronDown' : 'chevronRight'} size={12} />
+ </button>
+ {#if linksOpen}
+ <div class="links">
+ {#each links as link (link.id)}
+ <a
+ class="item link"
+ role="menuitem"
+ href={fullscreen ? undefined : link.url}
+ target="_blank"
+ rel="noreferrer"
+ aria-disabled={fullscreen}
+ title={fullscreen ? 'Exit fullscreen first. This leaves the map' : link.url}
+ onclick={() => !fullscreen && onclose()}
+ >{link.label}</a>
+ {/each}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .ctx {
+ position: absolute;
+ z-index: 800;
+ min-width: 220px;
+ max-width: 300px;
+ padding: 4px;
+ display: flex;
+ flex-direction: column;
+ background: rgba(24, 24, 24, 0.97);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ outline: none;
+ }
+ .item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 5px 8px;
+ border-radius: var(--radius-1);
+ font-size: var(--fs-sm);
+ color: var(--text-2);
+ text-align: left;
+ text-decoration: none;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .item > span:not(.fmt) {
+ flex: 1;
+ }
+ .item:hover,
+ .item:focus-visible {
+ background: var(--bg-3);
+ color: var(--text-1);
+ outline: none;
+ }
+ .fmt {
+ min-width: 34px;
+ font-size: 10px;
+ color: var(--text-3);
+ }
+ .coords {
+ font-size: var(--fs-xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .rule {
+ height: 1px;
+ margin: 4px 6px;
+ background: var(--border);
+ }
+ .answer {
+ margin: 0 8px 4px 29px;
+ font-size: var(--fs-xs);
+ line-height: 1.35;
+ color: var(--text-1);
+ white-space: normal;
+ }
+ .answer.dim {
+ color: var(--text-3);
+ }
+ .answer.warn {
+ color: var(--warn, #e2a03f);
+ }
+ .links {
+ display: flex;
+ flex-direction: column;
+ padding-left: 21px;
+ }
+ .link {
+ font-size: var(--fs-xs);
+ }
+ .link[aria-disabled='true'] {
+ color: var(--text-3);
+ cursor: not-allowed;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapContextMenu.test.js b/frontend/src/tools/satellite/MapContextMenu.test.js
new file mode 100644
index 0000000..0156d6e
--- /dev/null
+++ b/frontend/src/tools/satellite/MapContextMenu.test.js
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import MapContextMenu from './MapContextMenu.svelte';
+
+function props(overrides = {}) {
+ return {
+ at: { lat: 50.4501, lon: 30.5234, x: 120, y: 80 },
+ frame: { width: 1000, height: 700 },
+ zoom: 17,
+ format: 'dd',
+ fullscreen: false,
+ lookup: null,
+ onpick: vi.fn(),
+ onclose: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe('the right-click menu', () => {
+ it('is a menu of the point clicked, placed where it was clicked', () => {
+ const { body } = render(MapContextMenu, { props: props() });
+ expect(body).toContain('role="menu"');
+ expect(body).toContain('left: 120px');
+ expect(body).toContain('top: 80px');
+ expect(body).toMatch(/50\.4501/);
+ });
+
+ it('offers the point in every format and every act on it', () => {
+ const { body } = render(MapContextMenu, { props: props() });
+ for (const text of [
+ 'DD',
+ 'DMS',
+ 'MGRS',
+ 'What is here?',
+ 'Save place here…',
+ 'Measure from here',
+ 'Sun and moon from here',
+ 'Imagery history here',
+ 'Centre the map here',
+ 'Open in…',
+ ]) {
+ expect(body).toContain(text);
+ }
+ });
+
+ it('keeps the links folded until asked, so the menu opens short', () => {
+ const { body } = render(MapContextMenu, { props: props() });
+ expect(body).not.toContain('Google Earth');
+ });
+
+ it('states the lookup where it was asked, while it runs and once it answered', () => {
+ expect(
+ render(MapContextMenu, { props: props({ lookup: { busy: true } }) }).body
+ ).toContain('Looking it up…');
+ expect(
+ render(MapContextMenu, { props: props({ lookup: { text: 'Maidan Nezalezhnosti, Kyiv' } }) }).body
+ ).toContain('Maidan Nezalezhnosti, Kyiv');
+ expect(
+ render(MapContextMenu, { props: props({ lookup: { error: 'Lookup failed: offline' } }) }).body
+ ).toContain('Lookup failed: offline');
+ });
+});
diff --git a/frontend/src/tools/satellite/MapLayers.svelte b/frontend/src/tools/satellite/MapLayers.svelte
new file mode 100644
index 0000000..d3a59a6
--- /dev/null
+++ b/frontend/src/tools/satellite/MapLayers.svelte
@@ -0,0 +1,272 @@
+<script>
+ /**
+ * What is drawn over the imagery, listed in one place.
+ *
+ * Before, a layer was wherever it had been added: OSM labels and the case's
+ * saved pins were buttons in the toolbox, a sheet's points and a Timeline
+ * window were cards floating over the map with their own close buttons, and
+ * nothing said they were the same kind of thing. They are: each is something
+ * laid over the picture, on or off, and none of them changes what the pointer
+ * does.
+ *
+ * A handoff layer — points another tool sent here — appears in the list when
+ * it arrives and leaves when it is closed, so the panel never shows a switch
+ * for something that is not there.
+ */
+ import DayPicker from '../../components/DayPicker.svelte';
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ /**
+ * `{ id, label, on, disabled, title, detail, toggle }`, plus three that
+ * only some layers carry: `actions` (buttons under the row), `controls`
+ * (its own settings, for a layer that is a question) and `note` (why it is
+ * on but drawing nothing yet).
+ */
+ rows,
+ open = $bindable(true),
+ } = $props();
+
+ const live = $derived(rows.filter((row) => row.on && !row.disabled).length);
+</script>
+
+<button type="button" class="sub-head" onclick={() => (open = !open)}>
+ <Icon name={open ? 'chevronDown' : 'chevronRight'} size={12} />
+ <Icon name="stack" size={13} />
+ <span>Layers</span>
+ <span class="count">{live}</span>
+</button>
+
+{#if open}
+ <ul class="layers">
+ {#each rows as row (row.id)}
+ <li>
+ <div class="row">
+ <button
+ type="button"
+ class="eye"
+ class:on={row.on}
+ disabled={row.disabled}
+ aria-pressed={Boolean(row.on)}
+ aria-label={row.label}
+ title={row.title ?? row.label}
+ onclick={row.toggle}
+ >
+ <Icon name="eye" size={13} />
+ </button>
+ <span class="name" class:off={!row.on || row.disabled}>{row.label}</span>
+ {#if row.detail}<span class="detail">{row.detail}</span>{/if}
+ </div>
+ <!-- A layer that is a question answers it here, under its own switch:
+ a card floating over the map is what the whole rework took away,
+ and a layer's settings are not a mode's panel. -->
+ {#if row.controls?.length}
+ <div class="settings">
+ {#each row.controls as control (control.label)}
+ <div class="setting">
+ <span class="setting-label">{control.label}</span>
+ <!-- A fixed handful of short answers reads as chips; an
+ open-ended list the analyst named themselves does not, and
+ wrapped one folder per line it stopped reading as a
+ control at all. -->
+ {#if control.list}
+ <select
+ class="select pick"
+ aria-label={control.label}
+ value={control.value}
+ onchange={(event) => control.pick(event.currentTarget.value)}
+ >
+ {#each control.options as option (option.id)}
+ <option value={option.id} title={option.title ?? option.label}
+ >{option.label}</option
+ >
+ {/each}
+ </select>
+ {:else}
+ <div class="chips">
+ {#each control.options as option (option.id)}
+ <button
+ class="chip"
+ class:on={control.value === option.id}
+ title={option.title ?? option.label}
+ onclick={() => control.pick(option.id)}
+ >{option.label}</button>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ <!-- Stacked, not side by side: two date fields do not fit the
+ width of this panel. The calendar is ours and opens in flow,
+ because the browser's own opened over the map and half
+ outside the window in a panel docked to this edge. -->
+ {#if control.day}
+ <div class="date">
+ <span>{control.day.label}</span>
+ <DayPicker
+ value={control.day.value}
+ min={control.day.min}
+ max={control.day.max}
+ label={control.day.title}
+ placeholder="Pick a day"
+ onpick={(day) => control.day.set(day)}
+ />
+ </div>
+ {/if}
+ {#if control.dates}
+ <div class="date">
+ <span>From</span>
+ <DayPicker
+ value={control.dates.first}
+ max={control.dates.today}
+ label="First day of detections to draw"
+ placeholder="Pick a day"
+ onpick={(day) => control.dates.setFirst(day)}
+ />
+ </div>
+ <div class="date">
+ <span>To</span>
+ <DayPicker
+ value={control.dates.last}
+ min={control.dates.first}
+ max={control.dates.max}
+ label="Last day; blank draws the first day alone"
+ placeholder="That day alone"
+ clearable
+ onpick={(day) => control.dates.setLast(day)}
+ />
+ </div>
+ {/if}
+ {/each}
+ </div>
+ {/if}
+ {#if row.note}
+ <p class="note">{row.note}</p>
+ {/if}
+ {#if row.actions?.length}
+ <nav class="acts" aria-label={row.label}>
+ {#each row.actions as act (act.label)}
+ <button class="btn btn-sm" class:quiet={act.quiet} onclick={act.run}>{act.label}</button>
+ {/each}
+ </nav>
+ {/if}
+ </li>
+ {/each}
+ </ul>
+{/if}
+
+<style>
+ .layers {
+ margin: 0 0 10px;
+ padding: 0 4px;
+ list-style: none;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 26px;
+ }
+ .eye {
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border-radius: var(--radius-1);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .eye:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ .eye.on {
+ color: var(--accent);
+ }
+ .eye:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .name {
+ flex: 1;
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ }
+ .name.off {
+ color: var(--text-3);
+ }
+ .detail {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .acts {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 2px 0 6px 30px;
+ }
+ /* indented under the switch they belong to, so the list still reads as a
+ list of layers rather than as a stack of panels */
+ .settings {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ padding: 2px 0 6px 30px;
+ }
+ .setting {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .setting-label {
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ }
+ /* the global .select is sized for a form, not for a panel docked over a map,
+ and left to itself it draws in the platform's font beside our own chips */
+ .pick {
+ padding: 4px 7px;
+ font-family: inherit;
+ font-size: 11px;
+ }
+ .chip {
+ padding: 3px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: 10px;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .chip:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .date {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .date span {
+ width: 34px;
+ padding-top: 4px;
+ }
+ .note {
+ margin: 0;
+ padding: 0 0 6px 30px;
+ font-size: 10px;
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapRail.svelte b/frontend/src/tools/satellite/MapRail.svelte
new file mode 100644
index 0000000..ff78f89
--- /dev/null
+++ b/frontend/src/tools/satellite/MapRail.svelte
@@ -0,0 +1,108 @@
+<script>
+ /**
+ * The map's toolbox: one strip, built from the registry (`lib/map/tools.js`).
+ *
+ * It replaced three stacked cards — a tool cluster, a view cluster and the
+ * engine's zoom buttons — which between them mixed what the pointer does with
+ * what the map shows. Only verbs live here now; what is *drawn* over the
+ * imagery is a layer and belongs in the panel on the right.
+ *
+ * The strip floats over the map rather than docking against the body's left
+ * edge, and that is deliberate twice over. The app already has a rail at that
+ * edge, and a second one flush beside it reads as one confused column. And
+ * chrome that lives inside the map surface travels with the surface: a
+ * detached window and (SPEC v3) a second compare surface get their own rail
+ * with no work, which a body-level toolbar would not give them.
+ *
+ * Height is reported out through `clientHeight` because the engine's own zoom
+ * buttons are stacked underneath it (`--map-controls-top`, see `engine.css`),
+ * and a rail that grows by a tool must push them down rather than be drawn on
+ * top of them.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ /** `railSections(...)` — the entries, cut into the groups it rules between. */
+ sections,
+ /** Per entry: `{ on, disabled, title }`, built by the host from its stores. */
+ state = {},
+ /** An entry was pressed. Arming, and the exclusion, are the host's. */
+ onpick,
+ /** The strip's own height, for whatever is stacked beneath it. */
+ height = $bindable(0),
+ } = $props();
+</script>
+
+<div class="rail card" bind:clientHeight={height}>
+ {#each sections as section, index (section.group)}
+ {#if index > 0}<div class="rule" aria-hidden="true"></div>{/if}
+ {#each section.entries as entry (entry.id)}
+ {@const is = state[entry.id] ?? {}}
+ <button
+ class="seat"
+ class:on={is.on}
+ disabled={is.disabled}
+ aria-pressed={entry.kind === 'mode' ? Boolean(is.on) : undefined}
+ onclick={() => onpick(entry.id)}
+ title={is.title ?? entry.hint ?? entry.label}
+ aria-label={entry.label}
+ >
+ <Icon name={entry.icon} size={16} />
+ </button>
+ {/each}
+ {/each}
+</div>
+
+<style>
+ /* In flow inside the tool's own corner (`.map-tools`), not positioned: the
+ panel slot beside it is placed at `left: 100%` of that corner, and an
+ absolutely positioned rail would leave it measuring against nothing and
+ slide the panel over the map. */
+ .rail {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 3px;
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ }
+ /* the whole of the rail's grammar: one line between two kinds of work */
+ .rule {
+ height: 1px;
+ margin: 2px 3px;
+ background: var(--border);
+ }
+ .seat {
+ position: relative;
+ display: grid;
+ place-items: center;
+ width: 30px;
+ height: 30px;
+ border-radius: var(--radius-1);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .seat:hover:not(:disabled) {
+ color: var(--text-1);
+ background: var(--bg-3);
+ }
+ /* Armed reads as an edge, not as a filled button: the accent is the app's
+ selection colour, and a rail of amber squares would spend it on chrome. */
+ .seat.on {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .seat.on::before {
+ content: '';
+ position: absolute;
+ top: 5px;
+ bottom: 5px;
+ left: -3px;
+ width: 2px;
+ background: var(--accent);
+ }
+ .seat:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapStatusBar.svelte b/frontend/src/tools/satellite/MapStatusBar.svelte
new file mode 100644
index 0000000..0acba41
--- /dev/null
+++ b/frontend/src/tools/satellite/MapStatusBar.svelte
@@ -0,0 +1,139 @@
+<script>
+ /**
+ * The instrument's status line: where you are, what the armed tool is
+ * reading, and the two acts that take something away from the map.
+ *
+ * It gathers what used to be three separate boxes — a coordinate HUD floating
+ * at the top, a measure reading inside the measure panel, and a bottom bar
+ * that mixed the imagery provider (a property of the picture, now a chip on
+ * the surface itself) with Save place and Capture (acts). One rule sorts
+ * them: a number the map is telling you reads on the left, an act that files
+ * something reads on the right.
+ *
+ * There is no band across the map. Two groups sit on one line with nothing
+ * painted between them, so the strip costs the map two corners rather than a
+ * full-width stripe.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ /** Formatted coordinates, already in the analyst's own unit. */
+ coords,
+ zoom,
+ /** The marker is off the centre and draggable, so the coordinates are its. */
+ pinned = false,
+ copy,
+ /** What the armed tool is reading right now, and its prompt when it has none. */
+ reading = '',
+ hint = '',
+ /** The acts: the host owns them, because it owns what they file. */
+ children,
+ } = $props();
+</script>
+
+<div class="status">
+ <div class="readouts card">
+ <button class="hud-coords mono" onclick={copy} title="Copy coordinates">
+ <Icon name="crosshair" size={13} />
+ {coords}
+ <span class="z">z{zoom}</span>
+ {#if pinned}<span class="pin-tag">pin</span>{/if}
+ <Icon name="copy" size={12} />
+ </button>
+ {#if reading || hint}
+ <span class="rule" aria-hidden="true"></span>
+ {#if reading}
+ <span class="measure-value mono">{reading}</span>
+ {:else}
+ <span class="hint">{hint}</span>
+ {/if}
+ {/if}
+ </div>
+ <div class="acts">
+ {@render children?.()}
+ </div>
+</div>
+
+<style>
+ .status {
+ position: absolute;
+ /* clear of the engine's own bottom line: the scale bracket under the
+ coordinates on one side, the tile credits on the other */
+ bottom: 34px;
+ left: 12px;
+ right: 12px;
+ z-index: 600;
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 10px;
+ /* only reached on a genuinely narrow map — a second row beats controls that
+ are off-screen */
+ flex-wrap: wrap;
+ pointer-events: none;
+ }
+ .status > * {
+ pointer-events: auto;
+ }
+ .readouts {
+ display: flex;
+ align-items: center;
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ }
+ .hud-coords {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 7px 13px;
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ cursor: pointer;
+ }
+ .hud-coords:hover {
+ color: var(--accent);
+ }
+ .z {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .pin-tag {
+ padding: 1px 4px;
+ border-radius: 3px;
+ font-family: var(--font-sans);
+ font-size: 9px;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--accent-text);
+ background: var(--accent);
+ }
+ .rule {
+ align-self: stretch;
+ width: 1px;
+ margin: 5px 0;
+ background: var(--border);
+ }
+ .measure-value {
+ padding: 0 13px;
+ font-size: var(--fs-sm);
+ font-weight: 700;
+ color: var(--accent);
+ }
+ .hint {
+ padding: 0 13px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ }
+ .acts {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px 10px;
+ padding: 8px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-lg, 6px);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelte
index 78118b4..0a7bad7 100644
--- a/frontend/src/tools/satellite/MapSurface.svelte
+++ b/frontend/src/tools/satellite/MapSurface.svelte
@@ -24,19 +24,25 @@
*/
import { onMount, tick } from 'svelte';
import { createMapEngine } from '../../lib/map/engine.js';
- import { createBasemaps } from '../../lib/map/basemap.js';
+ import { createBasemaps, OVERLAY_IDS } from '../../lib/map/basemap.js';
import { DEFAULT_LAYER, DEFAULT_MAXCC, SENTINEL_ID } from '../../lib/sentinel.js';
import Icon from '../../components/Icon.svelte';
+ import ImageryChip from './ImageryChip.svelte';
let {
/** The shared catalogue + meter (state/imagery.svelte.js). */
imagery,
- /** The basemap this surface is asked to show. */
- providerId,
+ /** The basemap this surface is asked to show. Changed from its own chip:
+ * which picture is on screen is the surface's, not the tool's. */
+ providerId = $bindable(),
/** 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,
+ /** This surface's Wayback release (state/wayback.svelte.js), likewise. */
+ wayback = null,
+ /** What is laid over the imagery: an id (`OVERLAY_IDS`), or `{ id, params }`
+ * for one whose address is a question — FIRMS's sensor and window. The
+ * tool decides which are offered; the surface only puts them on. */
+ overlays = [],
/** Scale bar in miles rather than metres. */
imperial = false,
/** The view the map opens on. Read once, at build. */
@@ -51,12 +57,17 @@
ready = $bindable(false),
refused = $bindable(false),
/** A mode armed above the map, which the cursor says: 'measuring' |
- * 'selecting' | 'grid-drawing' | null. */
+ * 'selecting' | 'grid-drawing' | 'tracing' | null. */
armed = null,
/** Hide this surface's own chrome for a screen capture. */
grabbing = false,
+ /** How far down the engine's zoom buttons start, so they stack under
+ * whatever the tool floats in the same corner (see `engine.css`). */
+ controlsTop = 58,
/** A click on the map, `{ lat, lon }`. */
onclick = () => {},
+ /** A right-click on the ground, `{ lat, lon, x, y }` in this surface's pixels. */
+ oncontextmenu = () => {},
/** 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
@@ -82,7 +93,12 @@
* 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));
+ const shown = $derived(
+ imagery.displayed(providerId, view.zoom, {
+ ...(s2?.variant ?? {}),
+ release: wayback?.release ?? null,
+ })
+ );
/** A pinned Sentinel-2 day *is* the acquisition date — the one provider that
* can answer "when was this taken?" without being asked. */
@@ -138,7 +154,7 @@
onWidgetFailed: onwidgetfailed,
});
showBasemap();
- basemaps.setLabels(labels);
+ showOverlays();
// 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) => {
@@ -148,11 +164,13 @@
bearing = Math.round(turned.bearing);
});
const offClick = engine.on('click', (at) => onclick(at));
+ const offMenu = engine.on('contextmenu', (at) => oncontextmenu(at));
ready = true;
return () => {
offSettled();
offRotate();
offClick();
+ offMenu();
basemaps.dispose();
engine.destroy();
engine = null;
@@ -172,11 +190,22 @@
showBasemap();
});
+ function showOverlays() {
+ const asked = new Map(
+ overlays.map((entry) =>
+ typeof entry === 'string' ? [entry, null] : [entry.id, entry.params ?? null]
+ )
+ );
+ for (const id of OVERLAY_IDS) basemaps.setOverlay(id, asked.has(id), asked.get(id));
+ }
+
$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);
+ // Read whole, before the guard, and deeply: `basemaps?.` would short-circuit
+ // the dependency away while the map is still being built, and a toggle would
+ // then never reach the layers again (build() applies the opening state). A
+ // layer that carries a question re-reads when the question changes.
+ JSON.stringify(overlays);
+ if (basemaps) showOverlays();
});
// debounce: the target moves a lot while panning — only ask once it settles
@@ -229,7 +258,9 @@
class:measuring={armed === 'measuring'}
class:selecting={armed === 'selecting'}
class:grid-drawing={armed === 'grid-drawing'}
+ class:tracing={armed === 'tracing'}
class:grabbing
+ style:--map-controls-top={`${controlsTop}px`}
>
<div class="map" bind:this={mapEl}></div>
@@ -239,8 +270,16 @@
{@render children?.()}
- <!-- imagery acquisition date: a compact, unobtrusive pill in the corner so it
- doesn't crowd the tool's own readouts -->
+ <!-- The picture this surface is showing, when it was taken, and the compass
+ reading how it is turned: all facts about this map and belonging to it,
+ which is what lets two surfaces sit side by side each saying its own. -->
+ <div class="surface-ctl">
+ <ImageryChip {imagery} bind:providerId {s2} {wayback} {shown} />
+
+ <!-- …and when the pixels under the crosshair were taken. Under the provider
+ rather than in the opposite corner: it describes that same picture, and
+ the corner it used to sit in is the instrument's, where the scale bracket
+ reads. -->
{#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
@@ -280,20 +319,27 @@
</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">
+ <!-- Which way is up, as one reading: the needle resets north, the number
+ opens for an exact angle. Middle-dragging the map is what turns it. -->
+ <div class="rotate-ctl" class:turned={bearing !== 0}>
<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 width="15" height="15" viewBox="0 0 16 16" style="transform: rotate({bearing}deg)">
+ <!-- A needle, not a rose: the outline is the whole instrument and the
+ filled half is north. Two colours and a disc read as decoration. -->
+ <path
+ d="M8 1.6 11.7 14 8 10.9 4.3 14Z"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="1.3"
+ stroke-linejoin="round"
+ />
+ <path d="M8 1.6 11.7 14 8 10.9Z" fill="currentColor" />
</svg>
- <span class="n">N</span>
</button>
{#if editingBearing}
<!-- svelte-ignore a11y_autofocus -->
@@ -316,6 +362,7 @@
{bearing}°
</button>
{/if}
+ </div>
</div>
</div>
@@ -359,15 +406,12 @@
}
.map-wrap.measuring :global(.map-surface),
.map-wrap.selecting :global(.map-surface),
- .map-wrap.grid-drawing :global(.map-surface) {
+ .map-wrap.grid-drawing :global(.map-surface),
+ .map-wrap.tracing :global(.map-surface) {
cursor: crosshair;
}
- /* imagery date: small, low-contrast pill tucked into the bottom-left corner */
+ /* imagery date: small, low-contrast pill riding under the provider it dates */
.date-pill {
- position: absolute;
- bottom: 12px;
- left: 12px;
- z-index: 600;
display: flex;
align-items: center;
gap: 5px;
@@ -377,12 +421,13 @@
color: var(--text-3);
background: rgba(24, 24, 24, 0.7);
backdrop-filter: blur(6px);
- pointer-events: none;
+ box-shadow: 0 0 0 1px var(--border);
}
/* 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);
+ color: var(--text-2);
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--ok, #46a758) 55%, transparent);
}
.date-pill .tag {
font-family: var(--font-sans);
@@ -398,58 +443,57 @@
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 {
+ /* the surface's own corner: what it is showing, then how it is turned */
+ .surface-ctl {
position: absolute;
top: 12px;
right: 12px;
z-index: 600;
display: flex;
flex-direction: column;
- align-items: center;
- gap: 4px;
+ align-items: flex-end;
+ gap: 8px;
+ /* the column is only as wide as its widest control, so the map stays
+ grabbable everywhere the controls are not */
+ pointer-events: none;
+ }
+ .surface-ctl > :global(*) {
+ pointer-events: auto;
+ }
+ /* The needle and its angle are one reading, so they are one control, built
+ like the chips above it: same fill, same 1px ring, same height. The disc
+ and the two-tone rose it replaces read as an ornament on an instrument
+ panel, and were the only round thing on the map. */
+ .rotate-ctl {
+ display: flex;
+ align-items: stretch;
+ height: 30px;
+ border-radius: var(--radius-1);
+ background: rgba(24, 24, 24, 0.88);
+ backdrop-filter: blur(6px);
+ box-shadow: 0 0 0 1px var(--border);
+ }
+ /* north-up is the resting state and says nothing; a turned map is a fact
+ worth seeing from across the screen */
+ .rotate-ctl.turned {
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--accent) 50%, transparent);
}
.compass {
- position: relative;
display: grid;
place-items: center;
- width: 38px;
- height: 38px;
+ width: 30px;
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);
+ min-width: 42px;
+ padding: 0 7px 0 5px;
+ text-align: left;
font-size: var(--fs-xs);
color: var(--text-1);
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
cursor: text;
}
.deg:hover {
@@ -457,7 +501,9 @@
}
.deg-input {
width: 52px;
- padding: 2px 4px;
- text-align: center;
+ padding: 0 4px;
+ border: none;
+ background: none;
+ text-align: left;
font-size: var(--fs-xs);
}</style>
diff --git a/frontend/src/tools/satellite/MapToolCluster.svelte b/frontend/src/tools/satellite/MapToolCluster.svelte
deleted file mode 100644
index f8057f6..0000000
--- a/frontend/src/tools/satellite/MapToolCluster.svelte
+++ /dev/null
@@ -1,179 +0,0 @@
-<script>
- import Icon from '../../components/Icon.svelte';
-
- let {
- fullscreen,
- toggleFullscreen,
- osmOverlay = $bindable(),
- baseIsImagery,
- toolsOpen,
- measureMode,
- toggleTools,
- gridMode,
- toggleGridMode,
- savedOverlay = $bindable(),
- savedCount,
- referenceCount,
- openRefPicker,
- setMeasureMode,
- sunMode,
- toggleSunMode,
- measureReadout,
- measureHint,
- clearMeasure,
- } = $props();
-</script>
-
-<!-- Tools: things that change what you are *doing* on the map. -->
-<div class="tool-cluster card">
- <button
- class="mtbtn"
- class:on={toolsOpen || measureMode}
- onclick={toggleTools}
- title="Measure tools"
- aria-label="Measure tools"
- ><Icon name="ruler" size={16} /></button>
- <button
- class="mtbtn"
- class:on={gridMode}
- onclick={toggleGridMode}
- title="Sweep an area cell by cell"
- aria-label="Grid Search"
- ><Icon name="grid" size={16} /></button>
- <button
- class="mtbtn"
- class:on={sunMode}
- onclick={toggleSunMode}
- title="Sun and moon path for a date"
- aria-label="Sun and moon"
- ><Icon name="sun" size={16} /></button>
- <button
- class="mtbtn"
- class:on={referenceCount}
- onclick={openRefPicker}
- title="Add a reference image or video over the map"
- aria-label="Add reference"
- ><Icon name="image" size={16} /></button>
-</div>
-
-<!-- View: what the map *shows you* — the frame, the labels over the imagery,
- the case's own saved work. None of them is a tool, so they continue the
- zoom column instead of sitting among the tools. -->
-<div class="view-cluster card">
- <button
- class="mtbtn"
- class:on={fullscreen}
- onclick={toggleFullscreen}
- title={fullscreen ? 'Exit fullscreen (Esc)' : 'Fullscreen map'}
- aria-label="Toggle fullscreen"
- ><Icon name={fullscreen ? 'minimize' : 'maximize'} size={16} /></button>
- <button
- class="mtbtn"
- class:on={osmOverlay}
- onclick={() => (osmOverlay = !osmOverlay)}
- disabled={!baseIsImagery}
- title={baseIsImagery
- ? 'Overlay OSM labels (roads, place names) on the imagery'
- : 'Labels overlay is only useful over satellite imagery'}
- aria-label="Toggle OSM labels overlay"
- ><Icon name="layers" size={16} /></button>
- <button
- class="mtbtn"
- class:on={savedOverlay}
- onclick={() => (savedOverlay = !savedOverlay)}
- disabled={!savedCount}
- title={savedCount
- ? 'Show this case\'s saved places and captures on the map'
- : 'Nothing is saved in this case yet'}
- aria-label="Show saved work on the map"
- ><Icon name="pin" size={16} /></button>
-</div>
-
-{#if toolsOpen}
- <div class="measure-panel card">
- <div class="measure-btns">
- <button class="btn btn-sm" class:on={measureMode === 'distance'} onclick={() => setMeasureMode('distance')}>
- <Icon name="ruler" size={14} /> Distance
- </button>
- <button class="btn btn-sm" class:on={measureMode === 'area'} onclick={() => setMeasureMode('area')}>
- <Icon name="polygon" size={14} /> Area
- </button>
- <button class="btn btn-sm" class:on={measureMode === 'angle'} onclick={() => setMeasureMode('angle')}>
- <Icon name="angle" size={14} /> Angle
- </button>
- </div>
- {#if measureMode}
- <div class="measure-readout">
- {#if measureReadout}
- <span class="measure-value mono">{measureReadout}</span>
- {:else}
- <span class="measure-hint">{measureHint[measureMode]}</span>
- {/if}
- <button class="btn btn-ghost btn-sm" onclick={clearMeasure} title="Clear points">
- <Icon name="reset" size={13} />
- </button>
- </div>
- {/if}
- </div>
-{/if}
-
-<style>
- .tool-cluster {
- display: flex;
- gap: 2px;
- padding: 4px;
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- }
- /* stacked directly under the engine's zoom bar (top 58px + 64px tall + its 8px
- margin), same width, so +/- and these read as one column of view controls */
- .view-cluster {
- position: absolute;
- top: 118px;
- left: 0;
- display: flex;
- flex-direction: column;
- gap: 2px;
- padding: 2px;
- background: rgba(24, 24, 24, 0.88);
- backdrop-filter: blur(6px);
- }
- .mtbtn {
- display: grid;
- place-items: center;
- width: 30px;
- height: 30px;
- border-radius: var(--radius-1);
- color: var(--text-2);
- cursor: pointer;
- }
- .mtbtn:hover { color: var(--text-1); background: var(--bg-3); }
- .mtbtn.on { color: var(--accent-text); background: var(--accent); }
- .mtbtn:disabled { opacity: 0.35; cursor: not-allowed; }
- .mtbtn:disabled:hover { color: var(--text-2); background: none; }
- .measure-panel {
- position: absolute;
- top: 0;
- left: calc(100% + 8px);
- width: max-content;
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 10px;
- background: rgba(24, 24, 24, 0.92);
- backdrop-filter: blur(6px);
- box-shadow: var(--shadow-2);
- }
- .measure-btns { display: flex; gap: 4px; }
- .measure-btns .btn.on { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
- .measure-readout {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
- padding-top: 6px;
- border-top: 1px solid var(--border);
- }
- .measure-value { font-size: var(--fs-md); font-weight: 700; color: var(--accent); }
- .measure-hint { font-size: var(--fs-xs); color: var(--text-3); }
-</style>
diff --git a/frontend/src/tools/satellite/MarkerMenu.svelte b/frontend/src/tools/satellite/MarkerMenu.svelte
new file mode 100644
index 0000000..a16d836
--- /dev/null
+++ b/frontend/src/tools/satellite/MarkerMenu.svelte
@@ -0,0 +1,191 @@
+<script>
+ /**
+ * The point the map is reading, as one small menu.
+ *
+ * It was three controls lying across the bottom bar — a full-width select of
+ * marker styles, a Move-pin toggle and a separator — which pushed Save place
+ * and Capture onto a second row and left the bar sitting on the engine's own
+ * scale bracket. They are two questions, both about the same thing, and both
+ * asked once a session: what marks the point, and whether that point is the
+ * centre of the map or one dropped somewhere.
+ *
+ * So the bar keeps a single square wearing the current mark, and the answers
+ * live behind it. What it costs to reach is right: the acts beside it are
+ * pressed all day, this is set and forgotten.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let {
+ /** 'crosshair' | 'pin' | 'none' — what is drawn at the point, captures included. */
+ style = $bindable(),
+ /** Whether the point is a dropped pin rather than the centre of the map. */
+ free = false,
+ /** Take the pin off the centre, or put the point back on it. */
+ toggleFree,
+ } = $props();
+
+ const STYLES = [
+ { id: 'crosshair', label: 'Crosshair', icon: 'crosshair' },
+ { id: 'pin', label: 'Pin', icon: 'pin' },
+ { id: 'none', label: 'None', icon: 'noMark' },
+ ];
+
+ let open = $state(false);
+ let wrap = $state();
+
+ const current = $derived(STYLES.find((entry) => entry.id === style) ?? STYLES[2]);
+
+ // Anywhere else closes it — the same rule as the capture menu next to it.
+ $effect(() => {
+ if (!open) return;
+ const onDown = (e) => {
+ if (wrap && !wrap.contains(e.target)) open = false;
+ };
+ document.addEventListener('mousedown', onDown, true);
+ return () => document.removeEventListener('mousedown', onDown, true);
+ });
+</script>
+
+<div class="marker-menu" bind:this={wrap}>
+ <button
+ class="btn btn-icon marker-button"
+ class:on={open || free}
+ onclick={() => (open = !open)}
+ title="What marks the point, and where it sits"
+ aria-label="Marker"
+ aria-expanded={open}
+ >
+ <Icon name={current.icon} size={14} />
+ <Icon name="chevronDown" size={11} />
+ </button>
+
+ {#if open}
+ <div class="menu card">
+ <div class="menu-row">
+ <span class="menu-label">Marker</span>
+ <div class="tiles" role="radiogroup" aria-label="Marker">
+ {#each STYLES as entry (entry.id)}
+ <button
+ class="tile"
+ class:on={style === entry.id}
+ role="radio"
+ aria-checked={style === entry.id}
+ onclick={() => (style = entry.id)}
+ >
+ <Icon name={entry.icon} size={18} />
+ <span>{entry.label}</span>
+ </button>
+ {/each}
+ </div>
+ </div>
+ <div class="menu-row">
+ <span class="menu-label">Point</span>
+ <div class="tiles" role="radiogroup" aria-label="Point">
+ <button
+ class="tile"
+ class:on={!free}
+ role="radio"
+ aria-checked={!free}
+ onclick={() => free && toggleFree()}
+ >
+ <Icon name="centre" size={18} />
+ <span>Centre</span>
+ </button>
+ <button
+ class="tile"
+ class:on={free}
+ role="radio"
+ aria-checked={free}
+ disabled={style === 'none'}
+ title={style === 'none' ? 'Pick a marker first' : 'Drag the pin anywhere'}
+ onclick={() => !free && toggleFree()}
+ >
+ <Icon name="move" size={18} />
+ <span>Dropped</span>
+ </button>
+ </div>
+ </div>
+ <div class="menu-hint">
+ {free ? 'The coordinates follow the pin.' : 'The coordinates are the map centre.'}
+ </div>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .marker-menu {
+ position: relative;
+ display: flex;
+ }
+ .marker-button {
+ gap: 2px;
+ padding: 6px 6px 6px 8px;
+ color: var(--text-2);
+ }
+ .marker-button.on {
+ border-color: var(--accent);
+ color: var(--accent);
+ }
+ .menu {
+ position: absolute;
+ bottom: calc(100% + 8px);
+ left: 0;
+ width: max-content;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ background: rgba(24, 24, 24, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .menu-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .menu-label {
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-3);
+ }
+ .tiles {
+ display: flex;
+ gap: 4px;
+ }
+ .tile {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 3px;
+ width: 64px;
+ padding: 7px 4px 5px;
+ border-radius: var(--r-sm);
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: 10px;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .tile:hover:not(:disabled) {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .tile.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .tile:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .menu-hint {
+ margin-top: 1px;
+ font-size: 10px;
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/tools/satellite/MarkerMenu.test.js b/frontend/src/tools/satellite/MarkerMenu.test.js
new file mode 100644
index 0000000..52c1952
--- /dev/null
+++ b/frontend/src/tools/satellite/MarkerMenu.test.js
@@ -0,0 +1,67 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import { readFileSync } from 'node:fs';
+import MarkerMenu from './MarkerMenu.svelte';
+import { paths } from '../../components/Icon.svelte';
+
+const source = readFileSync(new URL('./MarkerMenu.svelte', import.meta.url), 'utf8');
+
+const props = (over = {}) => ({ style: 'crosshair', free: false, toggleFree: vi.fn(), ...over });
+
+describe('the point the map is reading', () => {
+ it('costs the strip one square at rest', () => {
+ const { body } = render(MarkerMenu, { props: props() });
+ // the two acts beside it are pressed all day; this is set and forgotten, so
+ // the answers live behind the square rather than lying across the bar
+ expect(body).toContain('aria-label="Marker"');
+ expect(body).not.toContain('Crosshair');
+ expect(body).not.toContain('Dropped');
+ });
+
+ it('wears what is marking the point', () => {
+ const { body } = render(MarkerMenu, { props: props({ style: 'pin' }) });
+ expect(body).toContain('aria-expanded="false"');
+ // no marker is the crosshair's ring struck through, not an abstract glyph
+ expect(source).toContain("{ id: 'none', label: 'None', icon: 'noMark' }");
+ expect(body).not.toContain(paths.crosshair);
+ expect(body).toContain(paths.pin);
+ });
+
+ it('says a dropped pin is armed without opening anything', () => {
+ const { body } = render(MarkerMenu, { props: props({ free: true }) });
+ expect(body).toMatch(/class="btn btn-icon marker-button[^"]* on"/);
+ });
+
+ it('answers each question with icon tiles, one of them checked', () => {
+ // each choice is a picture first and a word under it
+ expect(source).toContain('<Icon name={entry.icon} size={18} />');
+ expect(source).toContain('<Icon name="centre" size={18} />');
+ expect(source).toContain('<Icon name="move" size={18} />');
+ expect(source.match(/role="radiogroup"/g)).toHaveLength(2);
+ expect(source).toContain('aria-checked={style === entry.id}');
+ expect(source).not.toContain('class="chip"');
+ for (const name of ['noMark', 'centre', 'move', 'crosshair', 'pin']) expect(paths[name]).toBeTruthy();
+ expect(paths.ghost).toBeUndefined();
+ });
+
+ it('opens upwards, because it sits at the foot of the map', () => {
+ expect(source).toContain('bottom: calc(100% + 8px)');
+ });
+
+ it('closes on a click anywhere else, like the capture menu beside it', () => {
+ expect(source).toContain("document.addEventListener('mousedown', onDown, true)");
+ expect(source).toContain('if (wrap && !wrap.contains(e.target)) open = false');
+ });
+
+ it('offers no pin to drop when nothing marks the point', () => {
+ expect(source).toContain("disabled={style === 'none'}");
+ expect(source).toContain("title={style === 'none' ? 'Pick a marker first'");
+ });
+
+ it('asks the host to move the pin rather than moving it itself', () => {
+ // the pin is a mark on a surface the tool owns (`createSurface`), and the
+ // coordinates that follow it are what a capture files
+ expect(source).toContain('onclick={() => !free && toggleFree()}');
+ expect(source).toContain('onclick={() => free && toggleFree()}');
+ });
+});
diff --git a/frontend/src/tools/satellite/MeasurePanel.svelte b/frontend/src/tools/satellite/MeasurePanel.svelte
new file mode 100644
index 0000000..b5582db
--- /dev/null
+++ b/frontend/src/tools/satellite/MeasurePanel.svelte
@@ -0,0 +1,62 @@
+<script>
+ /**
+ * The measure tools' settings, in the rail's one panel slot.
+ *
+ * It carries no reading of its own any more: a distance, an area and an angle
+ * are numbers the map is telling you, and those all belong in the status bar
+ * with the coordinates rather than in three different floating boxes.
+ */
+ import Icon from '../../components/Icon.svelte';
+
+ let { mode, setMode, clear } = $props();
+
+ const TOOLS = [
+ { id: 'distance', label: 'Distance', icon: 'ruler' },
+ { id: 'area', label: 'Area', icon: 'polygon' },
+ { id: 'angle', label: 'Angle', icon: 'angle' },
+ ];
+</script>
+
+<div class="measure-panel card">
+ <div class="tools">
+ {#each TOOLS as tool (tool.id)}
+ <button
+ class="btn btn-sm"
+ class:on={mode === tool.id}
+ onclick={() => setMode(tool.id)}
+ >
+ <Icon name={tool.icon} size={14} /> {tool.label}
+ </button>
+ {/each}
+ </div>
+ {#if mode}
+ <button class="btn btn-ghost btn-sm clear" onclick={clear} title="Clear points">
+ <Icon name="reset" size={13} /> Clear points
+ </button>
+ {/if}
+</div>
+
+<style>
+ .measure-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ width: max-content;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.92);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ }
+ .tools {
+ display: flex;
+ gap: 4px;
+ }
+ .tools .btn.on {
+ background: var(--accent);
+ border-color: var(--accent);
+ color: var(--accent-text);
+ }
+ .clear {
+ align-self: flex-start;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/PlaceDialog.svelte b/frontend/src/tools/satellite/PlaceDialog.svelte
index 6074765..58fdc6e 100644
--- a/frontend/src/tools/satellite/PlaceDialog.svelte
+++ b/frontend/src/tools/satellite/PlaceDialog.svelte
@@ -13,7 +13,9 @@
* coordinates, the zoom and the bearing the map was on, none of which this
* dialog may change.
*/
+ import { untrack } from 'svelte';
import Modal from '../../components/Modal.svelte';
+ import ConfirmDialog from '../../components/ConfirmDialog.svelte';
import FolderSelect from '../../components/FolderSelect.svelte';
import RelationList from '../../components/RelationList.svelte';
import RelationPicker from '../../components/RelationPicker.svelte';
@@ -21,7 +23,7 @@
let {
/** `{ id, title, notes, folder, lat, lon, zoom, bearing, relation, relations }`;
* a null id means this point does not exist yet. */
- draft,
+ draft = $bindable(),
caseId,
folders = [],
saving = false,
@@ -33,7 +35,28 @@
onwalk,
/** A relation was corrected or taken back: re-read them. */
onchanged,
+ /** Hand this place over to the full editor, which closes this. */
+ ondetails,
} = $props();
+
+ // The fields here are the ones an analyst fills at the moment of saving; the rest
+ // of what a place holds — how precise it is, the source's wording, how the point
+ // was found — is edited in the panel every other surface opens. So this hands over
+ // rather than growing a second copy of that form, and asks first if anything was
+ // typed: handing over re-reads the place from the case, which would drop it.
+ // read once, on purpose: this is what the dialog opened on, not what it now holds
+ const opened = untrack(() => ({
+ title: draft.title,
+ folder: draft.folder,
+ notes: draft.notes,
+ }));
+ const touched = $derived(
+ draft.title !== opened.title ||
+ draft.folder !== opened.folder ||
+ draft.notes !== opened.notes ||
+ Boolean(draft.relation)
+ );
+ let discarding = $state(false);
</script>
<Modal title={draft.id ? 'Edit place' : 'Save place'} {onclose} width="420px">
@@ -79,7 +102,15 @@
placeholder="Add observations, links, context…"
bind:value={draft.notes}
></textarea>
- <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:12px">
+ <div class="acts">
+ {#if draft.id && ondetails}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Precision, the source's own wording, how the point was found"
+ onclick={() => (touched ? (discarding = true) : ondetails())}
+ >Edit more details</button>
+ {/if}
+ <div class="spacer"></div>
<button class="btn" onclick={onclose}>Cancel</button>
<button class="btn btn-primary" onclick={onsave} disabled={saving}>
{saving ? 'Saving…' : 'Save'}
@@ -87,7 +118,31 @@
</div>
</Modal>
+{#if discarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This place has edits that Save has not taken."
+ detail="The full editor opens on what the case holds."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => {
+ discarding = false;
+ ondetails();
+ }}
+ oncancel={() => (discarding = false)}
+ />
+{/if}
+
<style>
+ .acts {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 12px;
+ }
+ .spacer {
+ flex: 1;
+ }
.sat-info-rows {
display: flex;
flex-direction: column;
diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelte
index 9a64af9..e1d7e33 100644
--- a/frontend/src/tools/satellite/SavedOverlay.svelte
+++ b/frontend/src/tools/satellite/SavedOverlay.svelte
@@ -24,6 +24,7 @@
onpost,
onshowproofs,
onrefresh,
+ ontrace,
} = $props();
const GLYPH = { place: 'pin', capture: 'satellite', screenshot: 'screen', proof: 'proof' };
@@ -78,6 +79,9 @@
onedit: close(onedit),
onproof: close(onproof),
onpost: close(onpost),
+ // tracing takes over the map, so the card that armed it gets out of
+ // the way first — the same rule as every other act here
+ ontrace: ontrace && close(ontrace),
onshowproofs: close(onshowproofs),
// opening a related media leaves the map, so close the card first — the
// same gesture as every other row here, rather than a popup that
@@ -138,8 +142,10 @@
* How tightly a mark is pinned, as a shape under its pin (ONTOLOGY §2).
*
* A pin dropped on a guess is the lie this fixes: "somewhere on the north quay"
- * draws as the circle it is. A footprint wins over a radius when both are set,
- * because a traced shape says more than the circle around it.
+ * draws as the circle it is. A place states its precision in one form, so the two
+ * are alternatives rather than a stack; a point written before that rule holds both
+ * and its traced shape is what draws, because a shape says more than the circle
+ * around it.
*
* A mark with neither returns nothing and draws exactly as it always has —
* absence is a state, never something to flag.
diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelte
index c6e66d8..089bcd2 100644
--- a/frontend/src/tools/satellite/SavedPopup.svelte
+++ b/frontend/src/tools/satellite/SavedPopup.svelte
@@ -25,6 +25,7 @@
onopen,
onedit,
onproof,
+ ontrace,
onpost,
onshowproofs,
onentity, // a related entity was picked: leave for its own tool
@@ -245,6 +246,16 @@
{:else}
<button type="button" class="link" onclick={() => onedit(row)}>Edit</button>
{/if}
+ {#if row.kind === 'place' && ontrace}
+ <button
+ type="button"
+ class="link"
+ onclick={() => ontrace(row)}
+ title={row.footprint
+ ? 'Draw this shape again on the map'
+ : 'Draw the area this place really covers'}
+ >{row.footprint ? 'Retrace' : 'Trace'} footprint</button>
+ {/if}
{#if row.source_url}
<a
class="link"
diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelte
index 02dcb58..bb6d810 100644
--- a/frontend/src/tools/satellite/SentinelPicker.svelte
+++ b/frontend/src/tools/satellite/SentinelPicker.svelte
@@ -33,12 +33,14 @@
</select>
</div>
{#if s2.layerHint}<div class="menu-hint">{s2.layerHint}</div>{/if}
- <div class="menu-hint dim">
- {s2.layersSource === 'instance'
- ? 'These layers come from your configuration.'
- : 'Could not read your configuration; showing the standard layers.'}
- <button class="linkish" onclick={() => s2.loadLayers(true)}>Refresh</button>
- </div>
+ <!-- Silent when the layers are the configured ones, which is the normal
+ case and was a line of panel saying so on every open. -->
+ {#if s2.layersSource !== 'instance'}
+ <div class="menu-hint dim">
+ Could not read your configuration; these are the standard layers.
+ <button class="linkish" onclick={() => s2.loadLayers(true)}>Refresh</button>
+ </div>
+ {/if}
<div class="menu-sep" aria-hidden="true"></div>
@@ -61,9 +63,7 @@
<span class="cc-value mono">{maxccLabel(shown)}</span>
</div>
</div>
- <div class="menu-hint dim">
- Passes cloudier than this are not rendered, and drop out of the calendar.
- </div>
+ <div class="menu-hint dim">Cloudier passes drop out of the calendar.</div>
<div class="menu-sep" aria-hidden="true"></div>
@@ -133,9 +133,7 @@
<button class="linkish" onclick={() => s2.loadPasses(true)}>Refresh</button>
</div>
{:else}
- <div class="menu-hint dim">
- Dates with a pass are checked at the crosshair before the map changes.
- </div>
+ <div class="menu-hint dim">Each date is checked at the crosshair first.</div>
{/if}
</div>
{/if}
@@ -143,22 +141,30 @@
<style>
.s2-wrap { position: relative; display: flex; }
+ /* Down and to the left of its button, because the picker now rides in the
+ surface's own top-right corner: opening upwards put a calendar off the top
+ of the map, where the surface clips it. The height is capped for the same
+ reason at the other end — a month of passes must not run off the bottom. */
.s2-menu {
position: absolute;
- bottom: calc(100% + 8px);
- left: 0;
- width: max-content;
- max-width: 320px;
+ top: calc(100% + 8px);
+ right: 0;
+ /* Stated rather than grown: at `max-content` the hint lines set the width,
+ the calendar then stretched to fill it, and a month of 40px cells is a
+ date picker the size of the thing it is picking on. */
+ width: 246px;
+ max-height: 70vh;
+ overflow-y: auto;
display: flex;
flex-direction: column;
- gap: 4px;
- padding: 12px;
+ gap: 3px;
+ padding: 10px;
background: rgba(24, 24, 24, 0.96);
backdrop-filter: blur(6px);
box-shadow: var(--shadow-2);
z-index: 700;
}
- .s2-menu .select { max-width: 190px; }
+ .s2-menu .select { max-width: 150px; padding: 4px 6px; font-size: var(--fs-xs); }
.menu-row { display: flex; align-items: center; gap: 10px; justify-content: space-between; }
.menu-label { font-size: var(--fs-xs); color: var(--text-3); font-weight: 600; }
.chips { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; }
@@ -175,13 +181,13 @@
}
.chip:hover { color: var(--text-1); border-color: var(--border-strong); }
.chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
- .cc { display: flex; align-items: center; gap: 8px; }
- .cc input[type='range'] { width: 120px; accent-color: var(--accent); cursor: pointer; }
- .cc-value { font-size: 10px; color: var(--text-2); min-width: 58px; text-align: right; }
- .menu-hint { font-size: 10px; color: var(--text-3); margin: -1px 0 5px; }
+ .cc { display: flex; align-items: center; gap: 6px; }
+ .cc input[type='range'] { width: 96px; accent-color: var(--accent); cursor: pointer; }
+ .cc-value { font-size: 10px; color: var(--text-2); min-width: 52px; text-align: right; }
+ .menu-hint { font-size: 10px; line-height: 1.35; color: var(--text-3); margin: -1px 0 4px; }
.menu-hint.dim { opacity: 0.75; }
.menu-hint .warn, .menu-hint.warn { color: var(--warn, #e2a03f); }
- .menu-sep { height: 1px; background: var(--border); margin: 4px 0 6px; }
+ .menu-sep { height: 1px; background: var(--border); margin: 3px 0 5px; }
.linkish {
background: none;
border: 0;
@@ -191,12 +197,12 @@
cursor: pointer;
text-decoration: underline;
}
- .cal { display: flex; flex-direction: column; gap: 6px; margin: 2px 0 6px; }
+ .cal { display: flex; flex-direction: column; gap: 4px; margin: 1px 0 5px; }
.cal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.cal-month { font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
.cal-nav {
display: flex;
- padding: 3px 5px;
+ padding: 2px 4px;
border: 1px solid var(--border);
border-radius: var(--r-sm);
background: var(--bg-2);
@@ -206,9 +212,11 @@
.cal-nav:hover { color: var(--text-1); border-color: var(--text-3); }
.cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
.cal-grid.busy { opacity: 0.5; pointer-events: none; }
- .cal-dow { text-align: center; font-size: 9px; color: var(--text-3); padding-bottom: 2px; }
+ .cal-dow { text-align: center; font-size: 9px; color: var(--text-3); padding-bottom: 1px; }
.cal-day {
- aspect-ratio: 1;
+ /* a square cell grew with the panel; a stated height keeps the month the
+ size of a month whatever else is in here */
+ height: 24px;
display: flex;
align-items: center;
justify-content: center;
diff --git a/frontend/src/tools/satellite/SunPanel.svelte b/frontend/src/tools/satellite/SunPanel.svelte
index aae6e1d..c01afe0 100644
--- a/frontend/src/tools/satellite/SunPanel.svelte
+++ b/frontend/src/tools/satellite/SunPanel.svelte
@@ -167,11 +167,8 @@
<style>
.sun-panel {
- position: absolute;
- /* beside the cluster, but below the band the centred coordinates readout
- occupies: on a narrow map the two would otherwise cross */
- top: 46px;
- left: calc(100% + 8px);
+ /* placed by the rail's panel slot, like every other tool's settings; it no
+ longer has to dodge a coordinates readout that used to float above it */
width: max-content;
min-width: 234px;
display: flex;
diff --git a/frontend/src/tools/satellite/SunPanel.test.js b/frontend/src/tools/satellite/SunPanel.test.js
index 68bcc62..18eb3aa 100644
--- a/frontend/src/tools/satellite/SunPanel.test.js
+++ b/frontend/src/tools/satellite/SunPanel.test.js
@@ -2,12 +2,13 @@ import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
const panel = readFileSync(new URL('./SunPanel.svelte', import.meta.url), 'utf8');
-const cluster = readFileSync(new URL('./MapToolCluster.svelte', import.meta.url), 'utf8');
describe('Sun & moon panel', () => {
- it('opens beside the tool cluster, clear of the centred coordinates readout', () => {
- expect(panel).toContain('left: calc(100% + 8px)');
- expect(panel).toContain('top: 46px');
+ it('is placed by the rail\'s panel slot rather than placing itself', () => {
+ // it used to carry its own corner, and a `top: 46px` that dodged a
+ // coordinates readout floating above it; both belong to the slot now
+ expect(panel).not.toContain('position: absolute');
+ expect(panel).not.toContain('left: calc(100% + 8px)');
});
it('can be dragged out of the way of the imagery it describes', () => {
@@ -46,11 +47,3 @@ describe('Sun & moon panel', () => {
expect(panel).toContain("{placing ? 'Click the map' : 'Move'}");
});
});
-
-describe('map tool cluster', () => {
- it('carries Sun & moon among the tools, not among the view toggles', () => {
- const tools = cluster.slice(cluster.indexOf('tool-cluster'), cluster.indexOf('view-cluster'));
- expect(tools).toContain('aria-label="Sun and moon"');
- expect(tools).toContain('class:on={sunMode}');
- });
-});
diff --git a/frontend/src/tools/satellite/WaybackPicker.svelte b/frontend/src/tools/satellite/WaybackPicker.svelte
new file mode 100644
index 0000000..a0d4044
--- /dev/null
+++ b/frontend/src/tools/satellite/WaybackPicker.svelte
@@ -0,0 +1,284 @@
+<script>
+ import Icon from '../../components/Icon.svelte';
+
+ /**
+ * Which Wayback release this surface shows, as a slider through time.
+ *
+ * `wb` is the store from `state/wayback.svelte.js`. The slider runs oldest on
+ * the left to newest on the right, the way a timeline reads, while the list
+ * under it runs newest first, the way the releases are published.
+ */
+ let { menuEl = $bindable(), wb } = $props();
+
+ // The label follows the drag; the map only moves on release, since every
+ // step in between would be a whole screen of tiles nobody stopped on.
+ let dragging = $state(null);
+
+ const list = $derived(wb.visible);
+ const last = $derived(Math.max(0, list.length - 1));
+ const sliderValue = $derived(
+ dragging ?? (wb.position < 0 ? last : Math.round(last - wb.position))
+ );
+ const sliderDate = $derived(list[last - sliderValue]?.date ?? wb.date);
+ // By position rather than by number: the newest release is not in a list
+ // narrowed to changes, yet it shows the latest change's pixels, and a
+ // release between two changes is highlighted as neither.
+ const onScreen = $derived(Number.isInteger(wb.position) ? wb.position : -1);
+</script>
+
+<div class="wb-wrap" bind:this={menuEl}>
+ <button
+ class="chip"
+ class:on={wb.menuOpen}
+ onclick={() => wb.toggleMenu()}
+ title="Wayback release"
+ aria-label="Wayback release"
+ aria-expanded={wb.menuOpen}
+ >
+ <Icon name="clock" size={13} />
+ <span class="mono">{wb.date || 'Newest'}</span>
+ </button>
+
+ {#if wb.menuOpen}
+ <div class="wb-menu card">
+ {#if wb.listNote}
+ <div class="menu-hint warn">{wb.listNote}</div>
+ {:else if !wb.releases.length}
+ <div class="menu-hint dim">Reading the release list…</div>
+ {:else}
+ <div class="step-row">
+ <button
+ class="nav"
+ onclick={() => wb.step(1)}
+ disabled={wb.position >= list.length - 1}
+ aria-label="Older release"
+ title="Older release"
+ ><Icon name="chevronLeft" size={13} /></button>
+ <span class="current mono">{sliderDate}</span>
+ <button
+ class="nav"
+ onclick={() => wb.step(-1)}
+ disabled={wb.position <= 0}
+ aria-label="Newer release"
+ title="Newer release"
+ ><Icon name="chevronRight" size={13} /></button>
+ </div>
+ <input
+ class="slider"
+ type="range"
+ min="0"
+ max={last}
+ step="1"
+ value={sliderValue}
+ disabled={list.length < 2}
+ oninput={(event) => (dragging = Number(event.currentTarget.value))}
+ onchange={(event) => {
+ const picked = list[last - Number(event.currentTarget.value)];
+ dragging = null;
+ if (picked) wb.pick(picked.release);
+ }}
+ aria-label="Release"
+ />
+
+ <div class="chips">
+ <button
+ class="chip-opt"
+ class:on={wb.changesOnly}
+ onclick={() => wb.setChangesOnly(true)}
+ title="Only releases whose pixels differ at the crosshair"
+ >Changes here</button>
+ <button
+ class="chip-opt"
+ class:on={!wb.changesOnly}
+ onclick={() => wb.setChangesOnly(false)}
+ >Every release</button>
+ </div>
+
+ {#if wb.changesOnly}
+ {#if wb.changesBusy}
+ <div class="menu-hint dim">Reading this point's history…</div>
+ {:else if wb.changesNote}
+ <div class="menu-hint warn">{wb.changesNote}</div>
+ {:else if wb.stale}
+ <div class="menu-hint">
+ <span class="warn">The map moved off this history.</span>
+ <button class="linkish" onclick={() => wb.loadChanges()}>Refresh</button>
+ </div>
+ {:else if wb.changes}
+ <div class="menu-hint dim">
+ {wb.changes.length} change{wb.changes.length === 1 ? '' : 's'} at the crosshair
+ </div>
+ {/if}
+ {/if}
+
+ <ul class="releases" aria-label="Releases">
+ {#each list as entry, index (entry.release)}
+ {@const shot = wb.picture(entry.release)}
+ <li>
+ <button
+ class="row mono"
+ class:on={index === onScreen}
+ onclick={() => wb.pick(entry.release)}
+ title={shot?.source ? `Taken by ${shot.source}` : undefined}
+ >
+ <span>{entry.date}</span>
+ {#if shot?.acquired}<span class="taken">taken {shot.acquired}</span>{/if}
+ </button>
+ </li>
+ {/each}
+ </ul>
+
+ <div class="menu-hint dim">
+ Release dates are Esri's; “taken” and the pill under the chip date the pixels.
+ </div>
+ {/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .wb-wrap {
+ position: relative;
+ display: flex;
+ }
+ .chip {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: 30px;
+ padding: 0 8px;
+ 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);
+ box-shadow: 0 0 0 1px var(--border);
+ cursor: pointer;
+ }
+ .chip:hover,
+ .chip.on {
+ color: var(--accent);
+ }
+ /* down and left of the chip, like the Sentinel-2 picker beside it: the
+ surface's own corner clips anything opening upwards */
+ .wb-menu {
+ position: absolute;
+ top: calc(100% + 8px);
+ right: 0;
+ width: 248px;
+ max-height: 70vh;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 10px;
+ background: rgba(24, 24, 24, 0.96);
+ backdrop-filter: blur(6px);
+ box-shadow: var(--shadow-2);
+ z-index: 700;
+ }
+ .step-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ }
+ .current {
+ font-size: var(--fs-sm);
+ color: var(--text-1);
+ }
+ .nav {
+ display: flex;
+ padding: 2px 4px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ cursor: pointer;
+ }
+ .nav:hover:not(:disabled) {
+ color: var(--text-1);
+ border-color: var(--text-3);
+ }
+ .nav:disabled {
+ opacity: 0.35;
+ cursor: default;
+ }
+ .slider {
+ width: 100%;
+ accent-color: var(--accent);
+ cursor: pointer;
+ }
+ .chips {
+ display: flex;
+ gap: 4px;
+ }
+ .chip-opt {
+ padding: 4px 9px;
+ border-radius: var(--r-sm);
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .chip-opt:hover {
+ color: var(--text-1);
+ }
+ .chip-opt.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .releases {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ max-height: 220px;
+ overflow-y: auto;
+ }
+ .row {
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ width: 100%;
+ padding: 3px 8px;
+ border-radius: var(--r-sm);
+ font-size: var(--fs-xs);
+ color: var(--text-2);
+ text-align: left;
+ cursor: pointer;
+ }
+ .taken {
+ color: var(--text-3);
+ }
+ .row:hover {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ .row.on {
+ color: var(--accent);
+ background: var(--accent-soft);
+ }
+ .menu-hint {
+ font-size: 10px;
+ line-height: 1.35;
+ color: var(--text-3);
+ }
+ .menu-hint.dim {
+ opacity: 0.8;
+ }
+ .menu-hint .warn,
+ .menu-hint.warn {
+ color: var(--warn, #e2a03f);
+ }
+ .linkish {
+ background: none;
+ border: 0;
+ padding: 0;
+ color: var(--accent);
+ font-size: 10px;
+ cursor: pointer;
+ text-decoration: underline;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/WaybackPicker.test.js b/frontend/src/tools/satellite/WaybackPicker.test.js
new file mode 100644
index 0000000..3567c01
--- /dev/null
+++ b/frontend/src/tools/satellite/WaybackPicker.test.js
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render } from 'svelte/server';
+import WaybackPicker from './WaybackPicker.svelte';
+
+const RELEASES = [
+ { release: 26334, date: '2026-08-05' },
+ { release: 64776, date: '2023-08-31' },
+ { release: 10, date: '2014-02-20' },
+];
+
+/** A stand-in for `state/wayback.svelte.js`, in the state a case would be in. */
+function props(wb = {}) {
+ return {
+ wb: {
+ menuOpen: true,
+ releases: RELEASES,
+ listNote: '',
+ release: 64776,
+ date: '2023-08-31',
+ changesOnly: true,
+ changes: [64776, 10],
+ changesBusy: false,
+ changesNote: '',
+ stale: false,
+ visible: [RELEASES[1], RELEASES[2]],
+ position: 0,
+ toggleMenu: vi.fn(),
+ setChangesOnly: vi.fn(),
+ loadChanges: vi.fn(),
+ pick: vi.fn(),
+ step: vi.fn(),
+ picture: (release) =>
+ ({ 64776: { acquired: '2022-03-31', source: 'Maxar WV03' } })[release] ?? null,
+ ...wb,
+ },
+ };
+}
+
+describe('the Wayback chip', () => {
+ it('names the release on screen, and the newest before the list is read', () => {
+ expect(render(WaybackPicker, { props: props({ menuOpen: false }) }).body).toContain('2023-08-31');
+ const early = render(WaybackPicker, {
+ props: props({ menuOpen: false, releases: [], date: '' }),
+ });
+ expect(early.body).toContain('Newest');
+ });
+});
+
+describe('the picker', () => {
+ it('lists what it offers and marks the release on screen', () => {
+ const { body } = render(WaybackPicker, { props: props() });
+ expect(body).toMatch(/class="row mono[^"]* on"[^>]*><span>2023-08-31</);
+ expect(body).toContain('2014-02-20');
+ // narrowed to changes, so a release that changed nothing here is not offered
+ expect(body).not.toContain('>2026-08-05<');
+ expect(body).toContain('2 changes at the crosshair');
+ });
+
+ it('cannot step newer from the newest it offers', () => {
+ const { body } = render(WaybackPicker, { props: props() });
+ expect(body).toMatch(/<button[^>]*disabled[^>]*aria-label="Newer release"/);
+ expect(body).not.toMatch(/<button[^>]*disabled[^>]*aria-label="Older release"/);
+ });
+
+ it('says a history is being read, has failed, or belongs to somewhere else', () => {
+ expect(render(WaybackPicker, { props: props({ changesBusy: true }) }).body).toContain(
+ "Reading this point's history"
+ );
+ expect(
+ render(WaybackPicker, { props: props({ changesNote: 'Could not read it' }) }).body
+ ).toContain('Could not read it');
+ expect(render(WaybackPicker, { props: props({ stale: true }) }).body).toContain(
+ 'The map moved off this history.'
+ );
+ });
+
+ it('keeps release dates apart from when the pixels were taken', () => {
+ const { body } = render(WaybackPicker, { props: props() });
+ expect(body).toContain('taken 2022-03-31');
+ expect(body).toContain('Taken by Maxar WV03');
+ expect(body).toContain('the pill under the chip date the pixels');
+ });
+
+ it('says so when the release list cannot be read', () => {
+ const { body } = render(WaybackPicker, {
+ props: props({ releases: [], listNote: 'Could not read the release list: offline' }),
+ });
+ expect(body).toContain('Could not read the release list: offline');
+ expect(body).not.toContain('type="range"');
+ });
+});
diff --git a/frontend/src/tools/satellite/state/capture.svelte.js b/frontend/src/tools/satellite/state/capture.svelte.js
index f6b0862..2e10f92 100644
--- a/frontend/src/tools/satellite/state/capture.svelte.js
+++ b/frontend/src/tools/satellite/state/capture.svelte.js
@@ -51,6 +51,7 @@ 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';
+import { applyPrefs, prefs } from '../../../lib/state.svelte.js';
/** Standard output sizes for the centred button, named by what they are for. */
export const PRESETS = [
@@ -103,6 +104,29 @@ export function createCaptureState({
let extGate = $state(false); // the "you need the extension" explainer
let shotOpen = $state(false); // the paste/drop fallback dialog
+ /**
+ * The scale bar and north arrow tick, kept in settings.json rather than here.
+ *
+ * Every other option in this menu is answered per session — a size, a ratio,
+ * a resolution are decided for the shot being taken. This one is a house
+ * style: an analyst who wants a scale bar wants it on every capture, and
+ * ticking it again each morning would be the feature failing. So the store
+ * holds no copy of it. `prefs` is the one, filled from settings.json before
+ * any tool reads it, and a click writes both at once.
+ */
+ async function setScaleNorth(on) {
+ const want = !!on;
+ if (want === prefs.captureScaleNorth) return;
+ prefs.captureScaleNorth = want; // the tick answers the click, not the round trip
+ try {
+ applyPrefs(await api.put('/api/settings/prefs', { capture_scale_north: want }));
+ } catch {
+ // The capture still carries what is ticked; only the remembering failed,
+ // and saying so is worth one line rather than undoing their click.
+ notify('That tick applies to this session — it could not be saved', 'warn');
+ }
+ }
+
/** 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)];
@@ -175,6 +199,7 @@ export function createCaptureState({
form.append('bearing', String(bearing()));
form.append('provider', basemap().id);
form.append('framed', String(!!framed));
+ form.append('scale_north', String(prefs.captureScaleNorth));
const result = await api.post(`/api/cases/${owner.id}/satellite/screenshot`, form);
await reloadCase();
notify(
@@ -286,6 +311,7 @@ export function createCaptureState({
// pinned Sentinel-2 window is that date outright; every other provider's
// is Esri's best-effort estimate, or nothing.
imagery_date: pixels.imageryDate,
+ scale_north: prefs.captureScaleNorth,
});
await reloadCase();
notify(
@@ -376,6 +402,14 @@ export function createCaptureState({
set resolution(value) {
resolution = value;
},
+ // Read and written straight through to the preference, so the tick a second
+ // map tab shows is the same one this tab just set.
+ get scaleNorth() {
+ return prefs.captureScaleNorth;
+ },
+ set scaleNorth(value) {
+ setScaleNorth(value);
+ },
get mode() {
return mode;
},
diff --git a/frontend/src/tools/satellite/state/capture.svelte.test.js b/frontend/src/tools/satellite/state/capture.svelte.test.js
index 647fc54..4fcd107 100644
--- a/frontend/src/tools/satellite/state/capture.svelte.test.js
+++ b/frontend/src/tools/satellite/state/capture.svelte.test.js
@@ -1,6 +1,7 @@
// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createCaptureState, PRESETS, RATIOS } from './capture.svelte.js';
+import { prefs } from '../../../lib/state.svelte.js';
/**
* What a capture records, and what it refuses to record.
@@ -56,7 +57,7 @@ function store(overrides = {}) {
}
beforeEach(() => {
- api = { post: vi.fn(async () => ({})) };
+ api = { post: vi.fn(async () => ({})), put: vi.fn(async () => ({})) };
notify = vi.fn();
reloadCase = vi.fn(async () => {});
engine = {
@@ -71,6 +72,9 @@ beforeEach(() => {
rects = [];
armedOff = 0;
extension = '1.0.0';
+ // The marks tick lives in the app-wide preference rather than in the store,
+ // so one test ticking it would otherwise arrive ticked in the next.
+ prefs.captureScaleNorth = false;
});
describe('the output shape', () => {
@@ -320,3 +324,47 @@ describe('the paste fallback', () => {
expect(notify).toHaveBeenCalledWith(expect.stringContaining('refused'), 'danger', 6000);
});
});
+
+describe('the scale bar and north arrow tick', () => {
+ /**
+ * The one option in this menu that outlives the session. It is not held here:
+ * `prefs` is, so a second map tab shows the same tick and a reload keeps it.
+ */
+ it('starts off, and says so on the capture it takes', async () => {
+ const capture = store();
+ expect(capture.scaleNorth).toBe(false);
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].scale_north).toBe(false);
+ });
+
+ it('is remembered in settings the moment it is ticked', async () => {
+ const capture = store();
+ capture.scaleNorth = true;
+ await vi.waitFor(() => expect(api.put).toHaveBeenCalled());
+ expect(api.put.mock.calls[0]).toEqual([
+ '/api/settings/prefs',
+ { capture_scale_north: true },
+ ]);
+ expect(capture.scaleNorth).toBe(true);
+ });
+
+ it('rides on a tile capture and on a screen crop alike', async () => {
+ const capture = store();
+ capture.scaleNorth = true;
+ capture.run();
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalled());
+ expect(api.post.mock.calls[0][1].scale_north).toBe(true);
+ });
+
+ it('stays ticked for this session when settings refuse to keep it', async () => {
+ api.put = vi.fn(async () => {
+ throw new Error('no');
+ });
+ const capture = store();
+ capture.scaleNorth = true;
+ await vi.waitFor(() => expect(notify).toHaveBeenCalled());
+ expect(notify.mock.calls[0][1]).toBe('warn');
+ expect(capture.scaleNorth).toBe(true);
+ });
+});
diff --git a/frontend/src/tools/satellite/state/footprint.svelte.js b/frontend/src/tools/satellite/state/footprint.svelte.js
new file mode 100644
index 0000000..90bb266
--- /dev/null
+++ b/frontend/src/tools/satellite/state/footprint.svelte.js
@@ -0,0 +1,185 @@
+/**
+ * Tracing a place's footprint: the shape it really is, drawn by hand.
+ *
+ * A pin dropped on a guess is what this fixes. "Somewhere on the north quay" is
+ * a quay, not a circle around a point, and the case has held the field, its
+ * validation and its drawing since places grew a precision (ONTOLOGY §2) — the
+ * only way to fill it was to paste GeoJSON into Details, which is a thing
+ * nobody does. This is the gesture.
+ *
+ * Three rules, and each is about a shape being somebody's claim:
+ *
+ * - **It is traced for one place, named the whole time.** Tracing is armed from
+ * that place's card, so there is never a shape on the map looking for an owner.
+ * - **Nothing is written until Save.** Vertices are a draft on a scratch layer;
+ * the point's own footprint is untouched until the analyst says so, and Cancel
+ * leaves the place exactly as it was.
+ * - **A shape that is not an area, or that misses its own pin, is refused here**
+ * rather than by the backend: under three corners there is nothing to file, and
+ * a polygon traced beside the point describes somewhere else. The panel says so
+ * rather than sending a request to be told.
+ *
+ * @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 the place belongs to
+ * @param {() => object|null} deps.engine the map, through the façade
+ * @param {() => Promise<any>} deps.onSaved re-read the saved index, so the
+ * traced shape appears under its pin
+ * @param {(engine: object) => object} [deps.surface] the drawing layer factory
+ */
+import { createSurface } from '../../../lib/map/surface.js';
+import { containsPoint } from '../../../lib/measure.js';
+
+/** Matches the footprint already drawn under a pin (`SavedOverlay`). */
+const STROKE = { stroke: '#f5a623', strokeWidth: 2, strokeOpacity: 0.95 };
+const FILL = { fill: '#f5a623', fillOpacity: 0.16 };
+const DOT = { radius: 4, stroke: '#fff', strokeWidth: 2, fill: '#f5a623', fillOpacity: 1 };
+
+/** The cap the store enforces (engine/entities.py MAX_FOOTPRINT_POINTS). */
+const MAX_POINTS = 4096;
+
+/** A ring of clicked points as GeoJSON: lon first, and closed. */
+export function polygonOf(points) {
+ if (points.length < 3) return null;
+ const ring = points.map((point) => [point.lon, point.lat]);
+ return { type: 'Polygon', coordinates: [[...ring, ring[0]]] };
+}
+
+export function createFootprintState({
+ api,
+ notify,
+ caseId,
+ engine,
+ onSaved,
+ surface = createSurface,
+}) {
+ /** The place being traced: `{ id, title, footprint, radius_m, at }`, or null
+ * when off. `at` is the pin itself, which the shape has to contain. */
+ let place = $state(null);
+ let points = $state([]);
+ let saving = $state(false);
+ let layer = null;
+
+ function draw() {
+ const map = engine();
+ if (!map) return;
+ layer ??= surface(map);
+ layer.set([
+ points.length >= 3
+ ? { kind: 'polygon', points, style: { ...STROKE, ...FILL } }
+ : points.length === 2
+ ? { kind: 'line', points, style: STROKE }
+ : null,
+ ...points.map((point) => ({ kind: 'dot', at: point, style: DOT })),
+ ]);
+ }
+
+ function stop() {
+ place = null;
+ points = [];
+ layer?.clear();
+ }
+
+ /** Whether the shape as drawn holds the pin it belongs to. A place that carries no
+ * point of its own has nothing to contradict. */
+ function covers() {
+ if (points.length < 3) return false;
+ return place?.at ? containsPoint(points, place.at) : true;
+ }
+
+ return {
+ get on() {
+ return Boolean(place);
+ },
+ get place() {
+ return place;
+ },
+ get points() {
+ return points;
+ },
+ get saving() {
+ return saving;
+ },
+ /** Whether what is drawn is an area, which is the only thing worth saving. */
+ get complete() {
+ return points.length >= 3;
+ },
+ /** …and whether that area is this place's: a shape beside the pin is a shape
+ * for somewhere else, so the panel refuses it rather than the store. */
+ get covers() {
+ return covers();
+ },
+
+ /** Begin on a place. Starting again on another one drops the first draft. */
+ start(row) {
+ if (!row?.id) return false;
+ stop();
+ // `null` is a point the place does not have, and it numbers as 0 — which would
+ // put every untraced place in the Gulf of Guinea and refuse every shape drawn.
+ const lat = row.lat == null ? NaN : Number(row.lat);
+ const lon = row.lon == null ? NaN : Number(row.lon);
+ const at = Number.isFinite(lat) && Number.isFinite(lon) ? { lat, lon } : null;
+ place = {
+ id: row.id,
+ title: row.title || 'this place',
+ footprint: row.footprint || null,
+ radius_m: Number(row.radius_m) > 0 ? Number(row.radius_m) : null,
+ at,
+ };
+ return true;
+ },
+
+ /** A map click, while tracing. False means it was not ours. */
+ addPoint(at) {
+ if (!place) return false;
+ if (points.length >= MAX_POINTS) {
+ notify(`A footprint holds at most ${MAX_POINTS} points`, 'warn');
+ return true; // ours, and deliberately swallowed
+ }
+ points = [...points, at];
+ draw();
+ return true;
+ },
+
+ /** Take back the last corner. The gesture has no other way to be wrong. */
+ undo() {
+ points = points.slice(0, -1);
+ draw();
+ },
+
+ async save() {
+ const shape = polygonOf(points);
+ const cid = caseId();
+ if (!shape || !place || !cid || saving) return;
+ if (!covers()) {
+ notify('The shape has to contain the place it belongs to', 'warn', 4000);
+ return;
+ }
+ saving = true;
+ try {
+ // attrs merge server-side, so this writes the footprint and leaves
+ // everything else the place holds exactly where it was — except the
+ // radius, which the shape replaces: the map draws one of the two, and a
+ // circle that survived a tracing it can no longer be seen behind is a
+ // precision nobody can read.
+ await api.patch(`/api/cases/${cid}/entities/${place.id}`, {
+ attrs: { footprint: shape, radius_m: null },
+ });
+ stop();
+ await onSaved?.();
+ notify('Footprint saved', 'ok', 2000);
+ } catch (e) {
+ notify(`Could not save the footprint: ${e.message}`, 'danger', 6000);
+ } finally {
+ saving = false;
+ }
+ },
+
+ cancel: stop,
+ destroy() {
+ layer?.destroy();
+ layer = null;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/footprint.svelte.test.js b/frontend/src/tools/satellite/state/footprint.svelte.test.js
new file mode 100644
index 0000000..47f196e
--- /dev/null
+++ b/frontend/src/tools/satellite/state/footprint.svelte.test.js
@@ -0,0 +1,184 @@
+// @vitest-environment happy-dom
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createFootprintState, polygonOf } from './footprint.svelte.js';
+
+/**
+ * Tracing a footprint, apart from the map it is drawn on.
+ *
+ * What matters here is that a shape is one place's claim: it is never traced
+ * for nobody, never written before Save, and never sent as something the store
+ * would refuse.
+ */
+
+// The pin sits inside the triangle A-B-C below, which is where a place's own shape
+// has to be traced.
+const PLACE = { id: 'e1', kind: 'place', title: 'North quay', lat: 0.3, lon: 0.7, footprint: null };
+const A = { lat: 0, lon: 0 };
+const B = { lat: 0, lon: 1 };
+const C = { lat: 1, lon: 1 };
+
+let api;
+let notify;
+let layer;
+let surface;
+let engine;
+let saved;
+
+function store() {
+ return createFootprintState({
+ api,
+ notify,
+ caseId: () => 'case-1',
+ engine: () => engine,
+ onSaved: saved,
+ surface,
+ });
+}
+
+beforeEach(() => {
+ api = { patch: vi.fn(async () => ({})) };
+ notify = vi.fn();
+ layer = { set: vi.fn(), clear: vi.fn(), destroy: vi.fn() };
+ surface = vi.fn(() => layer);
+ engine = { id: 'map' };
+ saved = vi.fn(async () => {});
+});
+
+describe('a ring as GeoJSON', () => {
+ it('is lon-first and closed, which is what the store validates', () => {
+ expect(polygonOf([A, B, C])).toEqual({
+ type: 'Polygon',
+ coordinates: [[[0, 0], [1, 0], [1, 1], [0, 0]]],
+ });
+ });
+
+ it('is nothing at all below three corners, because that is not an area', () => {
+ expect(polygonOf([A, B])).toBe(null);
+ expect(polygonOf([])).toBe(null);
+ });
+});
+
+describe('tracing', () => {
+ it('is off until a place asks for it, and swallows no clicks meanwhile', () => {
+ const trace = store();
+ expect(trace.on).toBe(false);
+ expect(trace.addPoint(A)).toBe(false);
+ });
+
+ it('names the place it is tracing for', () => {
+ const trace = store();
+ trace.start(PLACE);
+ expect(trace.on).toBe(true);
+ expect(trace.place.title).toBe('North quay');
+ });
+
+ it('refuses to start on a row that is not an entity', () => {
+ const trace = store();
+ expect(trace.start({ title: 'nothing' })).toBe(false);
+ expect(trace.on).toBe(false);
+ });
+
+ it('takes the map clicks and draws them, back to front', () => {
+ const trace = store();
+ trace.start(PLACE);
+ expect(trace.addPoint(A)).toBe(true);
+ trace.addPoint(B);
+ trace.addPoint(C);
+ expect(trace.points).toHaveLength(3);
+ expect(trace.complete).toBe(true);
+ trace.undo();
+ expect(trace.points).toEqual([A, B]);
+ expect(trace.complete).toBe(false);
+ expect(layer.set).toHaveBeenCalled();
+ });
+
+ it('starting on a second place drops the first draft rather than mixing them', () => {
+ const trace = store();
+ trace.start(PLACE);
+ trace.addPoint(A);
+ trace.start({ ...PLACE, id: 'e2', title: 'Treeline' });
+ expect(trace.points).toEqual([]);
+ expect(trace.place.id).toBe('e2');
+ });
+});
+
+describe('what gets written', () => {
+ it('writes nothing before Save, and nothing at all on Cancel', async () => {
+ const trace = store();
+ trace.start(PLACE);
+ trace.addPoint(A);
+ trace.addPoint(B);
+ trace.addPoint(C);
+ trace.cancel();
+ expect(api.patch).not.toHaveBeenCalled();
+ expect(trace.on).toBe(false);
+ });
+
+ it('merges the shape onto the place, leaving everything else it holds', async () => {
+ const trace = store();
+ trace.start(PLACE);
+ for (const point of [A, B, C]) trace.addPoint(point);
+ await trace.save();
+ // the radius goes with it: the map draws one of the two, and a circle nobody can
+ // see behind the shape that replaced it is a precision nobody can read
+ expect(api.patch).toHaveBeenCalledWith('/api/cases/case-1/entities/e1', {
+ attrs: { footprint: polygonOf([A, B, C]), radius_m: null },
+ });
+ // and the case is re-read, so the shape appears under its pin
+ expect(saved).toHaveBeenCalled();
+ expect(trace.on).toBe(false);
+ });
+
+ it('sends nothing traced beside the place it belongs to', async () => {
+ // The shape and the pin are each drawn where they were put, and nothing said the
+ // two disagreed: saved, the place claimed an area it does not sit in.
+ const trace = store();
+ trace.start({ ...PLACE, lat: 40, lon: 40 });
+ for (const point of [A, B, C]) trace.addPoint(point);
+ expect(trace.complete).toBe(true);
+ expect(trace.covers).toBe(false);
+
+ await trace.save();
+
+ expect(api.patch).not.toHaveBeenCalled();
+ expect(trace.on).toBe(true); // theirs to move, not thrown away
+ });
+
+ it('takes a shape for a place that carries no point of its own', async () => {
+ // `null` numbers as 0, which would put the place off West Africa and refuse
+ // every shape drawn anywhere else
+ for (const row of [{ id: 'e9', title: 'From a sheet' }, { id: 'e9', lat: null, lon: null }]) {
+ const trace = store();
+ trace.start(row);
+ for (const point of [A, B, C]) trace.addPoint(point);
+ expect(trace.covers).toBe(true);
+
+ await trace.save();
+
+ expect(api.patch).toHaveBeenCalled();
+ }
+ });
+
+ it('sends nothing that is not an area', async () => {
+ const trace = store();
+ trace.start(PLACE);
+ trace.addPoint(A);
+ trace.addPoint(B);
+ await trace.save();
+ expect(api.patch).not.toHaveBeenCalled();
+ expect(trace.on).toBe(true); // still theirs to finish
+ });
+
+ it('keeps the draft when the save fails, so the work is not lost', async () => {
+ api.patch = vi.fn(async () => {
+ throw new Error('disk is full');
+ });
+ const trace = store();
+ trace.start(PLACE);
+ for (const point of [A, B, C]) trace.addPoint(point);
+ await trace.save();
+ expect(notify.mock.calls[0][0]).toContain('disk is full');
+ expect(trace.points).toHaveLength(3);
+ expect(trace.on).toBe(true);
+ });
+});
diff --git a/frontend/src/tools/satellite/state/imagery.svelte.js b/frontend/src/tools/satellite/state/imagery.svelte.js
index a42ad94..bae6904 100644
--- a/frontend/src/tools/satellite/state/imagery.svelte.js
+++ b/frontend/src/tools/satellite/state/imagery.svelte.js
@@ -32,6 +32,7 @@ import {
usageBlocked,
} from '../../../lib/usage.js';
import { variantId } from '../../../lib/sentinel.js';
+import { WAYBACK_ID, waybackId } from '../../../lib/wayback.js';
export const FALLBACK_PROVIDER = FREE_IMAGERY;
@@ -141,7 +142,8 @@ export function createImageryState({ api }) {
*
* @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
+ * @param {object} [variant] Sentinel-2's layer/window/ceiling, or the
+ * Wayback `release`, whichever the shown basemap reads
*/
displayed(chosenId, zoom, variant) {
const chosen = this.find(chosenId);
@@ -157,7 +159,8 @@ export function createImageryState({ api }) {
provider,
// what every downstream consumer asks for: the tile URL, the capture,
// the disk cache — never the bare provider id
- id: variantId(baseId, variant),
+ id:
+ baseId === WAYBACK_ID ? waybackId(baseId, variant?.release) : 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,
diff --git a/frontend/src/tools/satellite/state/imagery.svelte.test.js b/frontend/src/tools/satellite/state/imagery.svelte.test.js
index 32b39d9..e40a4e3 100644
--- a/frontend/src/tools/satellite/state/imagery.svelte.test.js
+++ b/frontend/src/tools/satellite/state/imagery.svelte.test.js
@@ -3,6 +3,7 @@ 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';
+import { WAYBACK_ID } from '../../../lib/wayback.js';
/**
* The catalogue, and the gap between the basemap chosen and the basemap shown.
@@ -15,6 +16,7 @@ import { SENTINEL_ID } from '../../../lib/sentinel.js';
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' };
+const WAYBACK = { id: WAYBACK_ID, label: 'Esri Wayback', imagery: true };
let api;
let settings;
@@ -42,7 +44,7 @@ beforeEach(() => {
};
api = {
get: vi.fn(async (path) => {
- if (path === '/api/satellite/providers') return [ESRI, MAPBOX, SENTINEL];
+ if (path === '/api/satellite/providers') return [ESRI, MAPBOX, SENTINEL, WAYBACK];
return settings;
}),
post: vi.fn(async () => ({})),
@@ -52,7 +54,7 @@ beforeEach(() => {
describe('the catalogue', () => {
it('is read from the backend, not assumed', async () => {
const imagery = await loaded();
- expect(imagery.providers).toHaveLength(3);
+ expect(imagery.providers).toHaveLength(4);
expect(imagery.find('mapbox-satellite')).toEqual(MAPBOX);
});
@@ -201,6 +203,23 @@ describe('Sentinel-2’s choices ride on the id', () => {
});
});
+describe('a Wayback release rides on the id too', () => {
+ it('so a capture names the release its pixels came from', async () => {
+ const imagery = await loaded();
+ const variant = { layer: 'TRUE_COLOR', from: '', to: '', maxcc: 100, release: 64776 };
+ expect(imagery.displayed(WAYBACK_ID, 16, variant).id).toBe('esri-wayback~64776');
+ // the newest release is the plain basemap, which the backend names
+ expect(imagery.displayed(WAYBACK_ID, 16, { ...variant, release: null }).id).toBe(WAYBACK_ID);
+ });
+
+ it('never leaks onto another basemap shown beside it', async () => {
+ const imagery = await loaded();
+ const variant = { layer: 'SWIR', from: '', to: '', maxcc: 100, release: 64776 };
+ expect(imagery.displayed(SENTINEL_ID, 16, variant).id).toBe('sentinel2~SWIR');
+ expect(imagery.displayed('esri-world-imagery', 16, variant).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();
diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.js
index 75bed07..d03242d 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.js
@@ -18,7 +18,7 @@
* @param {(id: string, entity: object, folder: string) => Promise<any>} deps.assignFolder
* @param {() => Promise<any>} deps.reloadCase
*/
-import { filterSaved, isMode, pendingLocate } from '../../../lib/geoTree.js';
+import { filterSaved, isMode, pendingLocate, savedFolders } from '../../../lib/geoTree.js';
const GROUP_KEY = 'azimut:satelliteSavedGroup';
const LOCATE_BATCH = 10;
@@ -36,6 +36,14 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
let proofs = $state([]);
let kind = $state('all');
let query = $state('');
+ /**
+ * Which folder the map is drawing, or null for every one of them.
+ *
+ * The map's own filter rather than the panel's: the tree browses folders as
+ * branches, and a busy case is read by taking the other folders off the
+ * picture. `null` is all, `''` is what nobody has filed yet.
+ */
+ let folder = $state(null);
let group = $state(loadGroup());
let locating = $state(null); // { done, total } while a pass runs
let acceptingId = $state(null);
@@ -223,6 +231,16 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
set query(value) {
query = value;
},
+ get folder() {
+ return folder;
+ },
+ set folder(value) {
+ folder = value;
+ },
+ /** The folders the rows on offer are filed under, each with its tally. */
+ get folders() {
+ return savedFolders(this.shownRows);
+ },
get group() {
return group;
},
@@ -247,7 +265,7 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
},
/** What the panel is showing, which is also what the map layer draws. */
get shown() {
- return filterSaved(this.shownRows, { kind, query });
+ return filterSaved(this.shownRows, { kind, query, folder });
},
get pending() {
return pendingLocate(rows);
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.js b/frontend/src/tools/satellite/state/wayback.svelte.js
new file mode 100644
index 0000000..e5890a5
--- /dev/null
+++ b/frontend/src/tools/satellite/state/wayback.svelte.js
@@ -0,0 +1,192 @@
+/**
+ * Which Wayback release a map shows, and which releases changed the point.
+ *
+ * Both questions reach Esri, so the store is about *when* it asks:
+ *
+ * - **The release list is read once**, the first time the basemap is shown or
+ * its picker opened, never on mount.
+ * - **The change list is read while the picker is open**, for the tile under
+ * the crosshair. A pan inside that tile has the same history and asks
+ * nothing; a pan out of it marks the list stale until it is read again.
+ * - **A failed read is said, not hidden.** An empty change list means the point
+ * never changed; a failed one means we do not know, and the picker falls back
+ * to every release rather than claiming there is nothing to see.
+ *
+ * The arithmetic is `lib/wayback.js`; this holds what was asked and what came back.
+ *
+ * @param {object} deps
+ * @param {object} deps.api the app's fetch wrapper
+ * @param {() => {lat: number, lon: number, zoom: number}} deps.place where the map points
+ */
+import {
+ changesKey,
+ positionOf,
+ releaseDate,
+ stepRelease,
+ visibleReleases,
+} from '../../../lib/wayback.js';
+
+export function createWaybackState({ api, place }) {
+ let releases = $state([]); // [{ release, date }], newest first
+ let listNote = $state('');
+ let listing = null; // the one in-flight read of the list
+ let release = $state(null); // null = the newest
+ let menuOpen = $state(false);
+ let changesOnly = $state(true);
+ let changes = $state(null); // [release] for `changesFor`, null when unknown
+ let pictures = $state({}); // release → { acquired, source } for those changes
+ let changesFor = $state('');
+ let changesBusy = $state(false);
+ let changesNote = $state('');
+ let changesRequest = 0;
+ const changesCache = new Map();
+
+ const hereKey = () => {
+ const { lat, lon, zoom } = place();
+ return changesKey(lat, lon, zoom);
+ };
+
+ async function loadReleases() {
+ if (releases.length) return releases;
+ listing ??= (async () => {
+ try {
+ const answer = await api.get('/api/satellite/wayback/releases');
+ releases = answer.releases ?? [];
+ listNote = '';
+ } catch (error) {
+ listNote = `Could not read the release list: ${error.message}`;
+ } finally {
+ listing = null;
+ }
+ return releases;
+ })();
+ return listing;
+ }
+
+ /** A history as the route answers it: each picture and the release that first showed it. */
+ function keep(list) {
+ changes = list.map((entry) => entry.release);
+ pictures = Object.fromEntries(list.map((entry) => [entry.release, entry]));
+ }
+
+ async function loadChanges() {
+ const key = hereKey();
+ if (changesCache.has(key)) {
+ keep(changesCache.get(key));
+ changesFor = key;
+ changesNote = '';
+ return changes;
+ }
+ const requestId = ++changesRequest;
+ const { lat, lon, zoom } = place();
+ changesBusy = true;
+ changesNote = '';
+ try {
+ const answer = await api.get(
+ `/api/satellite/wayback/changes?lat=${lat}&lon=${lon}&zoom=${Math.round(zoom)}`
+ );
+ if (requestId !== changesRequest) return changes;
+ changesCache.set(key, answer.changes ?? []);
+ keep(answer.changes ?? []);
+ changesFor = key;
+ } catch (error) {
+ if (requestId !== changesRequest) return changes;
+ changes = null;
+ pictures = {};
+ changesFor = '';
+ changesNote = `Could not read this point's history: ${error.message}`;
+ } finally {
+ if (requestId === changesRequest) changesBusy = false;
+ }
+ return changes;
+ }
+
+ return {
+ get releases() {
+ return releases;
+ },
+ get listNote() {
+ return listNote;
+ },
+ get release() {
+ return release;
+ },
+ get menuOpen() {
+ return menuOpen;
+ },
+ set menuOpen(value) {
+ menuOpen = value;
+ },
+ get changesOnly() {
+ return changesOnly;
+ },
+ get changes() {
+ return changes;
+ },
+ get changesBusy() {
+ return changesBusy;
+ },
+ get changesNote() {
+ return changesNote;
+ },
+ /** The point moved out of the tile the change list describes. */
+ get stale() {
+ return Boolean(changesFor) && changesFor !== hereKey();
+ },
+ /** What the provider id carries (`lib/wayback.js` `waybackId`). */
+ get variant() {
+ return { release };
+ },
+ /**
+ * The publication date of what is showing, '' until the list is read.
+ *
+ * Narrowed to changes, the newest release is not a picture of its own: it
+ * shows the latest change's pixels, so it is named by that change, the row
+ * the picker highlights, rather than by a date no row carries.
+ */
+ get date() {
+ if (release == null && changesOnly && changes?.length && !this.stale) {
+ return releaseDate(releases, changes[0]);
+ }
+ return releaseDate(releases, release);
+ },
+ /** When and by what a change's picture was taken, when its metadata says. */
+ picture(number) {
+ return pictures[number] ?? null;
+ },
+ /** The releases the picker offers. Every release until the changes are known. */
+ get visible() {
+ return visibleReleases(releases, changes, changesOnly && !this.stale);
+ },
+ get position() {
+ return positionOf(this.visible, releases, release);
+ },
+
+ loadReleases,
+ loadChanges,
+
+ toggleMenu() {
+ menuOpen = !menuOpen;
+ if (!menuOpen) return;
+ loadReleases();
+ loadChanges();
+ },
+
+ setChangesOnly(value) {
+ changesOnly = Boolean(value);
+ if (changesOnly && !changes) loadChanges();
+ },
+
+ /** Show one release. The newest is stored as null so the id stays plain. */
+ pick(next) {
+ release = next == null || next === releases[0]?.release ? null : next;
+ },
+
+ /** `-1` newer, `+1` older, through what the picker offers. */
+ step(direction) {
+ const next = stepRelease(this.visible, releases, release, direction);
+ if (next !== undefined) this.pick(next);
+ return next;
+ },
+ };
+}
diff --git a/frontend/src/tools/satellite/state/wayback.svelte.test.js b/frontend/src/tools/satellite/state/wayback.svelte.test.js
new file mode 100644
index 0000000..5400fcd
--- /dev/null
+++ b/frontend/src/tools/satellite/state/wayback.svelte.test.js
@@ -0,0 +1,159 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createWaybackState } from './wayback.svelte.js';
+
+/**
+ * Both questions this store asks reach Esri, so what it must get right is when
+ * it asks and what it refuses to claim.
+ */
+
+const RELEASES = [
+ { release: 26334, date: '2026-08-05' },
+ { release: 64776, date: '2023-08-31' },
+ { release: 25982, date: '2023-06-13' },
+ { release: 10, date: '2014-02-20' },
+];
+
+let at;
+let get;
+
+function store() {
+ return createWaybackState({ api: { get }, place: () => at });
+}
+
+beforeEach(() => {
+ at = { lat: 50.45, lon: 30.51, zoom: 15 };
+ get = vi.fn(async (path) => {
+ if (path.includes('/wayback/releases')) return { releases: RELEASES };
+ if (path.includes('/wayback/changes')) {
+ return {
+ changes: [
+ { release: 64776, acquired: '2022-03-31', source: 'Maxar WV03' },
+ { release: 10, acquired: '2011-09-20', source: 'DigitalGlobe WV02' },
+ ],
+ zoom: 15,
+ };
+ }
+ throw new Error(`unexpected ${path}`);
+ });
+});
+
+describe('asking Esri', () => {
+ it('asks nothing until it is used', () => {
+ store();
+ expect(get).not.toHaveBeenCalled();
+ });
+
+ it('reads the release list once, however often it is asked', async () => {
+ const wb = store();
+ await Promise.all([wb.loadReleases(), wb.loadReleases()]);
+ await wb.loadReleases();
+ expect(get.mock.calls.filter(([path]) => path.includes('/releases'))).toHaveLength(1);
+ expect(wb.date).toBe('2026-08-05');
+ });
+
+ it('opening the picker reads the list and this point’s history', async () => {
+ const wb = store();
+ wb.toggleMenu();
+ await vi.waitFor(() => expect(wb.changes).toEqual([64776, 10]));
+ expect(get).toHaveBeenCalledWith('/api/satellite/wayback/changes?lat=50.45&lon=30.51&zoom=15');
+ expect(wb.visible.map((entry) => entry.release)).toEqual([64776, 10]);
+ });
+
+ it('answers a nudge inside the same tile from memory', async () => {
+ const wb = store();
+ await wb.loadChanges();
+ at = { lat: 50.4501, lon: 30.5101, zoom: 15 };
+ expect(wb.stale).toBe(false);
+ await wb.loadChanges();
+ expect(get.mock.calls.filter(([path]) => path.includes('/changes'))).toHaveLength(1);
+ });
+
+ it('marks the history stale once the map leaves its tile, and offers every release meanwhile', async () => {
+ const wb = store();
+ await wb.loadReleases();
+ await wb.loadChanges();
+ at = { lat: 48.85, lon: 2.29, zoom: 15 };
+ expect(wb.stale).toBe(true);
+ // a history of somewhere else must not narrow what is offered here
+ expect(wb.visible).toHaveLength(4);
+ });
+});
+
+describe('what it refuses to claim', () => {
+ it('says a failed history is unknown rather than empty', async () => {
+ get = vi.fn(async (path) => {
+ if (path.includes('/releases')) return { releases: RELEASES };
+ throw new Error('could not read this point');
+ });
+ const wb = store();
+ await wb.loadReleases();
+ await wb.loadChanges();
+ expect(wb.changes).toBeNull();
+ expect(wb.changesNote).toContain('could not read this point');
+ // every release stays on offer: we do not know which changed
+ expect(wb.visible).toHaveLength(4);
+ });
+
+ it('says so when the release list cannot be read', async () => {
+ get = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ const wb = store();
+ await wb.loadReleases();
+ expect(wb.releases).toEqual([]);
+ expect(wb.listNote).toContain('offline');
+ });
+});
+
+describe('naming what is on screen', () => {
+ it('keeps when each picture was taken beside the release that showed it', async () => {
+ const wb = store();
+ await wb.loadChanges();
+ expect(wb.picture(64776)).toMatchObject({ acquired: '2022-03-31', source: 'Maxar WV03' });
+ expect(wb.picture(26334)).toBeNull();
+ });
+
+ it('names the newest release by the change it shows once narrowed to changes', async () => {
+ // the newest release carries the latest change's pixels; two dates for one
+ // picture read as two pictures
+ const wb = store();
+ await wb.loadReleases();
+ expect(wb.date).toBe('2026-08-05');
+ await wb.loadChanges();
+ expect(wb.date).toBe('2023-08-31');
+ wb.setChangesOnly(false);
+ expect(wb.date).toBe('2026-08-05');
+ });
+});
+
+describe('choosing a release', () => {
+ it('keeps the newest as the plain basemap', async () => {
+ const wb = store();
+ await wb.loadReleases();
+ wb.pick(26334);
+ expect(wb.release).toBeNull();
+ expect(wb.variant).toEqual({ release: null });
+ wb.pick(25982);
+ expect(wb.variant).toEqual({ release: 25982 });
+ });
+
+ it('steps through what the picker offers', async () => {
+ const wb = store();
+ await wb.loadReleases();
+ await wb.loadChanges();
+ // the newest release shows the latest change's pixels here, so one step
+ // older is the change before it
+ expect(wb.step(1)).toBe(10);
+ expect(wb.step(1)).toBeUndefined();
+ expect(wb.release).toBe(10);
+ expect(wb.step(-1)).toBe(64776);
+ });
+
+ it('reads the history when narrowed to changes it does not have yet', async () => {
+ const wb = store();
+ wb.setChangesOnly(false);
+ expect(get).not.toHaveBeenCalled();
+ wb.setChangesOnly(true);
+ await vi.waitFor(() => expect(wb.changes).toEqual([64776, 10]));
+ });
+});
diff --git a/frontend/src/tools/settings/ImageryTab.svelte b/frontend/src/tools/settings/ImageryTab.svelte
index 18c8972..d473810 100644
--- a/frontend/src/tools/settings/ImageryTab.svelte
+++ b/frontend/src/tools/settings/ImageryTab.svelte
@@ -57,7 +57,8 @@
<section class="group">
<h3>Providers</h3>
<p class="intro">
- Add provider keys to unlock more Satellite basemaps; usage appears on each card.
+ Add provider keys to unlock more Satellite basemaps and layers; usage appears on
+ each card.
</p>
<div class="cards">
@@ -94,14 +95,17 @@
type="checkbox"
bind:checked={enabled[k.id]}
onchange={saveProviderPrefs}
- title="Show or hide this basemap in the Satellite tab"
- aria-label="Show {k.label} in the Satellite tab"
+ title="Offer this in the Satellite tab"
+ aria-label="Offer {k.label} in the Satellite tab"
/>
{/if}
</div>
- <!-- one line either way: what it would cost, or what it has cost -->
- {#if keys[k.id] || count}
+ <!-- one line either way: what it would cost, or what it has cost. A
+ key that buys no tiles (FIRMS) has neither, and says so once. -->
+ {#if k.metered === false}
+ {#if !open[k.id]}<p class="card-cost">{k.cost}</p>{/if}
+ {:else if keys[k.id] || count}
<div class="card-meter">
<div class="meter-track" aria-hidden="true">
<div
@@ -173,7 +177,7 @@
<p class="overage">{k.cost}. {k.overage}</p>
- {#if keys[k.id] || count}
+ {#if k.metered !== false && (keys[k.id] || count)}
{#if usageBlocked(count, k.id, overrides, tiers)}
<p class="blocked">
<Icon name="alert" size={12} />
diff --git a/pyproject.toml b/pyproject.toml
index 6714065..c0ce3b0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -155,6 +155,7 @@ packages = ["src/azimut"]
"extension/maptools.js" = "azimut/extension/maptools.js"
"extension/mapdraw.js" = "azimut/extension/mapdraw.js"
"extension/mapref.js" = "azimut/extension/mapref.js"
+"extension/maplink.js" = "azimut/extension/maplink.js"
"extension/mapoverlay.js" = "azimut/extension/mapoverlay.js"
"extension/overlay.js" = "azimut/extension/overlay.js"
"extension/reverse.js" = "azimut/extension/reverse.js"
diff --git a/scripts/build_earth_fixture.py b/scripts/build_earth_fixture.py
new file mode 100644
index 0000000..d08d252
--- /dev/null
+++ b/scripts/build_earth_fixture.py
@@ -0,0 +1,154 @@
+"""Turn an Earth calibration run into the fixture the parser is tested against.
+
+ python scripts/build_earth_fixture.py /tmp/azimut-earth-calibration [more runs…]
+
+`frontend/calibration/earth.mjs` opens Google Earth at a camera it placed on
+the ground, then at the same camera a known step east, a known step north and
+at half the distance, and keeps a screenshot of each. This registers those
+screenshots against each other and writes `tests/fixtures/earth-scale.json`:
+
+* **how far the picture moved** for each step, in CSS pixels, found by phase
+ correlation on the middle of the window (Earth's toolbar, status bar and
+ buttons are round the edges and do not move with the map);
+* **where Earth draws its camera**, from the half-distance shot. Halving the
+ distance draws the ground twice as big about the camera's own pixel, so the
+ base shot shrunk by two about the middle of the window only lines up with it
+ if that pixel is the middle, and is shifted by half the difference if not.
+
+What it writes is measurement only. Whether the app's parse of each URL
+predicts it is `tests/test_mapsites.py`'s question, which is the point: the
+formula in `engine/mapsites.py` is checked against pictures, not against a
+second copy of itself.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from PIL import Image
+
+ROOT = Path(__file__).resolve().parents[1]
+OUT = ROOT / "tests" / "fixtures" / "earth-scale.json"
+
+#: A correlation peak below this is two pictures that do not share enough to say
+#: how far apart they are: imagery still arriving, or a label over everything.
+MIN_PEAK = 0.2
+
+
+def _grey(path: Path, shrink_about_middle: float | None = None) -> np.ndarray:
+ image = Image.open(path).convert("L")
+ if shrink_about_middle:
+ w, h = image.size
+ k = shrink_about_middle
+ # output(x) = input(middle + (x − middle)·k): content shrinks by k about the middle
+ image = image.transform(
+ image.size,
+ Image.Transform.AFFINE,
+ (k, 0, w / 2 * (1 - k), 0, k, h / 2 * (1 - k)),
+ resample=Image.Resampling.BICUBIC,
+ )
+ return np.asarray(image, dtype=float)
+
+
+def _middle(a: np.ndarray) -> np.ndarray:
+ h, w = a.shape
+ return a[int(h * 0.2) : int(h * 0.8), int(w * 0.2) : int(w * 0.8)]
+
+
+def _peak_offset(column: np.ndarray, at: int) -> float:
+ """Sub-pixel position of a correlation peak, from the parabola through it."""
+ n = len(column)
+ left, mid, right = column[(at - 1) % n], column[at], column[(at + 1) % n]
+ bend = left - 2 * mid + right
+ return at + ((left - right) / (2 * bend) if bend else 0.0)
+
+
+def moved(a: np.ndarray, b: np.ndarray) -> tuple[float, float, float]:
+ """How far the picture moved from `a` to `b`, in pixels, and how sure."""
+ a, b = _middle(a), _middle(b)
+ a, b = a - a.mean(), b - b.mean()
+ window = np.outer(np.hanning(a.shape[0]), np.hanning(a.shape[1]))
+ cross = np.fft.fft2(b * window) * np.conj(np.fft.fft2(a * window))
+ cross /= np.abs(cross) + 1e-9
+ surface = np.real(np.fft.ifft2(cross))
+ iy, ix = np.unravel_index(int(np.argmax(surface)), surface.shape)
+ dy = _peak_offset(surface[:, ix], int(iy))
+ dx = _peak_offset(surface[iy, :], int(ix))
+ if dy > surface.shape[0] / 2:
+ dy -= surface.shape[0]
+ if dx > surface.shape[1] / 2:
+ dx -= surface.shape[1]
+ return float(dx), float(dy), float(surface.max())
+
+
+def build(run: Path, case: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
+ trouble: list[str] = []
+ shot = lambda name, shrink=None: _grey(run / case["shots"][name]["image"], shrink) # noqa: E731
+ base = shot("base")
+ east = moved(base, shot("east"))
+ north = moved(base, shot("north"))
+ # the half-distance shot shrunk back by two: lined up with the base shot
+ # when Earth's camera is the middle of the window
+ half = moved(base, shot("half", 2.0))
+ for name, (_dx, _dy, peak) in (("east", east), ("north", north), ("half", half)):
+ if peak < MIN_PEAK:
+ trouble.append(f"the {name} shot registered weakly (peak {peak:.2f})")
+ return {
+ "id": case["id"],
+ "window": case["window"],
+ "base": case["shots"]["base"]["url"],
+ "east": {"d_lon": case["dLon"], "moved_px": round(east[0], 3), "across_px": round(east[1], 3)},
+ "north": {"d_lat": case["dLat"], "moved_px": round(north[1], 3), "across_px": round(north[0], 3)},
+ # camera pixel minus the middle of the window
+ "camera_offset_px": {"x": round(-2 * half[0], 2), "y": round(-2 * half[1], 2)},
+ }, trouble
+
+
+def main(runs: list[str]) -> int:
+ if not runs:
+ print(__doc__)
+ return 2
+ cases: dict[str, dict[str, Any]] = {}
+ dropped: list[str] = []
+ for folder in map(Path, runs):
+ raw = json.loads((folder / "earth-shots.json").read_text(encoding="utf-8"))
+ for case in raw["measured"]:
+ entry, trouble = build(folder, case)
+ if trouble:
+ dropped.append(f"{case['id']}: {'; '.join(trouble)}")
+ continue
+ cases[entry["id"]] = entry
+ print(
+ f"{entry['id']:<14} east {entry['east']['moved_px']:+9.3f} px "
+ f"north {entry['north']['moved_px']:+9.3f} px "
+ f"camera {entry['camera_offset_px']['x']:+.2f}, {entry['camera_offset_px']['y']:+.2f} px"
+ )
+ OUT.write_text(
+ json.dumps(
+ {
+ "what": "Google Earth screenshots of one camera, a known step east, a known step north "
+ "and at half the distance, registered against each other.",
+ "how": "frontend/calibration/earth.mjs takes the shots (npm run calibrate:earth); "
+ "scripts/build_earth_fixture.py registers them.",
+ "why": "Earth states its scale as a camera distance and a field of view. "
+ "tests/test_mapsites.py checks the parse of each base URL predicts how far the "
+ "picture moved, and that the camera is drawn at the middle of the window.",
+ "cases": sorted(cases.values(), key=lambda c: c["id"]),
+ },
+ indent=1,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ print(f"\n{len(cases)} cases → {OUT.relative_to(ROOT)}")
+ for line in dropped:
+ print(f" left out, {line}")
+ return 1 if dropped else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/scripts/build_map_fixture.py b/scripts/build_map_fixture.py
index 25d6085..2ee286c 100644
--- a/scripts/build_map_fixture.py
+++ b/scripts/build_map_fixture.py
@@ -38,18 +38,11 @@ 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
+from azimut.engine.mapsites import _CAMERA_CENTRE, _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).
@@ -137,8 +130,8 @@ def build(entry: dict[str, Any]) -> tuple[dict[str, Any] | None, list[str]]:
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
+ # The views that state a size rather than a level — Apple's span, Earth's
+ # distance, 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.
@@ -280,11 +273,7 @@ def main() -> int:
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)}")
@@ -317,6 +306,14 @@ def main() -> int:
"solved from its own two zooms.",
),
"how": "Rebuilt by scripts/build_map_fixture.py from tests/fixtures/map-sites.raw.json.",
+ # The offset the app ships as each site's starting answer, carried here
+ # so both suites read one copy of it: `tests/test_mapsites.py` checks it
+ # against the recordings above, and the extension's engine test checks
+ # that a fresh install draws from it (`extensionMapEngine.test.js`).
+ "hints": {
+ site: {"x": at[0], "y": at[1], "min_w": at[2]}
+ for site, at in _CAMERA_CENTRE.items()
+ },
"recordings": recordings,
}
if "rounding" in raw:
@@ -333,10 +330,6 @@ def main() -> int:
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:
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index 5da470d..00ca699 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -54,6 +54,7 @@ from pydantic import BaseModel
from .. import __version__, config
from ..engine import (
extinstall,
+ firms,
geo,
mapsites,
media as media_engine,
@@ -67,6 +68,9 @@ from .limits import MAX_IMAGE_BYTES
from .satellite import (
GridSaveIn,
apply_grid_marks,
+ firms_answer,
+ firms_key,
+ firms_sensors,
get_search_grid,
list_search_grids,
locate_on_save,
@@ -223,6 +227,12 @@ async def ingest_screenshot(
bearing: float | None = Form(default=None, ge=0, lt=360),
captured_at: str = Form(default=""),
title: str = Form(default="", max_length=200),
+ # burn a scale bar and a north arrow into the shot (the popup's tick), and
+ # how many image pixels the grab holds per CSS pixel — a zoom describes CSS
+ # pixels, so without the ratio a 2× screen would be told it covers twice
+ # the ground it does
+ scale_north: bool = Form(default=False),
+ device_scale: float = Form(default=1.0, gt=0, le=8),
# which extension build took the shot — provenance, nothing else keys on it
extension: str = Form(default="", max_length=32),
) -> dict[str, Any]:
@@ -272,6 +282,24 @@ async def ingest_screenshot(
raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc
site = parsed["site"]
+ # Neither mark is invented for a map we did not draw: the bar needs the
+ # view's own resolution, and the needle a heading somebody stated — most of
+ # these sites write no rotation into their URL, and the popup's field is
+ # where an analyst says which way the map was turned.
+ marks = (
+ tiles.burn_scale_north(
+ img,
+ meters_per_pixel=(
+ tiles.meters_per_pixel(lat, zoom) / device_scale
+ if lat is not None and zoom is not None
+ else None
+ ),
+ bearing=bearing,
+ units=config.load_settings().get("units", "metric"),
+ )
+ if scale_north
+ else None
+ )
attribution = ATTRIBUTIONS.get(site, f"© {urlsplit(url).netloc.lower()}")
img = tiles.burn_attribution(img, attribution)
@@ -308,6 +336,7 @@ async def ingest_screenshot(
"captured_at": captured.isoformat(timespec="seconds") if captured else None,
"attribution": attribution,
"attribution_burned": True,
+ "marks": marks,
"fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"width": img.width,
"height": img.height,
@@ -599,6 +628,65 @@ def sky(lat: float, lon: float, date: str | None = None) -> dict[str, Any]:
return satellite_sky(lat=lat, lon=lon, day=date, at=None, zone=None)
+# One screen of somebody else's map is one request: the panel has no tile grid
+# to hang tiles on, so it asks for a single picture over the ground it can see.
+# Capped because the width and the height arrive from a page — a window is at
+# most a few thousand pixels across, and a bigger number is a bigger bill for
+# NASA, not a sharper answer.
+FIRMS_IMAGE_MAX = 2560
+
+
[email protected]("/firms", dependencies=[Depends(require_token)])
+def firms_image(
+ south: float = Query(ge=-90, le=90),
+ west: float = Query(ge=-180, le=180),
+ north: float = Query(ge=-90, le=90),
+ east: float = Query(ge=-180, le=180),
+ width: int = Query(gt=0, le=FIRMS_IMAGE_MAX),
+ height: int = Query(gt=0, le=FIRMS_IMAGE_MAX),
+ sensor: str = "viirs",
+ window: str = "24h",
+ first: str = "",
+ last: str = "",
+) -> Response:
+ """Active fire detections over one rectangle of ground, as a picture.
+
+ The app's own map draws FIRMS as tiles (``/api/firms/tiles``). The panel
+ over Google or Yandex has no tile grid of its own, so it asks for the whole
+ of what it can see at once and lays that over the map — which is also one
+ request per settled view rather than a dozen, and the FIRMS allowance is
+ counted in requests.
+
+ Same key, same guard, same reason as the app's route: NASA puts the
+ MAP_KEY in the path, so it never crosses into a page.
+ """
+ key = firms_key()
+ if not key:
+ raise HTTPException(status_code=404, detail="no FIRMS key saved")
+ if north <= south or east <= west:
+ raise HTTPException(status_code=422, detail="the rectangle has no area")
+ try:
+ url = firms.image_url(
+ key,
+ bounds=firms.bounds_of(south, west, north, east),
+ width=width,
+ height=height,
+ sensor_id=sensor,
+ window=window,
+ first=first,
+ last=last,
+ )
+ except (KeyError, ValueError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return firms_answer(url)
+
+
[email protected]("/firms/sensors", dependencies=[Depends(require_token)])
+def firms_catalogue() -> dict[str, Any]:
+ """What the panel can offer, and whether a key makes it offerable at all."""
+ return firms_sensors()
+
+
@router.get("/grids", dependencies=[Depends(require_token)])
def grids(case_id: str) -> list[dict[str, Any]]:
"""The case's saved sweeps, as the picker's summaries."""
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 1be32aa..27b2db5 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -22,6 +22,7 @@ from pydantic import BaseModel, Field
from .. import config
from ..engine import (
cities,
+ firms,
geo,
google_tiles,
localtime,
@@ -31,6 +32,7 @@ from ..engine import (
sky,
tilecache,
tiles,
+ wayback,
)
from ..workspace import Case, CaseError
from . import events
@@ -80,6 +82,8 @@ class CaptureIn(BaseModel):
marker_y: int = Field(default=0, ge=-tiles.SIZE_MAX, le=tiles.SIZE_MAX)
marker_lat: float | None = Field(default=None, ge=-90, le=90)
marker_lon: float | None = Field(default=None, ge=-180, le=180)
+ # burn a scale bar and a north arrow into the crop (capture menu)
+ scale_north: bool = False
class PlaceIn(BaseModel):
@@ -135,6 +139,15 @@ def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _units() -> str:
+ """The analyst's measurement system, for anything drawn with a number on it.
+
+ Presentation only, as every display preference is: the capture's own
+ provenance keeps metres whatever the bar says.
+ """
+ return config.load_settings().get("units", "metric")
+
+
def saved_changed(case: Case) -> None:
"""Say that this case's saved work moved (``api/events.py``).
@@ -293,6 +306,44 @@ def sentinel_coverage(
return result
[email protected]("/satellite/wayback/releases")
+def wayback_releases() -> dict[str, Any]:
+ """Every World Imagery Wayback release, newest first.
+
+ Asked when the analyst shows the Wayback basemap, never on mount: it is a
+ request to Esri. Key-less and unmetered.
+ """
+ try:
+ listed = wayback.releases()
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"could not read the release list: {exc}") from exc
+ return {"releases": [{"release": r.number, "date": r.date} for r in listed]}
+
+
[email protected]("/satellite/wayback/changes")
+def wayback_changes(
+ lat: float = Query(ge=-90, le=90),
+ lon: float = Query(ge=-180, le=180),
+ zoom: int = Query(ge=1, le=22),
+) -> dict[str, Any]:
+ """The distinct pictures of a point, newest first, each with the release
+ that first published it and when it was taken.
+
+ A few small requests per picture found, so it is asked while the picker is
+ open and answered from memory for the same tile afterwards.
+ """
+ try:
+ found = wayback.local_changes(lat, lon, zoom)
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"could not read this point's history: {exc}") from exc
+ return {
+ "changes": [
+ {"release": c.release, "acquired": c.acquired, "source": c.source} for c in found
+ ],
+ "zoom": min(zoom, wayback.MAX_ZOOM),
+ }
+
+
@router.post("/satellite/usage/{meter}")
def record_widget_usage(meter: str) -> dict[str, Any]:
"""Count one billed *map load* for a widget basemap.
@@ -460,6 +511,118 @@ def tile_proxy(provider_id: str, z: int, x: int, y: int) -> Response:
raise HTTPException(status_code=404, detail="no imagery at this location/zoom")
+#: What FIRMS means by the placard it draws instead of detections. Its own
+#: wording, which covers both ways a key stops working.
+FIRMS_REFUSED = "FIRMS did not accept this key, or the account is over its limit"
+
+
+def firms_key() -> str | None:
+ """The FIRMS key, if the layer is usable at all.
+
+ Same three questions a keyed basemap answers (``tiles.all_providers``): is
+ there a key, has it been switched off in Settings, and was it last seen
+ failing. A key known to be dead withholds the layer until it changes or a
+ test passes, rather than drawing an empty map over a real one.
+ """
+ settings = config.load_settings()
+ if not settings.get("providers_enabled", {}).get("firms", True):
+ return None
+ if config.provider_key_bad("firms", settings):
+ return None
+ return (settings.get("api_keys") or {}).get("firms")
+
+
[email protected]("/firms/sensors")
+def firms_sensors() -> dict[str, Any]:
+ """What the fire layer can be asked, and whether it can be asked at all.
+
+ Read on mount by the Layers panel, so it touches no network: the sensors
+ and the windows are a catalogue, and ``keyed`` is a look at settings.json.
+ A layer nobody can use says so with the reason rather than failing on the
+ first tile.
+ """
+ return {
+ "keyed": bool(firms_key()),
+ "sensors": [{"id": s.id, "label": s.label} for s in firms.SENSORS],
+ "windows": list(firms.WINDOWS),
+ "max_zoom": firms.MAX_ZOOM,
+ "max_range_days": firms.MAX_RANGE_DAYS,
+ }
+
+
[email protected]("/firms/tiles/{z}/{x}/{y}")
+def firms_tile(
+ z: int,
+ x: int,
+ y: int,
+ sensor: str = "viirs",
+ window: str = "24h",
+ first: str = "",
+ last: str = "",
+) -> Response:
+ """One tile of active fire detections, proxied so the key stays here.
+
+ FIRMS puts the MAP_KEY in the *path*, so a tile URL the browser could build
+ would publish it in the page, in the network log and in a screenshot of
+ either. Everything else is this endpoint translating the map's z/x/y into
+ the bounding box a WMS wants (``engine/firms.py``).
+
+ Never cached to disk: the live layers are what is burning now, refreshed
+ upstream every fifteen minutes, and a cached fire is a lie with a timestamp.
+ """
+ key = firms_key()
+ if not key:
+ raise HTTPException(status_code=404, detail="no FIRMS key saved")
+ if firms.too_deep(z):
+ raise HTTPException(
+ status_code=422,
+ detail=f"FIRMS detections are drawn to z{firms.MAX_ZOOM}; deeper is one mark per pixel",
+ )
+ grid = 1 << z
+ if z < 0 or not (0 <= x < grid) or not (0 <= y < grid):
+ raise HTTPException(status_code=422, detail="tile coordinates out of range")
+ try:
+ url = firms.tile_url(
+ key, sensor_id=sensor, window=window, z=z, x=x, y=y, first=first, last=last
+ )
+ except (KeyError, ValueError) as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ return firms_answer(url)
+
+
+def firms_answer(url: str) -> Response:
+ """Fetch one FIRMS picture and hand it on, or say what FIRMS said.
+
+ Shared with the extension's own route (``api/ingest.py``): the two ask for
+ different rectangles and want exactly the same handling of a refusal, and
+ FIRMS refuses by answering 200 with an XML report in the body.
+ """
+ try:
+ response = httpx.get(url, headers={"User-Agent": tiles.USER_AGENT}, timeout=20)
+ except Exception as exc:
+ raise HTTPException(status_code=502, detail=f"FIRMS unreachable: {exc}") from exc
+ if response.status_code >= 400 or "xml" in response.headers.get("content-type", ""):
+ raise HTTPException(
+ status_code=502, detail=firms.service_error(response.text) or "FIRMS refused the request"
+ )
+ # A key FIRMS will not accept comes back as 200 and a picture saying so.
+ # Nothing in the answer is an error, so without this the map would tile that
+ # placard across the ground. It is an auth-shaped verdict and nothing else,
+ # which is what lets it bench the layer the way a dead basemap key is
+ # benched: the Layers row goes back to "add a key", with the reason.
+ if firms.is_placard(response.content):
+ config.record_provider_status("firms", False, FIRMS_REFUSED)
+ raise HTTPException(status_code=502, detail=FIRMS_REFUSED)
+ return Response(
+ content=response.content,
+ media_type="image/png",
+ # The browser may hold a picture for a few minutes — long enough for a
+ # pan back, short enough that a live layer is still live. FIRMS itself
+ # updates every fifteen.
+ headers={"Cache-Control": "private, max-age=300"},
+ )
+
+
@router.get("/satellite/imagery-date")
def imagery_date(
lat: float = Query(ge=-90, le=90),
@@ -471,7 +634,21 @@ def imagery_date(
Only Esri World Imagery exposes per-scene capture dates; for any other
provider we report ``supported: false`` so the UI can hide the readout.
+ A Wayback release answers from that release's own metadata, since the
+ pixels under a point differ from one release to the next.
"""
+ base_id, sep, spec = provider.partition(wayback.VARIANT_SEP)
+ if base_id == wayback.BASE_ID:
+ try:
+ number = wayback.parse_variant(spec) if sep else wayback.releases()[0].number
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+ except Exception:
+ return {"supported": True, "date": None, "source": None}
+ found = wayback.capture_date(lat, lon, int(zoom), number)
+ if found is None:
+ return {"supported": True, "date": None, "source": None}
+ return {"supported": True, **found}
if provider != "esri-world-imagery":
return {"supported": False, "date": None, "source": None}
result = tiles.esri_capture_date(lat, lon, int(zoom))
@@ -770,6 +947,7 @@ def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
provider, bearing=body.bearing, marker_style=body.marker_style,
marker_x=body.marker_x, marker_y=body.marker_y,
marker_lat=body.marker_lat, marker_lon=body.marker_lon,
+ scale_north=body.scale_north, units=_units(),
)
except tiles.TileFetchError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
@@ -825,6 +1003,11 @@ async def capture_screenshot(
provider: str = Form(),
bearing: float = Form(default=0.0, ge=0, le=360),
framed: bool = Form(default=False),
+ scale_north: bool = Form(default=False),
+ # How many image pixels the crop holds per CSS pixel. A zoom describes CSS
+ # pixels, so a 2× screen puts two of the file's pixels inside every one of
+ # them — without this the bar would state twice the ground it covers.
+ device_scale: float = Form(default=1.0, gt=0, le=8),
) -> dict[str, Any]:
"""File a user-made screenshot of a widget basemap as a capture.
@@ -864,6 +1047,21 @@ async def capture_screenshot(
except Exception as exc:
raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc
+ # Only onto a registered crop. A pasted screenshot's coordinates describe
+ # the map view at filing time rather than the picture itself, so nothing
+ # here knows what a pixel of it is worth — and a bar drawn over that would
+ # be the one mark on the capture that cannot be checked.
+ marks = (
+ tiles.burn_scale_north(
+ img,
+ meters_per_pixel=tiles.meters_per_pixel(lat, zoom) / device_scale,
+ bearing=bearing,
+ units=_units(),
+ )
+ if scale_north and framed
+ else None
+ )
+
year = datetime.now(timezone.utc).year
attribution = f"Map data ©{year} Google"
img = tiles.burn_attribution(img, attribution)
@@ -884,6 +1082,7 @@ async def capture_screenshot(
"bearing": bearing,
"attribution": attribution,
"attribution_burned": True,
+ "marks": marks,
"plus_code": plus_code,
"dms": geo.to_dms(lat, lon),
"fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index dddf3b6..4915dce 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -23,6 +23,7 @@ from ..engine import (
exportdir,
extinstall,
ffmpeg,
+ firms,
google_tiles,
reveal,
scrapers,
@@ -39,8 +40,10 @@ SIGNATURE_B64_MAX_CHARS = 4 * (config.SIGNATURE_MAX_BYTES // 3 + 1) + 1024
router = APIRouter(prefix="/api", tags=["settings"])
-# Providers managed by the Settings imagery tab.
-KEYED_PROVIDERS = ("mapbox", "google", "google_js", "sentinelhub")
+# Keys managed by the Settings imagery tab. Not all of them buy a basemap:
+# FIRMS buys a layer laid over whichever one is showing, and is unmetered, so
+# the card it gets there carries no meter and no eco threshold.
+KEYED_PROVIDERS = ("mapbox", "google", "google_js", "sentinelhub", "firms")
# Providers with configurable eco thresholds. Maps JS is excluded because each
# widget reload is billed.
ECO_TUNABLE = ("mapbox", "google", "sentinelhub")
@@ -59,6 +62,8 @@ class KeysIn(BaseModel):
google_js: str | None = None
# Sentinel Hub's "key" is a configuration-instance UUID, not a secret token
sentinelhub: str | None = None
+ # NASA FIRMS MAP_KEY: one key for both the global and the US/Canada service
+ firms: str | None = None
class HomeView(BaseModel):
@@ -96,6 +101,8 @@ class PrefsIn(BaseModel):
coord_format: str | None = None # one of config.COORD_FORMATS
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
+ # burn a scale bar and a north arrow into captures (the capture menu's tick)
+ capture_scale_north: bool | None = None
# whether saving a proof files its point as a place, or asks first
proof_place_auto: bool | None = None
post_mention: str | None = None # handle a new post draft is addressed to
@@ -126,6 +133,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"coord_format": settings.get("coord_format", "dd"),
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
+ "capture_scale_north": bool(settings.get("capture_scale_north", False)),
"proof_place_auto": bool(settings.get("proof_place_auto", True)),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
"post_target": settings.get("post_target", DEFAULT_POST_TARGET),
@@ -254,6 +262,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["units"] = body.units
if body.home_view is not None:
settings["home_view"] = body.home_view.model_dump()
+ if body.capture_scale_north is not None:
+ settings["capture_scale_north"] = bool(body.capture_scale_north)
if body.proof_place_auto is not None:
settings["proof_place_auto"] = bool(body.proof_place_auto)
if body.post_mention is not None:
@@ -626,6 +636,7 @@ class ImportedSettings(BaseModel):
home_view: ImportedHomeView = Field(
default_factory=lambda: ImportedHomeView.model_validate(DEFAULT_HOME_VIEW)
)
+ capture_scale_north: bool = False
proof_place_auto: bool = True
post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
post_target: str = DEFAULT_POST_TARGET
@@ -777,6 +788,24 @@ def test_key(provider: str) -> dict[str, Any]:
return verdict(True, "tile fetched")
except Exception as exc:
return verdict(False, str(exc))
+ if provider == "firms":
+ # The key is *asked about*, not used. A GetMap proves nothing here:
+ # FIRMS answers a key it rejects with 200 and a 28 KB picture saying so
+ # (`firms.PLACARD_SHA256`), so a test that fetched a tile called every
+ # bad key good. This endpoint exists to answer the question, and answers
+ # 403 with a sentence when the answer is no.
+ try:
+ response = httpx.get(
+ firms.STATUS_URL,
+ params={"MAP_KEY": key},
+ headers={"User-Agent": tiles.USER_AGENT},
+ timeout=15,
+ )
+ if response.status_code >= 400:
+ return verdict(False, firms.status_error(response.text))
+ return verdict(True, "key accepted")
+ except Exception as exc:
+ return verdict(False, str(exc))
if provider == "sentinelhub":
# One real tile over Paris (grid level 13 → TILEMATRIX 14). This checks
# the instance id *and* that the instance actually has a TRUE_COLOR
diff --git a/src/azimut/config.py b/src/azimut/config.py
index a7c010f..c3925b6 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -96,6 +96,11 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# metres, so a case reads the same whatever the reader's preference.
"coord_format": "dd",
"units": "metric",
+ # Whether a capture is filed with a scale bar and a north arrow burned into
+ # it (the capture menu's tick, and the extension popup's own). Off by
+ # default: what is drawn onto somebody's evidence is asked for, never
+ # assumed — and the tick is remembered here so it is asked for once.
+ "capture_scale_north": False,
# Where the Satellite tab opens before anything points it somewhere else
# (a case artifact, a "go to coords" handoff). {"lat", "lon", "zoom"}.
"home_view": {"lat": 43.0, "lon": 25.0, "zoom": 3},
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
index d8e8a63..6caec9d 100644
--- a/src/azimut/engine/entities.py
+++ b/src/azimut/engine/entities.py
@@ -844,6 +844,8 @@ def check_attrs(
if value is None or value == "":
continue
_CHECKS[attr.kind](attr, value)
+ if type_ == "place":
+ _check_place_precision(attrs, current or {})
def _check_text(attr: Attr, value: Any) -> None:
@@ -920,6 +922,68 @@ def _count_positions(node: Any, key: str, depth: int = 0) -> int:
return sum(_count_positions(child, key, depth + 1) for child in node)
+def _check_place_precision(attrs: Mapping[str, Any], current: Mapping[str, Any]) -> None:
+ """How tightly a place is pinned, stated once and around its own point.
+
+ Two rules, both about a shape being a claim somebody can read off the map:
+
+ - **A radius or a footprint, never both.** They answer the same question in two
+ forms, and the map can only draw one of them — which meant the circle silently
+ vanished the moment a shape was traced. So writing one asks for the other to be
+ cleared, and the surface that writes it is the one that gets the analyst's
+ consent first.
+ - **A footprint contains the point it belongs to.** Darwin Core's reading of
+ `footprintWKT`, and the only one that makes sense here: a shape traced beside
+ its pin describes somewhere else.
+
+ Both are judged against the patch rather than the stored result, so a place
+ written before these rules stays editable in every other respect.
+ """
+ radius = attrs.get("radius_m", current.get("radius_m"))
+ shape = attrs.get("footprint", current.get("footprint"))
+ touched = any(
+ key in attrs and attrs[key] != current.get(key) for key in ("radius_m", "footprint")
+ )
+ if radius and shape and touched:
+ raise CaseError("a place holds either a radius or a footprint, not both")
+ if not attrs.get("footprint"):
+ return
+ lat = attrs.get("lat", current.get("lat"))
+ lon = attrs.get("lon", current.get("lon"))
+ if not isinstance(lat, (int, float)) or not isinstance(lon, (int, float)):
+ return # a place with no point of its own has nothing to contradict
+ if not _covers_point(attrs["footprint"], float(lat), float(lon)):
+ raise CaseError("'footprint' must contain the place's own point")
+
+
+def _covers_point(shape: Mapping[str, Any], lat: float, lon: float) -> bool:
+ """Is the point inside one of this shape's outer rings?
+
+ Ray casting, on shapes this module has already validated. `engine.sentinel` owns
+ a second copy on purpose: a granule's geometry arrives from a service that may
+ have swapped the axes, so that one counts either reading as a hit, and here that
+ tolerance would accept a shape traced at the mirrored coordinates.
+ """
+ rings: list[Any] = []
+ coordinates = shape.get("coordinates") or []
+ if shape.get("type") == "Polygon":
+ rings = [coordinates[0]] if coordinates else []
+ else:
+ rings = [polygon[0] for polygon in coordinates if polygon]
+ return any(_inside(ring, lat, lon) for ring in rings)
+
+
+def _inside(ring: list[Any], lat: float, lon: float) -> bool:
+ inside = False
+ for index, position in enumerate(ring):
+ x1, y1 = float(position[0]), float(position[1])
+ following = ring[(index + 1) % len(ring)]
+ x2, y2 = float(following[0]), float(following[1])
+ if (y1 > lat) != (y2 > lat) and lon < (x2 - x1) * (lat - y1) / ((y2 - y1) or 1e-12) + x1:
+ inside = not inside
+ return inside
+
+
def _check_choice(attr: Attr, value: Any) -> None:
"""One of the readings the field declares, and nothing else.
diff --git a/src/azimut/engine/firms.py b/src/azimut/engine/firms.py
new file mode 100644
index 0000000..34fcbe6
--- /dev/null
+++ b/src/azimut/engine/firms.py
@@ -0,0 +1,291 @@
+"""NASA FIRMS active fire detections, as a layer over the map.
+
+FIRMS publishes thermal anomalies from the VIIRS and MODIS instruments: what
+was burning, where, and when it was seen. Two things make it worth wiring in
+rather than sending the analyst to the FIRMS site — it answers *both* halves of
+the question a case asks. **Live** ("is this burning now") is the last 24, 48 or
+72 hours, or the last week, which FIRMS serves as its own layers. **History**
+("was this burning on the day of the strike") is any date range back through the
+archive, which is the same layers asked with a ``TIME``.
+
+Three decisions are recorded here because none is obvious from the URLs:
+
+- **WMS, not the CSV API.** FIRMS offers both. The CSV would let the app draw
+ its own marks — clickable, styled by confidence — but a bbox of detections is
+ unbounded in a way a tile is not, and it would need paging, a zoom floor and a
+ cap before it drew anything. The WMS is a raster layer, which the map already
+ knows how to stack (``lib/map/basemap.js``), and one screen is one request
+ per tile whatever is burning. Drawing our own marks is the upgrade, not the
+ starting point.
+- **The key never reaches the browser.** FIRMS puts the MAP_KEY *in the path*,
+ so a direct tile URL would publish it in the page source, in the network log,
+ and in any screenshot of either. It is proxied like every other keyed
+ provider (``api/satellite.py``'s tile proxy is the same argument).
+- **A tile is a GetMap.** WMS speaks bounding boxes, the map speaks z/x/y, so
+ this module converts one to the other. FIRMS serves EPSG:3857 natively, which
+ is the projection the tile grid is already in — no reprojection, just the
+ four numbers of the tile's own square.
+
+Rate limit, from FIRMS: 5000 transactions per 10 minutes, and a long date range
+counts as more than one. Nothing here polls, and a layer that is off asks for
+nothing, so a single analyst never approaches it — but it is why this must not
+grow a refresh timer without a reason.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import math
+import re
+from dataclasses import dataclass
+from datetime import date, timedelta
+
+WMS_BASE = "https://firms.modaps.eosdis.nasa.gov/mapserver/wms/fires"
+# The whole of Web Mercator, in metres: the tile grid's own square.
+WORLD = 20037508.342789244
+TILE_SIZE = 256
+# FIRMS serves detections from the last seven days as its own layers, and
+# anything older through the archive. Asking the archive for a range longer
+# than this is refused upstream, so it is refused here with a reason.
+MAX_RANGE_DAYS = 31
+# Past this the detections are a smear of identical squares: FIRMS draws a
+# fixed-size symbol per detection, and VIIRS resolves 375 m. The layer stops
+# being asked for rather than drawing a screen of overlapping marks.
+MAX_ZOOM = 14
+
+
+@dataclass(frozen=True)
+class Sensor:
+ """One instrument, under the name FIRMS files it by.
+
+ The rolling layers are this name with the window appended (``…_24``,
+ ``…_7``); the same name alone is the WMS-Time layer, addressed by date. One
+ name, two ways of asking — which is why only the sensors that have both are
+ offered here. NOAA-21 has the rolling layers and no dated one, and a sensor
+ that could answer "now" but not "that day" would be a trap in a tool whose
+ whole point is the second question.
+ """
+
+ id: str
+ label: str
+ layer: str
+
+
+SENSORS: tuple[Sensor, ...] = (
+ # The default, and the reason to prefer it: VIIRS resolves 375 m where MODIS
+ # resolves 1 km, so a single burning building is a mark rather than a blur.
+ Sensor(id="viirs", label="VIIRS (S-NPP + NOAA-20)", layer="fires_viirs"),
+ Sensor(id="viirs_snpp", label="VIIRS Suomi-NPP", layer="fires_viirs_snpp"),
+ Sensor(id="viirs_noaa20", label="VIIRS NOAA-20", layer="fires_viirs_noaa20"),
+ # 1 km, and on orbit since 1999: the only one that can answer a question
+ # about a fire older than VIIRS itself.
+ Sensor(id="modis", label="MODIS (Terra + Aqua)", layer="fires_modis"),
+)
+
+# The rolling windows FIRMS serves as layers of their own, by the suffix it
+# files them under.
+WINDOWS: dict[str, str] = {"24h": "24", "48h": "48", "72h": "72", "7d": "7"}
+
+_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
+
+#: Where a MAP_KEY is asked about rather than used. It answers 200 for a key
+#: that works and 403 with a sentence for one that does not, which is the only
+#: honest test there is: the WMS answers a *picture* either way (below).
+STATUS_URL = "https://firms.modaps.eosdis.nasa.gov/mapserver/mapkey_status/"
+
+#: The placard FIRMS serves instead of refusing.
+#:
+#: A GetMap with a key it will not accept comes back **200, `image/png`, and a
+#: 28 KB picture saying so** — the same bytes for every bad key (verified
+#: 2026-09). Nothing in the HTTP answer says anything is wrong, so a map would
+#: happily tile that placard across the ground and a key test would call it a
+#: success. It is recognised by its own digest, exactly as the imagery
+#: providers' "no tile here" placards are (``engine/tiles.py``).
+PLACARD_SHA256 = "75d876f3c684a2021a356553a08257dc2d57cb13ff9d24c147476490c499cea4"
+
+
+def is_placard(content: bytes) -> bool:
+ """Is this FIRMS's "that key is no good" picture rather than a map?"""
+ return hashlib.sha256(content).hexdigest() == PLACARD_SHA256
+
+
+def sensor(sensor_id: str) -> Sensor:
+ """The sensor asked for, or a ``KeyError`` naming what is on offer."""
+ for entry in SENSORS:
+ if entry.id == sensor_id:
+ return entry
+ raise KeyError(f"unknown FIRMS sensor '{sensor_id}'")
+
+
+def parse_day(value: str) -> date:
+ """A ``YYYY-MM-DD`` from an address, or a ``ValueError``.
+
+ Strict rather than lenient: the dates reach a public service in a URL, and
+ `date.fromisoformat` would otherwise accept a whole grammar of forms that
+ FIRMS does not.
+ """
+ if not _DATE.match(value or ""):
+ raise ValueError(f"'{value}' is not a YYYY-MM-DD date")
+ return date.fromisoformat(value)
+
+
+def window_range(first: str, last: str) -> tuple[date, date]:
+ """The archive window, checked the way FIRMS checks it.
+
+ Ordered, and no longer than ``MAX_RANGE_DAYS`` — upstream answers a longer
+ range with an error, and counts a long one as several transactions.
+ """
+ start = parse_day(first)
+ end = parse_day(last or first)
+ if end < start:
+ start, end = end, start
+ if end - start > timedelta(days=MAX_RANGE_DAYS - 1):
+ raise ValueError(f"a FIRMS date range covers at most {MAX_RANGE_DAYS} days")
+ return start, end
+
+
+def layer_name(sensor_id: str, window: str) -> str:
+ """Which FIRMS layer answers this question.
+
+ A rolling window names the layer that already holds it; anything else is
+ the archive layer, which is dated by the ``TIME`` beside it.
+ """
+ entry = sensor(sensor_id)
+ suffix = WINDOWS.get(window)
+ return f"{entry.layer}_{suffix}" if suffix else entry.layer
+
+
+#: Web Mercator stops short of the poles, and a bbox that runs past it is a
+#: bbox the projection cannot express.
+LAT_LIMIT = 85.05112878
+
+
+def mercator(lat: float, lon: float) -> tuple[float, float]:
+ """One coordinate in EPSG:3857 metres.
+
+ The extension works in degrees — it reads them off somebody else's map —
+ and FIRMS is asked in metres, so the conversion happens on this side rather
+ than being a second copy of the projection in a content script.
+ """
+ clamped = max(-LAT_LIMIT, min(LAT_LIMIT, lat))
+ x = WORLD * lon / 180
+ y = WORLD * math.log(math.tan(math.radians(45 + clamped / 2))) / math.pi
+ return x, y
+
+
+def bounds_of(south: float, west: float, north: float, east: float) -> tuple[float, float, float, float]:
+ """A geographic rectangle as the square of metres WMS wants."""
+ left, bottom = mercator(south, west)
+ right, top = mercator(north, east)
+ return (left, bottom, right, top)
+
+
+def tile_bounds(z: int, x: int, y: int) -> tuple[float, float, float, float]:
+ """One tile's square in EPSG:3857 metres, as WMS wants it.
+
+ The grid is the map's; the numbers are the projection's. Row 0 is at the
+ top in the tile grid and at the north in the projection, which is the only
+ sign flip in here.
+ """
+ span = 2 * WORLD / (1 << z)
+ left = -WORLD + x * span
+ top = WORLD - y * span
+ return (left, top - span, left + span, top)
+
+
+def image_url(
+ key: str,
+ *,
+ bounds: tuple[float, float, float, float],
+ width: int,
+ height: int,
+ sensor_id: str = "viirs",
+ window: str = "24h",
+ first: str = "",
+ last: str = "",
+) -> str:
+ """A GetMap for one square of ground, with the key where FIRMS puts it.
+
+ Pure, so the shape of the request is read off a test rather than off a
+ fire: `test_firms.py` asserts the bbox, the projection and the date range
+ without asking NASA anything.
+ """
+ left, bottom, right, top = bounds
+ query = [
+ "SERVICE=WMS",
+ "VERSION=1.3.0",
+ "REQUEST=GetMap",
+ f"LAYERS={layer_name(sensor_id, window)}",
+ "FORMAT=image/png",
+ "TRANSPARENT=TRUE",
+ "CRS=EPSG:3857",
+ f"WIDTH={width}",
+ f"HEIGHT={height}",
+ f"BBOX={left:.6f},{bottom:.6f},{right:.6f},{top:.6f}",
+ ]
+ if window not in WINDOWS:
+ start, end = window_range(first, last)
+ query.append(f"TIME={start.isoformat()}/{end.isoformat()}")
+ return f"{WMS_BASE}/{key}/?{'&'.join(query)}"
+
+
+def tile_url(
+ key: str,
+ *,
+ sensor_id: str = "viirs",
+ window: str = "24h",
+ z: int,
+ x: int,
+ y: int,
+ first: str = "",
+ last: str = "",
+ size: int = TILE_SIZE,
+) -> str:
+ """…and the one a map tile is: the same request over the tile's own square.
+
+ The app's map is a grid of these. The extension asks for one image over the
+ whole of somebody else's map instead, because it has no tile grid to hang
+ them on — one screen, one request.
+ """
+ return image_url(
+ key,
+ bounds=tile_bounds(z, x, y),
+ width=size,
+ height=size,
+ sensor_id=sensor_id,
+ window=window,
+ first=first,
+ last=last,
+ )
+
+
+def too_deep(zoom: int) -> bool:
+ """Past the zoom where a detection mark still means one detection."""
+ return zoom > MAX_ZOOM
+
+
+def service_error(body: str) -> str:
+ """The human half of an OGC ExceptionReport, when FIRMS refuses.
+
+ Same reasoning as Sentinel Hub's: the service says exactly what is wrong
+ with the key or the layer, and "400 Bad Request" throws that away.
+ """
+ # The space matters: the report element `<ServiceExceptionReport>` starts
+ # with this element's own name, and a looser pattern reads the wrapper as
+ # the message and hands back the tag it was supposed to strip.
+ match = re.search(r"<ServiceException(?:\s[^>]*)?>(.*?)</ServiceException>", body, re.S)
+ if match:
+ return match.group(1).strip()[:200]
+ return (body or "").strip()[:200]
+
+
+def status_error(body: str) -> str:
+ """What the key-status endpoint said, when it refused.
+
+ It answers in plain text — sometimes wrapped in a scrap of HTML — and its
+ own sentence is better than "403": it names the two things that put a key
+ here, an id the service does not know and an account over its limit.
+ """
+ text = re.sub(r"<[^>]+>", " ", body or "")
+ text = " ".join(text.split())
+ return text[:200] or "FIRMS would not accept this key"
diff --git a/src/azimut/engine/mapsites.py b/src/azimut/engine/mapsites.py
index 95376b2..debebfa 100644
--- a/src/azimut/engine/mapsites.py
+++ b/src/azimut/engine/mapsites.py
@@ -21,10 +21,11 @@ out that what it draws drifts away from the middle of the screen. A malformed UR
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
+the map is drawn in the window it is looking at. Given it, the three 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
+satellite ``,3231m``, Earth's ``d`` and ``y`` — come back with a real ``zoom``
+like everyone else, and ``scale_source`` says which of the four 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.
@@ -32,6 +33,8 @@ it.
from __future__ import annotations
+import base64
+import binascii
import math
import re
from datetime import date
@@ -107,17 +110,21 @@ 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.
+#: How high a level 3D camera may sit before the ground under it stops being
+#: flat enough to draw 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.
+#: perspective cancels exactly — so a level 3D view is drawable near the middle
+#: of the screen. 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
+#: This is about 3D cameras only: Earth's 3D mode and Maps' Earth mode. Earth's
+#: default 2D mode is a flat Web Mercator map at every distance (measured, and
+#: seen flat with all of Europe on screen), so it has no ceiling.
+#:
+#: What this cannot account for is relief. A level 3D 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
@@ -199,6 +206,69 @@ def camera_pitch(site_id: str, u) -> float | None:
return _pitch(block[0]) if block else None
+def _protobuf_fields(blob: bytes) -> dict[int, int | bytes] | None:
+ """The top-level fields of a protobuf message, or None if it is not one.
+
+ Only what reading Earth's ``data=`` needs: varints and length-delimited
+ fields kept, fixed-width ones skipped, anything else refused.
+ """
+ fields: dict[int, int | bytes] = {}
+ at = 0
+
+ def varint() -> int:
+ nonlocal at
+ value = shift = 0
+ while at < len(blob) and shift < 64:
+ byte = blob[at]
+ at += 1
+ value |= (byte & 0x7F) << shift
+ if byte < 0x80:
+ return value
+ shift += 7
+ raise ValueError("truncated varint")
+
+ try:
+ while at < len(blob):
+ key = varint()
+ number, wire = key >> 3, key & 7
+ if wire == 0:
+ fields[number] = varint()
+ elif wire == 2:
+ size = varint()
+ if at + size > len(blob):
+ return None
+ fields[number] = blob[at:at + size]
+ at += size
+ elif wire in (1, 5):
+ at += 8 if wire == 1 else 4
+ else:
+ return None
+ except ValueError:
+ return None
+ return fields if at == len(blob) else None
+
+
+def _earth_in_3d(u) -> bool:
+ """Whether Earth is showing its 3D globe rather than its flat 2D map.
+
+ The address bar says so in the base64 protobuf after ``/data=``: pressing
+ Earth's "3D" button adds field 5 = 2 and pitches the camera, pressing it
+ again takes both away. A link with no ``data=`` opens the 2D map. Anything
+ that cannot be read is taken as 3D, whose rules are the stricter ones.
+ """
+ m = re.search(r"/data=([A-Za-z0-9_-]+)", u.path)
+ if not m:
+ return False
+ try:
+ blob = base64.urlsafe_b64decode(m[1] + "=" * (-len(m[1]) % 4))
+ except (binascii.Error, ValueError):
+ return True
+ fields = _protobuf_fields(blob)
+ if fields is None:
+ return True
+ return 5 in fields
+
+
def _view_kind(site_id: str, u) -> str | None:
"""Which camera the address bar describes, or None when it does not say.
@@ -214,7 +284,10 @@ def _view_kind(site_id: str, u) -> str | None:
block = re.search(r"@[^/]*", u.path)
if not block:
return None
- return _free_camera(block[0], _camera_number(block[0], "d"))
+ if _earth_in_3d(u):
+ return _free_camera(block[0], _camera_number(block[0], "d"))
+ # The 2D map is flat at any distance, so only a pitch stops it being one.
+ return VIEW_TILTED if _pitched(block[0]) else VIEW_MAP
if site_id == "google-maps":
block = re.search(r"@[^/]*", u.path)
if not block:
@@ -279,8 +352,55 @@ _PROJECTIONS = {
# 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.
+ # Earth's 2D map, measured by loading URLs a known step apart and
+ # registering the screenshots: pixels per degree north over pixels per
+ # degree east came out at 1/cos(lat) to 0.03% at 47° and 52°, which is
+ # spherical Mercator and not the ground's own ratio (0.3% away). Its 3D
+ # mode is refused past LEVEL_CEILING_M and is near enough to it below.
+ "google-earth": PROJ_SPHERICAL,
+}
+
+
+#: Where each site draws the coordinate its address bar names, as an offset in
+#: CSS pixels from the middle of the window — the starting answer the extension
+#: places its drawing with until it has measured one of its own.
+#:
+#: The middle of the window is not a neutral default, it is a table entry, and
+#: the wrong one on four of these sites: they keep a results panel or a header
+#: and centre the map in what is left. Yandex's camera sits 210 px right of the
+#: middle, Copernicus's 225, Bing's 40 px down. Until one is measured that is
+#: the whole drawing's error, and at level 3 Bing's 40 px is 450 km of ground.
+#:
+#: Every number came out of a browser (``docs/MAP_SITES.md``), and the two sites
+#: recorded at two window shapes measured the same offset in both — which is
+#: what makes a pixel count portable at all: a panel's width is the site's own
+#: CSS, not the analyst's screen. Sites that measured to the middle are absent
+#: because the middle is the default. ``apple-maps`` is absent for the opposite
+#: reason: its sidebar folds away below some width it never states, so its
+#: offset is 67 px in a wide window and nothing in a narrow one. That one is
+#: measured on the machine it is drawn on or not at all.
+#:
+#: The third number is what keeps the sideways half of this honest, and Apple is
+#: why. A **header** takes height, and its height is the same in a narrow window
+#: as in a wide one — so the vertical offset is claimed at any size. A **side
+#: panel** takes width, and a side panel is exactly the thing that folds away
+#: when the window gets narrow: that is the whole of Apple's 67 px becoming
+#: nothing. So a sideways offset is claimed only at or above the narrowest
+#: window it was actually recorded in, and below that the site starts centred
+#: horizontally and is measured like Apple. Yandex was driven at 1200 and 1600
+#: and measured 210 px in both; Copernicus has been driven at 1600 only, and
+#: says no more than that.
+#:
+#: This is a hint and never an answer. The extension measures the offset off the
+#: first zoom and keeps its own (``extension/mapoverlay.js``, ``seedFrame``),
+#: which is what covers a site that redecorates between two releases;
+#: ``tests/test_mapsites.py`` re-checks every entry here against the recording.
+#: (x, y, the narrowest window x has been measured in — 0 where x is 0)
+_CAMERA_CENTRE = {
+ "bing-maps": (0.0, 40.5, 0),
+ "openstreetmap": (0.0, 27.4, 0),
+ "yandex-maps": (210.0, 10.0, 1200),
+ "copernicus-browser": (225.0, 0.0, 1600),
}
@@ -322,13 +442,24 @@ _ZOOM_IS_TILES = {
#: 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.
+#: Which of the four 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).
+#: means the URL stated nothing a scale can be read out of, and nothing is
+#: drawn until it does.
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
+SCALE_DISTANCE = "distance" # Earth: the camera's distance to the ground, and its field of view
+
+#: The closest Earth's 2D map lets its camera come to the ground, in metres.
+#: Zoomed in until it stopped, it wrote ``25.00163587d``. A smaller ``d`` is not
+#: a camera Earth placed: loading one link, it once wrote ``1518a,10d`` for a
+#: camera 1528 m up, where ``a`` was not the ground at all.
+EARTH_CLOSEST_M = 24.9
+
+#: Lowest and highest ground there is, in metres (the Dead Sea shore, Everest).
+#: An ``a`` outside it is not the ground, so ``d`` is not a distance to it.
+_GROUND_M = (-450.0, 8900.0)
#: Where Mercator is cut, north and south. Every slippy map cuts at this value.
@@ -371,17 +502,46 @@ def _zoom_from_span(span_lat: float, height_px: float, lat: float) -> float | No
return math.log2(height_px / tall) if tall > 0 else None
+def _earth_height_m(camera: str) -> float | None:
+ """How tall Earth's view is on the ground, in metres, or None when its URL
+ does not say.
+
+ Measured rather than assumed (``docs/MAP_SITES.md``). Earth draws its map
+ as a camera ``d`` metres above the ground under the middle of the screen,
+ with ``y`` degrees of field of view across the window's height, so the
+ window covers ``2·d·tan(y/2)`` metres top to bottom: screenshots of URLs a
+ known step apart agreed to 0.06% from 2 km to 400 km out, at three window
+ shapes, and at ``y`` of 35 and 60.
+
+ ``d`` is that distance only once Earth has placed the camera itself, which
+ it does on every gesture by writing the ground's height into ``a``. A link
+ typed as ``0a`` with a whole ``d`` has not been placed, and over land 200 m
+ up it is drawn 7% nearer than it says, so it waits for the map to move.
+ """
+ distance = _camera_number(camera, "d")
+ fov = _camera_number(camera, "y")
+ ground = _camera_number(camera, "a")
+ if distance is None or fov is None or ground is None:
+ return None
+ if not 0 < fov < 180 or distance < EARTH_CLOSEST_M:
+ return None
+ if not _GROUND_M[0] <= ground <= _GROUND_M[1]:
+ return None
+ if ground == 0 and re.search(r",-?\d+d(?:,|$)", camera):
+ return None
+ return 2 * distance * math.tan(math.radians(fov) / 2)
+
+
def _scale(
- site_id: str, parsed: dict[str, Any], camera: float | None,
- camera_kind: str | None, height_px: float | None,
+ site_id: str, parsed: dict[str, Any], u, 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 zoom this view is at, and which of the four 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.
+ degrees, Earth's distance — 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:
@@ -389,8 +549,13 @@ def _scale(
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)
+ block = re.search(r"@[^/]*", u.path)
+ camera = block[0] if block else ""
+ if site_id == "google-earth":
+ from_distance = _zoom_from_height_m(_earth_height_m(camera), height_px, lat)
+ return (from_distance, SCALE_DISTANCE) if from_distance is not None else (None, None)
+ if site_id == "google-maps" and ",3a," not in camera: # Street View's radius is not a height
+ from_height = _zoom_from_height_m(_camera_number(camera, "m"), height_px, lat)
if from_height is not None:
return from_height, SCALE_HEIGHT_M
span_lat = parsed.get("span_lat")
@@ -401,6 +566,12 @@ def _scale(
return zoom, None
+def _centre_hint(site_id: str) -> dict[str, float] | None:
+ """The starting offset for this site's camera centre, or None for the middle."""
+ at = _CAMERA_CENTRE.get(site_id)
+ return {"x": at[0], "y": at[1], "min_w": at[2]} if at else None
+
+
def _projection(site_id: str) -> str | None:
"""Which flattening a site draws in, or None when we cannot say.
@@ -594,40 +765,6 @@ SITES: list[tuple[str, str, Callable, Callable | None, Callable]] = [
]
-#: 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]:
@@ -637,16 +774,22 @@ def _drawable(
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 camera looking straight down at a flat map (``view_kind``), since
+ Mercator says nothing about a pitched, panoramic or globe camera;
* 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).
+ ``far`` is the third fact, and it is a warning rather than a refusal — but
+ only for the one kind of far it describes. A **flat map drawn far out**
+ (Google and Bing below ``_GLOBE_BELOW``) goes on quoting a tile level while
+ its renderer curves, and out there the middle of the screen is still right
+ while the edges drift: a sweep of a whole region is worth seeing roughly, so
+ the drawing stays and says so (`maptools.js`, the verdict; `mapoverlay.js`
+ dims it). A **globe camera** — Earth's 3D mode past ``LEVEL_CEILING_M``, and
+ Google's Earth mode with it — is a perspective view of a sphere, where this
+ arithmetic is not approximately right but wrong, and ``VIEW_GLOBE`` is
+ refused rather than dimmed. ``far`` stays true there, because it has a
+ second job: it is what stops the extension measuring a site's layout off a
+ view that far out.
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``
@@ -656,10 +799,11 @@ def _drawable(
projection = _projection(site_id)
globe_below = _GLOBE_BELOW.get(site_id)
zoom = parsed.get("zoom")
- level = kind in (VIEW_MAP, VIEW_GLOBE)
+ level = kind == VIEW_MAP
return {
"view_kind": kind,
"projection": projection,
+ "centre_hint": _centre_hint(site_id),
"globe_below": globe_below,
"scale_source": scale_source,
"geometry": bool(level and projection),
@@ -674,10 +818,10 @@ def parse_map_url(url: str, height_px: float | None = None) -> dict[str, Any] |
"""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.
+ what turns Apple's span, Google's satellite metres and Earth's camera
+ distance into a zoom. All three 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)
@@ -695,15 +839,12 @@ def parse_map_url(url: str, height_px: float | None = None) -> dict[str, Any] |
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)
+ parsed["zoom"], source = _scale(site_id, parsed, u, 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),
}
diff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.py
index 2a724f5..c94071e 100644
--- a/src/azimut/engine/tiles.py
+++ b/src/azimut/engine/tiles.py
@@ -21,7 +21,7 @@ import httpx
from PIL import Image, ImageDraw, ImageFont
from .. import config
-from . import google_tiles, sentinel
+from . import google_tiles, pdffonts, sentinel, wayback
TILE_SIZE = 256
SIZE_MAX = 4096 # hard cap on a capture's width/height, in px
@@ -130,6 +130,17 @@ BUILTIN_PROVIDERS: tuple[Provider, ...] = (
max_zoom=17,
imagery=False,
),
+ # Every published release of World Imagery (engine/wayback.py). The same
+ # imagery and terms as the default basemap, one release at a time. The URL
+ # is a placeholder until a release is chosen: get_provider always resolves
+ # one, so no tile is ever asked for without it.
+ Provider(
+ id=wayback.BASE_ID,
+ label="Esri Wayback (imagery archive)",
+ url=wayback.TILE_TEMPLATE.format(release="{release}"),
+ attribution="Esri, Maxar, Earthstar Geographics, and the GIS User Community · World Imagery Wayback",
+ max_zoom=wayback.MAX_ZOOM,
+ ),
)
@@ -285,6 +296,8 @@ def get_provider(provider_id: str) -> Provider:
and a capture's provenance records the id it was actually rendered from.
"""
base_id, sep, spec = provider_id.partition(sentinel.VARIANT_SEP)
+ if base_id == wayback.BASE_ID:
+ return _wayback_provider(spec if sep else None)
for provider in all_providers():
if provider.id == base_id:
if not sep:
@@ -306,6 +319,36 @@ def get_provider(provider_id: str) -> Provider:
raise KeyError(f"unknown tile provider '{provider_id}'")
+def _wayback_provider(spec: str | None) -> Provider:
+ """One Wayback release as a provider, the newest when none is named.
+
+ The id always names the release, so a tile proxied for the plain basemap is
+ cached, and a capture filed from it is credited, under the release it came
+ from. Resolving the newest reads the release list, which only ever happens
+ because the analyst chose this basemap.
+ """
+ base = next(p for p in BUILTIN_PROVIDERS if p.id == wayback.BASE_ID)
+ try:
+ number = wayback.parse_variant(spec) if spec is not None else None
+ except ValueError as exc:
+ raise KeyError(str(exc)) from exc
+ try:
+ listed = wayback.releases()
+ except Exception as exc:
+ if number is None:
+ raise KeyError(f"could not read the Wayback release list: {exc}") from exc
+ listed = [] # a named release still draws; only its date is unknown
+ if number is None:
+ number = listed[0].number
+ release = wayback.find(number, listed)
+ return replace(
+ base,
+ id=wayback.variant_id(number),
+ label=f"Esri Wayback · {release.date if release else f'release {number}'}",
+ url=wayback.tile_url(number),
+ )
+
+
def _sentinel_key_from(url: str) -> str:
"""The instance UUID out of a built Sentinel Hub URL — rebuilding the
template for a variant needs the credential back, and the resolved provider
@@ -338,8 +381,14 @@ def unproject(x: float, y: float, zoom: int) -> tuple[float, float]:
return lat, lon
-def meters_per_pixel(lat: float, zoom: int) -> float:
- return 156543.03392 * math.cos(math.radians(lat)) / (1 << zoom)
+def meters_per_pixel(lat: float, zoom: float) -> float:
+ """Ground metres one pixel covers at this latitude and zoom.
+
+ Fractional zooms are real here rather than a rounding accident: a capture
+ stitched by this app sits on a whole level, but a map site read off its own
+ URL states things like ``lvl=17.4``, and half a level is 40% of the scale.
+ """
+ return 156543.03392 * math.cos(math.radians(lat)) / (2.0**zoom)
# -- crop fetching -------------------------------------------------------------
@@ -422,6 +471,8 @@ def fetch_crop(
marker_lat: float | None = None,
marker_lon: float | None = None,
bearing: float = 0.0,
+ scale_north: bool = False,
+ units: str = "metric",
fetch_tile: Callable[[httpx.Client, str], Image.Image | None] | None = None,
) -> tuple[Image.Image, dict[str, Any]]:
"""Stitch a width×height crop framed on (lat, lon). Returns (image, provenance).
@@ -437,6 +488,11 @@ def fetch_crop(
``bearing`` (degrees clockwise from north) rotates the crop: a larger
north-up canvas is stitched, rotated, then center-cropped to width×height so
the result matches a map turned to that heading.
+
+ ``scale_north`` burns a scale bar and a north arrow into the crop, read in
+ ``units`` (the analyst's display preference). Off by default: a capture is
+ somebody's evidence, and what is drawn onto it is asked for rather than
+ assumed.
"""
if provider.needs_key:
raise TileFetchError(f"provider '{provider.id}' requires an API key (settings.json)")
@@ -584,6 +640,17 @@ def fetch_crop(
marker_style = "crosshair"
_draw_crosshair(canvas, mx, my)
+ marks = (
+ burn_scale_north(
+ canvas,
+ meters_per_pixel=meters_per_pixel(lat, zoom),
+ bearing=bearing,
+ units=units,
+ )
+ if scale_north
+ else None
+ )
+
attribution = provider.attribution
if provider.session == "google":
# the exact copyright line for this viewport (e.g. "Map data ©2026
@@ -631,6 +698,10 @@ def fetch_crop(
"marker_style": marker_style,
"marker_x": int(marker_x),
"marker_y": int(marker_y),
+ # What was drawn over the imagery, if anything was asked for: the span
+ # the bar states and the heading the needle points at. A reader of the
+ # capture can tell an absent bar from an unbacked one.
+ "marks": marks,
# kept for backward-compatible readers of older captures
"crosshair": marker_style != "none",
}
@@ -799,6 +870,208 @@ def burn_attribution(img: Image.Image, text: str) -> Image.Image:
return out
+# -- scale bar and north arrow -------------------------------------------------
+#
+# Two marks, one switch, and both are *claims about the picture* rather than
+# decoration: this is how far that is, and that way is north. So neither is ever
+# invented. A capture with no metres-per-pixel gets no bar, and one whose
+# heading nobody stated gets no arrow — a map site that writes no rotation into
+# its URL is answered with the bar alone instead of an arrow pointing at a
+# guess, and the provenance records exactly what was burned in.
+#
+# Drawn here, in Pillow, because all three roads to a capture pass through this
+# process: the stitched tile crop below, the widget screenshot
+# (api/satellite.py) and the extension's own grab (api/ingest.py). The two
+# screen roads hand in the device pixel ratio their crop was taken at, since a
+# zoom describes CSS pixels and a 2× screen holds two of those per pixel of the
+# file.
+
+#: The 1/2/5×10ⁿ ladder a scale bar's span is chosen from, longest first.
+SCALE_STEPS = (5, 2, 1)
+#: How much of the capture's width the bar may span.
+SCALE_MAX_SHARE = 0.28
+#: Marks are drawn at this factor and downsampled — Pillow has no anti-aliasing
+#: for shapes, and a jagged needle looks like a mistake on somebody's evidence.
+MARK_SUPERSAMPLE = 4
+_FEET_PER_METRE = 3.280839895
+_FEET_PER_MILE = 5280
+
+
+def scale_span(
+ meters_per_pixel: float, max_px: float, units: str = "metric"
+) -> tuple[str, int] | None:
+ """The longest round span fitting ``max_px``, as ``(label, pixels)``.
+
+ Round means the 1/2/5×10ⁿ ladder every map uses, read in the analyst's own
+ units (Settings → General): a bar saying "500 m" is read at a glance where
+ one saying "437 m" is read twice. ``None`` when the arithmetic has nothing
+ to stand on — a zero or negative resolution, or a bar too small to label.
+ """
+ if not (meters_per_pixel > 0) or max_px <= 0:
+ return None
+ imperial = units == "imperial"
+ per_px = meters_per_pixel * (_FEET_PER_METRE if imperial else 1.0)
+ widest = per_px * max_px
+ if widest <= 0:
+ return None
+ decade = 10 ** math.floor(math.log10(widest))
+ span = next((step * decade for step in SCALE_STEPS if step * decade <= widest), decade)
+ pixels = round(span / per_px)
+ if pixels < 24: # narrower than its own label: no bar rather than a stub
+ return None
+ if imperial:
+ label = f"{_round_label(span / _FEET_PER_MILE)} mi" if span >= _FEET_PER_MILE \
+ else f"{_round_label(span)} ft"
+ else:
+ label = f"{_round_label(span / 1000)} km" if span >= 1000 else f"{_round_label(span)} m"
+ return label, pixels
+
+
+def _round_label(value: float) -> str:
+ """``2.0`` reads as ``2``; ``0.5`` stays ``0.5``."""
+ return f"{value:g}"
+
+
+def _mark_font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
+ """The bundled face, at a size. Falls back to Pillow's own if it is missing."""
+ try:
+ return ImageFont.truetype(str(pdffonts.FONT_DIR / "NotoSans-Bold.ttf"), size)
+ except OSError:
+ return ImageFont.load_default()
+
+
+def burn_scale_north(
+ img: Image.Image,
+ *,
+ meters_per_pixel: float | None = None,
+ bearing: float | None = None,
+ units: str = "metric",
+) -> dict[str, Any] | None:
+ """Draw the marks onto ``img`` in place, and report what was drawn.
+
+ Returns ``{"scale": "500 m" | None, "north": 12.0 | None}``, or ``None``
+ when neither mark could be backed — which is what the provenance records,
+ so a reader of the capture is never left wondering whether a missing bar
+ means "no scale" or "scale unknown".
+ """
+ # Sized off the shorter side: the same mark on a 4096px plate and on a
+ # 480px thumbnail-sized crop has to read as the same weight of ink.
+ unit = max(12, min(26, round(min(img.width, img.height) / 40)))
+ margin = round(unit * 1.1)
+ drawn: dict[str, Any] = {"scale": None, "north": None}
+
+ span = (
+ scale_span(meters_per_pixel, img.width * SCALE_MAX_SHARE, units)
+ if meters_per_pixel is not None
+ else None
+ )
+ if span:
+ _draw_scale_bar(img, *span, unit, margin)
+ drawn["scale"] = span[0]
+ if bearing is not None:
+ _draw_north_arrow(img, bearing % 360.0, unit, margin)
+ drawn["north"] = round(bearing % 360.0, 1)
+ return drawn if (drawn["scale"] or drawn["north"] is not None) else None
+
+
+#: White marks over a dark backing: imagery is snow and tarmac and everything
+#: between, so neither colour alone survives every capture.
+_MARK_INK = (255, 255, 255, 240)
+_MARK_BACKING = (10, 12, 16, 205)
+#: The needle's other half, dark enough to hold its own against white ground.
+_MARK_SHADE = (24, 27, 33, 235)
+
+
+def _draw_scale_bar(img: Image.Image, label: str, span_px: int, unit: int, margin: int) -> None:
+ """An open bar with end ticks, its span written above it, bottom-left."""
+ s = MARK_SUPERSAMPLE
+ pad = unit * 2 # room for a label wider than the bar, and for the backing
+ box_w, box_h = span_px + pad * 2, round(unit * 2.4)
+ layer = Image.new("RGBA", (box_w * s, box_h * s), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+
+ thick = max(3, round(unit * 0.24)) * s
+ tick = round(unit * 0.8) * s
+ x0, x1 = pad * s, (pad + span_px) * s
+ base = box_h * s - thick - s
+ edge = max(1, round(s * 1.2))
+
+ for grow, fill in ((edge, _MARK_BACKING), (0, _MARK_INK)):
+ draw.rectangle((x0 - grow, base - grow, x1 + grow, base + thick + grow), fill=fill)
+ for x in (x0, x1 - thick):
+ draw.rectangle(
+ (x - grow, base - tick - grow, x + thick + grow, base + grow), fill=fill
+ )
+
+ _mark_text(draw, ((x0 + x1) / 2, base - tick - round(unit * 0.34) * s), label, unit)
+
+ layer = layer.resize((box_w, box_h), Image.Resampling.LANCZOS)
+ # The padding is room for a label wider than its own bar — "1000 km" over a
+ # short one — so the box is allowed to start left of the margin but never
+ # left of the picture, where that overhang would be cut off mid-word.
+ img.paste(layer, (max(0, margin - pad), img.height - margin - box_h), layer)
+
+
+def _draw_north_arrow(img: Image.Image, bearing: float, unit: int, margin: int) -> None:
+ """A needle and its N, top-right, turned so it points at true north.
+
+ The capture was turned clockwise by the bearing, so north on the page sits
+ that many degrees anticlockwise of up — which is the direction Pillow's
+ ``rotate`` reads, and why the angle goes in unchanged.
+
+ Needle and letter turn together, as one rosette: the N belongs to the point
+ it names, and a letter left upright beside a turned needle reads as a label
+ for the capture rather than for the direction.
+ """
+ s = MARK_SUPERSAMPLE
+ box = round(unit * 4.4) # square, so no angle can clip a corner off
+ layer = Image.new("RGBA", (box * s, box * s), (0, 0, 0, 0))
+ draw = ImageDraw.Draw(layer)
+
+ centre = box * s / 2
+ half = round(unit * 0.58) * s # the needle's half-width at its base
+ tip = centre - round(unit * 1.1) * s
+ base = centre + round(unit * 1.1) * s
+ notch = centre + round(unit * 0.5) * s # the kite's inner corner, which reads as depth
+ edge = max(2, round(s * 1.6))
+
+ # Two-toned, like every compass needle: over snow the dark half carries it,
+ # over asphalt the pale one does, and the outline holds the silhouette on
+ # both. One ink on its own vanishes into half the imagery there is.
+ draw.polygon(
+ [
+ (centre, tip - edge * 1.8),
+ (centre + half + edge, base + edge),
+ (centre, notch),
+ (centre - half - edge, base + edge),
+ ],
+ fill=_MARK_BACKING,
+ )
+ draw.polygon([(centre, tip), (centre, notch), (centre - half, base)], fill=_MARK_INK)
+ draw.polygon([(centre, tip), (centre + half, base), (centre, notch)], fill=_MARK_SHADE)
+
+ _mark_text(draw, (centre, tip - round(unit * 0.45) * s), "N", unit)
+
+ if bearing:
+ layer = layer.rotate(bearing, resample=Image.Resampling.BICUBIC)
+ layer = layer.resize((box, box), Image.Resampling.LANCZOS)
+ img.paste(layer, (img.width - margin - box, margin), layer)
+
+
+def _mark_text(draw: ImageDraw.ImageDraw, at: tuple[float, float], text: str, unit: int) -> None:
+ """A mark's own label: centred on ``at``, sitting on that baseline."""
+ s = MARK_SUPERSAMPLE
+ draw.text(
+ at,
+ text,
+ font=_mark_font(round(unit * 1.05) * s),
+ fill=_MARK_INK,
+ anchor="ms",
+ stroke_width=max(2, round(s * 1.4)),
+ stroke_fill=_MARK_BACKING,
+ )
+
+
def _draw_crosshair(img: Image.Image, cx: int, cy: int) -> None:
"""Marker at (cx, cy): thin cross with an open middle, white with dark outline."""
draw = ImageDraw.Draw(img)
diff --git a/src/azimut/engine/wayback.py b/src/azimut/engine/wayback.py
new file mode 100644
index 0000000..0382d1d
--- /dev/null
+++ b/src/azimut/engine/wayback.py
@@ -0,0 +1,386 @@
+"""Esri World Imagery Wayback: every published release of World Imagery, dated.
+
+Esri republishes World Imagery a few times a month and keeps each release
+online under its own number. That archive is what answers "what did this place
+look like before", key-less, from the same imagery the default basemap already
+shows. Three services make it up, and all three are asked only once the analyst
+picks the basemap or opens its picker (local-first):
+
+- **The release list** (`CONFIG_URL`), one JSON document naming every release,
+ its publication date and its metadata service.
+- **The tilemap**, which answers for one tile and one release which release
+ that tile's pixels were actually published in. Walking it backwards is how
+ the releases that changed a point are found without downloading a tile per
+ release, the same walk Esri's own Wayback app makes.
+- **The metadata service** of each release, which says when the pixels under a
+ point were acquired and by which sensor. A release date is when Esri
+ published the mosaic, which can be years after the picture was taken.
+
+A release rides on the provider id as a variant, `esri-wayback~64776`, the way
+a Sentinel-2 window does (engine/sentinel.py). So the tile proxy, the disk
+cache and a capture's provenance all key on the release the pixels came from.
+Release tiles never change once published, which is why caching them is safe.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Callable
+
+import httpx
+
+BASE_ID = "esri-wayback"
+VARIANT_SEP = "~"
+
+CONFIG_URL = "https://s3-us-west-2.amazonaws.com/config.maptiles.arcgis.com/waybackconfig.json"
+_SERVICE = "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery"
+# {release} is filled per variant; {z}/{y}/{x} stay for tiles.tile_url.
+TILE_TEMPLATE = _SERVICE + "/WMTS/1.0.0/default028mm/MapServer/tile/{release}/{{z}}/{{y}}/{{x}}"
+TILEMAP_URL = _SERVICE + "/MapServer/tilemap/{release}/{z}/{row}/{col}"
+USER_AGENT = "Azimut/0.1 (+local OSINT workbench; single-user)"
+
+# The list names a metadata service per release. It is fetched from a bucket
+# and then asked questions server-side, so only the one host Esri uses, in the
+# one shape it uses, is ever followed.
+_METADATA_RE = re.compile(
+ r"^https://metadata\.maptiles\.arcgis\.com/arcgis/rest/services/"
+ r"World_Imagery_Metadata_[A-Za-z0-9_]{1,40}/MapServer$"
+)
+_DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}")
+# A release number is a URL path segment and a cache directory name: digits only.
+_RELEASE_RE = re.compile(r"^[0-9]{1,9}$")
+
+# The list changes a few times a month, so a session does not need to re-read it.
+LIST_TTL_S = 6 * 3600
+# The walk takes one small request per change it finds. A point with more than
+# this many distinct pictures in a decade is not one anybody reads a list of.
+MAX_STEPS = 80
+# The metadata service has fourteen sub-layers, one per level of detail: layer 0
+# describes zoom 23 and layer 13 everything from zoom 10 out.
+_METADATA_MAX_ZOOM = 23
+_METADATA_LAST_LAYER = 13
+# How many metadata questions go out side by side during a walk.
+METADATA_WORKERS = 12
+# Tiles are asked for at the view zoom, and World Imagery is offered to z19.
+MAX_ZOOM = 19
+
+
+@dataclass(frozen=True)
+class Release:
+ number: int
+ date: str # publication date, YYYY-MM-DD
+ metadata_url: str | None
+
+
+def parse_config(data: Any) -> list[Release]:
+ """The release list, newest first. Entries in any other shape are skipped."""
+ found: list[Release] = []
+ if not isinstance(data, dict):
+ return found
+ for key, entry in data.items():
+ if not isinstance(key, str) or not _RELEASE_RE.match(key) or not isinstance(entry, dict):
+ continue
+ match = _DATE_RE.search(str(entry.get("itemTitle") or ""))
+ if not match:
+ continue
+ metadata = str(entry.get("metadataLayerUrl") or "")
+ found.append(
+ Release(
+ number=int(key),
+ date=match.group(0),
+ metadata_url=metadata if _METADATA_RE.match(metadata) else None,
+ )
+ )
+ # Release numbers are not in date order, so the date sorts and the number
+ # only breaks a tie.
+ found.sort(key=lambda release: (release.date, release.number), reverse=True)
+ return found
+
+
+_lock = threading.Lock()
+_listed: tuple[float, list[Release]] | None = None
+_changes: dict[tuple[int, int, int, int], list["Change"]] = {}
+
+
+def reset() -> None:
+ """Forget what this session read. For tests, and nothing else."""
+ global _listed
+ with _lock:
+ _listed = None
+ _changes.clear()
+
+
+def _get(url: str, **kwargs: Any) -> httpx.Response:
+ return httpx.get(
+ url, headers={"User-Agent": USER_AGENT}, timeout=15, follow_redirects=True, **kwargs
+ )
+
+
+def releases(*, get: Callable[..., Any] | None = None) -> list[Release]:
+ """Every release, newest first, read once per `LIST_TTL_S`.
+
+ Raises when the list cannot be read and nothing was read before it.
+ """
+ global _listed
+ with _lock:
+ if _listed and time.monotonic() - _listed[0] < LIST_TTL_S:
+ return _listed[1]
+ response = (get or _get)(CONFIG_URL)
+ response.raise_for_status()
+ parsed = parse_config(response.json())
+ if not parsed:
+ raise ValueError("the Wayback release list came back empty")
+ with _lock:
+ _listed = (time.monotonic(), parsed)
+ return parsed
+
+
+def find(number: int, listed: list[Release]) -> Release | None:
+ return next((release for release in listed if release.number == number), None)
+
+
+def parse_variant(spec: str) -> int:
+ """``"64776"`` → ``64776``. The validation boundary for a path segment."""
+ if not _RELEASE_RE.match(spec):
+ raise ValueError(f"malformed Wayback release '{spec}'")
+ return int(spec)
+
+
+def variant_id(number: int) -> str:
+ return f"{BASE_ID}{VARIANT_SEP}{int(number)}"
+
+
+def tile_url(number: int) -> str:
+ """The XYZ template of one release, with `{z}`/`{x}`/`{y}` left to fill."""
+ return TILE_TEMPLATE.format(release=int(number))
+
+
+@dataclass(frozen=True)
+class Change:
+ """One picture a point has had: the release that first published it, and
+ when and by what it was taken, when the release's metadata says."""
+
+ release: int
+ acquired: str | None
+ source: str | None
+
+
+def local_changes(
+ lat: float,
+ lon: float,
+ zoom: int,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> list[Change]:
+ """The distinct pictures of this point, newest first.
+
+ Starts from the newest release and asks the tilemap which release that
+ tile really comes from, then continues from the release before that one,
+ until a release has no tile there. What the tilemap calls a change is a
+ change of bytes, and Esri republishes the same picture often: re-encoded
+ (neighbours of equal size, compared by content) or re-processed (a new
+ colour balance over the same acquisition, compared by the date and sensor
+ each release's metadata states). Either way the release that first
+ published the picture is the one kept.
+
+ One pooled connection carries the whole walk: a fresh TLS handshake per
+ step made a ten-change point take most of a minute.
+ """
+ if get is not None:
+ return _walk_changes(lat, lon, zoom, get)
+ with _open_client() as client:
+ return _walk_changes(lat, lon, zoom, client.get)
+
+
+def _open_client() -> httpx.Client:
+ return httpx.Client(
+ headers={"User-Agent": USER_AGENT},
+ timeout=15,
+ follow_redirects=True,
+ limits=httpx.Limits(max_connections=METADATA_WORKERS + 4),
+ )
+
+
+def _walk_changes(lat: float, lon: float, zoom: int, fetch: Callable[..., Any]) -> list[Change]:
+ from . import tiles
+
+ listed = releases(get=fetch)
+ order = {release.number: index for index, release in enumerate(listed)}
+ z = max(0, min(int(zoom), MAX_ZOOM))
+ x, y = tiles.project(lat, lon, z)
+ col, row = int(x), int(y)
+ key = (listed[0].number, z, row, col)
+ with _lock:
+ if key in _changes:
+ return _changes[key]
+
+ found: list[tuple[int, int]] = []
+ current = listed[0].number
+ for _ in range(MAX_STEPS):
+ response = fetch(TILEMAP_URL.format(release=current, z=z, row=row, col=col))
+ response.raise_for_status()
+ answer = response.json()
+ data = answer.get("data") if isinstance(answer, dict) else None
+ if not data or not data[0]:
+ break
+ select = answer.get("select") or []
+ chosen = int(select[0]) if select and str(select[0]).isdigit() else current
+ if chosen not in order:
+ break # a release the list does not know: stop rather than guess its date
+ size = answer.get("size") or [0]
+ if not found or found[-1][0] != chosen:
+ found.append((chosen, int(size[0] or 0)))
+ following = order[chosen] + 1
+ if following >= len(listed):
+ break
+ current = listed[following].number
+
+ def read_digest(number: int) -> str | None:
+ """The tile's hash, or None when it cannot be read: an unknown is never
+ a twin, so a dropped connection keeps a change rather than losing it."""
+ for _attempt in (1, 2):
+ try:
+ reply = fetch(tiles.tile_url(tile_url(number), z, col, row))
+ reply.raise_for_status()
+ return hashlib.sha256(reply.content).hexdigest()
+ except Exception:
+ continue
+ return None
+
+ # Only a run of neighbours sharing one size is ever compared, so those
+ # tiles are read up front and side by side rather than one per comparison.
+ twins = {
+ found[i][0]
+ for i in range(len(found))
+ for j in (i - 1, i + 1)
+ if 0 <= j < len(found) and found[i][1] and found[i][1] == found[j][1]
+ }
+ with ThreadPoolExecutor(max_workers=6) as pool:
+ digests = dict(zip(twins, pool.map(read_digest, twins)))
+
+ def twin(one: int, other: int) -> bool:
+ for number in (one, other):
+ if number not in digests:
+ digests[number] = read_digest(number)
+ return digests[one] is not None and digests[one] == digests[other]
+
+ distinct: list[tuple[int, int]] = []
+ for number, size in reversed(found): # oldest first, so the older twin stays
+ previous = distinct[-1] if distinct else None
+ if previous and size and previous[1] == size and twin(previous[0], number):
+ continue
+ distinct.append((number, size))
+
+ # What each picture is, asked at the middle of the tile the walk read, so
+ # every point of that tile gets the same answer the cache will give it.
+ centre = tiles.unproject(col + 0.5, row + 0.5, z)
+
+ def describe(number: int) -> dict[str, Any]:
+ release = find(number, listed)
+ if not release:
+ return {}
+ for _attempt in (1, 2):
+ try:
+ return _metadata(release, centre[0], centre[1], z, fetch)
+ except Exception:
+ continue
+ return {} # unknown, which never merges two pictures
+
+ numbers = [number for number, _ in distinct]
+ # The metadata service is the slow one, a couple of seconds a question, so
+ # a whole history is asked at once rather than six at a time.
+ with ThreadPoolExecutor(max_workers=METADATA_WORKERS) as pool:
+ described = list(pool.map(describe, numbers))
+
+ kept: list[tuple[Change, tuple[str, str] | None]] = []
+ for number, attrs in zip(numbers, described): # still oldest first
+ acquired = _day(attrs.get("SRC_DATE2"))
+ sensor = str(attrs.get("SRC_DESC") or "")
+ picture = (acquired, sensor) if acquired else None
+ if kept and picture and kept[-1][1] == picture:
+ continue # the same acquisition, published again
+ kept.append((Change(number, acquired, _source(attrs)), picture))
+ result = [change for change, _ in reversed(kept)]
+ with _lock:
+ _changes[key] = result
+ return result
+
+
+def _day(value: Any) -> str | None:
+ """SRC_DATE2 is epoch milliseconds; anything else is not a date we can state."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0:
+ return None
+ try:
+ return datetime.fromtimestamp(value / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
+ except (OverflowError, OSError, ValueError):
+ return None
+
+
+def _source(attrs: dict[str, Any]) -> str | None:
+ """Who took the picture, then with which satellite, as in `Maxar WV03`."""
+ return " ".join(str(part) for part in (attrs.get("NICE_DESC"), attrs.get("SRC_DESC")) if part) or None
+
+
+def metadata_layer(zoom: int) -> int:
+ return max(0, min(_METADATA_LAST_LAYER, _METADATA_MAX_ZOOM - int(zoom)))
+
+
+def _metadata(
+ release: Release, lat: float, lon: float, zoom: int, fetch: Callable[..., Any]
+) -> dict[str, Any]:
+ """The attributes one release's metadata states for a point, `{}` for none.
+
+ Raises when the service cannot be reached, which callers keep apart from
+ a release that simply says nothing there.
+ """
+ if not release.metadata_url:
+ return {}
+ params = {
+ "f": "json",
+ "where": "1=1",
+ "outFields": "SRC_DATE2,NICE_DESC,SRC_DESC,SAMP_RES,SRC_ACC",
+ "geometry": f'{{"spatialReference":{{"wkid":4326}},"x":{lon},"y":{lat}}}',
+ "geometryType": "esriGeometryPoint",
+ "spatialRel": "esriSpatialRelIntersects",
+ "returnGeometry": "false",
+ }
+ response = fetch(f"{release.metadata_url}/{metadata_layer(zoom)}/query", params=params)
+ response.raise_for_status()
+ features = response.json().get("features") or []
+ return (features[0].get("attributes") or {}) if features else {}
+
+
+def capture_date(
+ lat: float,
+ lon: float,
+ zoom: int,
+ number: int,
+ *,
+ get: Callable[..., Any] | None = None,
+) -> dict[str, Any] | None:
+ """When the pixels of one release were acquired at a point, and by what.
+
+ ``None`` when a service cannot be reached; a dict with ``date: None`` when
+ the release carries no metadata there. Never raises.
+ """
+ try:
+ release = find(number, releases(get=get))
+ except Exception:
+ return None
+ if release is None:
+ return {"date": None, "source": None, "release_date": None}
+ try:
+ attrs = _metadata(release, lat, lon, zoom, get or _get)
+ except Exception:
+ return None
+ return {
+ "date": _day(attrs.get("SRC_DATE2")),
+ "source": _source(attrs),
+ "release_date": release.date,
+ }
diff --git a/tests/fixtures/earth-scale.json b/tests/fixtures/earth-scale.json
new file mode 100644
index 0000000..8bef062
--- /dev/null
+++ b/tests/fixtures/earth-scale.json
@@ -0,0 +1,161 @@
+{
+ "what": "Google Earth screenshots of one camera, a known step east, a known step north and at half the distance, registered against each other.",
+ "how": "frontend/calibration/earth.mjs takes the shots (npm run calibrate:earth); scripts/build_earth_fixture.py registers them.",
+ "why": "Earth states its scale as a camera distance and a field of view. tests/test_mapsites.py checks the parse of each base URL predicts how far the picture moved, and that the camera is drawn at the middle of the window.",
+ "cases": [
+ {
+ "id": "chamonix",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@45.9237,6.8694,1047.58183037a,3626.26966449d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.004134260751366796,
+ "moved_px": -139.919,
+ "across_px": 0.011
+ },
+ "north": {
+ "d_lat": 0.0028758566415867997,
+ "moved_px": 139.95,
+ "across_px": 0.007
+ },
+ "camera_offset_px": {
+ "x": 0.18,
+ "y": 0.04
+ }
+ },
+ {
+ "id": "cher-1200",
+ "window": {
+ "w": 1200,
+ "h": 760
+ },
+ "base": "https://earth.google.com/web/@47.388462,2.352785,194.50073928a,2054.51135834d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.003166634254567225,
+ "moved_px": -140.029,
+ "across_px": 0.0
+ },
+ "north": {
+ "d_lat": 0.002143887985872412,
+ "moved_px": 140.0,
+ "across_px": 0.002
+ },
+ "camera_offset_px": {
+ "x": -0.1,
+ "y": 0.01
+ }
+ },
+ {
+ "id": "cher-1600",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@47.388462,2.352785,194.50053456a,2160.80568321d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.0025311545552019338,
+ "moved_px": -140.018,
+ "across_px": -0.002
+ },
+ "north": {
+ "d_lat": 0.0017136528582222645,
+ "moved_px": 139.992,
+ "across_px": 0.001
+ },
+ "camera_offset_px": {
+ "x": -0.13,
+ "y": 0.0
+ }
+ },
+ {
+ "id": "cher-60y",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@47.388462,2.352785,194.50053456a,2206.63410145d,60y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.004733150856423486,
+ "moved_px": -140.068,
+ "across_px": -0.001
+ },
+ "north": {
+ "d_lat": 0.003204457616717987,
+ "moved_px": 140.029,
+ "across_px": 0.007
+ },
+ "camera_offset_px": {
+ "x": -0.12,
+ "y": -0.01
+ }
+ },
+ {
+ "id": "cher-square",
+ "window": {
+ "w": 1000,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@47.388462,2.352785,194.50053456a,2206.63410145d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.0025848376839012034,
+ "moved_px": -140.004,
+ "across_px": 0.0
+ },
+ "north": {
+ "d_lat": 0.0017499976348558184,
+ "moved_px": 139.975,
+ "across_px": -0.001
+ },
+ "camera_offset_px": {
+ "x": -0.06,
+ "y": 0.02
+ }
+ },
+ {
+ "id": "flevoland",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@52.455,5.59,-5.53312649a,1550.32598002d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.0020176176667166096,
+ "moved_px": -139.913,
+ "across_px": -0.004
+ },
+ "north": {
+ "d_lat": 0.0012295046090821072,
+ "moved_px": 139.917,
+ "across_px": -0.013
+ },
+ "camera_offset_px": {
+ "x": -0.02,
+ "y": -0.01
+ }
+ },
+ {
+ "id": "france-400km",
+ "window": {
+ "w": 1600,
+ "h": 1000
+ },
+ "base": "https://earth.google.com/web/@47.38846198,2.35278498,229.45964543a,313395.88971768d,35y,0h,0t,0r",
+ "east": {
+ "d_lon": 0.36711002738619386,
+ "moved_px": -139.781,
+ "across_px": 0.026
+ },
+ "north": {
+ "d_lat": 0.2485423684058397,
+ "moved_px": 139.871,
+ "across_px": -0.0
+ },
+ "camera_offset_px": {
+ "x": -0.03,
+ "y": 0.0
+ }
+ }
+ ]
+}
diff --git a/tests/fixtures/map-link-writes.json b/tests/fixtures/map-link-writes.json
new file mode 100644
index 0000000..bfd47f8
--- /dev/null
+++ b/tests/fixtures/map-link-writes.json
@@ -0,0 +1,329 @@
+{
+ "_about": "A view written into each map site's address by extension/maplink.js, and what the app's parser must read back from it. Checked from both sides: frontend/src/lib/extensionMapLink.test.js writes, tests/test_map_link_writes.py parses.",
+ "writes": [
+ {
+ "site": "google-maps",
+ "name": "road map, a fraction written as a whole level",
+ "from": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://www.google.com/maps/@47.4,2.37,17z?entry=ttu",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "google-maps",
+ "name": "satellite metres, layer kept",
+ "from": "https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3?entry=ttu",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://www.google.com/maps/@47.4,2.37,17z/data=!3m1!1e3?entry=ttu",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "google-maps",
+ "name": "a place page keeps its place",
+ "from": "https://www.google.com/maps/place/Tour+Eiffel/@48.8583701,2.2944813,17z/data=!3m1!4b1",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://www.google.com/maps/place/Tour+Eiffel/@47.4,2.37,17z/data=!3m1!4b1",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "google-maps",
+ "name": "held to the level it draws",
+ "from": "https://www.google.com/maps/@47.388462,2.352785,15z",
+ "height": 1000,
+ "view": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 22,
+ "bearing": 0
+ },
+ "url": "https://www.google.com/maps/@48.85837,2.294481,21z",
+ "lands": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 21
+ }
+ },
+ {
+ "site": "google-earth",
+ "name": "distance from the window height, ground height kept",
+ "from": "https://earth.google.com/web/@47.39999999,2.3703724,211.05401095a,1601.93591136d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://earth.google.com/web/@47.4,2.37,211.05401095a,1812.99d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5
+ }
+ },
+ {
+ "site": "google-earth",
+ "name": "never closer than Earth places its camera",
+ "from": "https://earth.google.com/web/@48.85,2.29,35a,800d,35y,0h,0t,0r",
+ "height": 1000,
+ "view": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 23,
+ "bearing": 0
+ },
+ "url": "https://earth.google.com/web/@48.85837,2.294481,35a,25d,35y,0h,0t,0r",
+ "lands": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 22.6393
+ }
+ },
+ {
+ "site": "google-earth",
+ "name": "a view Earth never placed stays unplaced",
+ "from": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://earth.google.com/web/@47.4,2.37,0a,1813d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": null
+ }
+ },
+ {
+ "site": "bing-maps",
+ "name": "one decimal, style kept",
+ "from": "https://www.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://www.bing.com/maps?cp=47.4%7E2.37&lvl=16.5&style=h",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5
+ }
+ },
+ {
+ "site": "yandex-maps",
+ "name": "longitude first, a whole level, layer kept",
+ "from": "https://yandex.com/maps/?ll=2.352785,47.388462&z=15&l=sat",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://yandex.com/maps/?ll=2.37%2C47.4&z=17&l=sat",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "openstreetmap",
+ "name": "hash, a whole level, layers kept",
+ "from": "https://www.openstreetmap.org/#map=15/47.38846/2.35279&layers=H",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://www.openstreetmap.org/#map=17/47.4/2.37&layers=H",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "openstreetmap",
+ "name": "held to the level it draws",
+ "from": "https://www.openstreetmap.org/#map=15/47.38846/2.35279",
+ "height": 1000,
+ "view": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 22,
+ "bearing": 0
+ },
+ "url": "https://www.openstreetmap.org/#map=19/48.85837/2.29448",
+ "lands": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 19
+ }
+ },
+ {
+ "site": "apple-maps",
+ "name": "a link form stays a link form",
+ "from": "https://maps.apple.com/?ll=47.388462,2.352785&z=15&map=satellite",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://maps.apple.com/?map=satellite&ll=47.4%2C2.37&z=16.5",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5
+ }
+ },
+ {
+ "site": "apple-maps",
+ "name": "a place card closed by the move, its address dropped",
+ "from": "https://maps.apple.com/place?map=satellite&z=16&address=2+Route+du+Bois+Bernard,+18380+Presly,+France&coordinate=47.387736,2.353482&name=2+Route+du+Bois+Bernard",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://maps.apple.com/frame?map=satellite&center=47.4%2C2.37&z=16.5",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5
+ }
+ },
+ {
+ "site": "apple-maps",
+ "name": "the live span dropped for a z, layer kept",
+ "from": "https://maps.apple.com/frame?center=47.388462%2C2.352785&span=0.029055%2C0.056434&map=satellite",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://maps.apple.com/frame?map=satellite&center=47.4%2C2.37&z=16.5",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5
+ }
+ },
+ {
+ "site": "apple-maps",
+ "name": "a view past the pole written as the one Apple opens",
+ "from": "https://maps.apple.com/frame?center=70.1%2C15.6&span=0.029055%2C0.056434&map=satellite",
+ "height": 1000,
+ "view": {
+ "lat": 78.223,
+ "lon": 15.6,
+ "zoom": 12,
+ "bearing": 0
+ },
+ "url": "https://maps.apple.com/frame?map=satellite&center=70.495574%2C15.6&z=12",
+ "lands": {
+ "lat": 70.495574,
+ "lon": 15.6,
+ "zoom": 12
+ }
+ },
+ {
+ "site": "zoom-earth",
+ "name": "hash view, the day kept",
+ "from": "https://zoom.earth/maps/satellite-hd/#view=47.388462,2.352785,11z/date=2026-09-12,pm",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://zoom.earth/maps/satellite-hd/#view=47.4,2.37,17z/date=2026-09-12,pm",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "satellites-pro",
+ "name": "hash, a whole level",
+ "from": "https://satellites.pro/#47.388462,2.352785,15",
+ "height": 1000,
+ "view": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 16.5,
+ "bearing": 0
+ },
+ "url": "https://satellites.pro/#47.4,2.37,17",
+ "lands": {
+ "lat": 47.4,
+ "lon": 2.37,
+ "zoom": 17
+ }
+ },
+ {
+ "site": "copernicus-browser",
+ "name": "acquisition kept, held to 18",
+ "from": "https://browser.dataspace.copernicus.eu/?zoom=15&lat=47.38846&lng=2.35279&datasetId=S2_L2A_CDAS&fromTime=2026-09-01T00%3A00%3A00.000Z&toTime=2026-09-01T23%3A59%3A59.999Z",
+ "height": 1000,
+ "view": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 22,
+ "bearing": 0
+ },
+ "url": "https://browser.dataspace.copernicus.eu/?zoom=18&lat=48.85837&lng=2.29448&datasetId=S2_L2A_CDAS&fromTime=2026-09-01T00%3A00%3A00.000Z&toTime=2026-09-01T23%3A59%3A59.999Z",
+ "lands": {
+ "lat": 48.85837,
+ "lon": 2.294481,
+ "zoom": 18
+ }
+ }
+ ]
+}
diff --git a/tests/fixtures/map-sites.json b/tests/fixtures/map-sites.json
index 8bd2c84..1d6031d 100644
--- a/tests/fixtures/map-sites.json
+++ b/tests/fixtures/map-sites.json
@@ -3,10 +3,32 @@
"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.",
+ "hints": {
+ "bing-maps": {
+ "x": 0.0,
+ "y": 40.5,
+ "min_w": 0
+ },
+ "openstreetmap": {
+ "x": 0.0,
+ "y": 27.4,
+ "min_w": 0
+ },
+ "yandex-maps": {
+ "x": 210.0,
+ "y": 10.0,
+ "min_w": 1200
+ },
+ "copernicus-browser": {
+ "x": 225.0,
+ "y": 0.0,
+ "min_w": 1600
+ }
+ },
"recordings": [
{
- "label": "google-maps",
- "site": "google-maps",
+ "label": "apple-maps",
+ "site": "apple-maps",
"browser": "chromium",
"page_zoom": 1,
"window": {
@@ -15,10 +37,10 @@
},
"map_height": 1000,
"centre": {
- "x": 800.0,
+ "x": 867.5,
"y": 500.0
},
- "spread": 0.01,
+ "spread": 0.09,
"canvas": null,
"pan": {
"from": 0,
@@ -46,71 +68,163 @@
],
"steps": [
{
- "url": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "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": 15.0,
+ "zoom": 14.99998634768003,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "google-maps"
+ "scale_source": "span",
+ "site": "apple-maps"
},
{
- "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434",
"view": {
- "lat": 47.3941855,
- "lon": 2.365445,
- "zoom": 15.0,
+ "lat": 47.393517,
+ "lon": 2.36523,
+ "zoom": 14.999996940780553,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "google-maps"
+ "scale_source": "span",
+ "site": "apple-maps"
},
{
- "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217",
"view": {
- "lat": 47.3978168,
- "lon": 2.356862,
- "zoom": 16.0,
+ "lat": 47.397149,
+ "lon": 2.355199,
+ "zoom": 15.99999686323065,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "google-maps"
+ "scale_source": "span",
+ "site": "apple-maps"
},
{
- "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108",
"view": {
- "lat": 47.396219,
- "lon": 2.3616685,
- "zoom": 17.0,
+ "lat": 47.395551,
+ "lon": 2.359281,
+ "zoom": 16.999941303569063,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "google-maps"
+ "scale_source": "span",
+ "site": "apple-maps"
}
],
- "note": "the 2D map, with nothing round it: the camera is the middle of the window"
+ "note": "Apple states a span, never a live zoom, and draws 67 px right of centre here"
},
{
- "label": "google-maps satellite",
- "site": "google-maps",
+ "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": 1000,
+ "map_height": 919,
"centre": {
- "x": 799.87,
- "y": 499.97
+ "x": 800.02,
+ "y": 540.52
},
- "spread": 1.49,
+ "spread": 0.13,
"canvas": null,
"pan": {
"from": 0,
@@ -138,59 +252,59 @@
],
"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.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h",
"view": {
"lat": 47.388462,
"lon": 2.352785,
- "zoom": 15.001498318234315,
+ "zoom": 15.0,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "height_m",
- "site": "google-maps"
+ "scale_source": "zoom",
+ "site": "bing-maps"
},
{
- "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h",
"view": {
- "lat": 47.3941855,
- "lon": 2.365445,
- "zoom": 15.001788226067221,
+ "lat": 47.394273,
+ "lon": 2.36566,
+ "zoom": 15.0,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "height_m",
- "site": "google-maps"
+ "scale_source": "zoom",
+ "site": "bing-maps"
},
{
- "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h",
"view": {
- "lat": 47.3978168,
- "lon": 2.356862,
- "zoom": 16.00168880482045,
+ "lat": 47.398492,
+ "lon": 2.357077,
+ "zoom": 16.0,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "height_m",
- "site": "google-maps"
+ "scale_source": "zoom",
+ "site": "bing-maps"
},
{
- "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
+ "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h",
"view": {
- "lat": 47.396219,
- "lon": 2.3616685,
- "zoom": 17.00083951932319,
+ "lat": 47.397189,
+ "lon": 2.361883,
+ "zoom": 17.0,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "height_m",
- "site": "google-maps"
+ "scale_source": "zoom",
+ "site": "bing-maps"
}
],
- "note": "satellite quotes the viewport's height in metres instead of a level"
+ "note": "Bing sits under an 81 px header, so its camera is 40 px down"
},
{
- "label": "google-maps with its place panel open",
- "site": "google-maps",
+ "label": "copernicus-browser",
+ "site": "copernicus-browser",
"browser": "chromium",
"page_zoom": 1,
"window": {
@@ -199,10 +313,10 @@
},
"map_height": 1000,
"centre": {
- "x": 800.0,
- "y": 500.0
+ "x": 1025.03,
+ "y": 500.44
},
- "spread": 0.0,
+ "spread": 1.25,
"canvas": null,
"pan": {
"from": 0,
@@ -211,70 +325,78 @@
"dy": 200
},
"zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 1200,
+ "y": 300
+ }
+ },
{
"from": 2,
"to": 3,
"at": {
- "x": 1248,
- "y": 720
+ "x": 700,
+ "y": 800
}
}
],
"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://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.081,
- "lon": 2.3988,
- "zoom": 13.0,
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "google-maps"
+ "site": "copernicus-browser"
},
{
- "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://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.1040234,
- "lon": 2.4494401,
- "zoom": 13.0,
+ "lat": 47.38846,
+ "lon": 2.35279,
+ "zoom": 15.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "google-maps"
+ "site": "copernicus-browser"
},
{
- "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://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.1040234,
- "lon": 2.4494401,
- "zoom": 13.0,
+ "lat": 47.39138,
+ "lon": 2.35655,
+ "zoom": 16.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "google-maps"
+ "site": "copernicus-browser"
},
{
- "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",
+ "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.0911689,
- "lon": 2.4878923,
- "zoom": 14.0,
+ "lat": 47.3892,
+ "lon": 2.35306,
+ "zoom": 17.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "google-maps"
+ "site": "copernicus-browser"
}
],
- "note": "the panel covers the map but does not move the camera under it"
+ "note": "a 450 px panel; its address bar follows a zoom but not a pan"
},
{
- "label": "apple-maps",
- "site": "apple-maps",
+ "label": "google-earth",
+ "site": "google-earth",
"browser": "chromium",
"page_zoom": 1,
"window": {
@@ -283,15 +405,20 @@
},
"map_height": 1000,
"centre": {
- "x": 867.5,
- "y": 500.0
+ "x": 799.42,
+ "y": 500.51
+ },
+ "spread": 2.02,
+ "canvas": {
+ "x": 0,
+ "y": 0,
+ "w": 1600,
+ "h": 1000
},
- "spread": 0.09,
- "canvas": null,
"pan": {
"from": 0,
"to": 1,
- "dx": -300,
+ "dx": -320,
"dy": 200
},
"zooms": [
@@ -299,74 +426,73 @@
"from": 1,
"to": 2,
"at": {
- "x": 400,
- "y": 250
+ "x": 992,
+ "y": 300
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 1248,
- "y": 720
+ "x": 1280,
+ "y": 740
}
}
],
"steps": [
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.029055%2C0.056434",
+ "url": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
"lat": 47.388462,
"lon": 2.352785,
- "zoom": 14.99998634768003,
+ "zoom": null,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": null,
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434",
+ "url": "https://earth.google.com/web/@47.39403373,2.36595251,206.49927856a,4922.50082797d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.393517,
- "lon": 2.36523,
- "zoom": 14.999996940780553,
+ "lat": 47.39403373,
+ "lon": 2.36595251,
+ "zoom": 15.059143563741559,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217",
+ "url": "https://earth.google.com/web/@47.39694967,2.37010153,210.01806133a,2360.11894573d,35y,-0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.397149,
- "lon": 2.355199,
- "zoom": 15.99999686323065,
+ "lat": 47.39694967,
+ "lon": 2.37010153,
+ "zoom": 16.11959560788541,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108",
+ "url": "https://earth.google.com/web/@47.39529375,2.37499289,212.14829276a,1141.56889716d,35y,-0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.395551,
- "lon": 2.359281,
- "zoom": 16.999941303569063,
+ "lat": 47.39529375,
+ "lon": 2.37499289,
+ "zoom": 17.167482582869898,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
}
- ],
- "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",
+ "label": "google-earth",
+ "site": "google-earth",
"browser": "chromium",
"page_zoom": 1,
"window": {
@@ -375,102 +501,106 @@
},
"map_height": 760,
"centre": {
- "x": 597.5,
- "y": 380.02
+ "x": 599.42,
+ "y": 380.4
+ },
+ "spread": 1.58,
+ "canvas": {
+ "x": 0,
+ "y": 0,
+ "w": 1200,
+ "h": 760
},
- "spread": 0.18,
- "canvas": null,
"pan": {
"from": 0,
"to": 1,
"dx": -240,
- "dy": 160
+ "dy": 152
},
"zooms": [
{
"from": 1,
"to": 2,
"at": {
- "x": 936,
- "y": 213
+ "x": 744,
+ "y": 228
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 744,
+ "x": 960,
"y": 562
}
}
],
"steps": [
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.022082%2C0.039268",
+ "url": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
"lat": 47.388462,
"lon": 2.352785,
- "zoom": 14.999973302876091,
+ "zoom": null,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": null,
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.392617%2C2.362055&span=0.022080%2C0.045276",
+ "url": "https://earth.google.com/web/@47.39403081,2.36577244,206.20759942a,4922.79230946d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.392617,
- "lon": 2.362055,
- "zoom": 14.999990238003937,
+ "lat": 47.39403081,
+ "lon": 2.36577244,
+ "zoom": 14.663129541982356,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395042%2C2.369318&span=0.011039%2C0.022638",
+ "url": "https://earth.google.com/web/@47.39718693,2.37020577,209.93995048a,2151.034749d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.395042,
- "lon": 2.369318,
- "zoom": 16.000054556399927,
+ "lat": 47.39718693,
+ "lon": 2.37020577,
+ "zoom": 15.85748917498043,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393721%2C2.370890&span=0.005520%2C0.011319",
+ "url": "https://earth.google.com/web/@47.39542433,2.37535523,211.70640372a,851.59552764d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA",
"view": {
- "lat": 47.393721,
- "lon": 2.37089,
- "zoom": 16.999960042778163,
+ "lat": 47.39542433,
+ "lon": 2.37535523,
+ "zoom": 17.194327986443106,
"bearing": 0,
"projection": "webmercator"
},
- "scale_source": "span",
- "site": "apple-maps"
+ "scale_source": "distance",
+ "site": "google-earth"
}
- ],
- "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",
+ "label": "google-maps",
+ "site": "google-maps",
"browser": "chromium",
"page_zoom": 1,
"window": {
"w": 1600,
"h": 1000
},
- "map_height": 919,
+ "map_height": 1000,
"centre": {
- "x": 800.02,
- "y": 540.52
+ "x": 800.0,
+ "y": 500.0
},
- "spread": 0.13,
+ "spread": 0.01,
"canvas": null,
"pan": {
"from": 0,
@@ -498,7 +628,7 @@
],
"steps": [
{
- "url": "https://www.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h",
+ "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,
@@ -507,62 +637,62 @@
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "bing-maps"
+ "site": "google-maps"
},
{
- "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h",
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.394273,
- "lon": 2.36566,
+ "lat": 47.3941855,
+ "lon": 2.365445,
"zoom": 15.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "bing-maps"
+ "site": "google-maps"
},
{
- "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h",
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.398492,
- "lon": 2.357077,
+ "lat": 47.3978168,
+ "lon": 2.356862,
"zoom": 16.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "bing-maps"
+ "site": "google-maps"
},
{
- "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h",
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.397189,
- "lon": 2.361883,
+ "lat": 47.396219,
+ "lon": 2.3616685,
"zoom": 17.0,
"bearing": 0,
"projection": "webmercator"
},
"scale_source": "zoom",
- "site": "bing-maps"
+ "site": "google-maps"
}
],
- "note": "Bing sits under an 81 px header, so its camera is 40 px down"
+ "note": "the 2D map, with nothing round it: the camera is the middle of the window"
},
{
- "label": "yandex-maps",
- "site": "yandex-maps",
+ "label": "google-maps satellite",
+ "site": "google-maps",
"browser": "chromium",
"page_zoom": 1,
"window": {
"w": 1600,
"h": 1000
},
- "map_height": 980,
+ "map_height": 1000,
"centre": {
- "x": 1010.0,
- "y": 509.99
+ "x": 799.87,
+ "y": 499.97
},
- "spread": 0.0,
+ "spread": 1.49,
"canvas": null,
"pan": {
"from": 0,
@@ -571,6 +701,14 @@
"dy": 200
},
"zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
{
"from": 2,
"to": 3,
@@ -582,147 +720,139 @@
],
"steps": [
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15",
+ "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.0,
+ "zoom": 15.001498318234315,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "yandex-maps"
+ "scale_source": "height_m",
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15",
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.394291,
- "lon": 2.36566,
- "zoom": 15.0,
+ "lat": 47.3941855,
+ "lon": 2.365445,
+ "zoom": 15.001788226067221,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "yandex-maps"
+ "scale_source": "height_m",
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15",
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.394291,
- "lon": 2.36566,
- "zoom": 15.0,
+ "lat": 47.3978168,
+ "lon": 2.356862,
+ "zoom": 16.00168880482045,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "yandex-maps"
+ "scale_source": "height_m",
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.370767%2C47.391231&z=16",
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D",
"view": {
- "lat": 47.391231,
- "lon": 2.370767,
- "zoom": 16.0,
+ "lat": 47.396219,
+ "lon": 2.3616685,
+ "zoom": 17.00083951932319,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
- "scale_source": "zoom",
- "site": "yandex-maps"
+ "scale_source": "height_m",
+ "site": "google-maps"
}
],
- "note": "a 420 px results panel, and the map centred in what is left"
+ "note": "satellite quotes the viewport's height in metres instead of a level"
},
{
- "label": "yandex-maps in a smaller window",
- "site": "yandex-maps",
+ "label": "google-maps with its place panel open",
+ "site": "google-maps",
"browser": "chromium",
"page_zoom": 1,
"window": {
- "w": 1200,
- "h": 760
+ "w": 1600,
+ "h": 1000
},
- "map_height": 740,
+ "map_height": 1000,
"centre": {
- "x": 810.01,
- "y": 390.0
+ "x": 800.0,
+ "y": 500.0
},
- "spread": 0.04,
+ "spread": 0.0,
"canvas": null,
"pan": {
"from": 0,
"to": 1,
- "dx": -240,
- "dy": 160
+ "dx": -300,
+ "dy": 200
},
"zooms": [
- {
- "from": 1,
- "to": 2,
- "at": {
- "x": 936,
- "y": 213
- }
- },
{
"from": 2,
"to": 3,
"at": {
- "x": 744,
- "y": 562
+ "x": 1248,
+ "y": 720
}
}
],
"steps": [
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15",
+ "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.388462,
- "lon": 2.352785,
- "zoom": 15.0,
+ "lat": 47.081,
+ "lon": 2.3988,
+ "zoom": 13.0,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
"scale_source": "zoom",
- "site": "yandex-maps"
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15",
+ "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.393125,
- "lon": 2.363085,
- "zoom": 15.0,
+ "lat": 47.1040234,
+ "lon": 2.4494401,
+ "zoom": 13.0,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
"scale_source": "zoom",
- "site": "yandex-maps"
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16",
+ "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.395704,
- "lon": 2.365788,
- "zoom": 16.0,
+ "lat": 47.1040234,
+ "lon": 2.4494401,
+ "zoom": 13.0,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
"scale_source": "zoom",
- "site": "yandex-maps"
+ "site": "google-maps"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17",
+ "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.394451,
- "lon": 2.36508,
- "zoom": 17.0,
+ "lat": 47.0911689,
+ "lon": 2.4878923,
+ "zoom": 14.0,
"bearing": 0,
- "projection": "ellipsoidal"
+ "projection": "webmercator"
},
"scale_source": "zoom",
- "site": "yandex-maps"
+ "site": "google-maps"
}
],
- "note": "the panel is a fixed width, so the offset does not move with the window"
+ "note": "the panel covers the map but does not move the camera under it"
},
{
"label": "openstreetmap",
@@ -1001,20 +1131,20 @@
"note": "full-window Leaflet, crosshair dead centre"
},
{
- "label": "copernicus-browser",
- "site": "copernicus-browser",
+ "label": "yandex-maps",
+ "site": "yandex-maps",
"browser": "chromium",
"page_zoom": 1,
"window": {
"w": 1600,
"h": 1000
},
- "map_height": 1000,
+ "map_height": 980,
"centre": {
- "x": 1025.03,
- "y": 500.44
+ "x": 1010.0,
+ "y": 509.99
},
- "spread": 1.25,
+ "spread": 0.0,
"canvas": null,
"pan": {
"from": 0,
@@ -1022,75 +1152,159 @@
"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": 1200,
- "y": 300
+ "x": 936,
+ "y": 213
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 700,
- "y": 800
+ "x": 744,
+ "y": 562
}
}
],
"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://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15",
"view": {
- "lat": 47.38846,
- "lon": 2.35279,
+ "lat": 47.388462,
+ "lon": 2.352785,
"zoom": 15.0,
"bearing": 0,
- "projection": "webmercator"
+ "projection": "ellipsoidal"
},
"scale_source": "zoom",
- "site": "copernicus-browser"
+ "site": "yandex-maps"
},
{
- "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://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15",
"view": {
- "lat": 47.38846,
- "lon": 2.35279,
+ "lat": 47.393125,
+ "lon": 2.363085,
"zoom": 15.0,
"bearing": 0,
- "projection": "webmercator"
+ "projection": "ellipsoidal"
},
"scale_source": "zoom",
- "site": "copernicus-browser"
+ "site": "yandex-maps"
},
{
- "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://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16",
"view": {
- "lat": 47.39138,
- "lon": 2.35655,
+ "lat": 47.395704,
+ "lon": 2.365788,
"zoom": 16.0,
"bearing": 0,
- "projection": "webmercator"
+ "projection": "ellipsoidal"
},
"scale_source": "zoom",
- "site": "copernicus-browser"
+ "site": "yandex-maps"
},
{
- "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",
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17",
"view": {
- "lat": 47.3892,
- "lon": 2.35306,
+ "lat": 47.394451,
+ "lon": 2.36508,
"zoom": 17.0,
"bearing": 0,
- "projection": "webmercator"
+ "projection": "ellipsoidal"
},
"scale_source": "zoom",
- "site": "copernicus-browser"
+ "site": "yandex-maps"
}
],
- "note": "a 450 px panel; its address bar follows a zoom but not a pan"
+ "note": "the panel is a fixed width, so the offset does not move with the window"
},
{
"label": "zoom-earth",
diff --git a/tests/fixtures/map-sites.raw.json b/tests/fixtures/map-sites.raw.json
index d468e01..d4471aa 100644
--- a/tests/fixtures/map-sites.raw.json
+++ b/tests/fixtures/map-sites.raw.json
@@ -1,7 +1,7 @@
{
"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.",
+ "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": {
"lat": 47.388462,
"lon": 2.352785,
@@ -13,8 +13,8 @@
"pageZoom": 1,
"deviceScaleFactor": 1,
"protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
- "site": "google-maps",
- "label": "google-maps",
+ "site": "apple-maps",
+ "label": "apple-maps",
"link": null,
"window": {
"w": 1600,
@@ -47,16 +47,16 @@
"canvas": null,
"steps": [
{
- "url": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.029055%2C0.056434"
},
{
- "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434"
},
{
- "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217"
},
{
- "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108"
}
]
},
@@ -65,8 +65,60 @@
"pageZoom": 1,
"deviceScaleFactor": 1,
"protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
- "site": "google-maps",
- "label": "google-maps satellite",
+ "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,
@@ -99,16 +151,16 @@
"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.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h"
},
{
- "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h"
},
{
- "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h"
},
{
- "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
+ "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h"
}
]
},
@@ -117,8 +169,8 @@
"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",
+ "site": "copernicus-browser",
+ "label": "copernicus-browser",
"link": null,
"window": {
"w": 1600,
@@ -131,28 +183,36 @@
"dy": 200
},
"zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 1200,
+ "y": 300
+ }
+ },
{
"from": 2,
"to": 3,
"at": {
- "x": 1248,
- "y": 720
+ "x": 700,
+ "y": 800
}
}
],
"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://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://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://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://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://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://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"
+ "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"
}
]
},
@@ -160,10 +220,9 @@
"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,
+ "site": "google-earth",
+ "label": "google-earth",
+ "link": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r",
"window": {
"w": 1600,
"h": 1000
@@ -171,7 +230,7 @@
"pan": {
"from": 0,
"to": 1,
- "dx": -300,
+ "dx": -320,
"dy": 200
},
"zooms": [
@@ -179,32 +238,37 @@
"from": 1,
"to": 2,
"at": {
- "x": 400,
- "y": 250
+ "x": 992,
+ "y": 300
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 1248,
- "y": 720
+ "x": 1280,
+ "y": 740
}
}
],
- "canvas": null,
+ "canvas": {
+ "x": 0,
+ "y": 0,
+ "w": 1600,
+ "h": 1000
+ },
"steps": [
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.029055%2C0.056434"
+ "url": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393517%2C2.365230&span=0.029052%2C0.056434"
+ "url": "https://earth.google.com/web/@47.39403373,2.36595251,206.49927856a,4922.50082797d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.397149%2C2.355199&span=0.014525%2C0.028217"
+ "url": "https://earth.google.com/web/@47.39694967,2.37010153,210.01806133a,2360.11894573d,35y,-0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395551%2C2.359281&span=0.007263%2C0.014108"
+ "url": "https://earth.google.com/web/@47.39529375,2.37499289,212.14829276a,1141.56889716d,35y,-0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
}
]
},
@@ -212,10 +276,9 @@
"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,
+ "site": "google-earth",
+ "label": "google-earth",
+ "link": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r",
"window": {
"w": 1200,
"h": 760
@@ -224,39 +287,44 @@
"from": 0,
"to": 1,
"dx": -240,
- "dy": 160
+ "dy": 152
},
"zooms": [
{
"from": 1,
"to": 2,
"at": {
- "x": 936,
- "y": 213
+ "x": 744,
+ "y": 228
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 744,
+ "x": 960,
"y": 562
}
}
],
- "canvas": null,
+ "canvas": {
+ "x": 0,
+ "y": 0,
+ "w": 1200,
+ "h": 760
+ },
"steps": [
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.388462%2C2.352785&span=0.022082%2C0.039268"
+ "url": "https://earth.google.com/web/@47.388462,2.352785,0a,5129d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.392617%2C2.362055&span=0.022080%2C0.045276"
+ "url": "https://earth.google.com/web/@47.39403081,2.36577244,206.20759942a,4922.79230946d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.395042%2C2.369318&span=0.011039%2C0.022638"
+ "url": "https://earth.google.com/web/@47.39718693,2.37020577,209.93995048a,2151.034749d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
},
{
- "url": "https://maps.apple.com/frame?z=15&map=satellite&center=47.393721%2C2.370890&span=0.005520%2C0.011319"
+ "url": "https://earth.google.com/web/@47.39542433,2.37535523,211.70640372a,851.59552764d,35y,0h,0t,0r/data=CgRCAggBQgIIAEoNCP___________wEQAA"
}
]
},
@@ -265,8 +333,8 @@
"pageZoom": 1,
"deviceScaleFactor": 1,
"protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
- "site": "bing-maps",
- "label": "bing-maps",
+ "site": "google-maps",
+ "label": "google-maps",
"link": null,
"window": {
"w": 1600,
@@ -299,16 +367,16 @@
"canvas": null,
"steps": [
{
- "url": "https://www.bing.com/maps?cp=47.388462%7E2.352785&lvl=15&style=h"
+ "url": "https://www.google.com/maps/@47.388462,2.352785,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://www.bing.com/maps?cp=47.394273%7E2.365660&lvl=15&style=h"
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,15z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://www.bing.com/maps?cp=47.398492%7E2.357077&lvl=16&style=h"
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,16z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://www.bing.com/maps?cp=47.397189%7E2.361883&lvl=17&style=h"
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,17z?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
}
]
},
@@ -317,8 +385,8 @@
"pageZoom": 1,
"deviceScaleFactor": 1,
"protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
- "site": "yandex-maps",
- "label": "yandex-maps",
+ "site": "google-maps",
+ "label": "google-maps satellite",
"link": null,
"window": {
"w": 1600,
@@ -331,6 +399,14 @@
"dy": 200
},
"zooms": [
+ {
+ "from": 1,
+ "to": 2,
+ "at": {
+ "x": 400,
+ "y": 250
+ }
+ },
{
"from": 2,
"to": 3,
@@ -343,16 +419,16 @@
"canvas": null,
"steps": [
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15"
+ "url": "https://www.google.com/maps/@47.388462,2.352785,3231m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15"
+ "url": "https://www.google.com/maps/@47.3941855,2.365445,3230m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.365660%2C47.394291&z=15"
+ "url": "https://www.google.com/maps/@47.3978168,2.356862,1615m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
},
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.370767%2C47.391231&z=16"
+ "url": "https://www.google.com/maps/@47.396219,2.3616685,808m/data=!3m1!1e3?entry=ttu&g_ep=EgoyMDI2MDkwOC4wIKXMDSoASAFQAw%3D%3D"
}
]
},
@@ -361,50 +437,42 @@
"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",
+ "site": "google-maps",
+ "label": "google-maps with its place panel open",
"link": null,
"window": {
- "w": 1200,
- "h": 760
+ "w": 1600,
+ "h": 1000
},
"pan": {
"from": 0,
"to": 1,
- "dx": -240,
- "dy": 160
+ "dx": -300,
+ "dy": 200
},
"zooms": [
- {
- "from": 1,
- "to": 2,
- "at": {
- "x": 936,
- "y": 213
- }
- },
{
"from": 2,
"to": 3,
"at": {
- "x": 744,
- "y": 562
+ "x": 1248,
+ "y": 720
}
}
],
"canvas": null,
"steps": [
{
- "url": "https://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15"
+ "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://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15"
+ "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://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16"
+ "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://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17"
+ "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"
}
]
},
@@ -569,8 +637,8 @@
"pageZoom": 1,
"deviceScaleFactor": 1,
"protocol": "driven by hand, before frontend/calibration/protocol.mjs wrote the sequence down",
- "site": "copernicus-browser",
- "label": "copernicus-browser",
+ "site": "yandex-maps",
+ "label": "yandex-maps",
"link": null,
"window": {
"w": 1600,
@@ -582,37 +650,81 @@
"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": 1200,
- "y": 300
+ "x": 936,
+ "y": 213
}
},
{
"from": 2,
"to": 3,
"at": {
- "x": 700,
- "y": 800
+ "x": 744,
+ "y": 562
}
}
],
"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://yandex.com/maps/?l=sat&ll=2.352785%2C47.388462&z=15"
},
{
- "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://yandex.com/maps/?l=sat&ll=2.363085%2C47.393125&z=15"
},
{
- "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://yandex.com/maps/?l=sat&ll=2.365788%2C47.395704&z=16"
},
{
- "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"
+ "url": "https://yandex.com/maps/?l=sat&ll=2.365080%2C47.394451&z=17"
}
]
},
@@ -662,7 +774,7 @@
}
],
"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.",
+ "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 — 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": {
diff --git a/tests/test_firms.py b/tests/test_firms.py
new file mode 100644
index 0000000..a8b1c00
--- /dev/null
+++ b/tests/test_firms.py
@@ -0,0 +1,330 @@
+"""NASA FIRMS active fire layer: the WMS request, its guards, and the route.
+
+The point of these is that the shape of a request to a public service is read
+here rather than off a fire: every URL below is built without asking NASA
+anything, and the route tests stub the one call that would.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from urllib.parse import parse_qs, urlparse
+
+import httpx
+import pytest
+
+from azimut import config
+from azimut.engine import firms
+
+
+# -- the layer a question names ------------------------------------------------
+
+
+def test_a_rolling_window_names_the_layer_that_already_holds_it():
+ assert firms.layer_name("viirs", "24h") == "fires_viirs_24"
+ assert firms.layer_name("viirs_noaa20", "7d") == "fires_viirs_noaa20_7"
+
+
+def test_a_date_range_names_the_dated_layer_instead():
+ # FIRMS files the same detections under two names: one rolling, one dated
+ assert firms.layer_name("viirs", firms_dated := "dates") == "fires_viirs"
+ assert firms.layer_name("modis", firms_dated) == "fires_modis"
+
+
+def test_an_unknown_sensor_says_so_rather_than_building_a_url():
+ with pytest.raises(KeyError):
+ firms.layer_name("landsat", "24h")
+
+
+# -- the tile's square ---------------------------------------------------------
+
+
+def test_the_whole_world_is_one_tile_at_zoom_zero():
+ left, bottom, right, top = firms.tile_bounds(0, 0, 0)
+ assert (round(left), round(bottom)) == (-20037508, -20037508)
+ assert (round(right), round(top)) == (20037508, 20037508)
+
+
+def test_row_zero_is_the_north_because_the_two_grids_count_the_other_way():
+ _, _, _, top = firms.tile_bounds(1, 0, 0)
+ _, bottom, _, _ = firms.tile_bounds(1, 0, 1)
+ assert round(top) == 20037508 # north in the projection, row 0 in the grid
+ assert round(bottom) == -20037508
+
+
+def test_the_four_tiles_of_a_level_tile_the_level_above():
+ whole = firms.tile_bounds(0, 0, 0)
+ parts = [firms.tile_bounds(1, x, y) for x in (0, 1) for y in (0, 1)]
+ assert min(p[0] for p in parts) == pytest.approx(whole[0])
+ assert max(p[2] for p in parts) == pytest.approx(whole[2])
+ assert min(p[1] for p in parts) == pytest.approx(whole[1])
+ assert max(p[3] for p in parts) == pytest.approx(whole[3])
+
+
+# -- the request ---------------------------------------------------------------
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+def test_the_key_goes_in_the_path_where_firms_wants_it():
+ url = firms.tile_url("KEY123", z=3, x=4, y=2)
+ assert url.startswith(f"{firms.WMS_BASE}/KEY123/?")
+ # …and nowhere else: a key repeated in the query is a key logged twice
+ assert "KEY123" not in urlparse(url).query
+
+
+def test_a_tile_is_a_getmap_in_the_projection_the_grid_is_already_in():
+ query = _query(firms.tile_url("K", z=5, x=8, y=11))
+ assert query["REQUEST"] == ["GetMap"]
+ assert query["CRS"] == ["EPSG:3857"]
+ assert query["TRANSPARENT"] == ["TRUE"]
+ assert query["WIDTH"] == ["256"] and query["HEIGHT"] == ["256"]
+ # six decimals in the URL is a micrometre on the ground, and keeps the
+ # address readable
+ corners = [float(n) for n in query["BBOX"][0].split(",")]
+ assert corners == pytest.approx(firms.tile_bounds(5, 8, 11))
+
+
+def test_a_rolling_window_carries_no_dates():
+ # they would be two more things to keep in step with a layer that already
+ # means "the last 24 hours"
+ assert "TIME" not in _query(firms.tile_url("K", window="24h", z=1, x=0, y=0))
+
+
+def test_a_dated_window_carries_the_range_it_was_asked_for():
+ query = _query(
+ firms.tile_url("K", window="dates", first="2026-08-01", last="2026-08-09", z=1, x=0, y=0)
+ )
+ assert query["TIME"] == ["2026-08-01/2026-08-09"]
+ assert query["LAYERS"] == ["fires_viirs"]
+
+
+def test_one_day_is_a_range_of_itself():
+ query = _query(firms.tile_url("K", window="dates", first="2026-08-01", z=1, x=0, y=0))
+ assert query["TIME"] == ["2026-08-01/2026-08-01"]
+
+
+# -- what the service will not answer ------------------------------------------
+
+
+def test_a_backwards_range_is_read_the_way_it_was_meant():
+ assert firms.window_range("2026-08-09", "2026-08-01") == firms.window_range(
+ "2026-08-01", "2026-08-09"
+ )
+
+
+def test_a_range_longer_than_the_service_allows_is_refused_here():
+ with pytest.raises(ValueError, match="at most 31 days"):
+ firms.window_range("2026-01-01", "2026-03-01")
+
+
+def test_the_longest_allowed_range_is_allowed():
+ start, end = firms.window_range("2026-01-01", "2026-01-31")
+ assert (end - start).days == firms.MAX_RANGE_DAYS - 1
+
+
[email protected]("bad", ["", "2026-8-1", "01/08/2026", "yesterday", "2026-08-01T10:00"])
+def test_only_one_date_form_reaches_a_public_service(bad):
+ with pytest.raises(ValueError):
+ firms.parse_day(bad)
+
+
+def test_the_zoom_guard_stops_where_a_mark_stops_meaning_one_detection():
+ assert not firms.too_deep(firms.MAX_ZOOM)
+ assert firms.too_deep(firms.MAX_ZOOM + 1)
+
+
+def test_a_refusal_is_read_back_as_the_sentence_it_contains():
+ body = (
+ '<?xml version="1.0"?><ServiceExceptionReport>'
+ '<ServiceException code="InvalidKey">Invalid MAP_KEY</ServiceException>'
+ "</ServiceExceptionReport>"
+ )
+ assert firms.service_error(body) == "Invalid MAP_KEY"
+
+
+# -- the route -----------------------------------------------------------------
+
+
+def test_the_layer_says_it_needs_a_key_before_anything_is_drawn(client):
+ answer = client.get("/api/firms/sensors").json()
+ assert answer["keyed"] is False
+ # …and the catalogue is there either way, so the panel can be built
+ assert {s["id"] for s in answer["sensors"]} >= {"viirs", "modis"}
+ assert answer["max_zoom"] == firms.MAX_ZOOM
+
+
+def test_a_tile_without_a_key_is_a_404_rather_than_a_request(client):
+ assert client.get("/api/firms/tiles/3/4/2").status_code == 404
+
+
+def test_a_saved_key_lights_the_layer_up(client):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ assert client.get("/api/firms/sensors").json()["keyed"] is True
+
+
+def test_a_key_switched_off_withholds_the_layer_without_deleting_it(client):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ client.put("/api/settings/prefs", json={"providers_enabled": {"firms": False}})
+ assert client.get("/api/firms/sensors").json()["keyed"] is False
+ assert client.get("/api/firms/tiles/3/4/2").status_code == 404
+ # the key is still there, which is the whole difference from deleting it
+ assert config.load_settings()["api_keys"]["firms"] == "KEY123"
+
+
+def test_a_tile_deeper_than_the_layer_draws_is_refused_with_a_reason(client):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ answer = client.get(f"/api/firms/tiles/{firms.MAX_ZOOM + 1}/0/0")
+ assert answer.status_code == 422
+ assert str(firms.MAX_ZOOM) in answer.json()["detail"]
+
+
+def test_a_date_the_service_would_refuse_never_reaches_it(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+
+ def never(*args, **kwargs):
+ raise AssertionError("asked FIRMS for a range it refuses")
+
+ monkeypatch.setattr(httpx, "get", never)
+ answer = client.get(
+ "/api/firms/tiles/3/4/2",
+ params={"window": "dates", "first": "2026-01-01", "last": "2026-06-01"},
+ )
+ assert answer.status_code == 422
+
+
+def test_a_tile_comes_back_as_a_png_with_the_key_left_behind(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ asked = {}
+
+ def fake_get(url, **kwargs):
+ asked["url"] = url
+ return httpx.Response(
+ 200,
+ content=b"\x89PNG\r\n\x1a\n",
+ headers={"content-type": "image/png"},
+ request=httpx.Request("GET", url),
+ )
+
+ monkeypatch.setattr(httpx, "get", fake_get)
+ answer = client.get("/api/firms/tiles/3/4/2", params={"sensor": "modis", "window": "48h"})
+ assert answer.status_code == 200
+ assert answer.headers["content-type"] == "image/png"
+ assert "fires_modis_48" in asked["url"]
+ # the browser asked our own address; the credential stayed on this side
+ assert "KEY123" not in str(answer.request.url)
+
+
+#: Stands in for the 28 KB picture FIRMS really draws. What matters is the
+#: digest, so the tests point the module at this one rather than shipping a
+#: refusal placard into the repo.
+PLACARD = b"placard"
+
+
+def test_the_refusal_picture_is_recognised_for_what_it_is(monkeypatch):
+ monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
+ assert firms.is_placard(PLACARD)
+ assert not firms.is_placard(b"\x89PNG\r\n\x1a\n a real tile")
+
+
+def test_a_placard_is_refused_rather_than_tiled_over_the_ground(client, monkeypatch):
+ # FIRMS answers a key it rejects with 200 and a picture saying so, so
+ # nothing in the HTTP answer says anything is wrong
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
+ monkeypatch.setattr(
+ httpx,
+ "get",
+ lambda url, **kw: httpx.Response(
+ 200,
+ content=PLACARD,
+ headers={"content-type": "image/png"},
+ request=httpx.Request("GET", url),
+ ),
+ )
+ answer = client.get("/api/firms/tiles/3/4/2")
+ assert answer.status_code == 502
+ assert "key" in answer.json()["detail"]
+
+
+def test_that_refusal_benches_the_layer_the_way_a_dead_basemap_key_is_benched(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ monkeypatch.setattr(firms, "PLACARD_SHA256", hashlib.sha256(PLACARD).hexdigest())
+ monkeypatch.setattr(
+ httpx,
+ "get",
+ lambda url, **kw: httpx.Response(
+ 200,
+ content=PLACARD,
+ headers={"content-type": "image/png"},
+ request=httpx.Request("GET", url),
+ ),
+ )
+ client.get("/api/firms/tiles/3/4/2")
+ # the Layers row goes back to "add a key", with the reason, instead of
+ # asking for a thousand more placards
+ assert client.get("/api/firms/sensors").json()["keyed"] is False
+ assert config.load_settings()["provider_status"]["firms"]["ok"] is False
+
+
+def test_the_key_test_asks_the_service_about_the_key_rather_than_using_it(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "x"})
+ asked = {}
+
+ def fake_get(url, **kwargs):
+ asked["url"] = url
+ asked["params"] = kwargs.get("params")
+ return httpx.Response(
+ 403,
+ content=b"MAP_KEY is invalid or your have exceeded your transaction/time limit.",
+ headers={"content-type": "text/html"},
+ request=httpx.Request("GET", url),
+ )
+
+ monkeypatch.setattr(httpx, "get", fake_get)
+ answer = client.post("/api/settings/keys/firms/test").json()
+ assert answer["ok"] is False
+ assert "invalid" in answer["detail"]
+ # the endpoint that answers the question, not a GetMap that answers a
+ # picture either way
+ assert asked["url"] == firms.STATUS_URL
+ assert asked["params"] == {"MAP_KEY": "x"}
+
+
+def test_a_key_the_service_accepts_passes(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "KEY123"})
+ monkeypatch.setattr(
+ httpx,
+ "get",
+ lambda url, **kw: httpx.Response(
+ 200, content=b"current_transactions: 12", request=httpx.Request("GET", url)
+ ),
+ )
+ assert client.post("/api/settings/keys/firms/test").json()["ok"] is True
+
+
+def test_a_refusal_is_repeated_in_the_service_s_own_words():
+ said = firms.status_error("<html><body>MAP_KEY is invalid or your have exceeded</body></html>")
+ assert said.startswith("MAP_KEY is invalid")
+ assert "<" not in said
+ assert firms.status_error("") == "FIRMS would not accept this key"
+
+
+def test_a_service_exception_is_reported_with_what_it_said(client, monkeypatch):
+ client.put("/api/settings/keys", json={"firms": "BAD"})
+
+ def fake_get(url, **kwargs):
+ return httpx.Response(
+ 200,
+ content=b"<ServiceExceptionReport><ServiceException>Invalid MAP_KEY"
+ b"</ServiceException></ServiceExceptionReport>",
+ headers={"content-type": "text/xml"},
+ request=httpx.Request("GET", url),
+ )
+
+ monkeypatch.setattr(httpx, "get", fake_get)
+ answer = client.get("/api/firms/tiles/3/4/2")
+ assert answer.status_code == 502
+ assert "Invalid MAP_KEY" in answer.json()["detail"]
diff --git a/tests/test_ingest_api.py b/tests/test_ingest_api.py
index 851027a..3ca9439 100644
--- a/tests/test_ingest_api.py
+++ b/tests/test_ingest_api.py
@@ -444,3 +444,52 @@ def test_reading_back_reaches_attachments_and_nothing_else(client):
"/api/ingest/file", params={"case_id": cid, "path": "proofs/nothing.png"}, headers=headers
)
assert missing.status_code == 404
+
+
+# -- scale bar and north arrow -------------------------------------------------
+
+
+def test_the_popups_tick_draws_the_bar_and_leaves_the_needle_to_a_stated_heading(client):
+ """Google Maps writes no rotation into its URL, so a capture off it gets the
+ bar and no arrow — the popup says to type a bearing for that, and typing one
+ is the analyst stating which way the map was turned."""
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Ingest"}).json()["id"]
+
+ off = _post(client, token=token, case_id=cid).json()
+ assert off["marks"] is None
+
+ no_heading = _post(client, token=token, case_id=cid, scale_north="true").json()
+ assert no_heading["marks"]["scale"].endswith((" m", " km"))
+ assert no_heading["marks"]["north"] is None
+
+ stated = _post(
+ client, token=token, case_id=cid, scale_north="true", bearing="42"
+ ).json()
+ assert stated["marks"]["north"] == 42.0
+
+
+def test_a_grab_off_a_dense_screen_states_its_own_ground(client):
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Ingest"}).json()["id"]
+ one = _post(client, token=token, case_id=cid, scale_north="true", device_scale="1")
+ two = _post(client, token=token, case_id=cid, scale_north="true", device_scale="2")
+ assert one.json()["marks"]["scale"] != two.json()["marks"]["scale"]
+
+
+def test_a_capture_with_no_zoom_in_its_url_gets_no_bar(client):
+ """The bar is arithmetic on a zoom. Without one there is nothing to state,
+ and a capture still files — the position is fixable in the sidebar."""
+ token = _token(client)
+ cid = client.post("/api/cases", json={"name": "Ingest"}).json()["id"]
+ body = _post(
+ client,
+ token=token,
+ case_id=cid,
+ url="https://www.openstreetmap.org/",
+ lat=None,
+ lon=None,
+ zoom=None,
+ scale_north="true",
+ ).json()
+ assert body["marks"] is None
diff --git a/tests/test_map_link_writes.py b/tests/test_map_link_writes.py
new file mode 100644
index 0000000..2f6da83
--- /dev/null
+++ b/tests/test_map_link_writes.py
@@ -0,0 +1,63 @@
+"""A linked view, written into a map site's address, read back by the app.
+
+The extension's map tools follow another map by writing its camera into the
+site's own URL (``extension/maplink.js``). The tools then read their scale from
+that same URL through ``parse_map_url``, so the two have to agree: a writer that
+puts a level where the parser reads metres, or a fraction where the site loads a
+whole level, draws every mark at the wrong size until the map is touched.
+
+``tests/fixtures/map-link-writes.json`` holds each write once. The frontend
+suite asserts the writer still produces those URLs
+(``frontend/src/lib/extensionMapLink.test.js``); this one asserts the app's
+parser reads each of them as the view that was meant, so there is still only
+one parser.
+"""
+
+import json
+from pathlib import Path
+
+import pytest
+
+from azimut.engine.mapsites import parse_map_url
+
+WRITES = json.loads(
+ (Path(__file__).parent / "fixtures" / "map-link-writes.json").read_text(encoding="utf-8")
+)["writes"]
+
+
+def _id(case):
+ return f"{case['site']}: {case['name']}"
+
+
[email protected]("case", WRITES, ids=_id)
+def test_the_page_written_from_is_the_site_named(case):
+ assert parse_map_url(case["from"], case["height"])["site"] == case["site"]
+
+
[email protected]("case", WRITES, ids=_id)
+def test_the_written_address_reads_back_as_the_view(case):
+ parsed = parse_map_url(case["url"], case["height"])
+ lands = case["lands"]
+ assert parsed["site"] == case["site"]
+ assert parsed["lat"] == pytest.approx(lands["lat"], abs=1e-5)
+ assert parsed["lon"] == pytest.approx(lands["lon"], abs=1e-5)
+ if lands["zoom"] is None:
+ # a view Earth never placed: no scale until a gesture places it
+ assert parsed["zoom"] is None
+ else:
+ assert parsed["zoom"] == pytest.approx(lands["zoom"], abs=0.01)
+
+
+def test_every_site_the_writer_knows_is_covered():
+ sites = {case["site"] for case in WRITES}
+ assert sites == {
+ "google-maps",
+ "google-earth",
+ "bing-maps",
+ "yandex-maps",
+ "openstreetmap",
+ "apple-maps",
+ "zoom-earth",
+ "satellites-pro",
+ "copernicus-browser",
+ }
diff --git a/tests/test_mapsites.py b/tests/test_mapsites.py
index 36a9ece..25fba77 100644
--- a/tests/test_mapsites.py
+++ b/tests/test_mapsites.py
@@ -8,11 +8,12 @@ doesn't), anything else returns None, and nothing ever raises.
"""
import json
+import math
from pathlib import Path
import pytest
-from azimut.engine.mapsites import parse_map_url
+from azimut.engine.mapsites import _mercator_y, parse_map_url
_RECORDED = json.loads(
(Path(__file__).parent / "fixtures" / "map-sites.json").read_text(encoding="utf-8")
@@ -22,13 +23,24 @@ ROUNDING = _RECORDED["rounding"]
LAT, LON, Z = 45.197652, 11.777344, 6
+#: How closely the parse has to predict how far Earth's picture moved. Earth's
+#: own drawing agrees with its formula to about a thousandth at a 35° field of
+#: view, and a few thousandths at 60°, which nobody opens by hand.
+EARTH_SCALE_TOLERANCE = 0.004
+
+#: What Earth writes after ``/data=``: its 2D map, as an analyst's own URL had
+#: it, and a view after pressing Earth's "3D" button.
+EARTH_2D = "CgRCAggCMikKJwolCiExa01obVdjV2t6UmJfTFhSbDFjQ3JPZEJla1p4TWJGVksgAToDCgEwQgIIAEoICI7Vld4EEAE"
+EARTH_3D = "CgRCAggBKAJCAggASg0I____________ARAA"
+
# Mirrors frontend/src/lib/maplinks.js exactly: whatever Azimut can send the
# 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},{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),
+ # a link has no ground in it, so Earth's scale waits for the map to move
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,2733274d,35y,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),
@@ -184,8 +196,7 @@ def test_refusals_and_malformed_input():
# …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
+ # Earth's 2D map is a map, and pitched (its 3D button) 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
@@ -217,35 +228,125 @@ def test_satellite_is_still_a_straight_down_map():
assert parsed["geometry"] is True
-def test_a_level_free_camera_is_a_map_it_can_be_measured_on():
+def test_earths_2d_map_is_web_mercator_with_its_scale_in_the_url():
"""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's 2D map was registered screenshot against screenshot
+ (``tests/fixtures/earth-scale.json``): Web Mercator, drawn about the middle
+ of the window, ``2·d·tan(y/2)`` metres from top to bottom. So it is a map
+ like any other, with a projection and a scale read out of its URL.
+
+ Maps in Earth mode keeps its flattening and states no scale: Maps rewrites a
+ level ``a`` camera into ``,3231m`` as soon as it lands, so the view waits
+ for that instead.
"""
- earth = parse_map_url(f"https://earth.google.com/web/@{LAT},{LON},146a,666d,35y,0h,0t,0r")
+ earth = parse_map_url(
+ f"https://earth.google.com/web/@{LAT},{LON},146.5a,666.25d,35y,0h,0t,0r", height_px=1000
+ )
assert earth["view_kind"] == "map"
- assert earth["geometry"] is False # no projection to name
- assert earth["scale_source"] is None
+ assert earth["projection"] == "webmercator"
+ assert earth["geometry"] is True
+ assert earth["scale_source"] == "distance"
+ assert earth["far"] is False
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["scale_source"] is None
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"
+def test_only_earths_3d_camera_turns_into_a_globe_far_out():
+ """Earth's 2D map stays a flat Mercator however far out it goes (all of
+ Europe on screen, and 400 km out measured). Its 3D mode is a perspective
+ camera on a sphere, and past ``LEVEL_CEILING_M`` that is a globe. The address
+ bar says which one it is in its ``data=`` blob."""
+ far = f"https://earth.google.com/web/@{LAT},{LON},-0a,202330.09623202d,35y,0h,0t,0r"
+ flat = parse_map_url(f"{far}/data={EARTH_2D}?authuser=0", height_px=934)
+ assert (flat["view_kind"], flat["geometry"], flat["far"]) == ("map", True, False)
+ assert flat["scale_source"] == "distance"
+ globe = parse_map_url(f"{far}/data={EARTH_3D}", height_px=934)
+ assert (globe["view_kind"], globe["geometry"], globe["far"]) == ("globe", False, True)
+ # in close, the 3D camera is still a map
+ near = f"https://earth.google.com/web/@{LAT},{LON},146.5a,666.25d,35y,0h,0t,0r/data={EARTH_3D}"
+ assert parse_map_url(near)["view_kind"] == "map"
+ # a bare link opens the 2D map, and a blob nobody can read is taken as 3D,
+ # whose rules are the stricter ones
+ assert parse_map_url(far)["view_kind"] == "map"
+ assert parse_map_url(f"{far}/data=AAAA")["view_kind"] == "globe"
+
+
+def test_earth_states_no_scale_for_a_camera_it_has_not_placed():
+ """``d`` is a distance to the ground only once Earth has put the camera
+ there, which it does by writing the ground's height into ``a``."""
+
+ def scale(camera: str) -> str | None:
+ url = f"https://earth.google.com/web/@{LAT},{LON},{camera}"
+ return parse_map_url(url, height_px=1000)["scale_source"]
+
+ # Earth's own writing, over land and over the sea
+ assert scale("198.8634048a,2196.68868628d,35y,0h,0t,0r") == "distance"
+ assert scale("-0a,202330.09623202d,35y,0h,0t,0r") == "distance"
+ # a link, written as 0a with a whole d: over 200 m of ground it is drawn 7%
+ # nearer than it says, so it waits for the map to move
+ assert scale("0a,3000d,35y,0h,0t,0r") is None
+ # closer than Earth's map lets a camera come: loading a link, Earth once
+ # wrote this for a camera 1528 m up, where a was not the ground at all
+ assert scale("1518.44008742a,10.0137594d,35y,0h,0t,0r") is None
+ # a height no ground has, and a field of view that is missing or not one
+ assert scale("-7546.56236661a,8346.46045906d,35y,0h,0t,0r") is None
+ assert scale("198.86a,2196.69d,0y,0h,0t,0r") is None
+ assert scale("198.86a,2196.69d,0h,0t,0r") is None
+
+
+def _earth_cases() -> list[dict]:
+ path = Path(__file__).parent / "fixtures" / "earth-scale.json"
+ return json.loads(path.read_text(encoding="utf-8"))["cases"]
+
+
+def test_earths_scale_is_what_its_screenshots_measured():
+ """Every case in ``tests/fixtures/earth-scale.json``, predicted from its URL.
+
+ Each one is a camera Earth placed, opened again a known step east and north,
+ and the screenshots registered to a hundredth of a pixel. The parse of the
+ base URL, through Web Mercator, has to say how far the picture moved — at
+ three window shapes, two fields of view, three latitudes, over mountains and
+ 400 km out.
+ """
+ cases = _earth_cases()
+ assert len(cases) >= 6
+ for case in cases:
+ parsed = parse_map_url(case["base"], height_px=case["window"]["h"])
+ assert parsed["scale_source"] == "distance", case["id"]
+ world = 256 * 2 ** parsed["zoom"]
+ east = -case["east"]["d_lon"] / 360 * world
+ step = case["north"]["d_lat"]
+ north = (_mercator_y(parsed["lat"]) - _mercator_y(parsed["lat"] + step)) / 256 * world
+ tolerance = EARTH_SCALE_TOLERANCE
+ assert case["east"]["moved_px"] == pytest.approx(east, rel=tolerance), case["id"]
+ assert case["north"]["moved_px"] == pytest.approx(north, rel=tolerance), case["id"]
+ assert abs(case["east"]["across_px"]) < 0.5, case["id"]
+ assert abs(case["north"]["across_px"]) < 0.5, case["id"]
+
+
+def test_earth_draws_its_camera_at_the_middle_of_the_window():
+ """No table entry for Earth, and this is why: halving the distance draws the
+ ground twice as big about the camera's own pixel, and in every window that
+ pixel was the middle."""
+ for case in _earth_cases():
+ offset = case["camera_offset_px"]
+ assert abs(offset["x"]) < 1.5 and abs(offset["y"]) < 1.5, case["id"]
+
+
+def test_a_level_3d_camera_far_enough_out_is_a_globe():
+ """Level is not enough on its own for a 3D camera: past ``LEVEL_CEILING_M``
+ the ground under it 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/data={EARTH_3D}"
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"
+ # …and a 3D camera whose height the URL never states is not assumed to be low
+ bare = f"https://earth.google.com/web/@{LAT},{LON}/data={EARTH_3D}"
+ assert parse_map_url(bare)["view_kind"] == "globe"
def test_a_pitched_camera_is_not_a_map_however_it_is_written():
@@ -331,7 +432,17 @@ def test_a_stated_size_becomes_a_zoom_once_the_window_height_is_known():
)
assert satellite["scale_source"] == "height_m"
assert satellite["zoom"] == pytest.approx(15, abs=0.01)
- assert satellite["camera_kind"] == "height_m"
+
+ # Earth's view covers the same ground in a shorter window, so it is further out
+ earth = (
+ "https://earth.google.com/web/@47.38914743,2.35481038,"
+ "198.8634048a,2196.68868628d,35y,0h,0t,0r"
+ )
+ tall = parse_map_url(earth, height_px=1000)
+ assert tall["scale_source"] == "distance"
+ assert tall["zoom"] == pytest.approx(16.2234, abs=0.001) # registered: 16.22341
+ shorter = parse_map_url(earth, height_px=760)["zoom"]
+ assert shorter == pytest.approx(tall["zoom"] + math.log2(0.76))
apple = parse_map_url(
"https://maps.apple.com/frame?map=satellite"
@@ -355,40 +466,13 @@ 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
+ earth = parse_map_url("https://earth.google.com/web/@47.38,2.35,198.86a,2196.69d,35y,0h,0t,0r")
+ assert earth["zoom"] is None and earth["scale_source"] is None
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)
+ assert parse_map_url(url)["scale_source"] in {"zoom", "height_m", "span", "distance", None}
def test_view_kind_is_unclassified_rather_than_guessed():
@@ -450,8 +534,8 @@ def test_copernicus_2d_map_is_leaflet_and_drawable():
(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"),
+ # Earth's 3D camera far enough out to be a globe
+ (f"https://earth.google.com/web/@{LAT},{LON},0a,900000d,35y,0h,0t,0r/data={EARTH_3D}", "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"),
@@ -470,12 +554,16 @@ def test_yandex_is_elliptical_and_says_so():
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.
+ """A *flat map drawn far out* is warned about, not refused.
- 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.
+ A site becoming a globe on the way out does not change its URL shape, so the
+ zoom is the only warning there is — and out there 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.
+
+ The other globe is refused outright — see the test below, and the two are
+ not the same thing.
"""
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")
@@ -483,8 +571,10 @@ def test_the_globe_floor_is_a_warning_rather_than_a_floor():
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")
+ # Earth's own 3D 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/data={EARTH_3D}"
+ )
assert earth["view_kind"] == "globe" and earth["far"] is True
# OpenStreetMap has no globe to fall into, so it has no floor
@@ -493,12 +583,35 @@ def test_the_globe_floor_is_a_warning_rather_than_a_floor():
assert (flat["geometry"], flat["far"]) == (True, False)
+def test_a_globe_camera_is_refused_where_a_flat_map_drawn_far_out_is_not():
+ """The other globe: a perspective camera on a sphere, which is not a map.
+
+ Google's Earth mode is the case that separates the two, because it is the
+ one view that is a globe camera *and* has a named flattening. Mercator is
+ not approximately right out there, it is wrong — so ``geometry`` declines
+ even though the projection is known, and the extension says to zoom in
+ rather than dimming a drawing nobody can judge (`maptools.js`, ``REFUSALS``).
+ """
+ globe = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},900000a,35y,0h,0t,0r")
+ assert globe["view_kind"] == "globe"
+ assert globe["projection"] == "webmercator" # known, and still not enough
+ assert globe["geometry"] is False
+ # `far` stays true out there, because it has a second job: it is what stops
+ # the extension measuring a site's layout off a view that far out
+ assert globe["far"] is True
+
+ # …and the same camera in close is a map, which is the whole point of
+ # measuring the height rather than refusing the site
+ near = parse_map_url(f"https://www.google.com/maps/@{LAT},{LON},1000a,35y,0h,0t,0r")
+ assert (near["view_kind"], near["geometry"], near["far"]) == ("map", 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",
+ f"https://earth.google.com/web/@{LAT},{LON},0a,600d,35y,20h,60t,0r",
):
parsed = parse_map_url(url)
assert parsed["geometry"] is False
@@ -554,8 +667,8 @@ def test_every_site_this_parser_knows_has_been_driven_in_a_browser():
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"}
+ assert known == recorded
+ assert {site for _url, site, _zoom in OPEN_IN_LINKS} <= known
def test_the_recordings_cover_more_than_one_window():
@@ -654,3 +767,73 @@ def test_the_pitch_is_reported_so_a_refusal_can_name_it():
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
+
+
+#: Sites the extension starts unplaced on, and why each is left out of
+#: ``_CAMERA_CENTRE`` rather than measured into it.
+UNHINTED_ON_PURPOSE = {
+ "apple-maps": "its sidebar folds away below a width the URL never states, so"
+ " its offset is 67 px in a wide window and nothing in a narrow one",
+}
+
+
+def test_the_starting_offset_matches_what_the_browser_measured():
+ """The offset the extension starts drawing from, against the recording.
+
+ ``_CAMERA_CENTRE`` is the one place this parser states a number about pixels
+ rather than about a URL, and it exists because the alternative — starting at
+ the middle of the window — is a number too, and the wrong one on four of
+ these sites. So it is held to the recording the same way everything else
+ here is: every entry within a pixel and a half of where a browser drew the
+ camera, in every window the site was recorded in.
+
+ The other half is the drift gate. A site with no entry starts at the middle
+ of the window, which is a claim that the middle is right — so a recording
+ that says otherwise has to be either measured into the table or named in
+ ``UNHINTED_ON_PURPOSE`` with the reason it cannot be.
+ """
+ from azimut.engine.mapsites import _CAMERA_CENTRE, _centre_hint
+
+ for recording in RECORDINGS:
+ offset = (
+ recording["centre"]["x"] - recording["window"]["w"] / 2,
+ recording["centre"]["y"] - recording["window"]["h"] / 2,
+ )
+ hint = _centre_hint(recording["site"])
+ if hint:
+ assert hint["x"] == pytest.approx(offset[0], abs=1.5), recording["label"]
+ assert hint["y"] == pytest.approx(offset[1], abs=1.5), recording["label"]
+ # and a sideways offset is never claimed below a window it has been
+ # measured in, because that is where a side panel folds away
+ if hint["x"]:
+ assert hint["min_w"] <= recording["window"]["w"], recording["label"]
+ assert hint["min_w"] >= min(
+ r["window"]["w"] for r in RECORDINGS if r["site"] == recording["site"]
+ ), recording["label"]
+ # under a couple of pixels is the solve's own noise, not a layout
+ elif max(abs(o) for o in offset) >= 4:
+ assert recording["site"] in UNHINTED_ON_PURPOSE, (
+ f"{recording['label']} draws its camera {offset} from the middle of the"
+ " window and nothing says so: add it to _CAMERA_CENTRE or say why not"
+ )
+ # and nothing in the table that no browser was ever driven through
+ assert set(_CAMERA_CENTRE) <= {r["site"] for r in RECORDINGS}
+ assert set(UNHINTED_ON_PURPOSE) <= {r["site"] for r in RECORDINGS}
+ assert not set(UNHINTED_ON_PURPOSE) & set(_CAMERA_CENTRE)
+
+
+def test_the_starting_offset_reaches_the_extension_with_the_view():
+ """It travels the one channel the extension reads: the parse of its URL."""
+ hinted = parse_map_url("https://www.bing.com/maps?cp=47.388462~2.352785&lvl=15")
+ # a header, claimed at any width: its height does not change with one
+ assert hinted["centre_hint"] == {"x": 0.0, "y": 40.5, "min_w": 0}
+ # and a site that draws dead centre says nothing rather than saying zero
+ assert parse_map_url("https://www.google.com/maps/@47.388462,2.352785,15z")["centre_hint"] is None
+ # a side panel says how narrow a window it has been seen in, because that is
+ # the thing that folds away (`_CAMERA_CENTRE`)
+ panelled = parse_map_url("https://yandex.com/maps/?ll=2.352785%2C47.388462&z=15")
+ assert panelled["centre_hint"] == {"x": 210.0, "y": 10.0, "min_w": 1200}
+ narrowest = {
+ r["window"]["w"] for r in RECORDINGS if r["site"] == "yandex-maps"
+ }
+ assert panelled["centre_hint"]["min_w"] == min(narrowest)
diff --git a/tests/test_place_precision.py b/tests/test_place_precision.py
index 46595e3..878ab46 100644
--- a/tests/test_place_precision.py
+++ b/tests/test_place_precision.py
@@ -32,6 +32,11 @@ def _patch(client, cid, eid, attrs):
return client.patch(f"/api/cases/{cid}/entities/{eid}", json={"attrs": attrs})
+#: A ring around the point `_place` saves, which is where a place's own shape has to
+#: be: lon first, closed, and the pin inside it rather than on a corner.
+AROUND = [[14.54, 53.43], [14.56, 53.43], [14.56, 53.45], [14.54, 53.45], [14.54, 53.43]]
+
+
# -- nothing is required ------------------------------------------------------
@@ -140,9 +145,8 @@ def test_the_ladder_is_not_derived_from_plus_code_lengths():
def test_a_footprint_holds_a_polygon_when_a_circle_is_the_wrong_shape(client):
cid = _new_case(client, "Footprint place")
- ring = [[14.55, 53.44], [14.56, 53.44], [14.56, 53.45], [14.55, 53.44]]
- res = _place(client, cid, footprint={"type": "Polygon", "coordinates": [ring]})
+ res = _place(client, cid, footprint={"type": "Polygon", "coordinates": [AROUND]})
assert res.status_code == 200, res.text
assert res.json()["attrs"]["footprint"]["type"] == "Polygon"
@@ -192,6 +196,76 @@ def test_a_footprint_is_bounded_in_size_and_depth(client):
assert _place(client, cid, footprint=deep).status_code == 400
+def test_a_footprint_must_contain_the_point_it_belongs_to(client):
+ """A shape traced beside its pin describes somewhere else. The map let it happen:
+ the polygon drew where it was clicked and the pin stayed where it was, and nothing
+ said the two disagreed."""
+ cid = _new_case(client, "Shape elsewhere")
+ elsewhere = [[14.60, 53.50], [14.62, 53.50], [14.62, 53.52], [14.60, 53.50]]
+
+ res = _place(client, cid, footprint={"type": "Polygon", "coordinates": [elsewhere]})
+
+ assert res.status_code == 400
+ assert "contain" in res.json()["detail"]
+
+
+def test_a_multipolygon_counts_as_containing_the_point_in_any_of_its_parts(client):
+ """Two quays are one location, and the pin sits on one of them."""
+ cid = _new_case(client, "Two parts")
+ far = [[14.60, 53.50], [14.62, 53.50], [14.62, 53.52], [14.60, 53.50]]
+
+ res = _place(
+ client, cid, footprint={"type": "MultiPolygon", "coordinates": [[far], [AROUND]]}
+ )
+
+ assert res.status_code == 200, res.text
+
+
+def test_a_place_with_no_point_of_its_own_still_takes_a_footprint(client):
+ """Nothing to contradict: a record promoted from a sheet can hold the shape
+ without holding the pair, and refusing it would lose the only geometry it has."""
+ cid = _new_case(client, "Shape only")
+
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={
+ "type": "place",
+ "label": "Quay 4",
+ "attrs": {"footprint": {"type": "Polygon", "coordinates": [AROUND]}},
+ },
+ )
+
+ assert res.status_code == 200, res.text
+
+
+def test_a_place_states_its_precision_once(client):
+ """A radius and a footprint answer the same question in two forms, and the map
+ draws one of them — so a radius typed over a traced shape used to vanish from the
+ map without a word. Writing one asks for the other to be cleared with it."""
+ cid = _new_case(client, "Both forms")
+ eid = _place(client, cid, radius_m=500).json()["id"]
+ shape = {"type": "Polygon", "coordinates": [AROUND]}
+
+ assert _patch(client, cid, eid, {"footprint": shape}).status_code == 400
+ assert _patch(client, cid, eid, {"footprint": shape, "radius_m": None}).status_code == 200
+ # and the same the other way round, which is the half an analyst types by hand
+ assert _patch(client, cid, eid, {"radius_m": 500}).status_code == 400
+ assert _patch(client, cid, eid, {"radius_m": 500, "footprint": None}).status_code == 200
+
+
+def test_a_place_that_already_held_both_stays_editable(client):
+ """The rule is judged on the patch, not on the stored result: a point written
+ before it holds both, and its notes must not become unsavable because of that."""
+ cid = _new_case(client, "Written earlier")
+ eid = _place(client, cid, radius_m=500).json()["id"]
+ case = Case.open(cid)
+ case.update_entity(eid, {"attrs": {"footprint": {"type": "Polygon", "coordinates": [AROUND]}}})
+
+ assert _patch(client, cid, eid, {"method": "caption only"}).status_code == 200
+ # …and touching either form is still what resolves it
+ assert _patch(client, cid, eid, {"radius_m": 100}).status_code == 400
+
+
# -- what validation does and does not reach ----------------------------------
@@ -283,14 +357,13 @@ def test_a_footprint_reaches_the_index_whole(client):
"""A traced shape says more than the circle around it, so the overlay gets the
geometry itself and not a bounding radius computed here."""
cid = _new_case(client, "Index footprint")
- ring = [[14.55, 53.44], [14.56, 53.44], [14.56, 53.45], [14.55, 53.44]]
- eid = _place(client, cid, footprint={"type": "Polygon", "coordinates": [ring]}).json()["id"]
+ eid = _place(client, cid, footprint={"type": "Polygon", "coordinates": [AROUND]}).json()["id"]
row = next(
r for r in client.get(f"/api/cases/{cid}/satellite/index").json() if r["id"] == eid
)
- assert row["footprint"] == {"type": "Polygon", "coordinates": [ring]}
+ assert row["footprint"] == {"type": "Polygon", "coordinates": [AROUND]}
def test_a_place_with_no_precision_states_none_in_the_index(client):
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index eda9c3a..ea5b1a0 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -1108,3 +1108,88 @@ def test_index_counts_relations_and_marks_a_proposed_point(client):
assert rows["Checkpoint"]["relations"] == 0
assert rows["Checkpoint"]["status"] == "confirmed"
assert mine["id"] == rows["Checkpoint"]["id"]
+
+
+# -- scale bar and north arrow -------------------------------------------------
+
+
+def test_capture_burns_the_marks_only_when_the_menu_asked(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ frame = {"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 640, "height": 480}
+
+ plain = client.post(f"/api/cases/{cid}/satellite/capture", json=frame).json()
+ assert plain["marks"] is None
+
+ marked = client.post(
+ f"/api/cases/{cid}/satellite/capture", json={**frame, "scale_north": True}
+ ).json()
+ assert marked["marks"]["scale"].endswith(" m")
+ assert marked["marks"]["north"] == 0.0
+ # and it rides on the filed capture, not only on the answer
+ listed = client.get(f"/api/cases/{cid}/satellite").json()
+ assert [row["marks"] for row in listed].count(None) == 1
+
+
+def test_the_bar_is_read_in_the_analysts_units(client, monkeypatch):
+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ frame = {"lat": 48.8584, "lon": 2.2945, "zoom": 16, "width": 640, "height": 480,
+ "scale_north": True}
+
+ client.put("/api/settings/prefs", json={"units": "imperial"})
+ assert client.post(
+ f"/api/cases/{cid}/satellite/capture", json=frame
+ ).json()["marks"]["scale"].endswith(("ft", "mi"))
+
+ client.put("/api/settings/prefs", json={"units": "metric"})
+ assert client.post(
+ f"/api/cases/{cid}/satellite/capture", json=frame
+ ).json()["marks"]["scale"].endswith(("m", "km"))
+
+
+def test_a_screen_crop_takes_the_marks_and_a_pasted_shot_never_does(client):
+ """The bar states what a pixel is worth, and only a registered crop knows:
+ a pasted image's coordinates describe the map view when it was filed."""
+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ shot = {"lat": "48.8584", "lon": "2.2945", "zoom": "18", "provider": "google-js"}
+
+ framed = client.post(
+ f"/api/cases/{cid}/satellite/screenshot",
+ files={"image": ("shot.png", _png_bytes(), "image/png")},
+ data={**shot, "framed": "true", "scale_north": "true"},
+ ).json()
+ assert framed["marks"]["scale"]
+
+ pasted = client.post(
+ f"/api/cases/{cid}/satellite/screenshot",
+ files={"image": ("shot.png", _png_bytes(), "image/png")},
+ data={**shot, "framed": "false", "scale_north": "true"},
+ ).json()
+ assert pasted["marks"] is None
+
+
+def test_a_denser_screen_states_the_ground_it_really_covers(client):
+ """Two of the file's pixels per CSS pixel is half the ground per pixel, so
+ the same view on a 2× screen must not be told it spans twice as far."""
+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ shot = {"lat": "0", "lon": "0", "zoom": "14", "provider": "google-js",
+ "framed": "true", "scale_north": "true"}
+
+ def span(device_scale):
+ body = client.post(
+ f"/api/cases/{cid}/satellite/screenshot",
+ files={"image": ("shot.png", _png_bytes(w=900, h=600), "image/png")},
+ data={**shot, "device_scale": device_scale},
+ ).json()
+ return tiles.scale_span(
+ tiles.meters_per_pixel(0.0, 14) / float(device_scale), 900 * tiles.SCALE_MAX_SHARE
+ )[0], body["marks"]["scale"]
+
+ expected_1x, drawn_1x = span("1")
+ expected_2x, drawn_2x = span("2")
+ assert drawn_1x == expected_1x
+ assert drawn_2x == expected_2x
+ assert drawn_1x != drawn_2x
diff --git a/tests/test_tiles.py b/tests/test_tiles.py
index 85656fa..66e4554 100644
--- a/tests/test_tiles.py
+++ b/tests/test_tiles.py
@@ -750,3 +750,86 @@ def test_crop_still_leaves_the_poles_empty():
85.0, 0.0, 3, 700, 700, provider, fetch_tile=fake_fetch
)
assert prov["tiles_missing"] > 0
+
+
+# -- the scale bar and the north arrow -----------------------------------------
+
+
+def test_scale_span_climbs_the_round_ladder():
+ """Every span a bar may state is 1, 2 or 5 × a power of ten, in the unit."""
+ for mpp in (0.05, 0.3, 1.19, 9.55, 76.4, 300.0):
+ label, pixels = tiles.scale_span(mpp, 300)
+ number = float(label.split()[0])
+ decade = number / 10 ** math.floor(math.log10(number))
+ assert round(decade, 6) in (1.0, 2.0, 5.0), label
+ assert pixels <= 300
+
+
+def test_scale_span_reads_in_the_analysts_own_units():
+ metric, _ = tiles.scale_span(1.0, 300)
+ imperial, _ = tiles.scale_span(1.0, 300, "imperial")
+ assert metric.endswith(" m")
+ assert imperial.endswith(" ft")
+ # far enough out, each climbs to its own big unit
+ assert tiles.scale_span(50.0, 300)[0].endswith(" km")
+ assert tiles.scale_span(50.0, 300, "imperial")[0].endswith(" mi")
+
+
+def test_scale_span_refuses_what_it_cannot_back():
+ assert tiles.scale_span(0, 300) is None
+ assert tiles.scale_span(-1.0, 300) is None
+ assert tiles.scale_span(1.0, 0) is None
+ # a bar narrower than its own label is no bar
+ assert tiles.scale_span(1.0, 20) is None
+
+
+def test_burn_scale_north_draws_both_marks_and_says_what_it_drew():
+ img = Image.new("RGB", (900, 600), (60, 70, 60))
+ before = img.tobytes()
+ drawn = tiles.burn_scale_north(img, meters_per_pixel=1.19, bearing=0.0)
+ assert drawn == {"scale": "200 m", "north": 0.0}
+ assert img.tobytes() != before, "nothing was actually drawn"
+
+
+def test_burn_scale_north_draws_neither_mark_without_a_fact_behind_it():
+ """A capture off a map site that states no rotation gets the bar alone, and
+ one with no resolution at all is left exactly as it came in."""
+ img = Image.new("RGB", (900, 600), (60, 70, 60))
+ assert tiles.burn_scale_north(img, meters_per_pixel=1.19, bearing=None) == {
+ "scale": "200 m",
+ "north": None,
+ }
+ bare = Image.new("RGB", (900, 600), (60, 70, 60))
+ untouched = bare.tobytes()
+ assert tiles.burn_scale_north(bare, meters_per_pixel=None, bearing=None) is None
+ assert bare.tobytes() == untouched
+
+
+def test_fetch_crop_leaves_the_marks_off_unless_they_are_asked_for():
+ provider = tiles.BUILTIN_PROVIDERS[0]
+
+ def fake_fetch(client, url):
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+ plain, prov = tiles.fetch_crop(48.8584, 2.2945, 17, 640, 480, provider, fetch_tile=fake_fetch)
+ assert prov["marks"] is None
+
+ marked, prov = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 640, 480, provider, scale_north=True, fetch_tile=fake_fetch
+ )
+ assert prov["marks"]["scale"].endswith(" m")
+ assert prov["marks"]["north"] == 0.0
+ assert marked.tobytes() != plain.tobytes()
+
+
+def test_a_turned_crop_records_the_heading_its_needle_points_at():
+ provider = tiles.BUILTIN_PROVIDERS[0]
+
+ def fake_fetch(client, url):
+ return Image.new("RGB", (256, 256), (10, 120, 10))
+
+ _img, prov = tiles.fetch_crop(
+ 48.8584, 2.2945, 17, 640, 480, provider,
+ bearing=42.0, scale_north=True, fetch_tile=fake_fetch,
+ )
+ assert prov["marks"]["north"] == 42.0
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 1ba398d..80b1d49 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -139,7 +139,7 @@ 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 = "4c1ffa06f9e174599f5d85ae5142ed69e95fbbd7ef0e642df58372926f45bd45"
+EXTENSION_PAYLOAD = "ba3e0a83a1408aae09997f6893044fd8cc9188d5f41728c481b89094d67967b9"
# 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
diff --git a/tests/test_wayback.py b/tests/test_wayback.py
new file mode 100644
index 0000000..e068427
--- /dev/null
+++ b/tests/test_wayback.py
@@ -0,0 +1,444 @@
+"""Esri World Imagery Wayback: the release list, the walk, the metadata and the routes.
+
+Nothing here asks Esri anything. The three services are stubbed with the shapes
+they really answer with (read off the live services, 2026-09), so what is tested
+is how the app reads them.
+"""
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from azimut.engine import tiles, wayback
+
+META = "https://metadata.maptiles.arcgis.com/arcgis/rest/services/World_Imagery_Metadata_{}/MapServer"
+
+
[email protected](autouse=True)
+def fresh_session():
+ wayback.reset()
+ yield
+ wayback.reset()
+
+
+class Reply:
+ def __init__(self, payload=None, content=b"", status=200):
+ self.payload = payload
+ self.content = content
+ self.status_code = status
+
+ def raise_for_status(self):
+ if self.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ "refused", request=httpx.Request("GET", "https://x"), response=None
+ )
+
+ def json(self):
+ return self.payload
+
+
+def _config(*entries):
+ """`(release, date, metadata suffix)` → the JSON document Esri publishes."""
+ return {
+ str(number): {
+ "itemTitle": f"World Imagery (Wayback {date})",
+ "itemURL": f"https://wayback.maptiles.arcgis.com/.../tile/{number}/{{level}}/{{row}}/{{col}}",
+ "metadataLayerUrl": META.format(suffix),
+ }
+ for number, date, suffix in entries
+ }
+
+
+CONFIG = _config(
+ (10, "2014-02-20", "2014_r01"),
+ (64776, "2023-08-31", "2023_r08"),
+ (25982, "2023-06-13", "2023_r06"),
+ (26334, "2026-08-05", "2026_r10"),
+)
+
+
+def _get_config(url, **kwargs):
+ assert url == wayback.CONFIG_URL
+ return Reply(CONFIG)
+
+
+# -- the release list --------------------------------------------------------------
+
+
+def test_releases_are_sorted_by_date_because_their_numbers_are_not():
+ listed = wayback.parse_config(CONFIG)
+ assert [r.number for r in listed] == [26334, 64776, 25982, 10]
+ assert listed[0].date == "2026-08-05"
+
+
+def test_an_entry_in_any_other_shape_is_skipped():
+ listed = wayback.parse_config(
+ {
+ **CONFIG,
+ "../etc": {"itemTitle": "World Imagery (Wayback 2020-01-01)"},
+ "77": {"itemTitle": "no date in here"},
+ "78": "not an object",
+ }
+ )
+ assert {r.number for r in listed} == {26334, 64776, 25982, 10}
+ assert wayback.parse_config(["not", "a", "dict"]) == []
+
+
+def test_a_metadata_service_on_another_host_is_never_followed():
+ listed = wayback.parse_config(
+ {
+ "5": {
+ "itemTitle": "World Imagery (Wayback 2020-01-01)",
+ "metadataLayerUrl": "https://attacker.example/arcgis/rest/services/x/MapServer",
+ }
+ }
+ )
+ assert listed[0].metadata_url is None
+
+
+def test_the_list_is_read_once_per_session():
+ calls = []
+
+ def counting(url, **kwargs):
+ calls.append(url)
+ return Reply(CONFIG)
+
+ wayback.releases(get=counting)
+ wayback.releases(get=counting)
+ assert len(calls) == 1
+
+
+def test_an_empty_list_is_an_error_rather_than_a_basemap_with_no_release():
+ with pytest.raises(ValueError):
+ wayback.releases(get=lambda url, **k: Reply({}))
+
+
+def test_a_release_is_digits_and_nothing_else():
+ assert wayback.parse_variant("64776") == 64776
+ for bad in ("../x", "64776a", "", "1" * 10, "12~3"):
+ with pytest.raises(ValueError):
+ wayback.parse_variant(bad)
+
+
+# -- the provider ------------------------------------------------------------------
+
+
+def test_the_plain_basemap_resolves_to_the_newest_release(monkeypatch):
+ monkeypatch.setattr(wayback, "_get", _get_config)
+ provider = tiles.get_provider("esri-wayback")
+ # the release is in the id, so the cache and a capture key on it
+ assert provider.id == "esri-wayback~26334"
+ assert "/tile/26334/{z}/{y}/{x}" in provider.url
+ assert provider.label == "Esri Wayback · 2026-08-05"
+ assert provider.cacheable and provider.capturable and not provider.needs_key
+
+
+def test_a_named_release_keeps_its_number_and_its_date(monkeypatch):
+ monkeypatch.setattr(wayback, "_get", _get_config)
+ provider = tiles.get_provider("esri-wayback~25982")
+ assert provider.id == "esri-wayback~25982"
+ assert tiles.tile_url(provider.url, 15, 16594, 11271).endswith("/tile/25982/15/11271/16594")
+ assert provider.label.endswith("2023-06-13")
+
+
+def test_a_named_release_still_draws_when_the_list_is_unreachable(monkeypatch):
+ def down(url, **kwargs):
+ raise httpx.ConnectError("offline")
+
+ monkeypatch.setattr(wayback, "_get", down)
+ assert tiles.get_provider("esri-wayback~25982").label == "Esri Wayback · release 25982"
+ # …but the newest cannot be named without it
+ with pytest.raises(KeyError):
+ tiles.get_provider("esri-wayback")
+
+
+def test_a_malformed_release_is_refused_before_it_reaches_a_path(monkeypatch):
+ monkeypatch.setattr(wayback, "_get", _get_config)
+ with pytest.raises(KeyError):
+ tiles.get_provider("esri-wayback~../../etc")
+
+
+def test_listing_the_basemaps_asks_esri_nothing(client, monkeypatch):
+ # local-first: the catalogue is read on mount, the release list never is
+ monkeypatch.setattr(wayback, "_get", lambda *a, **k: pytest.fail("asked Esri on mount"))
+ ids = {p["id"] for p in client.get("/api/satellite/providers").json()}
+ assert "esri-wayback" in ids
+
+
+# -- the walk ----------------------------------------------------------------------
+
+
+def _walk(select_by_release, sizes=None, tiles_by_release=None, seen=None, pictures=None):
+ """A stub for the tilemap, the tiles and the metadata. `select_by_release[r]`
+ is the release the tilemap names when asked at `r`; None means no tile
+ there. `pictures[r]` is `(epoch ms, sensor)` or None for no metadata; by
+ default every release was taken on a different day."""
+ sizes = sizes or {}
+ tiles_by_release = tiles_by_release or {}
+ pictures = pictures if pictures is not None else {}
+
+ def get(url, **kwargs):
+ if url == wayback.CONFIG_URL:
+ return Reply(CONFIG)
+ if seen is not None:
+ seen.append(url)
+ if "/tilemap/" in url:
+ release = int(url.split("/tilemap/")[1].split("/")[0])
+ chosen = select_by_release.get(release)
+ if chosen is None:
+ return Reply({"data": [0], "valid": True})
+ return Reply({"data": [1], "select": [chosen], "size": [sizes.get(chosen, 100)]})
+ if url.split("?")[0].endswith("/query"):
+ suffix = url.split("World_Imagery_Metadata_")[1].split("/")[0]
+ release = next(int(k) for k, v in CONFIG.items() if v["metadataLayerUrl"].endswith(f"_{suffix}/MapServer"))
+ picture = pictures.get(release, (1_000_000_000_000 + release * 86_400_000, "WV03"))
+ if picture is None:
+ return Reply({"features": []})
+ stamp, sensor = picture
+ return Reply({"features": [{"attributes": {"SRC_DATE2": stamp, "NICE_DESC": "Maxar", "SRC_DESC": sensor}}]})
+ release = int(url.split("/tile/")[1].split("/")[0])
+ return Reply(content=tiles_by_release.get(release, str(release).encode()))
+
+ return get
+
+
+def _releases(changes):
+ return [change.release for change in changes]
+
+
+def test_the_walk_names_each_release_that_changed_the_point_newest_first():
+ get = _walk({26334: 64776, 25982: 10, 10: 10}, sizes={64776: 300, 10: 200})
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [64776, 10]
+
+
+def test_the_walk_stops_where_the_imagery_does():
+ get = _walk({26334: 26334}) # 64776 has no tile there
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [26334]
+
+
+def test_a_release_the_list_does_not_know_ends_the_walk_rather_than_guessing():
+ get = _walk({26334: 999})
+ assert wayback.local_changes(50.45, 30.52, 15, get=get) == []
+
+
+def test_two_neighbours_with_the_same_pixels_are_one_change_and_the_older_stays():
+ same = b"identical jpeg"
+ get = _walk(
+ {26334: 64776, 25982: 10, 10: 10},
+ sizes={64776: 14, 10: 14},
+ tiles_by_release={64776: same, 10: same},
+ )
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [10]
+
+
+def test_equal_sizes_with_different_pixels_are_still_two_changes():
+ get = _walk(
+ {26334: 64776, 25982: 10, 10: 10},
+ sizes={64776: 5, 10: 5},
+ tiles_by_release={64776: b"aaaaa", 10: b"bbbbb"},
+ )
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [64776, 10]
+
+
+def test_a_picture_published_again_is_one_change_dated_by_its_first_release():
+ # Mariupol, 2026-09: three releases re-processed one GE01 acquisition, and
+ # the tilemap counts each as a change because its bytes differ
+ taken = (1_696_377_600_000, "GE01") # 2023-10-04
+ get = _walk(
+ {26334: 26334, 64776: 25982, 10: 10},
+ sizes={26334: 300, 25982: 200, 10: 100},
+ pictures={26334: taken, 25982: taken, 10: (1_648_512_000_000, "WV03")},
+ )
+ changes = wayback.local_changes(50.45, 30.52, 15, get=get)
+ assert _releases(changes) == [25982, 10]
+ assert changes[0].acquired == "2023-10-04"
+ assert changes[0].source == "Maxar GE01"
+
+
+def test_the_same_day_from_another_satellite_is_another_picture():
+ get = _walk(
+ {26334: 64776, 25982: 10, 10: 10},
+ sizes={64776: 300, 10: 200},
+ pictures={64776: (1_696_377_600_000, "GE01"), 10: (1_696_377_600_000, "WV02")},
+ )
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [64776, 10]
+
+
+def test_a_release_without_metadata_is_never_merged_into_its_neighbour():
+ get = _walk(
+ {26334: 64776, 25982: 10, 10: 10},
+ sizes={64776: 300, 10: 200},
+ pictures={64776: None, 10: None},
+ )
+ changes = wayback.local_changes(50.45, 30.52, 15, get=get)
+ assert _releases(changes) == [64776, 10]
+ assert changes[0].acquired is None
+
+
+def test_a_tile_that_cannot_be_read_keeps_its_change_rather_than_failing_the_walk():
+ flaky = _walk(
+ {26334: 64776, 25982: 10, 10: 10},
+ sizes={64776: 5, 10: 5},
+ tiles_by_release={64776: b"same!", 10: b"same!"},
+ )
+
+ def get(url, **kwargs):
+ if "/tile/64776/" in url:
+ raise httpx.ConnectError("tls alert")
+ return flaky(url, **kwargs)
+
+ assert _releases(wayback.local_changes(50.45, 30.52, 15, get=get)) == [64776, 10]
+
+
+def test_the_same_tile_is_walked_once_per_session():
+ seen = []
+ get = _walk({26334: 26334}, seen=seen)
+ wayback.local_changes(50.45, 30.51, 15, get=get)
+ first = len(seen)
+ wayback.local_changes(50.4501, 30.5101, 15, get=get) # a nudge inside the same tile
+ assert len(seen) == first
+
+
+def test_the_walk_asks_at_the_view_zoom_but_never_past_the_basemap():
+ seen = []
+ wayback.local_changes(50.45, 30.52, 22, get=_walk({26334: 26334}, seen=seen))
+ assert "/tilemap/26334/19/" in seen[0]
+
+
+# -- when the pixels were taken ----------------------------------------------------
+
+
+def test_the_metadata_layer_follows_the_zoom():
+ assert wayback.metadata_layer(23) == 0
+ assert wayback.metadata_layer(15) == 8
+ # everything from zoom 10 out shares the last layer
+ assert wayback.metadata_layer(4) == 13
+
+
+def test_acquisition_date_is_read_from_that_release_and_that_level():
+ asked = []
+
+ def get(url, **kwargs):
+ if url == wayback.CONFIG_URL:
+ return Reply(CONFIG)
+ asked.append((url, kwargs.get("params")))
+ return Reply(
+ {"features": [{"attributes": {"SRC_DATE2": 1648684800000, "NICE_DESC": "Maxar", "SRC_DESC": "WV03"}}]}
+ )
+
+ found = wayback.capture_date(50.4501, 30.5234, 15, 64776, get=get)
+ assert found == {"date": "2022-03-31", "source": "Maxar WV03", "release_date": "2023-08-31"}
+ url, params = asked[0]
+ assert url == META.format("2023_r08") + "/8/query"
+ assert '"x":30.5234' in params["geometry"] and '"y":50.4501' in params["geometry"]
+
+
+def test_a_release_without_metadata_there_says_so_rather_than_inventing_a_date():
+ def get(url, **kwargs):
+ return Reply(CONFIG) if url == wayback.CONFIG_URL else Reply({"features": []})
+
+ assert wayback.capture_date(0, 0, 15, 10, get=get) == {
+ "date": None,
+ "source": None,
+ "release_date": "2014-02-20",
+ }
+
+
+def test_an_unreachable_metadata_service_is_an_unknown_not_an_error():
+ def get(url, **kwargs):
+ if url == wayback.CONFIG_URL:
+ return Reply(CONFIG)
+ raise httpx.ConnectError("offline")
+
+ assert wayback.capture_date(0, 0, 15, 10, get=get) is None
+
+
+# -- the routes --------------------------------------------------------------------
+
+
+def test_the_release_route_lists_numbers_and_dates(client, monkeypatch):
+ monkeypatch.setattr(wayback, "_get", _get_config)
+ body = client.get("/api/satellite/wayback/releases").json()
+ assert body["releases"][0] == {"release": 26334, "date": "2026-08-05"}
+
+
+def test_the_release_route_says_when_esri_cannot_be_reached(client, monkeypatch):
+ def down(url, **kwargs):
+ raise httpx.ConnectError("offline")
+
+ monkeypatch.setattr(wayback, "_get", down)
+ assert client.get("/api/satellite/wayback/releases").status_code == 502
+
+
+def _transport(get):
+ """The same stub, as the pooled client the route opens for its walk."""
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ reply = get(str(request.url))
+ if reply.payload is not None:
+ return httpx.Response(reply.status_code, json=reply.payload)
+ return httpx.Response(reply.status_code, content=reply.content)
+
+ return lambda: httpx.Client(transport=httpx.MockTransport(handler))
+
+
+def test_the_change_route_answers_for_a_point(client, monkeypatch):
+ monkeypatch.setattr(wayback, "_get", lambda *a, **k: pytest.fail("walked without pooling"))
+ monkeypatch.setattr(wayback, "_open_client", _transport(_walk({26334: 64776, 25982: 25982})))
+ body = client.get(
+ "/api/satellite/wayback/changes", params={"lat": 50.45, "lon": 30.52, "zoom": 16}
+ ).json()
+ assert [change["release"] for change in body["changes"]] == [64776, 25982]
+ assert body["changes"][0]["acquired"] and body["changes"][0]["source"] == "Maxar WV03"
+ assert body["zoom"] == 16
+
+
+def test_the_change_route_refuses_a_point_off_the_planet(client):
+ assert (
+ client.get(
+ "/api/satellite/wayback/changes", params={"lat": 91, "lon": 0, "zoom": 16}
+ ).status_code
+ == 422
+ )
+
+
+def test_imagery_date_dates_a_wayback_release_from_its_own_metadata(client, monkeypatch):
+ monkeypatch.setattr(
+ wayback,
+ "capture_date",
+ lambda lat, lon, zoom, number: {"date": "2022-03-31", "source": "Maxar", "release_date": "x"},
+ )
+ body = client.get(
+ "/api/satellite/imagery-date",
+ params={"lat": 1, "lon": 2, "zoom": 15, "provider": "esri-wayback~64776"},
+ ).json()
+ assert body["supported"] is True and body["date"] == "2022-03-31"
+
+
+def test_imagery_date_refuses_a_malformed_release(client):
+ response = client.get(
+ "/api/satellite/imagery-date",
+ params={"lat": 1, "lon": 2, "zoom": 15, "provider": "esri-wayback~x/y"},
+ )
+ assert response.status_code == 422
+
+
+def test_a_proxied_tile_is_cached_under_the_release_it_came_from(client, monkeypatch):
+ from azimut.api import satellite
+ from azimut.engine import tilecache
+
+ monkeypatch.setattr(wayback, "_get", _get_config)
+ asked = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ asked.append(str(request.url))
+ return httpx.Response(200, content=b"\xff\xd8jpeg", headers={"content-type": "image/jpeg"})
+
+ monkeypatch.setattr(satellite, "_tile_client", httpx.Client(transport=httpx.MockTransport(handler)))
+ assert client.get("/api/tiles/esri-wayback/15/16594/11271").status_code == 200
+ assert asked == [
+ "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/WMTS/1.0.0/"
+ "default028mm/MapServer/tile/26334/15/11271/16594"
+ ]
+ assert tilecache.get("esri-wayback~26334", 15, 16594, 11271) is not None