The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Write Copernicus layers in the app, read a rule as a layer, and lay a pass out as a figure (#104)
OsintMeThat602b4e807152
diff --git a/docs/IMAGERY_PROVIDERS.md b/docs/IMAGERY_PROVIDERS.mdindex 9c76264..69016cd 100644--- a/docs/IMAGERY_PROVIDERS.md+++ b/docs/IMAGERY_PROVIDERS.md@@ -187,7 +187,17 @@ templates are unsuitable as basemaps. Turn off **Show logo** and **Show warningsbecause the server burns both into every tile.`TIME` is a **mosaicking window**, so this layer is "mosaic over range X", not "the-imagery". Omitted, the layer's own default applies (the most recent pass).+imagery". Omitting it is **not** "the most recent pass": the mosaicking order is+applied per pixel over the whole archive, so wherever the newest scene has nodata+— a swath edge, a granule gap — the pixel comes from an older one and the tile is+a blend of dates that cannot be dated. Azimut therefore resolves the newest pass+over the crosshair and sends it as `TIME=day/day`, which leaves holes where that+pass has no pixels. A hole can be read; a blend cannot. The undated template is+kept for one case only: no pass could be resolved at all (deep polar winter, a+persistent gap), and then the map says "several dates" and the capture files no+date rather than naming the newest pass it mostly is not showing. The radar+basemap follows the same rule, where a blend would mix looks from opposite sides+of the track.**`MAXCC` is always sent, and defaults to 100.** A configuration instance carriesa cloud-coverage data filter of its own — the standard template ships 20% — and a@@ -214,9 +224,83 @@ window and file under another. `tiles.get_provider()` parses the variant;| Choice | UI | Notes ||--------|----|-------|| Layer | picker populated from **GetCapabilities** on a user request | `LAYERS` in `engine/sentinel.py` is a four-entry catalogue; the instance is authoritative. Analyzer checks keep missing products visible but disabled and use actual IDs such as `VEGETATION_INDEX`. An unverified catalogue cannot start check imagery. |-| Date | a **calendar**: candidate pass days are coloured by cloud, then checked at the crosshair | one day, not a range. Sent as `TIME=day/day` |+| Date | a **calendar**: candidate pass days are coloured by cloud, then checked at the crosshair | one day, not a range. Sent as `TIME=day/day`. "Most recent" is a WFS lookup that resolves to a day and sends it the same way, never an open window || Cloud | a **slider**, 0–100%, default 100 (no filter) | lower it and cloudier passes leave the tiles, the calendar and "most recent" together. Commits on release, so a drag is not a tile per step |+### Layers written in Azimut++A layer is a *name* the whole app already carries — the provider id, the tile+cache, a capture's provenance — plus a rendering. Normally the rendering is a+layer in the Copernicus dashboard; it can also be a script saved here+(`settings.json` → `sentinel_layers`, `engine/sentinel.py`). Nothing downstream+learns a new idea: `resolve_layer` turns the name into the request.++| | |+|---|---|+| Stored | `{"id", "label", "base", "script", "hint", "form"?}`, up to 40, script ≤ 4000 chars |+| `id` | the allowlisted layer-name shape, because it is a URL path segment *and* a directory name |+| `base` | a layer the **instance** serves, which supplies the data collection — an evalscript replaces a layer's style, never its source (the same arrangement the radar basemap uses). Never the Sentinel-1 layer: Sentinel-2 bands read through it render nothing |+| `script` | sent as `EVALSCRIPT=`, base64 then URL-escaped, with `LAYER=<base>` |+| `form` | how a form wrote it (`composite`/`index`), a memo and not the truth — the script renders. Unreadable, it is dropped and the layer reopens as its script |+| Offered | merged into `/api/satellite/sentinel/layers`, marked `custom`, so **every** map tab gets them: Satellite, both Compare sides, Detect and the analyzer builder all read that one route |+| Enabled | always, unlike a configured layer: a script on this machine needs no confirmation from GetCapabilities |+| Collision | a name written here wins over a configured one, so a layer later added to the dashboard cannot quietly change what a saved capture renders |+| Backup | carried in the settings bundle (the analyst's own work, and no credential) |++**A preview is a layer too.** A script is judged on pixels, so the picker renders+one before it is saved, under `AZIMUT_DRAFT_<digest of the script>`. The digest is+in the name because the name is what the disk cache keys on: change two numbers,+press Preview again, and the tiles have to be fetched rather than served from the+last attempt. Only one draft is kept, it is never offered in a picker, and it is+left out of the settings backup (this machine's scratch work).++**A layer that paints one quantity is also a Detect rule.** `(A − B) / (A + B)`+is `measure="nd"` and one band painted into all three channels — grey, not colour+— is `measure="band"` (`analysis_models.Rule`), so the builder offers each as the+rule it already is, an index with its threshold and a band on the line a band+rule starts at (`lib/customLayers.layerAsRule`). A colour composite does not come+over — three channels are not one number — and neither does a hand-written+script. The menu lists those too, greyed, with the reason+(`lib/customLayers.whyNotARule`): a layer silently missing from it reads as+"rules cannot be built from my layers at all".++**A rule's line moves on the readings, not on new imagery.**+`POST /compare/analyzers/check/values` sends what one rule read over the whole+ground a check was tested on (`detect_rules.rule_values`), quantised to sixteen+bits across the span actually measured and split over a PNG's red and green+channels — a canvas hands back eight-bit RGBA whatever the file held, so a 16-bit+greyscale would be truncated and the line would land in the wrong place. The+browser applies the same comparison the engine applies (`analyzerRules.passesValue`+mirrors `detect_rules._passes`), and `tests/test_detect_rules.py` proves the two+agree pixel for pixel at several lines. One rule at a time, only once its slider+is touched, and never a fetch: every rule of every tile would be tens of+megabytes on a press nobody made.++**A rule can be drawn as a layer, too.** The reverse direction+(`lib/map/ruleLayer.js`): a rule names the bands it reads, so the same+generators write the script that paints what it measures — `nd` and the+two-band published indices as `indexScript`, a `band` rule as a grey composite,+`brightness` as the visible bands averaged. It renders through the ordinary+draft-preview path, so it caches and resolves exactly as a hand-written layer+does. No threshold is baked in: the script's digest is the draft's name and so+the tile cache's key, and a threshold in it would refetch the frame at every+nudge of the slider.++### Figures: one place, one day, several renderings++`POST /api/cases/{case}/satellite/figure` renders the same ground through several+layers and lays the panels out as a Geo Proof (`engine/figures.py`,+`api/figures.py`). Each panel goes through the ordinary provider variant, so a+layer written here resolves and caches exactly as it does on the map, and is filed+as a real **capture** with its own provenance. The composer already lays panels+out, captions them, draws the footer and takes annotations, so a figure opens as a+composition that can be arrowed rather than a picture to accept or redo.++One day for every panel, by design: a figure is one acquisition seen several ways.+Panels of different dates would compare two things at once, which is Compare's job.+Up to 8 panels, 1–4 per row, each layer once. The footer states the day, the point+and `Copernicus Sentinel-2 L2A`.+### Dates come from WFS, and cost one request`GET /ogc/wfs/{instance}?TYPENAMES=DSS2&TIME=…&BBOX=…&OUTPUTFORMAT=application/json`diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 557a405..d7a5406 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -182,6 +182,7 @@ proof for publication.| ✅ **Geolocation worklists** | Opens recent sheets, tracks imported files awaiting a proof and indexes every proof point with its date, source and coordinates. || ✅ **Files & navigation** | Files work into the active folder, offers contextual actions and filters, and retraces tools and documents with guarded Back and Forward. || ✅ **Command palette** | Ctrl+K or ⌘K searches tools, cases and current-case documents, starts with recently added items and protects unsaved work. |+| ✅ **Copernicus layers & figures** | Writes composite, index and script layers with a preview on the map, offers them in every map tab, reads an index or single-band layer as a Detect rule, draws a rule back as a layer and moves its line live on the last test's readings, and lays several renderings of one pass out as a captioned figure. |---@@ -237,7 +238,9 @@ GPS-tagged clips promotable to places.Toward v3: GIF maker; curated tool links; full-text case search; clipboardimage/URL capture with provenance; EXIF/GPS import suggestions for place andtime; sun and moon times read against the terrain horizon the 3D map's DEM-supplies, since a ridge ends the day well before the flat horizon does.+supplies, since a ridge ends the day well before the flat horizon does; export+and import an analyzer as a file, checks included, so one can be shared without+handing over the settings backup and its keys.### v4: investigation layer@@ -305,6 +308,7 @@ stops making sense.- **Map files out of the case:** export pins, claims and Detect findings as KML or GeoJSON, with TimeStamp and TimeSpan so another viewer's time slider reads them.- **Update ffmpeg from the app:** download a static build into the workspace and prefer it at runtime, like the scraper update, if the bundled copy ever lags in a way users hit.- **Place names in their own script:** the Arabic or Cyrillic name under the Latin one, for searching local sources. Needs the engine's right-to-left text plugin, bundled rather than fetched.+- **Free band formulas in Detect:** a rule read on an expression the analyst writes. A normalised difference and a single band already work, including from a layer they wrote, so what is left is the general case — an arbitrary expression needs its own product family, a generated evalscript and thresholds calibrated on real scenes.- **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.- **A fire detection to click:** the points the app already draws close in, read back under the pointer for the detection's time, satellite, confidence and power.- **The sky over the area, not the tile:** Detect's pass list and its newest pass judged by the cloud over the drawn area (one small SCL read per pass) rather than the 110 km tile's figure.diff --git a/docs/UI.md b/docs/UI.mdindex be1c960..8f2b6c5 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -1658,7 +1658,15 @@ version. Eachside keeps its provider, Wayback release, Sentinel-2 day and reference layers.The source cards and mode controls use the application's shared theme, buttonsand spacing. The date is a chip beside the provider, reading the same for-Wayback and for Sentinel-2 on every map tab, so the card's layers icon means one thing. A+Wayback and for Sentinel-2 on every map tab, so the card's layers icon means one thing.+The Sentinel-2 chip's menu also writes layers of your own — **Composite** puts+three bands on red, green and blue, **Index** measures `(A − B) / (A + B)` on a+colour ramp and **Custom script** is the evalscript itself, with each form+writing the script the next tab shows. **Preview on the map** draws it over the+date already chosen without saving it; closing the panel keeps the draft and the+preview, and **Discard** is what throws them away. Saved, a layer joins the+picker in Satellite, Compare and Detect. Settings → Imagery → Copernicus keeps+the list. AWayback chip names the release, so the day its pixels were taken sits beside it,as it does under the chip on Satellite. Thecards float over the maps they describe, one per pane, so no bar takes the maps'@@ -2024,6 +2032,15 @@ screenshot gets neither, since its coordinates describe the map view at filingtime rather than the picture itself. What was drawn is written into thecapture's provenance.+**Build a figure** sits in the same menu while Sentinel-2 is on: the same ground+on the day already chosen, through the layers you pick, each panel captioned and+filed as its own capture. It opens in Geo Proof with its credit line written —+the day, the point and Copernicus Sentinel-2 L2A — ready to annotate. Up to+eight panels, one to four per row, each layer once, at the capture size the menu+is set to. Every panel is the same acquisition by design: panels of different+dates compare two things at once, which is what Compare is for, so an undated+map says to pick a date first.+Underneath, the **status line** reads where you are (coordinates, zoom, and thearmed tool's own measurement) on the left, and carries the two acts that takesomething off the map — Save place and Capture — on the right. What marks the@@ -2755,9 +2772,13 @@ basemap alone, or **New check**. A check of two dates splits the map between itspasses: the before pass on the left and the after pass on the right, each on itsown map with the two cameras held together and a handle to drag the cut, and**Before**, **Split** and **After** switch between the whole map on one and the-cut. A check of one date shows its pass on one map. An eye puts the basemap in-the passes' place and back. **Display** picks their Copernicus layer, with the-one that reads rule ★ best marked; it changes the picture, not the rule's bands.+cut. A check of one date shows its pass on one map. A satellite button puts the+basemap in the passes' place and back; it is not an eye, because the eye further+along takes the drawings off the imagery and two eyes would read as one switch.+**Display** picks their Copernicus layer, with the one that shows the ★ rule's+data best tagged by the bands it shows (“shows B08 · B04”) and the ones you+wrote tagged *yours*. The menu opens on one line saying what it is for: what you+look at, while rules read the bands themselves.Opening or selecting a check verifies the configuration's layers, without anetwork check on builder mount. The menu shows their actual IDs, including`VEGETATION_INDEX` where that is the configured NDVI display. Missing products@@ -2767,11 +2788,51 @@ or an available display, with a notice. If verification fails, the basemapstays on. Tile errors on either pass name the layer and date and offer**Retry imagery** or **Use basemap**.+**Reuse a formula** sits beside **Add a rule** once you have written a layer of your+own (Satellite → the date chip → Write a layer). A rule reads one number per+pixel, so a layer comes over when what it paints is a number: an index paints+`(A − B) / (A + B)` and darkens below a line, which is the `nd` measure with its+threshold; a composite that puts one band in all three channels is grey, not+colour, which is that band's reflectance, the `band` measure. The menu lists+every layer you have written — the ones that come over with their arithmetic, the+ones that do not with the reason, greyed. A colour composite is three channels+and no single number, and nobody can read a quantity out of a hand-written+script. Which dates the rule reads is the analyzer's question, not the layer's,+and a grey band brings no line: the gain it is drawn with says how bright it is,+never where the ground stops passing.++Each rule carries a coloured dot with its number, which shows or hides that+rule's pixels on the map. Until a test has run there are no pixels, so the dot is+drawn hollow and says what it is waiting for rather than answering nothing.++Moving a rule's line repaints its ground as you drag it. The first touch of the+slider fetches what that rule read over the whole frame — the same readings the+last test made, never new imagery, so it costs no Copernicus request — and from+then on the browser crosses the line itself. Only that rule's pixels move: the+pins, the candidates and the shares still answer for the last test, and the+button still reads **Test again**. A rule whose reading is in hand no longer dims+the picture when only its line moved, since the ground drawn is the ground the+next test will keep. Changing what a rule *reads* — its bands, its dates, its+context — drops the reading, and a ground class has no line to move.++**See it** beside what a rule reads draws the rule's own arithmetic on the map as+a Copernicus layer, so the quantity can be looked at continuously instead of as a+verdict. An index renders as `(A − B) / (A + B)` on a ramp, a band as that band+in grey, brightness as the visible bands averaged; a published index does the+same from its own two bands. No threshold is drawn into it, so moving the rule's+line costs no tiles — the ramp already shows where every value falls. A colour+change needs two dates, ground classes are a classification and radar is another+collection, so those say why instead of offering a press. While a rule is drawn+the Display chip reads *rule N* and the menu offers the display back; choosing+any display, or removing the rule, ends the drawing.+**Checks** are how an analyzer is proved, and one is needed to save it, with apin where something should be found; the others may be traps, where nothing maybe. A check is two passes (one, for one date) and the pins laid on them. It hasno frame: it reads the ground under its pins, the tile under each and the tile-across an edge when a pin is within 48 pixels of it, at most twelve tiles.+across an edge when a pin is within 48 pixels of it. A check holds up to 60 pins+and reads at most 20 tiles. Exceeding the tile limit shows the count and limit+in the console, even while placing pins, and disables **Test** before fetching.**New check** opens a drawer over the console that takes its passes: a look-upfor the ground at the middle of the map over 30 days, 90 days or a year, oneCopernicus request, or **Dates**, which picks each side from a calendar of the@@ -2795,7 +2856,13 @@ would return there, since it runs the engine's own evaluation, cleanup, sizes,shape and grouping. Each pin turns green or red as it comes out, and the rowunder the console says **2 of 2 found** or **1 of 1 flagged**, keeps a chip forevery rule, to hide its pixels and see which ones help, and switches the map-between **Rules** and **Detections**. Each rule's card gives the share of the+between **Rules** and **Detections**. One control holds the overlays: an eye and+the chevron beside it, joined, because the eye is the switch and the chevron says+what it switches. The chevron lists **Markers**, **Outlines** and **Check pins**+independently; the eye takes all of them off at once, which greys the list and+says the eye has them all off, and restores the choices when pressed again. The+satellite button is the separate one: it switches the imagery to the basemap.+Display choices do not rerun a test or change the saved analyzer. Each rule's card gives the share of themeasured ground it keeps, lays the pins along its slider where they were read(filled where they should be found, struck where none should), so the line can beset between them, and says what the pins would have come to without it (**Without@@ -2882,8 +2949,13 @@ candidate under review wears a ring on the map. **Add candidate**, or the map'swith `origin: manual`, the same pass pair, preview and verdicts. Manual candidateshave dashed map outlines and a Manual label.-Beside **Export as layer**, the eye (`H`) takes the candidates and areas off the-map, so the pass shows bare; leaving the review puts them back. When the run+Beside **Export as layer**, the same joined control as the bench's: the eye (`H`)+takes the candidates and areas off the map, so the pass shows bare, and the+chevron beside it switches **Markers** (including numbered groups) and+**Outlines** independently without rerunning the analysis. Leaving the review+puts them back. With markers hidden, an outline still opens its candidate and the+candidate under review has a highlighted outline. The eye restores the display+choices when pressed again. When the runread two passes, the blink (`B`) flips A against B on the map at Compare'snormal speed, and a chip over the map says which is showing, in Compare'sletters. Both passes are laid in the one map and kept loaded, so the blinkdiff --git a/frontend/e2e/detect.spec.js b/frontend/e2e/detect.spec.jsindex 18358d3..a0a63f6 100644--- a/frontend/e2e/detect.spec.js+++ b/frontend/e2e/detect.spec.js@@ -92,7 +92,7 @@ async function openDetect(page, withRun = false, withRoutine = false, twoRuns =});await page.goto('/#detect');await awaitMapReady(page);- return { errors, calls, prefs };+ return { errors, calls, prefs, run };}/** What starts with nothing picked and every category folded: open the first, take its first analyzer. */@@ -154,6 +154,59 @@ test('review isolates one result layer and restores the saved eye states on Backexpect(errors).toEqual([]);});+test('Results can hide markers while keeping selectable outlines and restore the display after the eye', async ({ page }) => {+ const { errors, run } = await openDetect(page, true);+ run.results[2].geometry = { type: 'Polygon', coordinates: [+ [[2.296, 48.859], [2.299, 48.859], [2.299, 48.861], [2.296, 48.861], [2.296, 48.859]],+ ] };+ const writes = [];+ page.on('request', (request) => {+ if (request.url().includes('/analysis/') && request.method() !== 'GET') writes.push(request.url());+ });+ await page.getByRole('button', { name: 'Saved', exact: true }).click();+ await page.getByRole('button', { name: /^North site pass/ }).click();+ const overlay = page.locator('.analysis-overlay');+ await expect(overlay.locator('.outline')).toHaveCount(3);+ await expect(overlay.locator('g')).toHaveCount(1);+ await expect(overlay.locator('text')).toHaveText('3');+ await page.getByRole('button', { name: 'Which overlays', exact: true }).click();+ const menu = page.getByRole('menu', { name: 'Overlay display' });+ await expect(menu.getByRole('menuitemcheckbox')).toHaveCount(2);+ // Review shortcuts must not write a verdict while the display menu owns the keyboard.+ await page.keyboard.press('d');+ await expect(overlay.locator('.outline')).toHaveCount(3);+ await menu.getByRole('menuitemcheckbox', { name: 'Markers', exact: true }).click();+ await expect(overlay.locator('circle, g, text')).toHaveCount(0);+ await expect(overlay.locator('.outline')).toHaveCount(3);+ await expect(overlay.locator('.outline.selected')).toHaveCount(1);+ await menu.getByRole('menuitemcheckbox', { name: 'Outlines', exact: true }).click();+ await expect(overlay.locator('.outline')).toHaveCount(0);+ await menu.getByRole('menuitemcheckbox', { name: 'Outlines', exact: true }).click();+ await page.keyboard.press('Escape');+ await expect(menu).toHaveCount(0);+ // A contour selects its candidate while its interior leaves room to pan the map.+ const outline = overlay.locator('.outline').last();+ const edge = await outline.evaluate((node) => {+ const point = node.getPointAtLength(node.getTotalLength() / 8).matrixTransform(node.getScreenCTM());+ return { x: point.x, y: point.y };+ });+ await page.mouse.click(edge.x, edge.y);+ await expect(page.locator('.review-body').getByText('Third candidate', { exact: true })).toBeVisible();+ await expect(overlay.locator('.outline.selected')).toHaveAttribute('stroke-width', '3');+ await page.keyboard.press('ArrowLeft');+ await expect(page.locator('.review-body').getByText(/^A longer candidate name/)).toBeVisible();+ await page.getByRole('button', { name: 'Hide the candidates and areas', exact: true }).click();+ await expect(overlay).toHaveCount(0);+ await page.keyboard.press('h');+ await expect(overlay.locator('.outline')).toHaveCount(3);+ await expect(overlay.locator('g')).toHaveCount(0);+ await page.getByRole('button', { name: 'Which overlays', exact: true }).click();+ await expect(menu.getByRole('menuitemcheckbox', { name: 'Markers', exact: true })).toHaveAttribute('aria-checked', 'false');+ await page.screenshot({ path: test.info().outputPath('results-outlines-only.png') });+ expect(writes).toEqual([]);+ expect(errors).toEqual([]);+});+test('clicking a Detect date opens a calendar of passes and previews the chosen day', async ({ page }) => {const { errors } = await openDetect(page);const now = new Date();@@ -404,7 +457,7 @@ const rulesCatalogue = {methods: [{ id: 'surface', single: false, sizes: {} }, { id: 'rules', single: false, clouds: true, sensor: 'sentinel2', frames: 4,sizes: { all: size(0, 0, 0, 0, 0), medium: size(2000, 0, 1, 0, 30) }, rules: true, measure: '' }],rules: { bands: ['B02', 'B03', 'B04', 'B08', 'B11', 'B12'], classes: ['vegetation', 'bare', 'water'],- max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 20, max_check_tiles: 12 },+ max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 60, max_check_tiles: 20 },examples: [],};@@ -577,6 +630,42 @@ test('an analyzer of your own is proved on a check made on the map: two passes,await expect(page.locator('.mark.pass')).toHaveCount(2);await page.screenshot({ path: test.info().outputPath('detect-builder-tested.png') });+ // Display choices leave the test, its pins and its imagery alone.+ const testsBeforeDisplay = log.tests.length;+ const overlay = page.locator('.analysis-overlay');+ await deck.getByRole('button', { name: 'Which overlays', exact: true }).click();+ const display = deck.getByRole('menu', { name: 'Overlay display' });+ await display.getByRole('menuitemcheckbox', { name: 'Markers', exact: true }).click();+ await expect(overlay.locator('g')).toHaveCount(0);+ await expect(overlay.locator('.outline')).toHaveCount(1);+ await expect(page.locator('.mark.pass')).toHaveCount(2);+ await display.getByRole('menuitemcheckbox', { name: 'Check pins', exact: true }).click();+ await expect(page.locator('.mark')).toHaveCount(0);+ await expect(overlay.locator('.outline')).toHaveCount(1);+ await page.screenshot({ path: test.info().outputPath('builder-outlines-only.png') });+ await display.getByRole('menuitemcheckbox', { name: 'Outlines', exact: true }).click();+ await expect(overlay.locator('.outline')).toHaveCount(0);+ await display.getByRole('menuitemcheckbox', { name: 'Outlines', exact: true }).click();+ await page.keyboard.press('Escape');+ await deck.getByRole('button', { name: 'Should be found', exact: true }).click();+ await expect(overlay.locator('.outline')).toHaveCSS('pointer-events', 'none');+ await page.keyboard.press('Escape');+ await expect(overlay.locator('.outline')).toHaveCSS('pointer-events', 'stroke');+ await deck.getByRole('button', { name: 'Hide the check overlays', exact: true }).click();+ await expect(overlay).toHaveCount(0);+ await expect(page.locator('.rule-layers')).toHaveCount(0);+ await expect(page.locator('.detect-tool .map')).toHaveCount(2);+ await deck.getByRole('button', { name: 'Hide the check overlays', exact: true }).click();+ await expect(overlay.locator('.outline')).toHaveCount(1);+ await expect(overlay.locator('g')).toHaveCount(0);+ await expect(page.locator('.mark')).toHaveCount(0);+ await deck.getByRole('button', { name: 'Which overlays', exact: true }).click();+ await display.getByRole('menuitemcheckbox', { name: 'Markers', exact: true }).click();+ await display.getByRole('menuitemcheckbox', { name: 'Check pins', exact: true }).click();+ await page.keyboard.press('Escape');+ await expect(page.locator('.mark.pass')).toHaveCount(2);+ expect(log.tests).toHaveLength(testsBeforeDisplay);+// the rules are on the ground: a change across both halves, a before-state on the before half, the tested ground tintedawait expect(page.locator('.rule-layers .part')).toHaveCount(3);await expect.poll(async () => near([250, 204, 21, 110])(await painted(page, 'shared', [log.center.x, log.center.y]))).toBe(true);@@ -690,6 +779,44 @@ test('an analyzer of one date is tried on one map, with no split and no before oexpect(errors).toEqual([]);});+test('a check holds sixty pins and shows a tile overflow while pins are still being placed', async ({ page }) => {+ test.setTimeout(60_000);+ const { errors } = await openDetect(page);+ const log = await answerBuilder(page);+ const overflow = 'these pins reach 21 tiles and a check reads at most 20: keep the pins of one place in a check and start another for ground further away';+ await page.route('**/api/compare/analyzers/check/plan', (route) => {+ const body = route.request().postDataJSON();+ log.plans.push(body);+ return body.check.marks.length === 60+ ? route.fulfill({ status: 422, json: { detail: overflow } })+ : route.fulfill({ json: { tiles: 20, missing: 40 } });+ });+ await page.getByRole('button', { name: 'Analyzers', exact: true }).click();+ await page.getByRole('button', { name: 'New analyzer', exact: true }).click();+ await page.getByRole('group', { name: 'Dates' }).getByRole('button', { name: 'One date' }).click();+ await page.getByRole('button', { name: /^Blank/ }).click();+ const deck = page.locator('.console');+ await deck.getByRole('button', { name: 'New check' }).click();+ await deck.getByRole('button', { name: 'Find passes', exact: true }).click();+ await page.getByLabel('Use 2026-09-10').getByRole('button', { name: 'Use', exact: true }).click();+ await deck.getByRole('button', { name: 'Place the pins' }).click();+ const box = await page.locator('.detect-tool .map').boundingBox();+ for (let i = 0; i < 60; i++) {+ await page.mouse.click(box.x + box.width * (0.3 + (i % 10) * 0.03), box.y + box.height * (0.2 + Math.floor(i / 10) * 0.03));+ }+ await expect(deck.locator('.count')).toHaveText('60 pins');+ await expect(deck.getByRole('button', { name: 'Should be found' })).toHaveAttribute('aria-pressed', 'true');+ await expect(deck.locator('.note.warn')).toHaveText(overflow);+ await expect(deck.locator('.test')).toBeDisabled();+ expect(log.plans.at(-1).check.marks).toHaveLength(60);+ expect(log.tests).toHaveLength(0);+ await page.mouse.click(box.x + box.width * 0.65, box.y + box.height * 0.25);+ await expect(page.getByText('A check holds at most 60 pins.', { exact: true })).toBeVisible();+ await expect(deck.locator('.count')).toHaveText('60 pins');+ await page.screenshot({ path: test.info().outputPath('detect-check-limit.png') });+ expect(errors).toEqual([]);+});+test('check displays use verified configuration layers and grey missing products with setup help', async ({ page }) => {const { errors } = await openDetect(page);await answerBuilder(page);diff --git a/frontend/src/components/CustomLayerForm.svelte b/frontend/src/components/CustomLayerForm.sveltenew file mode 100644index 0000000..5eae1c2--- /dev/null+++ b/frontend/src/components/CustomLayerForm.svelte@@ -0,0 +1,457 @@+<script>+ /**+ * One Copernicus layer being written: how its pixels are made, and what it is+ * called.+ *+ * Three ways in, the ones Copernicus Browser offers: three bands on red,+ * green and blue; one normalised difference on a ramp; or the JavaScript+ * itself. The first two *write* the script rather than being a different kind+ * of layer, so what is saved is always a script and everything downstream+ * stays one idea. Leaving a form for Custom script hands over the text it+ * generated, which is then yours to take anywhere.+ *+ * **The draft belongs to whoever opened this form**, not to the form, so+ * closing the panel to look at the preview on the map and reopening it keeps+ * what was typed. `lib/customLayers.startForm` makes one; this reads and+ * mutates it.+ *+ * The same form in both places it is needed, so Settings and the map picker+ * cannot drift. Settings manages the list and has no scene to try a script+ * on; the picker passes `onpreview` and draws the result on the map, which is+ * the only way to tell whether a script says what you meant.+ */+ import Icon from './Icon.svelte';+ import { asName, layerPayload, layerProblem } from '../lib/customLayers.js';+ import {+ COMPOSITE_PRESETS,+ INDEX_PRESETS,+ RAMPS,+ WAYS,+ bandLabel,+ rampGradient,+ scriptFor,+ } from '../lib/layerScripts.js';++ let {+ /** The draft, from `startForm`. Mutated here, owned by the caller. */+ form,+ /** Layer ids a script can read its data from (radar already excluded). */+ bases = [],+ /** The Sentinel-2 L2A bands, from the backend, which owns the list. */+ bands = [],+ /** Names already taken by something this form must not overwrite. */+ taken = [],+ scriptMax = 4000,+ /** Draw the script on the map as it stands. Absent = no preview here. */+ onpreview = null,+ onsave,+ oncancel,+ busy = false,+ /** Said under the buttons: what the last preview or save did. */+ note = '',+ } = $props();++ const choices = $derived(bands.length ? bands : ['B02', 'B03', 'B04', 'B08', 'B11', 'B12']);+ /** What would be saved, whichever way is open. */+ const script = $derived(+ scriptFor(form.way, { composite: form.composite, index: form.index, script: form.typed })+ );+ const problem = $derived(layerProblem({ ...form, script }, { taken, scriptMax }));+ const over = $derived(script.length > scriptMax);+ // Only a new layer is named here. An existing one keeps the name and the data+ // source every capture, cache directory and saved session was rendered from.+ const naming = $derived(!form.editing);+ const way = $derived(WAYS.find((entry) => entry.id === form.way) ?? WAYS[0]);+ const chosenRamp = $derived(RAMPS.find((entry) => entry.id === form.index.rampId) ?? RAMPS[0]);++ /** Leaving a form for the script carries its text over, so nothing is lost. */+ function go(next) {+ if (next === 'script' && form.way !== 'script') form.typed = script;+ form.way = next;+ }++ function useComposite(preset) {+ const [red, green, blue] = preset.bands;+ Object.assign(form.composite, { red, green, blue });+ if (!form.hint) form.hint = preset.hint;+ }++ function useIndex(preset) {+ Object.assign(form.index, { high: preset.high, low: preset.low, rampId: preset.rampId });+ if (!form.hint) form.hint = preset.hint;+ }+</script>++<div class="layer-form">+ <section class="block">+ <header class="block-head">+ <h4>How the pixels are made</h4>+ <span class="count mono" class:over title="Characters of script, and the budget">+ {script.length}/{scriptMax}+ </span>+ </header>++ <div class="ways" role="tablist" aria-label="How the pixels are made">+ {#each WAYS as entry (entry.id)}+ <button+ class="way"+ class:on={form.way === entry.id}+ role="tab"+ aria-selected={form.way === entry.id}+ title={entry.hint}+ onclick={() => go(entry.id)}+ >+ {entry.label}+ </button>+ {/each}+ </div>+ <p class="why">{way.hint}.</p>++ {#if form.way === 'composite'}+ <div class="presets">+ <span class="presets-label">Start from</span>+ {#each COMPOSITE_PRESETS as preset (preset.id)}+ <button class="chip" title={preset.hint} onclick={() => useComposite(preset)}>+ {preset.label}+ </button>+ {/each}+ </div>++ <!-- Three explicit binds rather than a loop over the channel names: a+ `bind:` through a computed key does not hold its channel. -->+ <div class="three">+ <label class="field">+ <span class="chan"><i class="dot red"></i> Red</span>+ <select class="input" aria-label="Red band" bind:value={form.composite.red}>+ {#each choices as entry (entry)}<option value={entry}>{bandLabel(entry)}</option>{/each}+ </select>+ </label>+ <label class="field">+ <span class="chan"><i class="dot green"></i> Green</span>+ <select class="input" aria-label="Green band" bind:value={form.composite.green}>+ {#each choices as entry (entry)}<option value={entry}>{bandLabel(entry)}</option>{/each}+ </select>+ </label>+ <label class="field">+ <span class="chan"><i class="dot blue"></i> Blue</span>+ <select class="input" aria-label="Blue band" bind:value={form.composite.blue}>+ {#each choices as entry (entry)}<option value={entry}>{bandLabel(entry)}</option>{/each}+ </select>+ </label>+ </div>++ <label class="field">+ <span class="row-label">+ Brightness <span class="readout mono">×{form.composite.gain}</span>+ </span>+ <input+ class="slider"+ type="range"+ min="0.5"+ max="8"+ step="0.1"+ aria-label="Brightness"+ bind:value={form.composite.gain}+ />+ </label>+ <p class="help">+ <Icon name="info" size={12} />+ <span>A band's value runs 0 to 1, so it needs multiplying to fill a channel.</span>+ </p>+ {:else if form.way === 'index'}+ <div class="presets">+ <span class="presets-label">Start from</span>+ {#each INDEX_PRESETS as preset (preset.id)}+ <button class="chip" title={preset.hint} onclick={() => useIndex(preset)}>+ {preset.label}+ </button>+ {/each}+ </div>++ <div class="two">+ <label class="field">+ <span>Band A</span>+ <select class="input" aria-label="Band A" bind:value={form.index.high}>+ {#each choices as entry (entry)}<option value={entry}>{bandLabel(entry)}</option>{/each}+ </select>+ </label>+ <label class="field">+ <span>Band B</span>+ <select class="input" aria-label="Band B" bind:value={form.index.low}>+ {#each choices as entry (entry)}<option value={entry}>{bandLabel(entry)}</option>{/each}+ </select>+ </label>+ </div>+ <p class="help">+ <Icon name="info" size={12} />+ <span>+ Each pixel becomes <span class="mono">(A − B) / (A + B)</span>, a number from −1 to 1.+ </span>+ </p>++ <label class="field">+ <span>Colours</span>+ <select class="input" aria-label="Colour ramp" bind:value={form.index.rampId}>+ {#each RAMPS as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}+ </select>+ </label>+ <div class="ramp">+ <span class="ramp-end mono">−1</span>+ <span+ class="ramp-bar"+ style:background={rampGradient(form.index.rampId)}+ role="img"+ aria-label={`${chosenRamp.label} ramp, from −1 to 1`}+ ></span>+ <span class="ramp-end mono">+1</span>+ </div>+ <p class="help">+ <Icon name="info" size={12} />+ <span>The number picks its colour along that bar.</span>+ </p>++ <label class="field">+ <span>Leave dark at or below</span>+ <input+ class="input narrow"+ type="number"+ min="-1"+ max="1"+ step="0.05"+ aria-label="Leave dark at or below"+ bind:value={form.index.threshold}+ placeholder="nothing"+ />+ </label>+ <p class="help">+ <Icon name="info" size={12} />+ <span>+ Empty draws the whole bar; a number hides everything under it, which is how a hotspot+ reads on its own.+ </span>+ </p>+ {:else}+ <textarea+ class="input script mono"+ bind:value={form.typed}+ spellcheck="false"+ rows="14"+ aria-label="Evalscript"+ placeholder="//VERSION=3 function setup() { … } function evaluatePixel(p) { … }"+ ></textarea>+ <p class="help">+ <Icon name="info" size={12} />+ <span>A Copernicus evalscript. The Composite and Index tabs write one for you to edit.</span>+ </p>+ {/if}+ </section>++ <section class="block">+ <header class="block-head"><h4>Name it</h4></header>++ <div class="two">+ <label class="field">+ <span>Name</span>+ <input+ class="input mono"+ value={form.id}+ disabled={!naming}+ placeholder="PLUME_SWIR"+ aria-label="Layer name"+ title={naming+ ? 'Capitals, digits and underscores'+ : 'A saved layer keeps its name: captures and caches are filed under it'}+ oninput={(e) => (form.id = asName(e.currentTarget.value))}+ />+ </label>+ <label class="field">+ <span>Reads data from</span>+ <select+ class="input"+ aria-label="Layer to read data from"+ bind:value={form.base}+ disabled={!naming}+ >+ {#each bases as base (base)}+ <option value={base}>{base}</option>+ {/each}+ {#if !bases.includes(form.base)}+ <option value={form.base}>{form.base}</option>+ {/if}+ </select>+ </label>+ </div>+ <p class="help">+ <Icon name="info" size={12} />+ <span>+ {#if naming}+ The name a capture records, and one layer of your Copernicus configuration whose+ satellite data this reads — its own colours are replaced by yours.+ {:else}+ Both are what everything already filed under this layer was rendered from, so neither+ changes.+ {/if}+ </span>+ </p>++ <div class="two">+ <label class="field">+ <span>Shown as</span>+ <input+ class="input"+ bind:value={form.label}+ maxlength="60"+ aria-label="Label"+ placeholder={form.id || 'SWIR plume'}+ title="What the layer picker calls it"+ />+ </label>+ <label class="field">+ <span>Note</span>+ <input+ class="input"+ bind:value={form.hint}+ maxlength="160"+ aria-label="Note"+ placeholder="Why you'd pick it"+ title="One clause under the name, for when you come back to it"+ />+ </label>+ </div>+ </section>++ <div class="actions">+ {#if onpreview}+ <button+ class="btn"+ disabled={busy || over || !script.trim()}+ onclick={() => onpreview({ base: form.base, script })}+ title="Draw this on the map, over the date already chosen. Nothing is saved"+ >+ <Icon name="eye" size={13} /> {busy ? 'Drawing…' : 'Preview on the map'}+ </button>+ {/if}+ <button+ class="btn primary"+ disabled={busy || !!problem}+ onclick={() => onsave(layerPayload(form, script))}+ title={problem || 'Keep this layer under its name'}+ >+ {form.editing ? 'Save changes' : 'Save layer'}+ </button>+ <button class="btn" onclick={oncancel} title="Close without keeping it">Cancel</button>+ </div>++ <!-- What just happened beats what is still missing: a preview needs no name,+ and Save already says why it is disabled. -->+ {#if note}+ <p class="hint" role="status">{note}</p>+ {:else if problem}+ <p class="hint" class:warn={!!form.id} role="status">{problem}</p>+ {:else}+ <p class="hint">Kept, it joins the layer picker in Satellite, Compare and Detect.</p>+ {/if}+</div>++<style>+ .layer-form { display: grid; gap: 12px; }++ .block {+ display: grid;+ gap: 9px;+ padding: 11px 12px 13px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .block-head { display: flex; align-items: baseline; gap: 10px; }+ .block-head h4 {+ margin: 0;+ font-size: var(--fs-xs);+ font-weight: 700;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--text-3);+ }+ .count { margin-left: auto; font-size: var(--fs-xs); color: var(--text-3); }+ .count.over { color: var(--warn); }++ .ways { display: flex; gap: 4px; flex-wrap: wrap; }+ .way {+ padding: 5px 11px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-1);+ color: var(--text-2);+ font-size: var(--fs-sm);+ cursor: pointer;+ }+ .way:hover { border-color: var(--text-3); color: var(--text-1); }+ .way.on {+ border-color: var(--accent);+ background: var(--accent-soft);+ color: var(--accent);+ font-weight: 600;+ }+ .why { margin: -3px 0 0; font-size: var(--fs-xs); color: var(--text-3); }++ .presets { display: flex; align-items: center; gap: 5px; flex-wrap: wrap; }+ .presets-label { margin-right: 2px; font-size: var(--fs-xs); color: var(--text-3); }+ .chip {+ padding: 2px 8px;+ border: 1px solid var(--border);+ border-radius: 999px;+ background: var(--bg-1);+ color: var(--text-2);+ font-size: var(--fs-xs);+ cursor: pointer;+ }+ .chip:hover { border-color: var(--accent); color: var(--accent); }++ .two, .three { display: grid; gap: 9px; }+ .two { grid-template-columns: 1fr 1fr; }+ .three { grid-template-columns: repeat(3, 1fr); }+ .field { display: grid; gap: 4px; min-width: 0; }+ .field > span { font-size: var(--fs-xs); color: var(--text-3); }+ .field .input { min-width: 0; }+ .narrow { max-width: 130px; }+ .chan { display: inline-flex; align-items: center; gap: 5px; }+ .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; }+ .dot.red { background: #e5484d; }+ .dot.green { background: #46a758; }+ .dot.blue { background: #3b82f6; }++ .row-label { display: flex; align-items: baseline; gap: 8px; }+ .readout { margin-left: auto; color: var(--text-2); }+ .slider { width: 100%; }++ .ramp { display: flex; align-items: center; gap: 7px; }+ .ramp-bar { flex: 1; height: 12px; border: 1px solid var(--border); border-radius: 3px; }+ .ramp-end { font-size: var(--fs-xs); color: var(--text-3); }++ .help {+ display: flex;+ align-items: flex-start;+ gap: 6px;+ margin: -2px 0 0;+ font-size: var(--fs-xs);+ line-height: 1.45;+ color: var(--text-3);+ }+ .help :global(svg) { flex: none; margin-top: 2px; opacity: 0.8; }++ /* `.mono` in app.css sizes itself at 0.92em of its *parent*, not of the input+ scale, so a code field and a mono input land a couple of points bigger than+ every control around them. Pinned back to the scale the form is written at. */+ .script,+ .field .input.mono { font-size: var(--fs-sm); }+ .script { resize: vertical; line-height: 1.5; white-space: pre; overflow-wrap: normal; }++ .actions { display: flex; gap: 8px; flex-wrap: wrap; }+ .hint { margin: 0; font-size: var(--fs-xs); color: var(--text-3); }+ .hint.warn { color: var(--warn); }++ @media (max-width: 620px) {+ .two, .three { grid-template-columns: 1fr; }+ }+</style>diff --git a/frontend/src/components/CustomLayerForm.test.js b/frontend/src/components/CustomLayerForm.test.jsnew file mode 100644index 0000000..030a54c--- /dev/null+++ b/frontend/src/components/CustomLayerForm.test.js@@ -0,0 +1,248 @@+// @vitest-environment happy-dom+import { afterEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import CustomLayerForm from './CustomLayerForm.svelte';+import { draftForm } from './customLayerForm.fixture.svelte.js';+import { compositeScript } from '../lib/layerScripts.js';++/**+ * The one form both Settings and the map picker open. What it must get right is+ * what a user cannot undo: a name already filed under something else, a script+ * the backend would refuse, a data source that cannot answer, and the+ * difference between a Preview the map can draw and a Save that changes what+ * every capture renders.+ *+ * The draft is the caller's object, not the form's, so these tests make one the+ * way the callers do and read it back afterwards.+ */++let live;+let target;+let form;++function open({+ layer = null,+ bases = ['TRUE_COLOR', 'SWIR'],+ bands = [],+ radarLayer = '',+ ...props+} = {}) {+ form = draftForm({ layer, bases, bands, radarLayer });+ target = document.createElement('div');+ document.body.append(target);+ live = mount(CustomLayerForm, {+ target,+ props: { form, bases, bands, onsave: vi.fn(), oncancel: vi.fn(), ...props },+ });+ flushSync();+ return target;+}++function reopen(props = {}) {+ unmount(live);+ live = null;+ target.remove();+ return open(props);+}++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+ form = null;+});++const button = (root, label) =>+ [...root.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));++it('opens on the composite form, which already renders something', () => {+ const root = open();+ // the SWIR composite the hot-spot panels are made of+ expect(root.querySelector('[aria-label="Red band"]').value).toBe('B12');+ expect(root.querySelector('textarea')).toBeNull();+ // nothing is saveable until it is named+ expect(button(root, 'Save layer').disabled).toBe(true);+});++it('names each band by what it sees, not just by its number', () => {+ const root = open({ bands: ['B11', 'B12'] });+ const options = [...root.querySelector('[aria-label="Red band"]').options].map((n) => n.text);+ // "B12" says nothing about why you would pick it; the wavelength does, and it+ // is how a figure's caption names it+ expect(options).toContain('B11 · Short-wave infrared 1 · 1.61 µm');+ expect(options).toContain('B12 · Short-wave infrared 2 · 2.19 µm');+});++it('never starts on the radar layer as a Sentinel-2 data source', () => {+ // a configuration that has one often lists it first, and a script reading+ // Sentinel-2 bands through it renders nothing at all+ open({ bases: ['RADAR', 'TRUE_COLOR'], radarLayer: 'RADAR' });+ expect(form.base).toBe('TRUE_COLOR'); // the layer every setup guide builds+});++it('falls back to a usable source when true colour is not configured', () => {+ open({ bases: ['RADAR', 'VEGETATION_INDEX'], radarLayer: 'RADAR' });+ expect(form.base).toBe('VEGETATION_INDEX');+});++it('explains every control rather than naming it', () => {+ const root = open();+ expect(root.textContent).toContain('needs multiplying to fill a channel');+ expect(root.textContent).toContain('satellite data this reads');+ button(root, 'Index').click();+ flushSync();+ expect(root.textContent).toContain('a number from −1 to 1');+ expect(root.textContent).toContain('picks its colour along that bar');+ expect(root.textContent).toContain('hides everything under it');+});++it('shows the ramp instead of only naming it', () => {+ const root = open();+ button(root, 'Index').click();+ flushSync();+ const bar = root.querySelector('.ramp-bar');+ expect(bar.getAttribute('aria-label')).toContain('Vegetation');+ expect(bar.getAttribute('style')).toContain('linear-gradient');+});++it('keeps an existing layer’s name and data source, since everything is filed under them', () => {+ const root = open({+ layer: {+ id: 'PLUME_SWIR', label: 'Plume', base: 'SWIR', hint: 'hot spots', script: '//VERSION=3',+ },+ });+ expect(root.querySelector('[aria-label="Layer name"]').disabled).toBe(true);+ expect(root.querySelector('[aria-label="Layer to read data from"]').disabled).toBe(true);+ expect(root.querySelector('textarea').value).toBe('//VERSION=3');+ expect(button(root, 'Save changes')).toBeDefined();+});++it('refuses a name the configuration already serves, and says so', () => {+ const root = open({ taken: ['SWIR'] });+ const name = root.querySelector('[aria-label="Layer name"]');+ name.value = 'SWIR';+ name.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+ expect(target.textContent).toContain('already a layer');+ expect(button(root, 'Save layer').disabled).toBe(true);+ expect(button(root, 'Save layer').title).toContain('already a layer');+});++it('lets the last action speak over what is still missing', () => {+ // a preview needs no name, so nagging for one would answer the wrong question+ const root = open({ onpreview: vi.fn(), note: 'Drawn on the map.' });+ expect(root.textContent).toContain('Drawn on the map.');+ expect(root.textContent).not.toContain('Name the layer.');+ // and Save still says why it cannot be pressed+ expect(button(root, 'Save layer').title).toBe('Name the layer.');+});++it('hands back what was typed, once it is saveable', () => {+ const onsave = vi.fn();+ const root = open({ onsave });+ const name = root.querySelector('[aria-label="Layer name"]');+ name.value = 'plume swir';+ name.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+ expect(name.value).toBe('PLUME_SWIR'); // typed into the only shape a name has+ button(root, 'Save layer').click();+ flushSync();+ expect(onsave).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'PLUME_SWIR', base: 'TRUE_COLOR' })+ );+});++it('only offers a preview where there is a map to draw it on', () => {+ expect(button(open(), 'Preview')).toBeUndefined();+ expect(button(reopen({ onpreview: vi.fn() }), 'Preview')).toBeDefined();+});++it('previews without a name, because nothing is being filed yet', () => {+ const onpreview = vi.fn();+ const root = open({ onpreview });+ expect(button(root, 'Preview').disabled).toBe(false);+ button(root, 'Preview').click();+ flushSync();+ const expected = compositeScript({ red: 'B12', green: 'B11', blue: 'B04' });+ expect(onpreview).toHaveBeenCalledWith(expect.objectContaining({ script: expected }));+});++it('will not send a script past the budget', () => {+ const root = open({ scriptMax: 20, onpreview: vi.fn() });+ button(root, 'Custom script').click();+ flushSync();+ const script = root.querySelector('textarea');+ script.value = 'x'.repeat(40);+ script.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+ expect(button(root, 'Preview').disabled).toBe(true);+ expect(target.textContent).toContain('40/20');+});++it('offers the bands the backend named, and falls back to the common ones', () => {+ const only = open({ bands: ['B02', 'B08'] });+ expect([...only.querySelector('[aria-label="Red band"]').options].map((n) => n.value)).toEqual([+ 'B02',+ 'B08',+ ]);+ // never an empty picker while the list is still being read+ const fallback = reopen();+ expect([...fallback.querySelector('[aria-label="Red band"]').options].length).toBeGreaterThan(3);+});++it('hands the generated script over on the way to Custom script', () => {+ // the arithmetic of each form is covered in lib/layerScripts.test.js; what is+ // worth pinning here is that leaving a form keeps what it wrote+ const root = open({ onpreview: vi.fn() });+ button(root, 'Custom script').click();+ flushSync();+ const carried = root.querySelector('textarea').value;+ expect(carried).toContain('//VERSION=3');+ expect(carried).toContain('2.5 * p.B12');+});++it('starts a composite or an index from the figures people publish', () => {+ const root = open();+ button(root, 'Natural').click();+ flushSync();+ expect(form.composite.red).toBe('B04');+ expect(form.hint).toBe('What the eye would see');++ button(root, 'Index').click();+ flushSync();+ button(root, 'NBR').click();+ flushSync();+ expect([form.index.high, form.index.low]).toEqual(['B08', 'B12']);+ expect(form.index.rampId).toBe('heat');+});++it('shows what an index is, and writes one', () => {+ const root = open({ onpreview: vi.fn() });+ button(root, 'Index').click();+ flushSync();+ expect(root.textContent).toContain('(A − B) / (A + B)');+ button(root, 'Custom script').click();+ flushSync();+ const script = root.querySelector('textarea').value;+ expect(script).toContain('(p.B08 - p.B04) / sum');+ expect(script).toContain('function colour(');+});++it('opens a saved layer on its script, not on a form that never wrote it', () => {+ const root = open({ layer: { id: 'X', base: 'TRUE_COLOR', script: '//VERSION=3\nmine\n' } });+ expect(root.querySelector('textarea').value).toBe('//VERSION=3\nmine\n');+ // and the forms are still there to start over from+ expect(button(root, 'Composite')).toBeDefined();+});++it('writes into the caller’s draft, so closing the form does not lose it', () => {+ const root = open();+ const label = root.querySelector('[aria-label="Label"]');+ label.value = 'SWIR plume';+ label.dispatchEvent(new Event('input', { bubbles: true }));+ button(root, 'Index').click();+ flushSync();+ // the caller holds this object and can hand it back to a fresh form+ expect(form.label).toBe('SWIR plume');+ expect(form.way).toBe('index');+});diff --git a/frontend/src/components/customLayerForm.fixture.svelte.js b/frontend/src/components/customLayerForm.fixture.svelte.jsnew file mode 100644index 0000000..77450d1--- /dev/null+++ b/frontend/src/components/customLayerForm.fixture.svelte.js@@ -0,0 +1,14 @@+/**+ * A reactive draft for the layer form's tests.+ *+ * The form mutates the object its caller hands it, and the callers hold that+ * object in `$state` — so a plain one from `startForm` would let every edit+ * land silently and the tests would watch a form that never moved. This wraps+ * it the way the callers do, which a `.test.js` file cannot.+ */+import { startForm } from '../lib/customLayers.js';++export function draftForm(options) {+ const form = $state(startForm(options));+ return form;+}diff --git a/frontend/src/lib/customLayers.js b/frontend/src/lib/customLayers.jsnew file mode 100644index 0000000..13c301d--- /dev/null+++ b/frontend/src/lib/customLayers.js@@ -0,0 +1,259 @@+/**+ * Copernicus layers written in Azimut rather than in the Copernicus dashboard.+ *+ * A layer is a *name* the rest of the app already carries everywhere — the+ * provider id, the tile cache, a capture's provenance — plus, here, a script+ * that says how to turn bands into pixels. What is new is only where the+ * rendering comes from; nothing downstream has to learn a new idea.+ *+ * A script renders through a **base layer**, which supplies the data+ * collection: an evalscript replaces a layer's style, never its source. That is+ * the arrangement the radar basemap has always used.+ *+ * Settings manages the list and the picker writes them, so both read this.+ * `engine/sentinel.py` owns the same rules on the backend.+ */++import { COMPOSITE_PRESETS, DEFAULT_GAIN, INDEX_PRESETS } from './layerScripts.js';++/** The shape every layer name has to hold: it is also a path segment and a+ * directory name, so it is an allowlist rather than something to escape. */+export const NAME_RE = /^[A-Z0-9_]{1,40}$/;++/** The name a layer being previewed renders under. It carries a digest of the+ * script, because the name is the tile cache's key (`engine/sentinel.py`). */+export const DRAFT_PREFIX = 'AZIMUT_DRAFT_';++export function isDraftLayer(id) {+ return String(id ?? '').startsWith(DRAFT_PREFIX);+}++/** Default script budget. The real figure comes from the backend+ * (`max_script`), which owns it; this is what a form starts with. */+export const SCRIPT_MAX = 4000;++/** What a name becomes as it is typed: the only characters a layer name holds. */+export function asName(text) {+ return String(text ?? '')+ .toUpperCase()+ .replace(/[^A-Z0-9_]+/g, '_')+ .replace(/^_+/, '')+ .slice(0, 40);+}++/**+ * Why this layer cannot be saved, in one clause, or '' when it can.+ *+ * @param {{id?: string, script?: string, base?: string}} draft+ * @param {{taken?: string[], scriptMax?: number}} [limits] `taken` is the names+ * already in use by something else, which saving over would silently change.+ */+export function layerProblem(draft, { taken = [], scriptMax = SCRIPT_MAX } = {}) {+ const name = String(draft?.id ?? '');+ if (!name) return 'Name the layer.';+ if (!NAME_RE.test(name)) return 'A name holds capitals, digits and underscores, up to 40.';+ if (taken.includes(name)) return 'That name is already a layer in your configuration.';+ if (!String(draft?.script ?? '').trim()) return 'Write the script.';+ if (String(draft.script).length > scriptMax) return `A script is at most ${scriptMax} characters.`;+ if (!NAME_RE.test(String(draft?.base ?? ''))) return 'Choose the layer to read through.';+ return '';+}++/**+ * Which configured layer a new script should read its data from.+ *+ * Not simply the first one on the list: a configuration that has a radar layer+ * often lists it first, and a Sentinel-2 script reading through it renders+ * nothing. True colour is the layer every setup guide builds, so it is the+ * answer whenever it is there.+ */+export function preferredBase(bases, radarLayer = '') {+ const usable = (bases ?? []).filter((id) => id && id !== radarLayer);+ return usable.find((id) => id === 'TRUE_COLOR') ?? usable[0] ?? 'TRUE_COLOR';+}++/** The layers a script can read its data from: the configured ones, less radar. */+export function dataSources(layers, radarLayer = '') {+ return (layers ?? [])+ .filter((entry) => !entry.custom && entry.id !== radarLayer)+ .map((entry) => entry.id);+}++/**+ * A layer being written, as the editor holds it while it is open.+ *+ * Owned by whoever opened the editor, not by the form, so closing the panel to+ * look at the map and reopening it keeps what was typed. The form reads and+ * mutates this object; it never starts a second one.+ */+export function startForm({ layer = null, bases = [], bands = [], radarLayer = '' } = {}) {+ const band = (wanted) => (bands.length && !bands.includes(wanted) ? bands[0] : wanted);+ const [red, green, blue] = COMPOSITE_PRESETS[0].bands;+ const first = INDEX_PRESETS[0];+ // How the layer was written, when a form wrote it. Without it a saved layer+ // could only reopen as JavaScript, including the ones nobody typed.+ const memo = layer?.form ?? null;+ return {+ // The layer this is an edit of, or '' for a new one. A saved layer keeps+ // its name, which is what every capture and cache is filed under.+ editing: layer?.id ?? '',+ id: layer?.id ?? '',+ label: layer?.label ?? '',+ hint: layer?.hint ?? '',+ base: layer?.base || preferredBase(bases, radarLayer),+ way: memo?.way ?? (layer ? 'script' : 'composite'),+ composite:+ memo?.way === 'composite'+ ? {+ red: band(memo.red),+ green: band(memo.green),+ blue: band(memo.blue),+ gain: memo.gain ?? DEFAULT_GAIN,+ }+ : { red: band(red), green: band(green), blue: band(blue), gain: DEFAULT_GAIN },+ index:+ memo?.way === 'index'+ ? {+ high: band(memo.high),+ low: band(memo.low),+ rampId: memo.ramp || first.rampId,+ threshold: memo.threshold ?? '',+ }+ : { high: band(first.high), low: band(first.low), rampId: first.rampId, threshold: '' },+ typed: layer?.script ?? '',+ };+}++/**+ * What a form wrote, as the layer remembers it — or null for a script somebody+ * typed, which has nothing to remember.+ *+ * An index is the one that earns its keep twice: it is also a quantity Detect+ * measures (a normalised difference of two bands), so the same arithmetic a+ * layer paints can be read as a rule.+ */+export function formMemo(form) {+ if (form?.way === 'composite') {+ const { red, green, blue, gain } = form.composite;+ return { way: 'composite', red, green, blue, gain: Number(gain) };+ }+ if (form?.way === 'index') {+ const { high, low, rampId, threshold } = form.index;+ const cut = threshold === '' || threshold === null || threshold === undefined+ ? null+ : Number(threshold);+ return { way: 'index', high, low, ramp: rampId, threshold: cut };+ }+ return null;+}++/**+ * Exactly the body the save route takes, and nothing else.+ *+ * The editor's draft holds more than a layer: which form is open, the text of+ * the other ways, the name it is an edit of. The route forbids what it does not+ * know (`CustomLayerIn`), and rightly — so the payload is spelled out here+ * rather than being whatever the draft happened to be carrying.+ * `tests/test_sentinel_custom_layers.py` reads this list.+ */+export function layerPayload(form, script) {+ return {+ id: form.id,+ label: form.label,+ base: form.base,+ hint: form.hint,+ script,+ form: formMemo(form),+ };+}++/**+ * A layer as a Detect rule, or null when it is not one quantity.+ *+ * A rule measures a number per pixel, so a layer comes over when what it paints+ * *is* a number. Two of the forms are:+ *+ * - an index, `(A − B) / (A + B)`, which is the `nd` measure exactly, so the+ * threshold the layer darkens below becomes the line the rule crosses;+ * - a composite that paints one band into all three channels — grey, not+ * colour — which is that band's reflectance, the `band` measure.+ *+ * A colour composite is three channels and no single number, and a hand-written+ * script is JavaScript nobody can read a quantity out of. `whyNotARule` says+ * which, so the menu can show the layer and the reason rather than hide it.+ */+export function layerAsRule(layer) {+ const memo = layer?.form;+ // `on` is left out on purpose: which dates a rule reads is the analyzer's+ // question, not the layer's.+ if (memo?.way === 'index' && memo.high && memo.low) {+ return { measure: 'nd', bands: [memo.high, memo.low], op: 'ge', value: memo.threshold ?? 0 };+ }+ if (memo?.way === 'composite' && memo.red && memo.red === memo.green && memo.green === memo.blue) {+ // No line comes with it: a grey band has a gain, which is how bright it is+ // drawn, never where the ground stops passing. The rule takes its own.+ return { measure: 'band', band: memo.red };+ }+ return null;+}++/**+ * Why this layer cannot become a rule, in one clause, or '' when it can.+ *+ * Said rather than hidden: a layer missing from the menu with no reason reads+ * as "rules cannot be built from my layers at all", which is the opposite of+ * what is true.+ */+export function whyNotARule(layer) {+ if (layerAsRule(layer)) return '';+ const memo = layer?.form;+ if (!memo) return 'written as a script, so no quantity to read';+ if (memo.way === 'composite') return 'three bands in colour, not one quantity';+ return 'nothing measurable in it';+}++/**+ * The arithmetic a layer turns into, in the menu's words, or '' when it is none.+ */+export function layerRuleWords(layer) {+ const rule = layerAsRule(layer);+ if (!rule) return '';+ if (rule.measure === 'band') return `${rule.band} reflectance`;+ const [high, low] = rule.bands;+ const line = layer.form.threshold == null ? '' : ` ≥ ${layer.form.threshold}`;+ return `(${high} − ${low}) / (${high} + ${low})${line}`;+}++/** The layers the list already holds, and what the editor is allowed to keep. */+export async function readCustomLayers(api) {+ const body = await api.get('/api/satellite/sentinel/custom-layers');+ return {+ layers: body.layers ?? [],+ max: body.max ?? 40,+ scriptMax: body.max_script ?? SCRIPT_MAX,+ bands: body.bands ?? [],+ radarLayer: body.radar_layer ?? '',+ };+}++export function saveCustomLayer(api, layer) {+ return api.put('/api/satellite/sentinel/custom-layers', layer);+}++export function deleteCustomLayer(api, ident) {+ return api.del(`/api/satellite/sentinel/custom-layers/${encodeURIComponent(ident)}`);+}++/**+ * Render a script before it is saved. The name comes back carrying a digest of+ * the script, so pressing Preview again after an edit fetches tiles instead of+ * serving the last attempt's from the disk cache.+ */+export async function previewLayer(api, { base, script }) {+ const body = await api.put('/api/satellite/sentinel/draft-layer', { base, script });+ return body.id;+}++export function clearPreview(api) {+ return api.del('/api/satellite/sentinel/draft-layer');+}diff --git a/frontend/src/lib/customLayers.test.js b/frontend/src/lib/customLayers.test.jsnew file mode 100644index 0000000..eb54866--- /dev/null+++ b/frontend/src/lib/customLayers.test.js@@ -0,0 +1,217 @@+import { expect, it } from 'vitest';+import { newRule } from './map/analyzerRules.js';+import {+ DRAFT_PREFIX,+ NAME_RE,+ asName,+ dataSources,+ formMemo,+ isDraftLayer,+ layerAsRule,+ layerPayload,+ layerProblem,+ layerRuleWords,+ preferredBase,+ startForm,+ whyNotARule,+} from './customLayers.js';++/**+ * A layer name is a URL path segment and a directory name on three operating+ * systems before it is anything else, so the rules here have to match+ * `engine/sentinel.py`'s allowlist exactly — the backend refuses what this lets+ * through, and a form that offers a name the save rejects is a dead end.+ */++it('types a name into the only shape a layer name has', () => {+ expect(asName('plume swir')).toBe('PLUME_SWIR');+ expect(asName('b12/b11 ratio')).toBe('B12_B11_RATIO');+ expect(asName(' leading')).toBe('LEADING');+ // the variant separator and traversal cannot survive being typed+ expect(asName('a~b')).toBe('A_B');+ expect(asName('../escape')).toBe('ESCAPE');+ expect(asName('x'.repeat(60))).toHaveLength(40);+ expect(NAME_RE.test(asName('é&plume'))).toBe(true);+});++it('says in one clause why a layer cannot be saved', () => {+ const ok = { id: 'PLUME', base: 'TRUE_COLOR', script: '//VERSION=3' };+ expect(layerProblem(ok)).toBe('');+ expect(layerProblem({ ...ok, id: '' })).toBe('Name the layer.');+ expect(layerProblem({ ...ok, id: 'plume' })).toContain('capitals');+ expect(layerProblem({ ...ok, script: ' ' })).toBe('Write the script.');+ expect(layerProblem({ ...ok, base: '' })).toContain('read through');+ expect(layerProblem({ ...ok, script: 'x'.repeat(50) }, { scriptMax: 10 })).toContain('10');+});++it('refuses a name the configuration already uses', () => {+ // saving over it would silently change what everything filed under that name+ // renders, captures included+ const problem = layerProblem(+ { id: 'SWIR', base: 'TRUE_COLOR', script: '//VERSION=3' },+ { taken: ['TRUE_COLOR', 'SWIR'] }+ );+ expect(problem).toContain('already a layer');+});++it('tells a layer being previewed from one that was kept', () => {+ expect(isDraftLayer(`${DRAFT_PREFIX}A1B2C3`)).toBe(true);+ expect(isDraftLayer('PLUME_SWIR')).toBe(false);+ expect(isDraftLayer(undefined)).toBe(false);+});++it('never reads Sentinel-2 bands through the radar layer', () => {+ // a configuration with radar often lists it first, and a script reading+ // through it renders nothing at all+ const configured = [{ id: 'RADAR' }, { id: 'TRUE_COLOR' }, { id: 'SWIR' }];+ expect(dataSources(configured, 'RADAR')).toEqual(['TRUE_COLOR', 'SWIR']);+ expect(preferredBase(['RADAR', 'SWIR', 'TRUE_COLOR'], 'RADAR')).toBe('TRUE_COLOR');+ // true colour is what every setup guide builds, so it wins over list order+ expect(preferredBase(['SWIR', 'TRUE_COLOR'])).toBe('TRUE_COLOR');+ // and without it, the first layer that can answer+ expect(preferredBase(['RADAR', 'VEGETATION_INDEX'], 'RADAR')).toBe('VEGETATION_INDEX');+ // nothing configured yet: the name the standard template ships+ expect(preferredBase([], 'RADAR')).toBe('TRUE_COLOR');+});++it('leaves a script out of what another script reads from', () => {+ const mixed = [{ id: 'TRUE_COLOR' }, { id: 'PLUME_SWIR', custom: true }];+ expect(dataSources(mixed)).toEqual(['TRUE_COLOR']);+});++it('starts a draft on a composite that already renders something', () => {+ const form = startForm({ bases: ['TRUE_COLOR'], bands: ['B04', 'B08', 'B11', 'B12'] });+ expect(form.way).toBe('composite');+ expect(form.composite).toMatchObject({ red: 'B12', green: 'B11', blue: 'B04' });+ expect(form.base).toBe('TRUE_COLOR');+ expect(form.editing).toBe('');+});++it('starts a draft of a saved layer on its script, keeping what it is filed as', () => {+ const form = startForm({+ layer: { id: 'PLUME', label: 'Plume', base: 'SWIR', hint: 'hot', script: '//VERSION=3' },+ bases: ['TRUE_COLOR', 'SWIR'],+ });+ // nothing records which form once wrote a saved layer+ expect(form.way).toBe('script');+ expect(form.typed).toBe('//VERSION=3');+ expect(form.editing).toBe('PLUME');+ expect(form.base).toBe('SWIR');+});++it('keeps a draft’s bands to what the instance actually carries', () => {+ // an instance that answered with a short list must not leave the form holding+ // a band it cannot ask for+ const form = startForm({ bands: ['B02', 'B03'] });+ expect(['B02', 'B03']).toContain(form.composite.red);+ expect(['B02', 'B03']).toContain(form.index.high);+});++it('sends the save route exactly the body it takes, and nothing else', () => {+ // the draft carries which form is open, the other ways' text and the name it+ // is an edit of; the route forbids what it does not know+ const form = startForm({ bases: ['TRUE_COLOR'] });+ form.id = 'PLUME_SWIR';+ form.label = 'SWIR plume';+ form.hint = 'hot spots';+ const body = layerPayload(form, '//VERSION=3');+ expect(Object.keys(body).sort()).toEqual(['base', 'form', 'hint', 'id', 'label', 'script']);+ expect(body).toMatchObject({ id: 'PLUME_SWIR', base: 'TRUE_COLOR', script: '//VERSION=3' });+});++it('remembers what a form said, so the layer does not reopen as JavaScript', () => {+ const form = startForm({ bases: ['TRUE_COLOR'] });+ expect(formMemo(form)).toEqual({+ way: 'composite', red: 'B12', green: 'B11', blue: 'B04', gain: 2.5,+ });++ form.way = 'index';+ form.index.threshold = 0.1;+ expect(formMemo(form)).toEqual({+ way: 'index', high: 'B08', low: 'B04', ramp: 'vegetation', threshold: 0.1,+ });+ // an empty threshold box is no threshold, not zero+ form.index.threshold = '';+ expect(formMemo(form).threshold).toBeNull();++ // a script somebody typed has nothing to remember+ form.way = 'script';+ expect(formMemo(form)).toBeNull();+});++it('reopens a saved layer on the form that wrote it', () => {+ const layer = {+ id: 'PLUME_SWIR',+ base: 'TRUE_COLOR',+ script: '//VERSION=3',+ form: { way: 'index', high: 'B12', low: 'B11', ramp: 'heat', threshold: 0.15 },+ };+ const form = startForm({ layer, bases: ['TRUE_COLOR'] });+ expect(form.way).toBe('index');+ expect(form.index).toEqual({ high: 'B12', low: 'B11', rampId: 'heat', threshold: 0.15 });+ // and one with no memo is JavaScript, which is all anyone can say about it+ expect(startForm({ layer: { ...layer, form: null } }).way).toBe('script');+});++it('reads an index layer as the Detect rule it already is', () => {+ // `(A − B) / (A + B)` is what a rule measures with `nd`, so the line the+ // layer paints with is the line the rule crosses+ const rule = layerAsRule({+ form: { way: 'index', high: 'B12', low: 'B11', ramp: 'heat', threshold: 0.15 },+ });+ expect(rule).toEqual({ measure: 'nd', bands: ['B12', 'B11'], op: 'ge', value: 0.15 });++ // an index with no threshold still reads, from zero+ expect(layerAsRule({ form: { way: 'index', high: 'B08', low: 'B04' } }).value).toBe(0);+});++it('reads a band painted grey as the band rule it already is', () => {+ // the same band in all three channels is not a colour, it is that band's+ // reflectance — which the engine measures as `band`+ const grey = { form: { way: 'composite', red: 'B12', green: 'B12', blue: 'B12', gain: 2.5 } };+ expect(layerAsRule(grey)).toEqual({ measure: 'band', band: 'B12' });+ // and it brings no line: the gain is how bright it is drawn, not a threshold+ expect(newRule('band', 'b', { band: 'B12' })).toMatchObject({ op: 'ge', value: 0.25 });+});++it('refuses to invent a rule out of what is not one quantity', () => {+ // three different channels are not a number, and JavaScript is not readable as one+ expect(layerAsRule({ form: { way: 'composite', red: 'B12', green: 'B11', blue: 'B04' } })).toBeNull();+ expect(layerAsRule({ form: { way: 'composite', red: 'B12' } })).toBeNull();+ expect(layerAsRule({ form: null })).toBeNull();+ expect(layerAsRule({})).toBeNull();+});++it('says why a layer cannot become a rule rather than leaving it out', () => {+ // the menu shows every layer, so each one that cannot come over carries why+ expect(whyNotARule({ form: { way: 'index', high: 'B12', low: 'B11' } })).toBe('');+ expect(whyNotARule({ form: { way: 'composite', red: 'B12', green: 'B12', blue: 'B12' } })).toBe('');+ expect(whyNotARule({ form: { way: 'composite', red: 'B12', green: 'B11', blue: 'B04' } }))+ .toBe('three bands in colour, not one quantity');+ expect(whyNotARule({ form: null })).toContain('script');+});++it('says the arithmetic a layer turns into', () => {+ expect(layerRuleWords({ form: { way: 'index', high: 'B12', low: 'B11', threshold: 0.15 } }))+ .toBe('(B12 − B11) / (B12 + B11) ≥ 0.15');+ expect(layerRuleWords({ form: { way: 'index', high: 'B08', low: 'B04', threshold: null } }))+ .toBe('(B08 − B04) / (B08 + B04)');+ expect(layerRuleWords({ form: { way: 'composite', red: 'B12', green: 'B12', blue: 'B12' } }))+ .toBe('B12 reflectance');+ expect(layerRuleWords({ form: null })).toBe('');+});++it('becomes a whole rule the engine accepts, with the analyzer deciding the dates', () => {+ const layer = { form: { way: 'index', high: 'B12', low: 'B11', threshold: 0.15 } };+ const { measure, ...line } = layerAsRule(layer);+ // what the builder does: the layer brings the quantity and the line, the+ // analyzer brings which dates it is read on+ const rule = newRule(measure, 'b', line);+ expect(rule).toMatchObject({+ measure: 'nd', bands: ['B12', 'B11'], on: 'b', op: 'ge', value: 0.15, around: 0,+ });+ // and the fields the engine's model needs are all there+ for (const key of ['index', 'band', 'polarisation', 'classes', 'upper']) {+ expect(rule).toHaveProperty(key);+ }+});diff --git a/frontend/src/lib/figures.js b/frontend/src/lib/figures.jsnew file mode 100644index 0000000..3f88b19--- /dev/null+++ b/frontend/src/lib/figures.js@@ -0,0 +1,17 @@+/**+ * Figures: the same ground on one day, through several layers.+ *+ * The layout and the wording belong to the backend (`engine/figures.py`), which+ * writes the Geo Proof. What the browser needs is the shape of the request, so+ * the dialog can stop a figure the route would refuse rather than render four+ * panels and then fail.+ *+ * These two numbers mirror the engine's. `tests/test_figures.py` reads this+ * file and fails if they drift.+ */++/** Panels a figure may hold. Past this it is a contact sheet, not a figure. */+export const MAX_PANELS = 8;++/** Panels per row, which is what the published figures this was built for use. */+export const DEFAULT_PER_ROW = 2;diff --git a/frontend/src/lib/layerScripts.js b/frontend/src/lib/layerScripts.jsnew file mode 100644index 0000000..41188c0--- /dev/null+++ b/frontend/src/lib/layerScripts.js@@ -0,0 +1,275 @@+/**+ * Scripts written from a form instead of by hand.+ *+ * Copernicus Browser has three ways to make a layer and so does this: three+ * bands on red, green and blue; one normalised difference on a colour ramp; or+ * JavaScript. The first two are the ones people actually reach for, and neither+ * is worth typing out — but both produce a script, not a special kind of layer,+ * so everything downstream stays one idea. The generated text is the text the+ * editor shows, so switching to Custom script hands over something readable+ * that can then be taken anywhere.+ *+ * `evaluatePixel` always returns `dataMask` as the fourth channel: where the+ * pass has no pixels the tile must be transparent, so a hole reads as a hole+ * rather than as black ground.+ */++/** The gain a reflectance band needs to fill a channel. Copernicus's own+ * examples use 2.5, and so does every composite in their gallery. */+export const DEFAULT_GAIN = 2.5;++/**+ * What each Sentinel-2 L2A band sees, and at what wavelength.+ *+ * "B12" says nothing about why you would pick it; "SWIR 2 · 2.19 µm" does, and+ * it is also how a figure's caption names it ("B11 hotspot 1.61 µm"). Central+ * wavelengths are Sentinel-2A's. B10 is absent because the atmospheric+ * correction consumes it and Level-2A does not carry it.+ */+export const BANDS = Object.freeze({+ B01: { label: 'Coastal aerosol', um: 0.443 },+ B02: { label: 'Blue', um: 0.49 },+ B03: { label: 'Green', um: 0.56 },+ B04: { label: 'Red', um: 0.665 },+ B05: { label: 'Red edge 1', um: 0.705 },+ B06: { label: 'Red edge 2', um: 0.74 },+ B07: { label: 'Red edge 3', um: 0.783 },+ B08: { label: 'Near infrared', um: 0.842 },+ B8A: { label: 'Near infrared, narrow', um: 0.865 },+ B09: { label: 'Water vapour', um: 0.945 },+ B11: { label: 'Short-wave infrared 1', um: 1.61 },+ B12: { label: 'Short-wave infrared 2', um: 2.19 },+});++/** A band as a picker row reads it: "B12 · SWIR 2 · 2.19 µm". */+export function bandLabel(id) {+ const known = BANDS[id];+ return known ? `${id} · ${known.label} · ${known.um} µm` : id;+}++/** The same, short enough for a readout beside a slider. */+export function bandShort(id) {+ const known = BANDS[id];+ return known ? `${id} · ${known.um} µm` : id;+}++/** Colour ramps, as value→RGB stops over a normalised difference (−1…1). */+export const RAMPS = Object.freeze([+ {+ id: 'grey',+ label: 'Greyscale',+ stops: [[-1, [0, 0, 0]], [1, [1, 1, 1]]],+ },+ {+ id: 'vegetation',+ label: 'Vegetation',+ stops: [+ [-0.2, [0.05, 0.05, 0.05]],+ [0, [0.75, 0.72, 0.68]],+ [0.3, [0.9, 0.85, 0.3]],+ [0.6, [0.2, 0.6, 0.2]],+ [0.9, [0, 0.27, 0]],+ ],+ },+ {+ id: 'water',+ label: 'Water',+ stops: [+ [-0.5, [0.72, 0.66, 0.52]],+ [0, [0.85, 0.82, 0.72]],+ [0.2, [0.4, 0.68, 0.84]],+ [0.6, [0.1, 0.33, 0.68]],+ [1, [0.02, 0.1, 0.35]],+ ],+ },+ {+ id: 'heat',+ label: 'Heat',+ stops: [+ [-0.2, [0.02, 0.02, 0.06]],+ [0.1, [0.4, 0.05, 0.3]],+ [0.4, [0.85, 0.2, 0.1]],+ [0.7, [0.98, 0.72, 0.1]],+ [1, [1, 1, 0.85]],+ ],+ },+ {+ id: 'divergent',+ label: 'Loss to gain',+ stops: [+ [-1, [0.7, 0.1, 0.1]],+ [-0.1, [0.92, 0.6, 0.5]],+ [0, [0.96, 0.96, 0.96]],+ [0.1, [0.5, 0.75, 0.55]],+ [1, [0.05, 0.4, 0.15]],+ ],+ },+]);++export function ramp(id) {+ return RAMPS.find((entry) => entry.id === id) ?? RAMPS[0];+}++/**+ * A ramp as a CSS gradient, so the form can show the colours instead of naming+ * them. The stops run over −1…1, which is where a normalised difference lives,+ * and the bar is drawn across that whole range so two ramps can be compared.+ */+export function rampGradient(id) {+ const stops = ramp(id).stops;+ const at = (value) => Math.round(((Number(value) + 1) / 2) * 1000) / 10;+ const parts = stops.map(+ ([value, [r, g, b]]) =>+ `rgb(${Math.round(r * 255)} ${Math.round(g * 255)} ${Math.round(b * 255)}) ${at(value)}%`+ );+ return `linear-gradient(to right, ${parts.join(', ')})`;+}++/** The bands a script asks for, each once, with the nodata mask last. */+function inputs(bands) {+ return [...new Set(bands.filter(Boolean)), 'dataMask'].map((band) => `"${band}"`).join(', ');+}++/** A number as JavaScript, without a float's trailing noise. */+function num(value) {+ return String(Math.round(Number(value) * 1000) / 1000);+}++/**+ * Three bands as colour.+ *+ * @param {{red: string, green: string, blue: string, gain?: number}} choice+ */+export function compositeScript({ red, green, blue, gain = DEFAULT_GAIN } = {}) {+ const bands = [red, green, blue];+ const factor = num(gain);+ const channels = bands.map((band) => `${factor} * p.${band}`).join(', ');+ const same = new Set(bands).size === 1;+ return `//VERSION=3+// ${same ? `${red} alone, as grey` : `${red} → red, ${green} → green, ${blue} → blue`}.+// Gain ${factor}: reflectance is 0…1 and a channel needs filling.+function setup() {+ return {+ input: [${inputs(bands)}],+ output: { bands: 4 },+ };+}+function evaluatePixel(p) {+ // dataMask last: no pass here has to read as a hole, not as black ground+ return [${channels}, p.dataMask];+}+`;+}++/**+ * One normalised difference on a colour ramp.+ *+ * @param {{high: string, low: string, rampId?: string, threshold?: number|null}} choice+ * `threshold` darkens everything at or below it, which is how a hotspot or a+ * burn is read off a ramp without guessing where the colour changes.+ */+export function indexScript({ high, low, rampId = 'grey', threshold = null } = {}) {+ const chosen = ramp(rampId);+ const stops = chosen.stops+ .map(([at, [r, g, b]]) => ` [${num(at)}, [${num(r)}, ${num(g)}, ${num(b)}]],`)+ .join('\n');+ const cut = threshold === null || threshold === undefined || threshold === '' ? null : num(threshold);+ return `//VERSION=3+// (${high} − ${low}) / (${high} + ${low}), on the ${chosen.label.toLowerCase()} ramp.+${cut === null ? '' : `// Everything at or below ${cut} is left dark.\n`}function setup() {+ return {+ input: [${inputs([high, low])}],+ output: { bands: 4 },+ };+}+const stops = [+${stops}+];+// The colour of the last stop this value has reached.+function colour(value) {+ let found = stops[0][1];+ for (const [at, rgb] of stops) if (value >= at) found = rgb;+ return found;+}+function evaluatePixel(p) {+ const sum = p.${high} + p.${low};+ const index = sum === 0 ? 0 : (p.${high} - p.${low}) / sum;+${cut === null ? '' : ` if (index <= ${cut}) return [0.04, 0.04, 0.04, p.dataMask];\n`} const [r, g, b] = colour(index);+ return [r, g, b, p.dataMask];+}+`;+}++/**+ * The visible bands averaged, as grey.+ *+ * What a `brightness` rule measures, drawn. Its own generator rather than a+ * composite of the three, because a composite puts each band on its own channel+ * — which is true colour, not the one number the rule reads.+ */+export function brightnessScript({ gain = DEFAULT_GAIN } = {}) {+ const factor = num(gain);+ return `//VERSION=3+// B02, B03 and B04 averaged, as grey.+// Gain ${factor}: reflectance is 0…1 and a channel needs filling.+function setup() {+ return {+ input: [${inputs(['B02', 'B03', 'B04'])}],+ output: { bands: 4 },+ };+}+function evaluatePixel(p) {+ const mean = (p.B02 + p.B03 + p.B04) / 3;+ // dataMask last: no pass here has to read as a hole, not as black ground+ return [${factor} * mean, ${factor} * mean, ${factor} * mean, p.dataMask];+}+`;+}++/** The three ways to make one, in the order Copernicus Browser offers them. */+export const WAYS = Object.freeze([+ {+ id: 'composite',+ label: 'Composite',+ hint: 'Put three bands on red, green and blue, like a false-colour image',+ },+ {+ id: 'index',+ label: 'Index',+ hint: 'Measure one difference between two bands and colour it',+ },+ {+ id: 'script',+ label: 'Custom script',+ hint: 'Write the evalscript yourself, or edit what the forms wrote',+ },+]);++/**+ * Composites worth starting from, as the figures people publish use them.+ * Offered as presses rather than defaults: the form opens on the first.+ */+export const COMPOSITE_PRESETS = Object.freeze([+ { id: 'swir', label: 'SWIR', hint: 'Hot ground and burn scars', bands: ['B12', 'B11', 'B04'] },+ { id: 'natural', label: 'Natural', hint: 'What the eye would see', bands: ['B04', 'B03', 'B02'] },+ { id: 'infrared', label: 'Infrared', hint: 'Vegetation in red', bands: ['B08', 'B04', 'B03'] },+ { id: 'agriculture', label: 'Agriculture', hint: 'Crop vigour and bare soil', bands: ['B11', 'B08', 'B02'] },+]);++/**+ * Indices worth starting from: the named ones Detect already measures, so the+ * two tools read the same arithmetic off the same pairs.+ */+export const INDEX_PRESETS = Object.freeze([+ { id: 'ndvi', label: 'NDVI', hint: 'Vegetation', high: 'B08', low: 'B04', rampId: 'vegetation' },+ { id: 'ndwi', label: 'NDWI', hint: 'Open water', high: 'B03', low: 'B08', rampId: 'water' },+ { id: 'nbr', label: 'NBR', hint: 'Burn severity', high: 'B08', low: 'B12', rampId: 'heat' },+ { id: 'ndbi', label: 'NDBI', hint: 'Built-up ground', high: 'B11', low: 'B08', rampId: 'grey' },+]);++/** The script a form's state says, for whichever way is open. */+export function scriptFor(way, choice) {+ if (way === 'composite') return compositeScript(choice.composite);+ if (way === 'index') return indexScript(choice.index);+ return choice.script;+}diff --git a/frontend/src/lib/layerScripts.test.js b/frontend/src/lib/layerScripts.test.jsnew file mode 100644index 0000000..5bb6031--- /dev/null+++ b/frontend/src/lib/layerScripts.test.js@@ -0,0 +1,115 @@+import { expect, it } from 'vitest';+import {+ DEFAULT_GAIN,+ RAMPS,+ WAYS,+ compositeScript,+ indexScript,+ ramp,+ scriptFor,+} from './layerScripts.js';++/**+ * The Composite and Index forms do not make a different kind of layer: they+ * write the script a Custom one would have been typed as. So what matters is+ * the text — that it is a valid evalscript, that it says what the form said,+ * and that it keeps the nodata mask, without which a hole in the pass renders+ * as black ground and reads as burnt or flooded.+ */++const valid = (script) => {+ expect(script.startsWith('//VERSION=3')).toBe(true);+ expect(script).toContain('function setup()');+ expect(script).toContain('function evaluatePixel(');+ expect(script).toContain('output: { bands: 4 }');+ expect(script).toContain('p.dataMask');+};++it('writes three bands onto three channels', () => {+ const script = compositeScript({ red: 'B12', green: 'B11', blue: 'B04' });+ valid(script);+ expect(script).toContain('input: ["B12", "B11", "B04", "dataMask"]');+ expect(script).toContain(`return [${DEFAULT_GAIN} * p.B12, ${DEFAULT_GAIN} * p.B11, ${DEFAULT_GAIN} * p.B04, p.dataMask]`);+ expect(script).toContain('B12 → red');+});++it('asks for a band once, however many channels read it', () => {+ // a single band on all three is grey, and Sentinel Hub refuses a repeated input+ const script = compositeScript({ red: 'B11', green: 'B11', blue: 'B11' });+ expect(script).toContain('input: ["B11", "dataMask"]');+ expect(script).toContain('B11 alone, as grey');+ expect(script).toContain('p.B11, 2.5 * p.B11, 2.5 * p.B11');+});++it('carries the gain, without a float’s trailing noise', () => {+ expect(compositeScript({ red: 'B04', green: 'B03', blue: 'B02', gain: 1.1 })).toContain('1.1 * p.B04');+ expect(compositeScript({ red: 'B04', green: 'B03', blue: 'B02', gain: 3 })).toContain('3 * p.B04');+});++it('writes a normalised difference, guarded against a zero sum', () => {+ const script = indexScript({ high: 'B08', low: 'B04', rampId: 'vegetation' });+ valid(script);+ expect(script).toContain('input: ["B08", "B04", "dataMask"]');+ expect(script).toContain('const sum = p.B08 + p.B04;');+ // two dark bands over water sum to zero, and a NaN would paint the first stop+ expect(script).toContain('sum === 0 ? 0 : (p.B08 - p.B04) / sum');+ expect(script).toContain('(B08 − B04) / (B08 + B04)');+});++it('puts the chosen ramp’s stops in the script, and names it', () => {+ const script = indexScript({ high: 'B08', low: 'B04', rampId: 'heat' });+ expect(script).toContain('on the heat ramp');+ for (const [at] of ramp('heat').stops) expect(script).toContain(`[${at},`);+ expect(script).toContain('function colour(');+});++it('leaves the ramp whole unless a threshold is asked for', () => {+ const whole = indexScript({ high: 'B08', low: 'B04' });+ expect(whole).not.toContain('left dark');+ expect(whole).not.toContain('index <=');++ const cut = indexScript({ high: 'B12', low: 'B11', threshold: 0.1 });+ expect(cut).toContain('at or below 0.1 is left dark');+ expect(cut).toContain('if (index <= 0.1) return [0.04, 0.04, 0.04, p.dataMask];');+});++it('treats an empty threshold box as no threshold', () => {+ // the form's number input hands back '' when it is cleared+ for (const nothing of ['', null, undefined]) {+ expect(indexScript({ high: 'B08', low: 'B04', threshold: nothing })).not.toContain('index <=');+ }+ // and zero is a threshold, not an absence+ expect(indexScript({ high: 'B08', low: 'B04', threshold: 0 })).toContain('index <= 0)');+});++it('offers the three ways in, and an unknown ramp falls back rather than breaking', () => {+ expect(WAYS.map((way) => way.id)).toEqual(['composite', 'index', 'script']);+ expect(ramp('nonsense')).toBe(RAMPS[0]);+ for (const entry of RAMPS) {+ expect(entry.stops.length).toBeGreaterThan(1);+ // stops run upward, or `colour` would never reach the later ones+ const ats = entry.stops.map(([at]) => at);+ expect([...ats].sort((one, other) => one - other)).toEqual(ats);+ for (const [, rgb] of entry.stops) {+ expect(rgb).toHaveLength(3);+ for (const channel of rgb) expect(channel).toBeGreaterThanOrEqual(0);+ for (const channel of rgb) expect(channel).toBeLessThanOrEqual(1);+ }+ }+});++it('hands over whichever way is open', () => {+ const state = {+ composite: { red: 'B12', green: 'B11', blue: 'B04' },+ index: { high: 'B08', low: 'B04' },+ script: '//VERSION=3\nmine\n',+ };+ expect(scriptFor('composite', state)).toContain('p.B12');+ expect(scriptFor('index', state)).toContain('const sum');+ expect(scriptFor('script', state)).toBe('//VERSION=3\nmine\n');+});++it('stays well inside the script budget, whatever the form says', () => {+ const longest = indexScript({ high: 'B8A', low: 'B12', rampId: 'divergent', threshold: -0.35 });+ expect(longest.length).toBeLessThan(2000);+});diff --git a/frontend/src/lib/map/analyzerRules.js b/frontend/src/lib/map/analyzerRules.jsindex e3b3e1a..df873bf 100644--- a/frontend/src/lib/map/analyzerRules.js+++ b/frontend/src/lib/map/analyzerRules.js@@ -776,6 +776,95 @@ export function suggestedLayer(rule, layers = []) {return firstOf(wanted, ids) ?? fallback;}+/**+ * Whether a reading crosses a rule's line.+ *+ * The mirror of `detect_rules._passes`, and it has to stay the mirror: it is+ * what repaints the ground while the slider moves, against the very readings+ * the last test made. `tests/test_detect_rules.py` proves the two agree pixel+ * for pixel at several lines; if this drifts, the line gets set against a+ * picture that lies.+ */+export function passesValue(rule, value) {+ if (rule.op === 'ge') return value >= rule.value;+ if (rule.op === 'le') return value <= rule.value;+ if (rule.op === 'between') return value >= rule.value && value <= rule.upper;+ return Math.abs(value) >= rule.value;+}++/**+ * One rule's bit redrawn through the mask, from the reading the engine sent.+ *+ * Every other rule's bit, the measured bit and the kept bit are left exactly as+ * the test wrote them: only the line of this rule moved, so only its own ground+ * may change. Unmeasured ground carries no reading and stays out.+ *+ * @param {Uint8Array} bits the tile's mask, one byte a pixel+ * @param {number} index which rule's bit to redraw+ * @param {Float64Array|number[]} values that rule's reading, pixel for pixel+ */+export function redrawRule(bits, index, values, rule) {+ const out = new Uint8Array(bits);+ const bit = 1 << index;+ const seen = 1 << MEASURED_BIT;+ for (let p = 0; p < out.length; p++) {+ if (!(out[p] & seen)) continue;+ if (passesValue(rule, values[p])) out[p] |= bit;+ else out[p] &= ~bit;+ }+ return out;+}++/** The share of the measured ground a redrawn rule keeps, 0 to 1. */+export function shareOf(masks, index) {+ let seen = 0;+ let kept = 0;+ const bit = 1 << index;+ const measured = 1 << MEASURED_BIT;+ for (const bits of masks) {+ for (let p = 0; p < bits.length; p++) {+ if (!(bits[p] & measured)) continue;+ seen++;+ if (bits[p] & bit) kept++;+ }+ }+ return seen ? kept / seen : 0;+}++/**+ * What a rule reads, apart from where its line sits.+ *+ * The reading the engine sends answers for the bands, the dates and the context+ * — never for the threshold, which is the point. Two recipes with the same+ * reading key can share one download; a change to this key drops it.+ */+export function readingKey(rule) {+ return [rule.measure, rule.index, ...rule.bands, rule.band, rule.polarisation,+ [...(rule.classes ?? [])].sort().join('+'), rule.on, rule.around].join('|');+}++/** Each rule as what it reads and where its line sits, kept apart. */+export function linesOf(recipe) {+ return (recipe?.rules ?? []).map((rule) => ({+ key: readingKey(rule),+ line: [rule.op, rule.value, rule.upper].join('|'),+ }));+}++/**+ * What the suggested display layer lets you see, in the words of the data the+ * ranking rule reads — "shows B11 · B12".+ *+ * Not "for rule ★": the star is at the other end of the screen, so naming it+ * sends the reader hunting for what it means. The bands say it on the spot.+ */+export function suggestedWords(rule) {+ const bands = ruleBands(rule);+ if (bands.length) return `shows ${bands.join(' · ')}`;+ if (rule?.measure === 'class') return 'shows the ground classes';+ return '';+}+// -- pins on a rule's line -----------------------------------------------------------const unit = (value) => Math.max(0, Math.min(1, value));diff --git a/frontend/src/lib/map/bench.svelte.js b/frontend/src/lib/map/bench.svelte.jsindex 9b68614..bb46fc5 100644--- a/frontend/src/lib/map/bench.svelte.js+++ b/frontend/src/lib/map/bench.svelte.js@@ -23,10 +23,12 @@ import { clone, viewZone } from './analyzers.js';import { canPickPass } from './detectWhen.js';import { isoDay } from '../sentinel.js';import { availableDisplayLayer, displayLayers, DISPLAY_LAYERS } from '../sentinelLayers.js';+import { clearPreview, dataSources, isDraftLayer, preferredBase, previewLayer } from '../customLayers.js';+import { ruleLayerScript } from './ruleLayer.js';import {RULE_COLOURS, checkDated, checkKey, datesOf, markOutcomes, marksBounds, newCheck, passSource, readingRecipe,- readsOneDate, readsRadar, recipeBands, recipeProblem, sensorOf, signalOf, signature, suggestedLayer, testedCheck,- withFlippedMark, withMark, withoutMark,+ readsOneDate, readsRadar, recipeBands, recipeProblem, sensorOf, signalOf, signature, suggestedLayer,+ linesOf, readingKey, suggestedWords, testedCheck, withFlippedMark, withMark, withoutMark,} from './analyzerRules.js';/** A lookup looks at the ground round the middle of the map, never a whole country. */@@ -73,10 +75,37 @@ export class Bench {basemap = $state(false);layer = $state('TRUE_COLOR');displayNotice = $state('');+ /**+ * A rule drawn as imagery: `{ index, id, back }`, or null.+ *+ * `id` is a draft layer, which is deliberately never in `offered` — it is+ * scratch, kept out of every picker and out of the settings backup. So it is+ * held here rather than in `layer`, which stays the display the analyst chose+ * and comes back when the rule is let go of.+ */+ ruleLayer = $state(null);+ ruleLayerBusy = $state(false);+ /**+ * Per rule index, what that rule read over the whole ground, as the engine+ * sent it: `{ key, low, high, steps, size, tiles }`.+ *+ * A test sends a verdict, which answers whether the line is crossed and never+ * where it should be. With the reading in hand the browser applies the same+ * comparison itself, so the ground repaints as the slider moves and nothing+ * is asked again. One rule at a time, and only once its slider is touched:+ * every rule of every tile would be tens of megabytes on a press nobody made.+ */+ readings = $state({});+ readingBusy = $state(null);/** Where the split sits, as a percentage of the map from its left edge. */divider = $state(50);/** What the map paints: each rule's pixels, or the detections alone. */view = $state('rules');+ /** Display choices for this builder session, independent of the recipe and its tests. */+ hideOverlays = $state(false);+ markers = $state(true);+ outlines = $state(true);+ checkPins = $state(true);/** Per rule, whether its pixels are painted. One added since the last toggle is shown. */shown = $state([]);hover = $state(null);@@ -130,6 +159,9 @@ export class Bench {destroy() {this.#gone = true;this.#dispose?.();+ // The draft is this machine's scratch work and only one is kept, so leaving+ // it behind would have the next preview serve it from the tile cache.+ if (this.ruleLayer) void clearPreview(this.#api).catch(() => {});}// -- what is being built ---------------------------------------------------------@@ -161,7 +193,10 @@ export class Bench {const state = this.#layerState();if (!state || this.radar) return '';if (state.layersSource !== 'instance') return 'Check your Copernicus layers before testing.';- return state.layers.some((entry) => entry.id === 'TRUE_COLOR') ? ''+ // A rule reads band products, not the display layer, so what it needs is a+ // layer the *instance* serves to read them through. One written here is a+ // script over a base layer and cannot stand in for it.+ return state.layers.some((entry) => entry.id === 'TRUE_COLOR' && !entry.custom) ? '': 'Optical rules need a Sentinel-2 L2A layer named TRUE_COLOR.';}checkLayers(force = false) {@@ -323,7 +358,7 @@ export class Bench {dropPin({ lon: x, lat: y }) {if (!this.check || !this.pinning || this.choosingPasses) return;- const most = this.#limits.max_marks ?? 20;+ const most = this.#limits.max_marks ?? 60;if (this.marks.length >= most) {this.#say(`A check holds at most ${most} pins.`, 'warn');return;@@ -345,15 +380,21 @@ export class Bench {*/get imagery() {const check = this.check;+ const shown = this.shownLayer;if (!check || this.basemap || !check.b?.date) return { mode: 'basemap' };- if (!this.radar && !this.offered.some((entry) => entry.id === this.layer && entry.enabled !== false)) return { mode: 'basemap' };- const after = { ...check.b, layer: this.layer };- const before = this.single || !check.a?.date ? null : { ...check.a, layer: this.layer };+ // A drawn rule is a draft, which is never offered: it is checked for by name.+ if (!this.radar && !isDraftLayer(shown)+ && !this.offered.some((entry) => entry.id === shown && entry.enabled !== false)) return { mode: 'basemap' };+ const after = { ...check.b, layer: shown };+ const before = this.single || !check.a?.date ? null : { ...check.a, layer: shown };const shape = (source) => (this.radar ? { provider: 'sentinel1', date: source.date, time: source.time ?? '' }- : { provider: 'sentinel2', date: source.date, layer: this.layer });+ : { provider: 'sentinel2', date: source.date, layer: shown });return before ? { mode: 'swipe', a: shape(before), b: shape(after) } : { mode: 'single', b: shape(after) };}+ /** The layer on the map: a rule being drawn, else the display that was chosen. */+ get shownLayer() { return this.ruleLayer?.id ?? this.layer; }+/** Whether the map is split between the two passes. */get split() { return this.imagery.mode === 'swipe'; }@@ -361,6 +402,8 @@ export class Bench {setLayer(id) {if (!this.offered.some((entry) => entry.id === id && entry.enabled !== false)) return;+ // Choosing a display is choosing what the map draws, so it ends a drawn rule.+ this.hideRule();this.layer = id;this.displayNotice = '';this.basemap = false;@@ -369,12 +412,49 @@ export class Bench {b: check.b?.date ? { ...check.b, layer: id } : check.b }));}+ /**+ * Draw a rule's own arithmetic on the map, instead of a layer that merely+ * shows its bands well.+ *+ * It renders through the ordinary draft-preview path, so the tiles cache and+ * resolve exactly as a layer written by hand does. It costs what any unseen+ * display layer costs: the tiles the viewport asks for.+ */+ async showRule(index) {+ const script = ruleLayerScript(this.#recipe.rules[index]);+ if (!script || this.radar || this.ruleLayerBusy) return;+ if (this.ruleLayer?.index === index) return this.hideRule();+ this.ruleLayerBusy = true;+ try {+ const bases = dataSources(this.offered, this.#radarLayer());+ const id = await previewLayer(this.#api, {+ base: preferredBase(bases, this.#radarLayer()), script,+ });+ if (this.#gone) return;+ this.ruleLayer = { index, id, back: this.ruleLayer?.back ?? this.layer };+ this.basemap = false;+ } catch (error) {+ if (!this.#gone) this.#say(error.message || 'That rule could not be drawn', 'bad');+ } finally {+ this.ruleLayerBusy = false;+ }+ }++ /** Let the drawn rule go, and put the chosen display back. */+ hideRule() {+ if (!this.ruleLayer) return;+ this.ruleLayer = null;+ void clearPreview(this.#api).catch(() => {});+ }+/** The layer that shows best what the ranking rule reads, among those offered. */#suggested() {return suggestedLayer(this.#recipe.rules[Math.max(0, signalOf(this.#recipe))], this.offered);}#adoptLayer(check) {+ // Another check, another ground: a rule drawn over the last one is let go of.+ this.ruleLayer = null;const own = check.b?.layer;this.layer = availableDisplayLayer(own || this.#suggested(), this.offered) || own || this.#suggested();this.displayNotice = own && own !== this.layer ? `${own} is unavailable; showing ${this.layer}.` : '';@@ -382,6 +462,11 @@ export class Bench {get suggestion() { return this.#suggested(); }+ /** What that layer shows, said as the bands the ranking rule reads. */+ get suggestionWords() {+ return suggestedWords(this.#recipe.rules[Math.max(0, signalOf(this.#recipe))]);+ }+// -- what each rule paints -------------------------------------------------------isShown(index) { return this.shown[index] ?? true; }@@ -389,6 +474,49 @@ export class Bench {/** Whether a rule's pixels are on the map now: the eye is open and the map shows rules. */painted(index) { return this.view === 'rules' && this.isShown(index); }+ /** What a reading answers for: the check it was read on, and what the rule+ * reads — never where its line sits, which is the whole point. */+ #readingKey(index) {+ const rule = this.#recipe.rules[index];+ return rule ? `${checkKey(this.check)}|${readingKey(rule)}` : '';+ }++ /** Whether a rule's line can move without asking the engine again. */+ isLive(index) {+ return this.readings[index]?.key === this.#readingKey(index);+ }++ /**+ * Fetch one rule's reading, so its line can be moved live.+ *+ * Never fetches imagery: the engine reads the same cached frames the test+ * read and refuses otherwise, so this costs no Copernicus request.+ */+ async loadReading(index) {+ const key = this.#readingKey(index);+ if (!key || this.isLive(index) || this.readingBusy !== null) return;+ if (!this.detail || this.#recipe.rules[index]?.measure === 'class') return;+ this.readingBusy = index;+ try {+ const answer = await this.#api.post('/api/compare/analyzers/check/values',+ { recipe: readingRecipe(this.#recipe), check: this.check, rule: index });+ if (this.#gone) return;+ if (answer?.ready) this.readings = { ...this.readings, [index]: { ...answer, key } };+ } catch {+ // A reading is a convenience: without it the line still moves, it just+ // waits for Test. Nothing is said, because nothing was asked out loud.+ } finally {+ if (!this.#gone) this.readingBusy = null;+ }+ }++ /** The readings that still answer for the rules as they stand. */+ get live() {+ return Object.entries(this.readings)+ .filter(([index]) => this.isLive(Number(index)))+ .map(([index, reading]) => ({ index: Number(index), reading }));+ }+/** A rule's eye; with the detections alone on the map every eye reads closed, so one pressed opens its rule. */toggleRule(index) {const opening = this.view === 'detections';@@ -396,15 +524,17 @@ export class Bench {this.shown = this.#recipe.rules.map((_, i) => (i === index ? opening || !this.isShown(i) : this.isShown(i)));}- /** A rule was removed: its eye goes with it. */+ /** A rule was removed: its eye goes with it, and so does what it was drawing. */ruleRemoved(index) {this.shown = this.#recipe.rules.map((_, i) => this.isShown(i)).filter((_, i) => i !== index);this.hover = null;+ if (this.ruleLayer) this.hideRule();}/** The ranking rule was moved to the top: the eyes follow it. */rulesReordered(order) {this.shown = order.map((i) => this.isShown(i));+ if (this.ruleLayer) this.ruleLayer = { ...this.ruleLayer, index: order.indexOf(this.ruleLayer.index) };}hoverRule(index) { this.hover = index; }@@ -472,6 +602,26 @@ export class Bench {return !!last?.detail && (last.signature !== this.current || last.key !== checkKey(this.check));}+ /**+ * Whether the picture is older than the rules in a way a reading cannot cover.+ *+ * A line that moved on a rule whose reading is in hand is not stale at all:+ * the ground is redrawn from the very numbers the test measured, so dimming it+ * would call a live picture old. Anything else — another rule, the pins, the+ * passes, what a rule reads — still waits for Test.+ */+ get staleToDraw() {+ if (!this.stale) return false;+ const last = this.last;+ const live = new Set(this.live.map((row) => row.index));+ if (!live.size || !last?.lines || last.key !== checkKey(this.check)) return true;+ const now = linesOf(this.#recipe);+ if (now.length !== last.lines.length) return true;+ // every rule either reads what it read, or is one whose line can move live+ return !now.every((line, i) => line.key === last.lines[i].key+ && (line.line === last.lines[i].line || live.has(i)));+ }+/** Why the check on the bench cannot be tested yet, or ''. */get blocked() {const check = this.check;@@ -556,8 +706,9 @@ export class Bench {this.tests[id] = { ...before, busy: false, error: 'Copernicus returned nothing for this check.' };return;}- const next = { busy: false, error: '', detail: before?.detail ?? null, signature: before?.signature ?? '', key: before?.key ?? '' };- if (detail) Object.assign(next, { detail: answer, signature: signed, key });+ const next = { busy: false, error: '', detail: before?.detail ?? null, signature: before?.signature ?? '',+ key: before?.key ?? '', lines: before?.lines ?? [] };+ if (detail) Object.assign(next, { detail: answer, signature: signed, key, lines: linesOf(this.#recipe) });this.tests[id] = next;// The answer belongs to the rules and pins it was asked with; if either moved meanwhile it is only shown.const latest = this.#find(id);@@ -678,8 +829,8 @@ export class Bench {markProbe(expect) {if (!this.probe || !this.check) return;const { point } = this.probe;- if (this.marks.length >= (this.#limits.max_marks ?? 20)) {- this.#say(`A check holds at most ${this.#limits.max_marks ?? 20} pins.`, 'warn');+ if (this.marks.length >= (this.#limits.max_marks ?? 60)) {+ this.#say(`A check holds at most ${this.#limits.max_marks ?? 60} pins.`, 'warn');return;}this.#patch((check) => withMark(check, [point.lon, point.lat], expect));diff --git a/frontend/src/lib/map/bench.svelte.test.js b/frontend/src/lib/map/bench.svelte.test.jsindex bc8ee19..a8e3180 100644--- a/frontend/src/lib/map/bench.svelte.test.js+++ b/frontend/src/lib/map/bench.svelte.test.js@@ -3,8 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { flushSync } from 'svelte';import { Bench, lookupBounds } from './bench.svelte.js';import { newCheck, newRecipe, newRule, signature } from './analyzerRules.js';+import { displayLayers } from '../sentinelLayers.js';const METHODS = [{ id: 'rules', sizes: { all: { min_area: 0, cleanup: 0 } } }];+/** What the engine names a layer previewed before it is saved. */+const DRAFT = 'AZIMUT_DRAFT_ABC123DEF456';const VIEW = { west: 2, south: 48, east: 2.2, north: 48.2 };const PLOT = [2.01, 48.01];const REEF = [2.05, 48.05];@@ -15,7 +18,7 @@ const settle = async () => {/** A bench on a recipe of two dates, with an engine that answers what a real one would. */function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {}, layerState = null,- limits = { max_checks: 12, max_marks: 20 } } = {}) {+ limits = { max_checks: 12, max_marks: 60 } } = {}) {const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });const calls = [];const api = {@@ -30,10 +33,21 @@ function make({ dates = 'two', sensor = 'sentinel2', checks = [], answers = {},tiles: [{ x: 1, y: 2, box: { west: 0, east: 1, north: 1, south: 0 }, mask: 'AAAA' }], size: 512,rules: body.recipe.rules.map(() => ({ share: 0.05, kept: 0.05 })), candidates: [], readings: [] };}+ if (url.endsWith('/check/values')) {+ return answer ?? { ready: true, missing: 0, size: 512, rule: body.rule, low: -1, high: 1,+ steps: 65535, tiles: [{ x: 1, y: 2, box: { west: 0, east: 1, north: 1, south: 0 }, values: 'AAAA' }] };+ }if (url.endsWith('/probe')) return answer ?? { ready: true, imaged: true, measured: true, kept: true, rules: [] };if (url.endsWith('/acquisitions')) return answer ?? { dates: [{ date: '2023-08-13', cloud: 3, coverage: 1 }], truncated: false };throw new Error(`unexpected ${url}`);}),+ // Drawing a rule renders it through the ordinary draft-preview path.+ put: vi.fn(async (url, body) => {+ calls.push([url, body]);+ if (url.endsWith('/draft-layer')) return { id: DRAFT };+ throw new Error(`unexpected ${url}`);+ }),+ del: vi.fn(async (url) => { calls.push([url, null]); return {}; }),};const fly = vi.fn();const say = vi.fn();@@ -135,6 +149,27 @@ describe('making a check', () => {expect(say).toHaveBeenCalledWith('A check holds at most 1 pins.', 'warn');});+ it.each([{ max_marks: 60 }, {}])('keeps sixty pins and refuses another from either the map or a probe with limits %j', (limits) => {+ const { bench, recipe, say } = open({ limits, checks: [made('Plot')] });+ bench.select(bench.checks[0].id);+ bench.arm('empty');+ for (let i = 0; i < 58; i++) bench.dropPin({ lon: REEF[0] + i / 10000, lat: REEF[1] });+ bench.probe = { point: { lon: REEF[0], lat: REEF[1] }, pin: null };+ bench.markProbe('empty');+ expect(bench.marks).toHaveLength(60);+ expect(recipe.checks[0].marks).toHaveLength(60);+ bench.dropPin({ lon: REEF[0], lat: REEF[1] });+ bench.probe = { point: { lon: REEF[0], lat: REEF[1] }, pin: null };+ bench.markProbe('empty');+ expect(bench.marks).toHaveLength(60);+ expect(say).toHaveBeenCalledTimes(2);+ expect(say).toHaveBeenLastCalledWith('A check holds at most 60 pins.', 'warn');+ bench.removePin(59);+ bench.markProbe('empty');+ expect(bench.marks).toHaveLength(60);+ expect(bench.probe).toBe(null);+ });+it('changes the passes of a check already kept, and forgets what they had answered', () => {const kept = { ...made('Plot'), result: { signature: 'x', count: 1, covered: [true] } };const { bench, recipe } = open({ checks: [kept] });@@ -331,13 +366,16 @@ describe('what a test would cost', () => {});it('carries the engine’s own words when the pins reach too much ground', async () => {- const refusal = new Error('these pins reach 14 tiles and a check reads at most 12');+ const refusal = new Error('these pins reach 21 tiles and a check reads at most 20');const kept = made('Plot');const { bench } = open({ checks: [kept], answers: { '/api/compare/analyzers/check/plan': refusal } });bench.select(kept.id);await settle();expect(bench.blocked).toBe(refusal.message);expect(bench.plan.error).toBe(refusal.message);+ expect(bench.canTest).toBe(false);+ await bench.test();+ expect(bench.last).toBe(null);});it('adds up what every check still lacks for Test all', async () => {@@ -714,3 +752,178 @@ describe('the passes a lookup finds', () => {expect(lookupBounds(null)).toBe(null);});});++it('offers a layer written in Azimut as a display, and says it is yours', () => {+ // the bench reads the same list every map tab does, so a script written on+ // the Satellite map is on the analyzer's Display menu without a request+ const offered = displayLayers(+ [{ id: 'TRUE_COLOR', label: 'True colour' }, { id: 'PLUME_SWIR', label: 'My plume', custom: true }],+ false+ );+ const mine = offered.find((entry) => entry.id === 'PLUME_SWIR');+ expect(mine.enabled).toBe(true);+ expect(mine.custom).toBe(true);+});++describe('a rule drawn as imagery', () => {+ /** A bench on a check, with a display the catalogue serves. */+ const bench0 = () => {+ const state = $state({ layers: [{ id: 'TRUE_COLOR' }, { id: 'SWIR' }], layersSource: 'instance',+ loadLayers: vi.fn(async () => true) });+ const kept = made('Plot');+ const found = open({ checks: [kept], layerState: state });+ found.bench.select(kept.id);+ flushSync();+ return found;+ };++ it('puts the rule\u2019s own arithmetic on the map, and gives the display back after', async () => {+ const { bench, api } = bench0();+ expect(bench.imagery.b.layer).toBe('TRUE_COLOR');++ await bench.showRule(0); // the default rule measures brightness+ flushSync();+ const [url, body] = api.put.mock.calls[0];+ expect(url).toBe('/api/satellite/sentinel/draft-layer');+ expect(body.script).toContain('(p.B02 + p.B03 + p.B04) / 3');+ expect(body.base).toBe('TRUE_COLOR'); // a script needs a data source, never radar+ // the draft is what the map draws, while the chosen display waits underneath+ expect(bench.shownLayer).toBe(DRAFT);+ expect(bench.imagery.b.layer).toBe(DRAFT);+ expect(bench.layer).toBe('TRUE_COLOR');++ bench.hideRule();+ flushSync();+ expect(bench.shownLayer).toBe('TRUE_COLOR');+ expect(bench.imagery.b.layer).toBe('TRUE_COLOR');+ });++ it('draws nothing for a rule that is not one quantity', async () => {+ const { bench, recipe, api } = bench0();+ recipe.rules = [newRule('class', 'b')];+ flushSync();+ await bench.showRule(0);+ expect(api.put).not.toHaveBeenCalled();+ expect(bench.ruleLayer).toBe(null);+ });++ it('pressing the same rule again lets it go', async () => {+ const { bench } = bench0();+ await bench.showRule(0); flushSync();+ expect(bench.ruleLayer.index).toBe(0);+ await bench.showRule(0); flushSync();+ expect(bench.ruleLayer).toBe(null);+ });++ it('choosing a display is choosing what the map draws, so it ends the drawing', async () => {+ const { bench } = bench0();+ await bench.showRule(0); flushSync();+ expect(bench.shownLayer).toBe(DRAFT);+ bench.setLayer('SWIR');+ flushSync();+ expect(bench.ruleLayer).toBe(null);+ expect(bench.shownLayer).toBe('SWIR');+ });++ it('removing the rule removes what it was drawing', async () => {+ const { bench, recipe } = bench0();+ recipe.rules = [newRule('brightness', 'b'), newRule('brightness', 'b')];+ flushSync();+ await bench.showRule(0); flushSync();+ recipe.rules = [recipe.rules[1]];+ bench.ruleRemoved(0);+ flushSync();+ expect(bench.ruleLayer).toBe(null);+ });+});++describe('moving a line without asking again', () => {+ /** A bench on a tested check, which is what a reading needs. */+ async function tested() {+ const found = open({ checks: [made('The plot')] });+ found.bench.select(found.recipe.checks[0].id);+ flushSync();+ await settle();+ await found.bench.test();+ await settle();+ return found;+ }++ it('fetches one rule’s reading, once, and never the imagery with it', async () => {+ const { bench, api, calls } = await tested();+ expect(bench.isLive(0)).toBe(false);+ await bench.loadReading(0);+ flushSync();+ expect(bench.isLive(0)).toBe(true);+ const asked = calls.filter(([url]) => url.endsWith('/check/values'));+ expect(asked).toHaveLength(1);+ // the route reads the cache the test filled; nothing says `read`+ expect(asked[0][1].rule).toBe(0);+ expect(asked[0][1].read).toBeUndefined();++ // asking again while it still answers costs nothing+ await bench.loadReading(0);+ expect(calls.filter(([url]) => url.endsWith('/check/values'))).toHaveLength(1);+ expect(api.post).toBeDefined();+ });++ it('keeps the reading while only the line moves, and drops it when the bands change', async () => {+ const { bench, recipe } = await tested();+ await bench.loadReading(0);+ flushSync();++ // the line is the one thing a reading does not answer for+ recipe.rules[0] = { ...recipe.rules[0], value: 0.42 };+ flushSync();+ expect(bench.isLive(0)).toBe(true);+ expect(bench.live.map((row) => row.index)).toEqual([0]);++ // what it reads is+ recipe.rules[0] = { ...recipe.rules[0], measure: 'nd', bands: ['B12', 'B11'] };+ flushSync();+ expect(bench.isLive(0)).toBe(false);+ expect(bench.live).toEqual([]);+ });++ it('stops calling the picture old when the only change is a line it can redraw', async () => {+ const { bench, recipe } = await tested();+ expect(bench.stale).toBe(false);+ await bench.loadReading(0);+ flushSync();++ // the line moved: the verdict below is older, but the ground is redrawn+ // from the very numbers the test measured, so the layer is not dimmed+ recipe.rules[0] = { ...recipe.rules[0], value: 0.42 };+ flushSync();+ expect(bench.stale).toBe(true);+ expect(bench.staleToDraw).toBe(false);++ // a second rule whose reading nobody has asked for does dim it+ recipe.rules = [...recipe.rules, newRule('band', 'b')];+ flushSync();+ expect(bench.staleToDraw).toBe(true);+ });++ it('calls the picture old when what a rule reads changes, reading or not', async () => {+ const { bench, recipe } = await tested();+ await bench.loadReading(0);+ flushSync();+ recipe.rules[0] = { ...recipe.rules[0], measure: 'nd', bands: ['B12', 'B11'] };+ flushSync();+ expect(bench.staleToDraw).toBe(true);+ });++ it('asks for nothing before a test, and nothing for a ground class', async () => {+ const { bench, recipe, calls } = open({ checks: [made('The plot')] });+ bench.select(recipe.checks[0].id); flushSync(); await settle();+ // no test has read the frames, so there is nothing cached to read back+ await bench.loadReading(0);+ expect(calls.filter(([url]) => url.endsWith('/check/values'))).toEqual([]);++ await bench.test(); await settle();+ recipe.rules = [newRule('class', 'b')];+ flushSync();+ await bench.loadReading(0);+ expect(calls.filter(([url]) => url.endsWith('/check/values'))).toEqual([]);+ });+});diff --git a/frontend/src/lib/map/engine.css b/frontend/src/lib/map/engine.cssindex ddad36b..23145ae 100644--- a/frontend/src/lib/map/engine.css+++ b/frontend/src/lib/map/engine.css@@ -49,6 +49,18 @@color: var(--text-2);}+/* The engine parks its control corners at z-index 2, which is under the ground+ overlays every tool paints in the 500s (rules, detections, marks). The zoom+ buttons and the attribution ended up behind a translucent layer: still there,+ still clickable, and looking broken. They climb over the overlays and stay+ under the tool's own chrome, which starts at 600. */+.maplibregl-ctrl-top-left,+.maplibregl-ctrl-top-right,+.maplibregl-ctrl-bottom-left,+.maplibregl-ctrl-bottom-right {+ z-index: 580;+}+/* zoom +/- (topleft) sits directly under the tool cluster instead of theengine's default corner margin, which used to land it on top of that cluster.How far down is the tool's own business — a map with no cluster over it saysdiff --git a/frontend/src/lib/map/liveRule.test.js b/frontend/src/lib/map/liveRule.test.jsnew file mode 100644index 0000000..0a036e4--- /dev/null+++ b/frontend/src/lib/map/liveRule.test.js@@ -0,0 +1,69 @@+import { expect, it } from 'vitest';+import { KEPT_BIT, MEASURED_BIT, newRule, passesValue, readingKey, redrawRule, shareOf } from './analyzerRules.js';++/**+ * Moving a rule's line without asking the engine again.+ *+ * The engine sends what each rule read, pixel for pixel; the browser applies the+ * same comparison. `tests/test_detect_rules.py` proves the two agree on real+ * tiles — these are the arithmetic and the care taken with everything that is+ * not this rule.+ */++const SEEN = 1 << MEASURED_BIT;+const KEPT = 1 << KEPT_BIT;++it('crosses a line the way the engine crosses it', () => {+ const at = (op, value, upper = 0) => ({ ...newRule('band', 'b'), op, value, upper });+ expect(passesValue(at('ge', 0.25), 0.3)).toBe(true);+ expect(passesValue(at('ge', 0.25), 0.25)).toBe(true); // the line itself passes+ expect(passesValue(at('ge', 0.25), 0.2)).toBe(false);+ expect(passesValue(at('le', -0.2), -0.3)).toBe(true);+ expect(passesValue(at('le', -0.2), -0.1)).toBe(false);+ expect(passesValue(at('between', 0.1, 0.4), 0.25)).toBe(true);+ expect(passesValue(at('between', 0.1, 0.4), 0.45)).toBe(false);+ // a move either way is read as a size, whichever side it went+ expect(passesValue(at('moved', 0.05), -0.2)).toBe(true);+ expect(passesValue(at('moved', 0.05), 0.01)).toBe(false);+});++it('redraws one rule and leaves every other bit of the mask alone', () => {+ const rule = { ...newRule('nd', 'b'), op: 'ge', value: 0.5 };+ // measured+rule1+kept measured+rule1 measured not measured+ const bits = new Uint8Array([SEEN | 0b10 | KEPT, SEEN | 0b10, SEEN, 0]);+ const values = [0.9, 0.1, 0.9, 0.9];+ const out = redrawRule(bits, 0, values, rule);++ // rule 0 set where its reading crosses, cleared where it does not+ expect([...out].map((b) => !!(b & 1))).toEqual([true, false, true, false]);+ // rule 1, the measured bit and the kept bit are untouched+ expect([...out].map((b) => !!(b & 0b10))).toEqual([true, true, false, false]);+ expect([...out].map((b) => !!(b & SEEN))).toEqual([true, true, true, false]);+ expect([...out].map((b) => !!(b & KEPT))).toEqual([true, false, false, false]);+ // and the mask it was given is not written through+ expect(bits[1] & 1).toBe(0);+});++it('never paints ground the sensor did not measure', () => {+ // cloud and missing imagery carry no reading, so a line can never catch them+ const rule = { ...newRule('band', 'b'), op: 'ge', value: -99 };+ const out = redrawRule(new Uint8Array([0, SEEN]), 0, [5, 5], rule);+ expect(out[0] & 1).toBe(0);+ expect(out[1] & 1).toBe(1);+});++it('counts the share of measured ground a redrawn rule keeps', () => {+ const masks = [new Uint8Array([SEEN | 1, SEEN, 0, SEEN | 1])];+ expect(shareOf(masks, 0)).toBeCloseTo(2 / 3);+ expect(shareOf([new Uint8Array([0, 0])], 0)).toBe(0);+});++it('keys a reading on everything but where the line sits', () => {+ const rule = newRule('nd', 'b', { bands: ['B12', 'B11'] });+ const moved = { ...rule, op: 'le', value: 0.9, upper: 1 };+ // the download answers for the bands and the dates, never the threshold+ expect(readingKey(moved)).toBe(readingKey(rule));+ expect(readingKey({ ...rule, bands: ['B08', 'B04'] })).not.toBe(readingKey(rule));+ expect(readingKey({ ...rule, on: 'a' })).not.toBe(readingKey(rule));+ expect(readingKey({ ...rule, around: 60 })).not.toBe(readingKey(rule));+});diff --git a/frontend/src/lib/map/mapStacking.test.js b/frontend/src/lib/map/mapStacking.test.jsnew file mode 100644index 0000000..87f93f7--- /dev/null+++ b/frontend/src/lib/map/mapStacking.test.js@@ -0,0 +1,75 @@+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { expect, it } from 'vitest';++/**+ * Who sits over whom on a map.+ *+ * The engine parks its own control corners at `z-index: 2`, far under the+ * overlays every tool paints on the ground. Left alone, the zoom buttons, the+ * attribution and the split handle end up behind a translucent layer: still+ * there, still clickable, and looking broken.+ *+ * Three bands, and this is the gate on them:+ * ground overlays 500–579 what is drawn on the earth+ * map controls 580 the engine's corners, the split handle+ * tool chrome 600+ chips, panels, menus+ *+ * A new overlay drawn on the ground joins GROUND below. If it needs to sit over+ * the zoom buttons it is not ground, it is chrome, and it belongs at 600+.+ */++const here = dirname(fileURLToPath(import.meta.url));+const root = join(here, '..', '..');+const read = (path) => readFileSync(join(root, path), 'utf8');++/** The z-index a selector's block declares, in the source given. */+function zOf(source, selector) {+ const at = source.indexOf(selector);+ expect(at, `${selector} is not in the source any more`).toBeGreaterThan(-1);+ const found = /z-index:\s*(-?\d+)/.exec(source.slice(at));+ expect(found, `${selector} declares no z-index`).not.toBe(null);+ return Number(found[1]);+}++/** Every layer painted on the ground, with the selector that carries its z-index. */+const GROUND = [+ ['tools/detect/RuleLayers.svelte', '.rule-layers {'],+ ['tools/detect/DetectAreas.svelte', '.detect-areas {'],+ ['tools/detect/AnalysisOverlay.svelte', '.analysis-overlay {'],+ ['tools/detect/CheckMarks.svelte', '.mark {'],+];++it('keeps the engine’s own controls above everything drawn on the ground', () => {+ const engine = read('lib/map/engine.css');+ const controls = zOf(engine, '.maplibregl-ctrl-top-left,');+ expect(controls).toBeGreaterThanOrEqual(580);++ for (const [path, selector] of GROUND) {+ const z = zOf(read(path), selector);+ expect(z, `${selector} would cover the zoom buttons`).toBeLessThan(controls);+ }+});++it('keeps the split handle level with the controls, not with the ground', () => {+ // Inside the second map's own layer the handle was trapped in that stacking+ // context, and every overlay painted over it. It rides in its own rail.+ const source = read('tools/detect/SecondPass.svelte');+ const controls = zOf(read('lib/map/engine.css'), '.maplibregl-ctrl-top-left,');+ expect(zOf(source, '.split-rail')).toBe(controls);+ // and the map underneath it stays below the ground overlays+ expect(zOf(source, '.second ')).toBeLessThan(500);+});++it('leaves the tool’s own chrome above the controls', () => {+ // A chip or a panel the analyst reads has to clear the zoom buttons.+ const controls = zOf(read('lib/map/engine.css'), '.maplibregl-ctrl-top-left,');+ for (const [path, selector] of [+ ['tools/detect/CheckBench.svelte', '.bench-root'],+ ['tools/satellite/MapStatusBar.svelte', '.status {'],+ ]) {+ expect(zOf(read(path), selector), `${selector} would hide under the controls`)+ .toBeGreaterThan(controls);+ }+});diff --git a/frontend/src/lib/map/pictureDate.js b/frontend/src/lib/map/pictureDate.jsindex 287bb84..a06d572 100644--- a/frontend/src/lib/map/pictureDate.js+++ b/frontend/src/lib/map/pictureDate.js@@ -2,28 +2,31 @@* When the picture on a map surface was taken, as the case records it.** A capture and a saved comparison file the date of the pixels they show. Two- * providers name it outright: a Sentinel-1 pass (its day and UTC time) and a- * pinned Sentinel-2 day. Esri and Wayback only estimate it from their metadata,- * so their date is kept with `exact: false`, which the Time panel shows as `~`.+ * providers name it outright: a Sentinel-1 pass (its day and UTC time) and the+ * Sentinel-2 day the tiles were rendered from. Esri and Wayback only estimate it+ * from their metadata, so their date is kept with `exact: false`, which the Time+ * panel shows as `~`. A Sentinel-2 view with no day is a blend of the archive+ * and files no date at all, rather than the newest pass it mostly is not.*/const DAY = /^\d{4}-\d{2}-\d{2}$/;const TIME = /^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/;/**- * @param {{ radarPass?: { date: string, time?: string } | null, pinnedDay?: string | null,- * estimated?: string | null }} shown+ * @param {{ radarPass?: { date: string, time?: string } | null, day?: string | null,+ * estimated?: string | null }} shown `day` is the Sentinel-2 acquisition the+ * mosaicking window named, which is exact however it was chosen.* @returns {{ imageryDate: string | null, imageryExact: boolean, imageryWhen: string | null }}* `imageryDate` is the day, as a capture shows it; `imageryWhen` adds a radar* pass's time as a UTC instant.*/-export function pictureDate({ radarPass = null, pinnedDay = null, estimated = null } = {}) {+export function pictureDate({ radarPass = null, day = null, estimated = null } = {}) {if (radarPass?.date && DAY.test(radarPass.date)) {const when = TIME.test(radarPass.time ?? '') ? `${radarPass.date}T${radarPass.time}Z` : radarPass.date;return { imageryDate: radarPass.date, imageryExact: true, imageryWhen: when };}- if (pinnedDay && DAY.test(pinnedDay)) {- return { imageryDate: pinnedDay, imageryExact: true, imageryWhen: pinnedDay };+ if (day && DAY.test(day)) {+ return { imageryDate: day, imageryExact: true, imageryWhen: day };}if (estimated && DAY.test(estimated)) {return { imageryDate: estimated, imageryExact: false, imageryWhen: estimated };diff --git a/frontend/src/lib/map/pictureDate.test.js b/frontend/src/lib/map/pictureDate.test.jsindex 4c6d329..2a5d232 100644--- a/frontend/src/lib/map/pictureDate.test.js+++ b/frontend/src/lib/map/pictureDate.test.js@@ -8,12 +8,18 @@ describe('the date a map picture was taken', () => {});});- it('takes a pinned Sentinel-2 day as the acquisition itself', () => {- expect(pictureDate({ pinnedDay: '2026-08-30', estimated: '2020-01-01' })).toEqual({+ it('takes the Sentinel-2 day the window named as the acquisition itself', () => {+ expect(pictureDate({ day: '2026-08-30', estimated: '2020-01-01' })).toEqual({imageryDate: '2026-08-30', imageryExact: true, imageryWhen: '2026-08-30',});});+ it('files no date for a Sentinel-2 view with no day, which blends the archive', () => {+ expect(pictureDate({ day: null })).toEqual({+ imageryDate: null, imageryExact: true, imageryWhen: null,+ });+ });+it('keeps a provider estimate, marked as one', () => {expect(pictureDate({ estimated: '2024-05-03' })).toMatchObject({ imageryDate: '2024-05-03', imageryExact: false });});diff --git a/frontend/src/lib/map/ruleLayer.js b/frontend/src/lib/map/ruleLayer.jsnew file mode 100644index 0000000..9402ad1--- /dev/null+++ b/frontend/src/lib/map/ruleLayer.js@@ -0,0 +1,77 @@+/**+ * A rule, drawn as a Copernicus layer.+ *+ * A test paints a verdict: the ground that passes, the ground that does not.+ * That answers whether the line is crossed, never where the line should be. For+ * that you have to see the *quantity* itself, continuous, over the whole frame+ * — which is exactly what a layer does.+ *+ * Nothing here is guessed. A rule already names the bands it reads+ * (`ruleBands`), and the same generators the writing bench uses turn them into+ * a script (`lib/layerScripts.js`), so the layer is the rule's own arithmetic+ * rather than the least-bad configured layer the Display menu can suggest.+ *+ * **No threshold is baked in**, on purpose. `indexScript` can darken everything+ * below a line, but the script's digest is the draft's name and therefore the+ * tile cache's key: a threshold in it would mean new tiles, and new Copernicus+ * requests, every time the slider moved. The ramp shows where every value falls,+ * which is what the line is set against.+ */++import { brightnessScript, compositeScript, indexScript } from '../layerScripts.js';+import { ruleBands } from './analyzerRules.js';++/** The ramp each published index reads best on, matching `INDEX_PRESETS`. */+const INDEX_RAMPS = Object.freeze({+ ndvi: 'vegetation', ndwi: 'water', mndwi: 'water', nbr: 'heat', ndbi: 'grey',+});++/**+ * The script that draws what a rule measures, or '' when it is not one picture.+ *+ * @param {{measure: string, index?: string, bands?: string[], band?: string}} rule+ */+export function ruleLayerScript(rule) {+ if (!rule) return '';+ const bands = ruleBands(rule);+ // A normalised difference is a normalised difference whether the analyst+ // chose the bands or picked a published name for the pair.+ if (rule.measure === 'nd' && bands.length === 2) {+ return indexScript({ high: bands[0], low: bands[1], rampId: 'divergent' });+ }+ if (rule.measure === 'index' && bands.length === 2) {+ return indexScript({ high: bands[0], low: bands[1], rampId: INDEX_RAMPS[rule.index] ?? 'grey' });+ }+ if (rule.measure === 'band' && rule.band) {+ return compositeScript({ red: rule.band, green: rule.band, blue: rule.band });+ }+ if (rule.measure === 'brightness') return brightnessScript();+ return '';+}++/**+ * Why a rule cannot be drawn, in one clause, or '' when it can.+ *+ * Said rather than hidden: the button is on every rule, and a rule that cannot+ * be drawn says so where you press it.+ */+export function whyNoLayer(rule) {+ if (ruleLayerScript(rule)) return '';+ switch (rule?.measure) {+ // Two acquisitions subtracted. One picture of one day cannot hold it.+ case 'colour': return 'a colour change is the move between two dates, not one picture';+ case 'class': return 'ground classes are a classification, not a quantity';+ case 'radar': return 'radar reads another collection';+ case 'index': return `${String(rule.index ?? '').toUpperCase()} is more than two bands`;+ default: return 'nothing to draw';+ }+}++/** What the drawn layer shows, for the button's tooltip. */+export function ruleLayerWords(rule) {+ if (!ruleLayerScript(rule)) return '';+ const bands = ruleBands(rule);+ if (rule.measure === 'band') return `${rule.band} reflectance, as grey`;+ if (rule.measure === 'brightness') return `${bands.join(' · ')} averaged, as grey`;+ return `(${bands[0]} − ${bands[1]}) / (${bands[0]} + ${bands[1]}), on a ramp`;+}diff --git a/frontend/src/lib/map/ruleLayer.test.js b/frontend/src/lib/map/ruleLayer.test.jsnew file mode 100644index 0000000..d64fa09--- /dev/null+++ b/frontend/src/lib/map/ruleLayer.test.js@@ -0,0 +1,88 @@+import { expect, it } from 'vitest';+import { newRule } from './analyzerRules.js';+import { ruleLayerScript, ruleLayerWords, whyNoLayer } from './ruleLayer.js';++/**+ * A rule drawn as imagery.+ *+ * What matters is that the layer is the rule's *own* arithmetic, not a layer+ * that happens to show its bands well — and that a rule which is not one+ * quantity says so instead of drawing something that would be read as the+ * measure.+ */++it('draws a chosen pair as the normalised difference the rule measures', () => {+ const script = ruleLayerScript(newRule('nd', 'b', { bands: ['B12', 'B11'] }));+ // the arithmetic, in the rule's own order: high first+ expect(script).toContain('(p.B12 - p.B11) / sum');+ expect(script).toContain('const sum = p.B12 + p.B11;');+ // and it asks for exactly those bands+ expect(script).toContain('input: ["B12", "B11", "dataMask"]');+});++it('draws a published index from its own bands, on a ramp that suits it', () => {+ const ndvi = ruleLayerScript(newRule('index', 'b', { index: 'ndvi' }));+ expect(ndvi).toContain('(p.B08 - p.B04) / sum');+ expect(ndvi).toContain('vegetation ramp');++ const ndwi = ruleLayerScript(newRule('index', 'b', { index: 'ndwi' }));+ expect(ndwi).toContain('(p.B03 - p.B08) / sum');+ expect(ndwi).toContain('water ramp');++ expect(ruleLayerScript(newRule('index', 'b', { index: 'nbr' }))).toContain('(p.B08 - p.B12) / sum');+ expect(ruleLayerScript(newRule('index', 'b', { index: 'ndbi' }))).toContain('(p.B11 - p.B08) / sum');+});++it('never bakes the threshold in, so moving the line costs no tiles', () => {+ // the script is the draft's name is the tile cache's key: a threshold in it+ // would fetch the whole frame again at every nudge of the slider+ const low = ruleLayerScript(newRule('nd', 'b', { bands: ['B12', 'B11'], op: 'ge', value: 0.1 }));+ const high = ruleLayerScript(newRule('nd', 'b', { bands: ['B12', 'B11'], op: 'ge', value: 0.6 }));+ expect(low).toBe(high);+ expect(low).not.toContain('left dark');+});++it('draws a band as that band in grey, not as a colour', () => {+ const script = ruleLayerScript(newRule('band', 'b', { band: 'B11' }));+ expect(script).toContain('B11 alone, as grey');+ expect(script).toContain('input: ["B11", "dataMask"]');+});++it('draws brightness as the visible bands averaged', () => {+ const script = ruleLayerScript(newRule('brightness', 'b'));+ expect(script).toContain('const mean = (p.B02 + p.B03 + p.B04) / 3;');+ expect(script).toContain('input: ["B02", "B03", "B04", "dataMask"]');+});++it('refuses what one picture of one day cannot hold, and says which', () => {+ const colour = newRule('colour', 'change');+ expect(ruleLayerScript(colour)).toBe('');+ expect(whyNoLayer(colour)).toContain('between two dates');++ const ground = newRule('class', 'b');+ expect(ruleLayerScript(ground)).toBe('');+ expect(whyNoLayer(ground)).toContain('classification');++ const radar = newRule('radar', 'b');+ expect(ruleLayerScript(radar)).toBe('');+ expect(whyNoLayer(radar)).toContain('another collection');++ // BSI is four bands, so it is not the two-band generator's job+ const bsi = newRule('index', 'b', { index: 'bsi' });+ expect(ruleLayerScript(bsi)).toBe('');+ expect(whyNoLayer(bsi)).toContain('BSI');+});++it('says nothing against a rule it can draw', () => {+ expect(whyNoLayer(newRule('nd', 'b', { bands: ['B12', 'B11'] }))).toBe('');+ expect(whyNoLayer(newRule('band', 'b', { band: 'B08' }))).toBe('');+ expect(whyNoLayer(newRule('brightness', 'b'))).toBe('');+});++it('says what the drawn layer shows, in the rule’s own terms', () => {+ expect(ruleLayerWords(newRule('nd', 'b', { bands: ['B12', 'B11'] })))+ .toBe('(B12 − B11) / (B12 + B11), on a ramp');+ expect(ruleLayerWords(newRule('band', 'b', { band: 'B11' }))).toBe('B11 reflectance, as grey');+ expect(ruleLayerWords(newRule('brightness', 'b'))).toBe('B02 · B03 · B04 averaged, as grey');+ expect(ruleLayerWords(newRule('class', 'b'))).toBe('');+});diff --git a/frontend/src/lib/radar.js b/frontend/src/lib/radar.jsindex 45f76ac..5d75fa5 100644--- a/frontend/src/lib/radar.js+++ b/frontend/src/lib/radar.js@@ -46,7 +46,7 @@ export function sameTrack(one, other) {/** How a pass reads: "2026-05-14 · 05:42 UTC". */export function passLabel(pass) {- if (!validPass(pass)) return 'Most recent';+ if (!validPass(pass)) return 'Several passes';return `${pass.date} · ${pass.time.slice(0, 5)} UTC`;}diff --git a/frontend/src/lib/radar.test.js b/frontend/src/lib/radar.test.jsindex 8f0df75..df631a1 100644--- a/frontend/src/lib/radar.test.js+++ b/frontend/src/lib/radar.test.js@@ -16,7 +16,9 @@ describe('a Sentinel-1 pass on the provider id', () => {it('reads as a day, a UTC time and a direction', () => {expect(passLabel({ date: '2026-05-14', time: '05:42:10' })).toBe('2026-05-14 · 05:42 UTC');- expect(passLabel(null)).toBe('Most recent');+ // no pass means no window was sent, so the tiles blend the archive: the+ // label says that rather than naming a pass that is mostly not there+ expect(passLabel(null)).toBe('Several passes');expect(orbitMark('descending')).toBe('↓');expect(orbitMark('ascending')).toBe('↑');});diff --git a/frontend/src/lib/sentinelLayers.js b/frontend/src/lib/sentinelLayers.jsindex 83c819b..3a4d074 100644--- a/frontend/src/lib/sentinelLayers.js+++ b/frontend/src/lib/sentinelLayers.js@@ -10,10 +10,19 @@ export function displayLayerFamily(id) {return DISPLAY_LAYERS.find((entry) => entry.id === id || entry.aliases.includes(id))?.id ?? id;}+/**+ * Every layer a picker may offer, with the ones it cannot render disabled and+ * told why.+ *+ * A configured layer is only offerable once the instance has confirmed it+ * serves it: offering one it does not just 400s on selection. A layer written+ * in Azimut needs no such confirmation — its script is on this machine and+ * renders through a base layer — so it is always offered.+ */export function displayLayers(layers, verified, radarLayer = '') {const offered = layers.filter((entry) => entry.id !== radarLayer).map((entry) => ({- ...entry, enabled: verified,- reason: verified ? '' : 'Check your Copernicus layers first.',+ ...entry, enabled: entry.custom ? true : verified,+ reason: entry.custom || verified ? '' : 'Check your Copernicus layers first.',}));for (const { id, label } of DISPLAY_LAYERS) {if (offered.some((entry) => displayLayerFamily(entry.id) === id)) continue;diff --git a/frontend/src/lib/sentinelLayers.test.js b/frontend/src/lib/sentinelLayers.test.jsindex 0c150bb..c1ffc03 100644--- a/frontend/src/lib/sentinelLayers.test.js+++ b/frontend/src/lib/sentinelLayers.test.js@@ -24,3 +24,24 @@ it('keeps a custom configured display and handles an empty configuration', () =>expect(availableDisplayLayer('NDVI', options)).toBe('MY_GROUND');expect(displayLayers([], true).every((entry) => !entry.enabled)).toBe(true);});++it('offers a layer written in Azimut whether or not the instance has been asked', () => {+ const mine = { id: 'PLUME_SWIR', label: 'SWIR plume', custom: true };+ for (const verified of [true, false]) {+ const row = displayLayers([mine], verified).find((entry) => entry.id === 'PLUME_SWIR');+ // the script is on this machine; GetCapabilities has no say in it+ expect(row.enabled).toBe(true);+ expect(row.reason).toBe('');+ }+});++it('still withholds a configured layer until the instance confirms it', () => {+ const row = displayLayers([{ id: 'SWIR', label: 'SWIR' }], false).find((e) => e.id === 'SWIR');+ expect(row.enabled).toBe(false);+ expect(row.reason).toBe('Check your Copernicus layers first.');+});++it('lets a layer written in Azimut be the display layer', () => {+ const offered = displayLayers([{ id: 'PLUME_SWIR', label: 'Plume', custom: true }], false);+ expect(availableDisplayLayer('PLUME_SWIR', offered)).toBe('PLUME_SWIR');+});diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelteindex 2456967..3c9a2f6 100644--- a/frontend/src/tools/Compare.svelte+++ b/frontend/src/tools/Compare.svelte@@ -336,13 +336,13 @@api,place: () => ({ lat: view.lat, lon: view.lon }),onBilled: () => imagery.refreshUsage(),- peer: () => (b.present && b.providerId === RADAR_ID ? s1b.pass : null),+ peer: () => (b.present && b.providerId === RADAR_ID ? s1b.shownPass : null),});const s1b = createRadarState({api,place: () => ({ lat: view.lat, lon: view.lon }),onBilled: () => imagery.refreshUsage(),- peer: () => (a.present && a.providerId === RADAR_ID ? s1a.pass : null),+ peer: () => (a.present && a.providerId === RADAR_ID ? s1a.shownPass : null),});$effect(() => {@@ -354,10 +354,10 @@const both = $derived(a.present && b.present);const activeView = $derived(view);const shownA = $derived(- imagery.displayed(a.providerId, view.zoom, { ...s2a.variant, release: wba.release, pass: s1a.pass })+ imagery.displayed(a.providerId, view.zoom, { ...s2a.variant, release: wba.release, pass: s1a.shownPass }));const shownB = $derived(- imagery.displayed(b.providerId, view.zoom, { ...s2b.variant, release: wbb.release, pass: s1b.pass })+ imagery.displayed(b.providerId, view.zoom, { ...s2b.variant, release: wbb.release, pass: s1b.shownPass }));const labelA = $derived(imagery.find(a.providerId)?.label ?? 'Imagery A');const labelB = $derived(imagery.find(b.providerId)?.label ?? 'Imagery B');@@ -384,7 +384,7 @@sentinel: {layer: sentinel.layer,date: sentinel.date,- effectiveDate: sentinel.date || sentinel.latest,+ effectiveDate: sentinel.day,maxcc: sentinel.maxcc,},waybackRelease: wayback.release,@@ -392,9 +392,11 @@};}- /** A side's radar pass as a session keeps it. */+ /** A side's radar pass as a session keeps it: the pass the tiles were+ * rendered from, so reopening the session draws the same look rather than+ * whichever pass is newest that day. */function radarSpec(radar) {- return { date: radar.pass?.date ?? '', time: radar.pass?.time ?? '' };+ return { date: radar.shownPass?.date ?? '', time: radar.shownPass?.time ?? '' };}const archive = $derived(stripArchive(sideSpec(a, s2a, wba, s1a), sideSpec(b, s2b, wbb, s1b)));@@ -806,13 +808,18 @@s2bPassTimer = setTimeout(() => s2b.loadPasses(), 600);return () => clearTimeout(s2bPassTimer);});+ // Each side's "most recent" is resolved to a day, which is then the window its+ // tiles are rendered from: a side is one acquisition, never a blend of the+ // archive, or the difference between the two sides would be partly a+ // difference between dates nobody chose. Unresolved, the lookup goes out at+ // once; afterwards the debounce keeps a pan from spending a request per frame.$effect(() => {if (!a.ready || shownA.provider?.id !== SENTINEL_ID) return;view.lat;view.lon;s2a.maxcc;clearTimeout(s2aLatestTimer);- s2aLatestTimer = setTimeout(() => s2a.resolveLatest().catch(() => {}), 900);+ s2aLatestTimer = setTimeout(() => s2a.resolveLatest().catch(() => {}), s2a.resolved ? 900 : 0);return () => clearTimeout(s2aLatestTimer);});$effect(() => {@@ -821,9 +828,30 @@view.lon;s2b.maxcc;clearTimeout(s2bLatestTimer);- s2bLatestTimer = setTimeout(() => s2b.resolveLatest().catch(() => {}), 900);+ s2bLatestTimer = setTimeout(() => s2b.resolveLatest().catch(() => {}), s2b.resolved ? 900 : 0);return () => clearTimeout(s2bLatestTimer);});+ // Both sides' radar passes are resolved the same way: a side is one look, not+ // a blend of every pass over the point.+ $effect(() => {+ if (!a.ready || shownA.provider?.id !== RADAR_ID) return;+ view.lat;+ view.lon;+ clearTimeout(s1aLatestTimer);+ s1aLatestTimer = setTimeout(() => s1a.resolveLatest().catch(() => {}), s1a.resolved ? 900 : 0);+ return () => clearTimeout(s1aLatestTimer);+ });+ $effect(() => {+ if (!b.ready || shownB.provider?.id !== RADAR_ID) return;+ view.lat;+ view.lon;+ clearTimeout(s1bLatestTimer);+ s1bLatestTimer = setTimeout(() => s1b.resolveLatest().catch(() => {}), s1b.resolved ? 900 : 0);+ return () => clearTimeout(s1bLatestTimer);+ });+ let s1aLatestTimer;+ let s1bLatestTimer;+$effect(() => {if (a.ready && shownA.provider?.id === WAYBACK_ID) wba.loadReleases();});@@ -943,7 +971,7 @@layer: sentinel.layer,// A difference is only honest over named acquisitions. Freeze a live// "latest" pass to the date it meant when this workspace is saved.- date: difference ? sentinel.date || sentinel.latest : sentinel.date,+ date: difference ? sentinel.day : sentinel.date,maxcc: sentinel.maxcc,},wayback_release: wayback.release,@@ -2136,7 +2164,7 @@function evolutionSide(target, sentinel, wayback, radar) {const spec = sideSpec(target, sentinel, wayback, radar);if (target.providerId === WAYBACK_ID) return { ...spec, wayback_date: wayback.date };- return { ...spec, sentinel: { ...spec.sentinel, date: sentinel.date || sentinel.latest || '' } };+ return { ...spec, sentinel: { ...spec.sentinel, date: sentinel.day } };}/** The ground a picker row's picture shows: the evolution's centre, at its scale. */diff --git a/frontend/src/tools/Detect.svelte b/frontend/src/tools/Detect.svelteindex 7a91be3..cc43e45 100644--- a/frontend/src/tools/Detect.svelte+++ b/frontend/src/tools/Detect.svelte@@ -81,7 +81,7 @@let prefsLoaded = $state(false);const wayback = createWaybackState({ api, place: () => view });const s1 = createRadarState({ api, place: () => view, onBilled: () => imagery.refreshUsage() });- const shown = $derived(imagery.displayed(providerId, view.zoom, { ...s2.variant, release: wayback.release, pass: s1.pass }));+ const shown = $derived(imagery.displayed(providerId, view.zoom, { ...s2.variant, release: wayback.release, pass: s1.shownPass }));/** The metered archives. Any of them can be put on the map from its chip, with* its Copernicus layer and day, but none is remembered as the basemap: Detect* opens on free imagery every time. */@@ -122,6 +122,8 @@: layers);let showZones = $state(true);let selectedResult = $state(null);+ let resultMarkers = $state(true);+ let resultOutlines = $state(true);let areaGroups = $state([]);let highlight = $state([]);let manual = $state(null);@@ -139,6 +141,30 @@layersAsked = true;untrack(() => s2.loadLayers(false, true));});+ // A basemap with no date sends no mosaicking window, and Sentinel Hub then+ // blends the whole archive pixel by pixel. Detect pins a date whenever it+ // shows a pass; this covers the map before a run, so the ground an analyst+ // draws a zone on is one acquisition like everything that follows it.+ $effect(() => {+ if (!engine || shown.provider?.id !== SENTINEL) return;+ view.lat;+ view.lon;+ s2.maxcc;+ clearTimeout(s2LatestTimer);+ s2LatestTimer = setTimeout(() => s2.resolveLatest().catch(() => {}), s2.resolved ? 900 : 0);+ return () => clearTimeout(s2LatestTimer);+ });+ $effect(() => {+ if (!engine || shown.provider?.id !== RADAR_ID) return;+ view.lat;+ view.lon;+ clearTimeout(s1LatestTimer);+ s1LatestTimer = setTimeout(() => s1.resolveLatest().catch(() => {}), s1.resolved ? 900 : 0);+ return () => clearTimeout(s1LatestTimer);+ });+ let s2LatestTimer;+ let s1LatestTimer;+// What the last test found, outlined and pinned on the ground it judged.const previewLayer = $derived(builder?.detail ? [{id: 'builder-preview', visible: true,@@ -216,8 +242,8 @@});const marks = $derived(zoneMarks(zones));- const mapDate = $derived(s2.date || '');- const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.pass) : mapDate);+ const mapDate = $derived(s2.day);+ const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.shownPass) : mapDate);let passCloud = $state(null);let passContext = $state(null);const cloudyPass = $derived(providerId !== RADAR_ID && passCloud > ADVISED_MAXCC);@@ -707,16 +733,22 @@onusage={() => imagery.refreshUsage()} onimageryfallback={() => builder.setBasemap(true)} />{/if}{#if builder}- <RuleLayers {engine} {element} detail={builder.detail} rules={builder.recipe.rules} shown={paintedRules}- hover={builder.hovered} colours={builder.colours} split={builder.split} divider={builder.divider} stale={builder.stale} />- {#if previewLayer.length}- <AnalysisOverlay {engine} layers={previewLayer} onpick={(_, id) => {+ {#if !builder.hideOverlays}+ <RuleLayers {engine} {element} detail={builder.detail} rules={builder.recipe.rules} shown={paintedRules}+ hover={builder.hovered} colours={builder.colours} split={builder.split} divider={builder.divider}+ live={builder.live} stale={builder.staleToDraw} />+ {/if}+ {#if previewLayer.length && !builder.hideOverlays}+ <AnalysisOverlay {engine} layers={previewLayer} markers={builder.markers} outlines={builder.outlines}+ interactive={!builder.pinning && !measuring} onpick={(_, id) => {const row = builder.detail.candidates.find((candidate) => candidate.id === id);if (row) void builder.probeAt({ lon: row.coordinates[0], lat: row.coordinates[1] });}} />{/if}- <CheckMarks {engine} pins={builder.pins} armed={!!builder.pinning} selected={builder.probe?.pin ?? null}- onpick={(index) => builder.probePin(index)} />+ {#if builder.checkPins && !builder.hideOverlays}+ <CheckMarks {engine} pins={builder.pins} armed={!!builder.pinning} selected={builder.probe?.pin ?? null}+ onpick={(index) => builder.probePin(index)} />+ {/if}{#if builder.probe}<RuleProbe {engine} probe={builder.probe} rules={builder.recipe.rules} colours={builder.colours} single={builder.single}width={element?.clientWidth ?? 0} height={(element?.clientHeight ?? 0) - builder.reach} onclose={() => builder.closeProbe()}@@ -726,6 +758,8 @@{/if}{:else if !bare && (focusedRunId || savedVisible) && visibleRunLayers.some((layer) => layer.visible)}<AnalysisOverlay {engine} layers={visibleRunLayers} selected={selectedResult} active={!manual}+ markers={resultMarkers} outlines={resultOutlines}+ interactive={!measuring && drawing === 'select'}onpick={(run, result) => panel?.pick(run, result)} />{/if}{#if areaGroups.length && !manual && !bare && !builder}@@ -808,6 +842,8 @@bind:focusedRunIdbind:showZonesbind:selectedResult+ bind:markers={resultMarkers}+ bind:outlines={resultOutlines}bind:areaGroupsbind:highlightbind:barediff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 06d496a..474c969 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -44,6 +44,7 @@import { deletedToast, RESTORABLE } from '../lib/trash.js';import { extensionVersion, mapLinkRelay, onActivated } from '../lib/extBridge.js';import { SENTINEL_ID } from '../lib/sentinel.js';+ import { RADAR_ID } from '../lib/radar.js';import { WAYBACK_ID } from '../lib/wayback.js';import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';@@ -110,6 +111,7 @@import CaptureDetails from './satellite/CaptureDetails.svelte';import PlaceDialog from './satellite/PlaceDialog.svelte';import CaptureOptions from './satellite/CaptureOptions.svelte';+ import FigureDialog from './satellite/FigureDialog.svelte';import SavedTree from './satellite/SavedTree.svelte';import SavedSearch from './satellite/SavedSearch.svelte';import SavedOverlay from './satellite/SavedOverlay.svelte';@@ -160,6 +162,9 @@let rotating = $state(false);let rotatePivot = $state({ x: 0, y: 0 }); // grabbed point, map-wrap-local pxlet captureHover = $state(false); // previewing the crop frame (capture group hover)+ // A figure is several renderings of *one* Copernicus acquisition, so it needs+ // a dated pass and more than one layer to render it through.+ let figureOpen = $state(false);// The case's saved work — both indexes, the panel's filter and the Locate// pass — is its own store (state/saved.svelte.js).const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });@@ -419,6 +424,14 @@api,});const isSentinel = $derived(currentProvider?.id === SENTINEL_ID);+ /** Why a figure cannot be built from what is on screen, or '' when it can. */+ const figureProblem = $derived(+ !s2.day+ ? 'A figure needs a dated pass: every panel is the same acquisition.'+ : s2.layers.length < 2+ ? 'A figure needs more than one layer. Check your Copernicus layers, or write one.'+ : ''+ );// --- Esri Wayback: which release of World Imagery ---// The release rides on the provider id like a Sentinel-2 window, and both@@ -443,7 +456,7 @@// 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, release: wb.release, pass: s1.pass })+ imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release, pass: s1.shownPass }));// Fullscreen: the tool covers the whole viewport; SAVED stays collapsible (item 4).@@ -680,21 +693,40 @@});let s2PassTimer;- // Naming the date of what's on screen is why you'd pick this basemap, so the- // latest pass is resolved as soon as Sentinel-2 is actually being displayed —- // one metadata request, on the user's own action (choosing the basemap), and- // only once per place. Not on mount: no tab may phone out by being opened.+ // The date of what's on screen is why you'd pick this basemap, and it is also+ // what the tiles are rendered from: "most recent" is resolved to a day and+ // that day becomes the mosaicking window, so the picture is one acquisition+ // instead of a per-pixel blend of the archive. One metadata request, on the+ // user's own action (choosing the basemap), and only once per place and+ // ceiling. Not on mount: no tab may phone out by being opened.$effect(() => {if (!mapReady || shown.provider?.id !== SENTINEL_ID) return;center.lat;center.lon;s2.maxcc; // a new ceiling can make a different pass the most recent oneclearTimeout(s2LatestTimer);- // debounced: panning must not spend a request per frame- s2LatestTimer = setTimeout(() => s2.resolveLatest().catch(() => {}), 900);+ // With nothing resolved yet the tiles have no window and blend dates, so+ // that lookup goes out at once; afterwards the resolved day holds while a+ // new one is found, and the debounce keeps a pan from spending a request+ // per frame.+ const wait = s2.resolved ? 900 : 0;+ s2LatestTimer = setTimeout(() => s2.resolveLatest().catch(() => {}), wait);});let s2LatestTimer;+ // The radar basemap carries the same rule: no window blends every pass in the+ // archive, which mixes looks from opposite sides of the track. One lookup, on+ // the user's own action, once per place.+ $effect(() => {+ if (!mapReady || shown.provider?.id !== RADAR_ID) return;+ center.lat;+ center.lon;+ clearTimeout(s1LatestTimer);+ s1LatestTimer = setTimeout(() => s1.resolveLatest().catch(() => {}), s1.resolved ? 900 : 0);+ return () => clearTimeout(s1LatestTimer);+ });+ let s1LatestTimer;+// 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(() => {@@ -2493,8 +2525,30 @@bind:scaleNorth={capture.scaleNorth}openScreenshot={() => (capture.shotOpen = true)}openExtensionGate={() => (capture.extGate = true)}+ openFigure={isSentinel ? () => (figureOpen = true) : null}+ figureBlocked={figureProblem}/></MapStatusBar>+ {#if figureOpen && caseState.current}+ <FigureDialog+ caseId={caseState.current.id}+ day={s2.day}+ maxcc={s2.maxcc}+ view={{ lat: center.lat, lon: center.lon, zoom: center.zoom, bearing }}+ width={capture.size[0]}+ height={capture.size[1]}+ layers={s2.layers}+ scaleNorth={capture.scaleNorth}+ onclose={() => (figureOpen = false)}+ onbuilt={(built) => {+ figureOpen = false;+ // Straight into the composer: a figure is made to be annotated, and+ // its panels are already filed whether or not it is opened now.+ uiState.openProof = built.proof.name;+ uiState.tool = 'proof';+ }}+ />+ {/if}{#if pointMenu}<MapContextMenuat={pointMenu}diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.jsindex d299b04..8fcce42 100644--- a/frontend/src/tools/Satellite.test.js+++ b/frontend/src/tools/Satellite.test.js@@ -734,10 +734,11 @@ describe('a map in more than one window', () => {surface.indexOf('{#if s2 && shown.provider?.id === SENTINEL_ID}'),surface.indexOf('{:else if s1 && shown.provider?.id === RADAR_ID}'));- // the pill always reads the day, marks a pinned one, and says how it was chosen- expect(s2Pill).toContain('{pinnedDay ?? s2.latest ?? \'\'}');- expect(s2Pill).toContain('class:exact={!!pinnedDay}');- expect(s2Pill).toContain("{s2.latest ? 'latest' : 'most recent'}");+ // the pill reads the day the window named, and says so rather than naming a+ // pass when the tiles blend the archive+ expect(s2Pill).toContain("{renderedDay ?? (s2.undated ? 'several dates' : 'finding…')}");+ expect(s2Pill).toContain('class:exact={!!renderedDay}');+ expect(s2Pill).toContain('class:undated={!renderedDay && s2.undated}');});it('opens that tab on the map alone', () => {@@ -856,7 +857,7 @@ describe('Esri Wayback', () => {});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, pass: s1.pass })');+ expect(source).toContain('imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release, pass: s1.shownPass })');expect(source).toContain('wayback={wb}');// …and the radar pass beside itexpect(source).toContain('{s1}');diff --git a/frontend/src/tools/detect/AnalysisOverlay.render.test.js b/frontend/src/tools/detect/AnalysisOverlay.render.test.jsnew file mode 100644index 0000000..7bd0881--- /dev/null+++ b/frontend/src/tools/detect/AnalysisOverlay.render.test.js@@ -0,0 +1,99 @@+// @vitest-environment happy-dom+import { afterEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import AnalysisOverlay from './AnalysisOverlay.svelte';+import { liveProps } from './props.fixture.svelte.js';++const engine = { on: () => () => {}, setView: vi.fn(), getZoom: () => 12,+ latLngToContainerPoint: ({ lon, lat }) => ({ x: lon * 100, y: lat * 100 }) };+const row = (id, lon, extra = {}) => ({ id, coordinates: [lon, 1], bbox: [lon, 1, lon + 0.1, 1.1],+ review: 'new', phenomenon: 'Surface change', ...extra });+const layer = (extra = {}) => ({ id: 'run', visible: true, input: { recipe: { colour: '#f6a81a', style: 'both' } },+ results: [row('a', 1), row('b', 1.1, { origin: 'manual' }), row('c', 2), row('gone', 3, { review: 'dismissed' })], ...extra });+let live, target;+afterEach(() => { if (live) unmount(live); target?.remove(); vi.clearAllMocks(); });+function open(extra = {}) {+ const props = liveProps({ engine, layers: [layer()], ...extra });+ target = document.createElement('div'); document.body.append(target);+ live = mount(AnalysisOverlay, { target, props }); flushSync();+ return props;+}++it('hides markers and numbered groups independently from outlines without changing results', () => {+ const props = open();+ expect(target.querySelectorAll('.outline')).toHaveLength(3);+ expect(target.querySelectorAll('g')).toHaveLength(2);+ expect(target.querySelector('text').textContent).toBe('2');+ props.markers = false; flushSync();+ expect(target.querySelectorAll('circle, g, text')).toHaveLength(0);+ expect(target.querySelectorAll('.outline')).toHaveLength(3);+ expect(props.layers[0].results).toHaveLength(4);+ props.markers = true; props.outlines = false; flushSync();+ expect(target.querySelectorAll('.outline')).toHaveLength(0);+ expect(target.querySelectorAll('g')).toHaveLength(2);+ props.markers = false; flushSync();+ expect(target.querySelector('svg').children).toHaveLength(0);+});++it('selects an exact candidate through its outline and highlights it with the markers hidden', () => {+ const onpick = vi.fn();+ const props = open({ markers: false, selected: 'b', onpick });+ const paths = [...target.querySelectorAll('.outline')];+ expect(paths.map((path) => path.getAttribute('tabindex'))).toEqual(['0', '0', '0']);+ expect(paths[1].getAttribute('stroke')).toBe('#f6a81a');+ expect(paths[1].getAttribute('stroke-width')).toBe('3');+ expect(paths[1].getAttribute('stroke-dasharray')).toBe('5 3');+ paths[1].dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ expect(onpick).toHaveBeenLastCalledWith('run', 'b');+ paths[0].dispatchEvent(new MouseEvent('click', { bubbles: true, button: 1 }));+ expect(onpick).toHaveBeenCalledTimes(1);+ const key = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true });+ paths[2].dispatchEvent(key);+ expect(key.defaultPrevented).toBe(true);+ expect(onpick).toHaveBeenLastCalledWith('run', 'c');+ props.selected = 'c'; flushSync();+ expect(paths[1].classList.contains('selected')).toBe(false);+ expect(paths[2].classList.contains('selected')).toBe(true);+ expect(engine.setView).not.toHaveBeenCalled();+});++it('preserves pin-only recipes and draws no empty selectable outline for a point', () => {+ open({ layers: [layer({ input: { recipe: { colour: '#f6a81a', style: 'pins' } } }),+ layer({ id: 'points', results: [row('point', 4, { geometry: { type: 'Point', coordinates: [4, 1] } })] })] });+ expect(target.querySelectorAll('.outline')).toHaveLength(0);+ expect(target.querySelectorAll('g')).toHaveLength(3);+});++it('respects hidden layers and the active gate with either display choice', () => {+ const props = open({ layers: [layer({ visible: false })] });+ expect(target.querySelector('svg').children).toHaveLength(0);+ props.layers = [layer()]; props.active = false; flushSync();+ expect(target.querySelector('svg').children).toHaveLength(0);+});++it('leaves the click to drawing or measurement without hiding the outlines', () => {+ const onpick = vi.fn();+ const props = open({ markers: false, interactive: false, onpick });+ const paths = [...target.querySelectorAll('.outline')];+ expect(paths).toHaveLength(3);+ expect(paths.every((path) => path.classList.contains('passive') && path.getAttribute('tabindex') === '-1')).toBe(true);+ paths[0].dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ paths[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ expect(onpick).not.toHaveBeenCalled();+ props.markers = true; flushSync();+ target.querySelector('g').dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ expect(engine.setView).not.toHaveBeenCalled();+});++it('relays zoom to the map when the pointer is over a clickable outline', () => {+ const container = document.createElement('div'), canvas = document.createElement('canvas');+ container.append(canvas); document.body.append(container);+ const zoomed = vi.fn(); canvas.addEventListener('wheel', zoomed);+ open({ engine: { ...engine, container }, markers: false });+ const shape = target.querySelector('.outline');+ const original = document.elementsFromPoint;+ document.elementsFromPoint = () => [shape, canvas];+ shape.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: -120 }));+ expect(zoomed).toHaveBeenCalledTimes(1);+ document.elementsFromPoint = original; container.remove();+});diff --git a/frontend/src/tools/detect/AnalysisOverlay.svelte b/frontend/src/tools/detect/AnalysisOverlay.svelteindex f9afa91..ae4cd75 100644--- a/frontend/src/tools/detect/AnalysisOverlay.svelte+++ b/frontend/src/tools/detect/AnalysisOverlay.svelte@@ -2,7 +2,7 @@import { displayGroups } from '../../lib/map/analyzers.js';import { candidatePaths } from '../../lib/map/detectReview.js';import { relayWheel } from '../../lib/map/wheelRelay.js';- let { engine, layers = [], selected = null, onpick = () => {}, active = true } = $props();+ let { engine, layers = [], selected = null, onpick = () => {}, active = true, markers = true, outlines = true, interactive = true } = $props();let svg = $state(null);let revision = $state(0);$effect(() => {@@ -19,9 +19,9 @@const shown = $derived.by(() => {if (!engine || !active) return [];return layers.filter((layer) => layer.visible).map((layer) => ({ ...layer,- boxes: visible(layer.results).map((row) => ({ id: row.id, manual: row.origin === 'manual',- path: candidatePaths(row.geometry ?? rectangle(row), project) })),- groups: displayGroups(visible(layer.results), project),+ boxes: visible(layer.results).map((row) => ({ id: row.id, label: row.phenomenon || 'Candidate', manual: row.origin === 'manual',+ path: candidatePaths(row.geometry ?? rectangle(row), project) })).filter((shape) => shape.path),+ groups: markers ? displayGroups(visible(layer.results), project) : [],}));});function rectangle(row) {@@ -29,6 +29,7 @@return { type: 'Polygon', coordinates: [[[w, n], [e, n], [e, s], [w, s], [w, n]]] };}function pick(layer, group) {+ if (!interactive) return;if (group.rows.length > 1 && engine) {const [lon, lat] = group.rows[0].coordinates;engine.setView({ lon, lat }, engine.getZoom() + 2);@@ -39,17 +40,25 @@<svg class="analysis-overlay" bind:this={svg} aria-label="Analysis candidates"onwheel={(event) => relayWheel(event, { engine, root: svg })}>{#each shown as layer (layer.id)}- {#if layer.input.recipe.style !== 'pins'}+ {#if outlines && layer.input.recipe.style !== 'pins'}{#each layer.boxes as shape (shape.id)}- <path d={shape.path} fill={layer.displayColour || layer.display_colour || layer.input.recipe.colour} fill-opacity="0.08" fill-rule="evenodd"- stroke={layer.displayColour || layer.display_colour || layer.input.recipe.colour} stroke-width="1.5" stroke-dasharray={shape.manual ? '5 3' : undefined} />+ <path class="outline" class:selected={shape.id === selected} class:passive={!interactive} d={shape.path}+ fill={layer.displayColour || layer.display_colour || layer.input.recipe.colour} fill-opacity="0.08" fill-rule="evenodd"+ stroke={layer.displayColour || layer.display_colour || layer.input.recipe.colour}+ stroke-width={shape.id === selected ? 3 : 1.5} stroke-dasharray={shape.manual ? '5 3' : undefined}+ role="button" tabindex={markers || !interactive ? -1 : 0} aria-disabled={!interactive} aria-label={`${shape.label} outline`}+ onclick={(event) => { if (interactive && event.button === 0) onpick(layer.id, shape.id); }}+ onkeydown={(event) => { if (interactive && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault(); onpick(layer.id, shape.id);+ } }} />{/each}{/if}{#each layer.groups as group, i (i)}{@const kept = group.rows.every((row) => row.review === 'kept' || row.review === 'noted')}- <g role="button" tabindex="0" aria-label={group.rows.length > 1 ? `${group.rows.length} candidates` : group.rows[0].phenomenon}+ <g class:passive={!interactive} role="button" tabindex={interactive ? 0 : -1} aria-disabled={!interactive}+ aria-label={group.rows.length > 1 ? `${group.rows.length} candidates` : group.rows[0].phenomenon}onclick={(event) => { if (event.button === 0) pick(layer, group); }}- onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') pick(layer, group); }}>+ onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(layer, group); } }}><!-- The one under review wears a ring, so the panel and the map arenever about two different candidates. -->{#if group.rows.some((row) => row.id === selected)}@@ -69,5 +78,9 @@<style>.analysis-overlay { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 545; pointer-events: none; }g { pointer-events: auto; cursor: pointer; }+ .outline { pointer-events: stroke; cursor: pointer; }+ .outline.selected { filter: drop-shadow(0 0 2px #fff); }+ .outline:focus-visible { stroke: #fff; stroke-width: 2.5; outline: none; }+ .outline.passive, g.passive { pointer-events: none; }text { fill: #111; text-anchor: middle; font: bold 11px system-ui; pointer-events: none; }</style>diff --git a/frontend/src/tools/detect/AnalyzerBuilder.fromLayer.svelte.test.js b/frontend/src/tools/detect/AnalyzerBuilder.fromLayer.svelte.test.jsnew file mode 100644index 0000000..a708e23--- /dev/null+++ b/frontend/src/tools/detect/AnalyzerBuilder.fromLayer.svelte.test.js@@ -0,0 +1,140 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import { newRecipe } from '../../lib/map/analyzerRules.js';++/**+ * Building a rule out of a layer written here.+ *+ * The menu lists *every* layer, because a layer silently missing from it reads+ * as "rules cannot be built from my layers", which is the opposite of what is+ * true. The ones that are one quantity are offered; the ones that are not carry+ * the reason and cannot be pressed.+ */++const LAYERS = [+ { id: 'PLUME', label: 'Plume', form: { way: 'index', high: 'B12', low: 'B11', threshold: 0.15 } },+ { id: 'B12_GREY', label: 'B12', form: { way: 'composite', red: 'B12', green: 'B12', blue: 'B12', gain: 2.5 } },+ { id: 'FALSE_COLOUR', label: 'False colour', form: { way: 'composite', red: 'B08', green: 'B04', blue: 'B03', gain: 2.5 } },+ { id: 'HAND', label: 'Hand written', form: null },+];++let served = LAYERS;+const got = vi.fn();+vi.mock('../../lib/api.js', () => ({+ api: {+ get: vi.fn(async (path) => {+ got(path);+ return { layers: served, max: 40, bands: [], radar_layer: 'RADAR' };+ }),+ post: vi.fn(async () => ({ tiles: 1, missing: 0 })),+ },+}));+vi.mock('../../lib/state.svelte.js', () => ({ toast: vi.fn() }));++const AnalyzerBuilder = (await import('./AnalyzerBuilder.svelte')).default;++const METHODS = [{ id: 'rules', sizes: { all: {} } }];+let live, target;+// A rune, so the builder's `$bindable` recipe is the reactive object it expects.+let recipe = $state(null);++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+ document.body.innerHTML = '';+});++async function open({ wait = true } = {}) {+ recipe = { ...newRecipe(METHODS, { dates: 'two' }), name: 'Mine' };+ target = document.createElement('div');+ document.body.append(target);+ live = mount(AnalyzerBuilder, {+ target,+ props: {+ catalogue: { rules: { max_rules: 6 }, methods: METHODS, radar_layer: 'RADAR' },+ get recipe() { return recipe; },+ set recipe(next) { recipe = next; },+ isNew: true,+ layers: [],+ },+ });+ if (!wait) return recipe;+ await vi.waitFor(() => {+ flushSync();+ if (!target.querySelector('.from-layer')) throw new Error('not read yet');+ });+ return recipe;+}++const button = (label) =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));+const options = () => [...target.querySelectorAll('.layer-opt')];++beforeEach(() => {+ served = LAYERS;+ got.mockClear();+});++it('lists every layer written here, offered or with the reason it is not', async () => {+ await open();+ button('Reuse a formula').click();+ flushSync();+ const rows = options().map((node) => ({+ name: node.querySelector('.layer-name').textContent.trim(),+ says: node.querySelector('.layer-sum').textContent.trim(),+ off: node.disabled,+ }));+ expect(rows).toEqual([+ { name: 'Plume', says: '(B12 − B11) / (B12 + B11) ≥ 0.15', off: false },+ { name: 'B12', says: 'B12 reflectance', off: false },+ { name: 'False colour', says: 'three bands in colour, not one quantity', off: true },+ { name: 'Hand written', says: 'written as a script, so no quantity to read', off: true },+ ]);+});++it('adds an index layer as the normalised difference it paints', async () => {+ const made = await open();+ const before = made.rules.length;+ button('Reuse a formula').click();+ flushSync();+ options()[0].click();+ flushSync();+ expect(recipe.rules).toHaveLength(before + 1);+ expect(recipe.rules.at(-1)).toMatchObject({+ measure: 'nd', bands: ['B12', 'B11'], op: 'ge', value: 0.15,+ });+});++it('adds a band painted grey as that band, on the line a band rule starts at', async () => {+ const made = await open();+ const before = made.rules.length;+ button('Reuse a formula').click();+ flushSync();+ options()[1].click();+ flushSync();+ expect(recipe.rules).toHaveLength(before + 1);+ // the gain the layer is drawn with is not a threshold, so the rule takes its own+ expect(recipe.rules.at(-1)).toMatchObject({ measure: 'band', band: 'B12', op: 'ge', value: 0.25 });+});++it('reads the layer list once, even when there is nothing in it', async () => {+ /*+ * A regression with teeth: waiting on `mine.length` made an empty list its+ * own trigger. The read assigns a fresh array, the array is the effect's+ * dependency, and the effect reads again — forever. One analyzer builder in a+ * test file took a worker from 7 seconds to a 4 GB heap death.+ */+ served = [];+ await open({ wait: false });+ await vi.waitFor(() => expect(got).toHaveBeenCalled());+ const after = got.mock.calls.length;+ // nothing more arrives on its own+ await new Promise((resolve) => setTimeout(resolve, 60));+ flushSync();+ expect(got.mock.calls.length).toBe(after);+ expect(after).toBeLessThanOrEqual(1);+ // and with nothing to offer, the button is not there at all+ expect(target.querySelector('.from-layer')).toBe(null);+});diff --git a/frontend/src/tools/detect/AnalyzerBuilder.svelte b/frontend/src/tools/detect/AnalyzerBuilder.svelteindex 6033513..e67ccb4 100644--- a/frontend/src/tools/detect/AnalyzerBuilder.svelte+++ b/frontend/src/tools/detect/AnalyzerBuilder.svelte@@ -28,6 +28,7 @@import AnalyzerSettings from './AnalyzerSettings.svelte';import RuleRow from './RuleRow.svelte';import Icon from '../../components/Icon.svelte';+ import { layerAsRule, layerRuleWords, readCustomLayers, whyNotARule } from '../../lib/customLayers.js';let {catalogue,@@ -82,6 +83,45 @@if (recipe.rules.length >= most) return;recipe.rules = [...recipe.rules, newRule(radar ? 'radar' : 'index', single ? 'b' : 'a')];}++ /**+ * A rule out of a layer you wrote.+ *+ * A layer that paints one quantity is already a rule: an index is `nd`, and a+ * band painted grey into all three channels is `band`. So the arithmetic you+ * settled on looking at the map comes over as the rule it was, rather than+ * being typed a second time from memory.+ *+ * Every layer is listed, including the ones that cannot come over, each with+ * the reason (`whyNotARule`). Hiding them would say rules cannot be built+ * from your layers at all, which is the opposite of what is true.+ */+ let mine = $state([]); // every layer written here, read when the builder opens+ let fromLayerOpen = $state(false);+ // Read once, and never again on the answer. Waiting on `mine.length` instead+ // would make an empty list its own trigger: the read assigns a fresh array,+ // the array is the effect's dependency, and the effect reads again forever.+ let asked = false;++ $effect(() => {+ if (radar || asked) return;+ asked = true;+ // A local file, not a request to Copernicus: reading it costs nothing.+ untrack(() =>+ readCustomLayers(api)+ .then((found) => (mine = found.layers ?? []))+ .catch(() => {})+ );+ });++ function addFromLayer(layer) {+ const made = layerAsRule(layer);+ fromLayerOpen = false;+ if (!made || recipe.rules.length >= most) return;+ const { measure, ...line } = made;+ recipe.rules = [...recipe.rules, newRule(measure, single ? 'b' : 'a', line)];+ toast(`${layer.label || layer.id} added as a rule`, 'ok');+ }function remove(i) {recipe.rules = recipe.rules.filter((_, k) => k !== i);bench.ruleRemoved(i);@@ -167,17 +207,51 @@{#each recipe.rules as _, i (i)}<RuleRow bind:rule={recipe.rules[i]} {recipe} index={i} colour={RULE_COLOURS[i % RULE_COLOURS.length]}signal={i === signal} reading={bench.detail?.rules?.[i] ?? null} stale={bench.stale}+ tested={!!bench.detail}ticks={pinTicks(recipe.rules[i], bench.marks, bench.detail?.readings, i)}effect={bench.stale ? '' : describeWithout(bench.marks, bench.detail?.covered, bench.detail?.without?.[i]?.covered)}match={recipe.match} shown={bench.painted(i)} ontoggle={() => bench.toggleRule(i)}+ drawn={bench.ruleLayer?.index === i} drawing={bench.ruleLayerBusy && bench.ruleLayer?.index !== i}+ onsee={() => bench.showRule(i)} onlive={() => void bench.loadReading(i)}bands={limits.bands} classes={limits.classes} maxAround={limits.max_around}canRemove={recipe.rules.length > 1} onremove={() => remove(i)} onsignal={() => rank(i)}onhover={(index) => bench.hoverRule(index)} />{/each}- <button class="btn btn-sm" disabled={recipe.rules.length >= most}- title={recipe.rules.length >= most ? `At most ${most} rules per analyzer` : undefined} onclick={add}>- <Icon name="plus" size={13} /> Add a rule- </button>+ <div class="add-rule">+ <button class="btn btn-sm" disabled={recipe.rules.length >= most}+ title={recipe.rules.length >= most ? `At most ${most} rules per analyzer` : undefined} onclick={add}>+ <Icon name="plus" size={13} /> Add a rule+ </button>+ {#if mine.length}+ <div class="from-layer">+ <button class="btn btn-sm" class:on={fromLayerOpen}+ disabled={recipe.rules.length >= most}+ title="A formula you wrote, as the rule it already is"+ onclick={() => (fromLayerOpen = !fromLayerOpen)}>+ Reuse a formula <Icon name="chevronDown" size={12} />+ </button>+ {#if fromLayerOpen}+ <div class="layer-menu card" role="menu">+ {#each mine as row (row.id)}+ {@const why = whyNotARule(row)}+ <button class="layer-opt" role="menuitem" disabled={!!why}+ title={why ? `Cannot become a rule: ${why}` : 'Add it as a rule'}+ onclick={() => addFromLayer(row)}>+ <span class="layer-name">{row.label || row.id}</span>+ <span class="layer-sum" class:mono={!why}>+ {why || layerRuleWords(row)}+ </span>+ </button>+ {/each}+ <p class="layer-note">+ A rule reads one number per pixel, so an index or a band comes over and a+ colour composite does not.+ </p>+ </div>+ {/if}+ </div>+ {/if}+ </div></section>{:else if tab === 'checks'}<AnalyzerChecks {bench} />@@ -206,6 +280,45 @@</div><style>+ /* Add a rule, and the shortcut for one you already settled on looking at the+ map: an index layer you wrote is the same arithmetic. */+ .add-rule { display: flex; gap: 6px; flex-wrap: wrap; }+ .from-layer { position: relative; }+ .from-layer .btn.on { border-color: var(--accent); color: var(--accent); }+ .layer-menu {+ position: absolute;+ z-index: 40;+ top: calc(100% + 5px);+ left: 0;+ display: grid;+ gap: 2px;+ min-width: 260px;+ max-width: min(360px, 80vw);+ padding: 5px;+ }+ .layer-opt {+ display: grid;+ gap: 1px;+ padding: 6px 8px;+ border: 0;+ border-radius: var(--r-sm);+ background: none;+ text-align: left;+ cursor: pointer;+ }+ .layer-opt:hover:not(:disabled) { background: var(--bg-2); }+ /* Shown and not offered: the row is the explanation of why it is not there. */+ .layer-opt:disabled { cursor: default; opacity: 0.55; }+ .layer-name { font-size: var(--fs-sm); color: var(--text-1); }+ .layer-sum { font-size: var(--fs-xs); color: var(--text-3); }+ .layer-note {+ margin: 3px 2px 1px;+ padding-top: 5px;+ border-top: 1px solid var(--border);+ font-size: var(--fs-xs);+ line-height: 1.4;+ color: var(--text-3);+ }.builder { grid-template-columns: minmax(0, 1fr); align-content: start; gap: 10px; }.panel { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; transition: opacity 0.15s var(--ease); }.panel.locked { opacity: 0.4; pointer-events: none; user-select: none; }diff --git a/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js b/frontend/src/tools/detect/AnalyzerChecks.svelte.test.jsindex 3fa0ce6..a8075db 100644--- a/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js+++ b/frontend/src/tools/detect/AnalyzerChecks.svelte.test.js@@ -25,7 +25,7 @@ function open({ dates = 'two', checks = [] } = {}) {const api = { post: vi.fn(async (url, body) => (url.endsWith('/plan') ? { tiles: 1, missing: 2 }: { ready: true, missing: 0, count: 1, covered: body.check.marks.map((mark) => mark.expect === 'found'), size: 512, tiles: [],rules: [], candidates: [], readings: [] })) };- bench = new Bench({ api, recipe, limits: { max_checks: 2, max_marks: 20 }, viewBounds: () => null });+ bench = new Bench({ api, recipe, limits: { max_checks: 2, max_marks: 60 }, viewBounds: () => null });target = document.createElement('div');document.body.append(target);live = mount(AnalyzerChecks, { target, props: { bench } });diff --git a/frontend/src/tools/detect/CheckBench.svelte b/frontend/src/tools/detect/CheckBench.svelteindex d870807..7297da8 100644--- a/frontend/src/tools/detect/CheckBench.svelte+++ b/frontend/src/tools/detect/CheckBench.svelte@@ -18,6 +18,7 @@import PassDates from './PassDates.svelte';import Icon from '../../components/Icon.svelte';import CopernicusLayersHelp from '../../components/CopernicusLayersHelp.svelte';+ import OverlayDisplay from './OverlayDisplay.svelte';let { bench } = $props();@@ -39,7 +40,10 @@const pinCount = $derived(bench.marks.length);/** The layer's name without its explanation: "NDVI (vegetation index)" is NDVI on a button. */const layerLabel = $derived((bench.offered.find((entry) => entry.id === bench.layer && entry.enabled !== false)?.label ?? 'Choose a layer').replace(/\s*\(.*$/, ''));+ /** A rule's own arithmetic is the imagery, so the chip says that rather than a layer nobody chose. */+ const drawnRule = $derived(bench.ruleLayer ? bench.ruleLayer.index + 1 : 0);const suggestion = $derived(bench.suggestion);+ const suggestionWords = $derived(bench.suggestionWords);/** How every pin came out, from the last test, with the count of what it found. */const outcome = $derived.by(() => {@@ -165,9 +169,11 @@{/if}<button class="cmp-icon" aria-label="Change the passes" title="Change the passes" onclick={() => bench.changePasses()}><Icon name="calendar" size={14} /></button>+ <!-- Not an eye: this one swaps the imagery, while the eye below takes the+ drawings off it. Two eyes a few inches apart read as the same switch. --><button class="cmp-icon eye" class:on={!bench.basemap} aria-pressed={!bench.basemap} aria-label="Passes on the map"title={bench.basemap ? 'Show the passes' : 'Show the basemap'} onclick={() => bench.setBasemap(!bench.basemap)}>- <Icon name={bench.basemap ? 'eyeOff' : 'eye'} size={15} /></button>+ <Icon name="satellite" size={15} /></button>{#if !bench.radar}<div class="pick look-pick"><button class="select look" class:off={bench.basemap} aria-haspopup="menu" aria-expanded={open === 'look'}@@ -175,17 +181,27 @@open = open === 'look' ? '' : 'look';if (open === 'look') void bench.checkLayers();}}>- <Icon name="layers" size={14} /><span>Display: {layerLabel}</span><Icon name="chevronDown" size={13} />+ <Icon name="layers" size={14} /><span>Display: {drawnRule ? `rule ${drawnRule}` : layerLabel}</span><Icon+ name="chevronDown" size={13} /></button>{#if open === 'look'}<div class="menu look-menu cmp-glass" role="menu" aria-label="Copernicus layer">+ <p class="layer-aside">What you look at. Rules read the bands themselves.</p>+ {#if drawnRule}+ <button class="layer-drawn" role="menuitem" onclick={() => { bench.hideRule(); open = ''; }}>+ Rule {drawnRule} is drawn on the map. Put this display back.+ </button>+ {/if}{#each bench.offered as entry (entry.id)}<button role="menuitemradio" aria-checked={bench.layer === entry.id} disabled={entry.enabled === false}title={entry.reason || entry.hint || undefined}onclick={() => { bench.setLayer(entry.id); open = ''; }}>- <span class="grow">{entry.label}<span class="layer-id cmp-mono">{entry.id}</span>+ <span class="grow">{entry.label}{#if entry.custom}<span class="layer-mine">yours</span>{/if}<span+ class="layer-id cmp-mono">{entry.id}</span>{#if entry.reason}<span class="layer-reason">{entry.reason}</span>{/if}</span>- {#if entry.enabled !== false && entry.id === suggestion}<small>for rule ★</small>{/if}+ {#if entry.enabled !== false && entry.id === suggestion && suggestionWords}+ <small>{suggestionWords}</small>+ {/if}</button>{/each}<hr />@@ -229,13 +245,17 @@onclick={() => bench.arm('empty')}><i class="shape shape-empty" aria-hidden="true"></i>Should stay empty</button><span class="count cmp-mono">{pinCount} pin{pinCount === 1 ? '' : 's'}</span></div>+ <span class="overlay-acts">+ <OverlayDisplay bind:markers={bench.markers} bind:outlines={bench.outlines} bind:checkPins={bench.checkPins}+ bind:hidden={bench.hideOverlays} what="the check overlays" upward />+ </span><button class="btn test" class:btn-primary={!bench.tested} class:done={bench.tested} disabled={!bench.canTest}title={bench.blocked || undefined} onclick={() => bench.test()}>{bench.testLabel}</button></div>- {#if bench.pinning}- <p class="note" role="status">Click the ground where {bench.pinning === 'found' ? 'a candidate should be found' : 'none should be'} (Esc stops).</p>- {:else if bench.blocked && bench.dated}+ {#if bench.blocked && bench.dated && (!bench.pinning || bench.plan?.error)}<p class="note" class:warn={!!bench.plan?.error} role="status">{bench.blocked}</p>+ {:else if bench.pinning}+ <p class="note" role="status">Click the ground where {bench.pinning === 'found' ? 'a candidate should be found' : 'none should be'} (Esc stops).</p>{/if}{/if}@@ -283,6 +303,7 @@.head, .tools, .result { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; min-width: 0; }.head { position: relative; }.grow { flex: 1; }+ .overlay-acts { display: inline-flex; margin-left: auto; }/* Which check is on the map, which pass of it, and how the passes are shown. */.pick { position: relative; min-width: 0; }@@ -335,6 +356,28 @@.look-pick { position: static; }.look-menu { left: auto; right: 10px; width: 320px; max-width: calc(100% - 20px); gap: 0; }.layer-id, .layer-reason { display: block; font-size: var(--fs-xs); color: var(--glass-muted); }+ /* Said where the two are confused: the display is what the eye reads, never+ what a rule measures. A rule reads the bands straight from the archive. */+ .layer-aside {+ margin: 0; padding: 7px 10px 8px; font-size: var(--fs-xs);+ color: var(--glass-muted); border-bottom: 1px solid var(--glass-line);+ }+ .layer-drawn {+ width: 100%; padding: 7px 10px; border: 0; border-bottom: 1px solid var(--glass-line);+ background: none; color: var(--accent); font-size: var(--fs-xs); text-align: left; cursor: pointer;+ }+ /* A layer written in Azimut, so the list says which ones are the analyst's own+ rather than the configuration's. */+ .layer-mine {+ margin-left: 6px;+ padding: 0 4px;+ border: 1px solid var(--glass-line);+ border-radius: 3px;+ font-size: 9px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--glass-muted);+ }.layer-reason { white-space: normal; }.layer-setup, .layer-status { display: grid; gap: 7px; padding: 8px 10px; font-size: var(--fs-xs); }.layer-status { border-top: 1px solid var(--glass-line); color: var(--warn); }diff --git a/frontend/src/tools/detect/CheckBench.svelte.test.js b/frontend/src/tools/detect/CheckBench.svelte.test.jsindex 35262fa..bac2b96 100644--- a/frontend/src/tools/detect/CheckBench.svelte.test.js+++ b/frontend/src/tools/detect/CheckBench.svelte.test.js@@ -21,19 +21,25 @@ afterEach(() => {vi.useRealTimers();});-function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers, layerState = null } = {}) {+function open({ dates = 'two', sensor = 'sentinel2', checks = [], layers, layerState = null, planError = '' } = {}) {const recipe = $state({ ...newRecipe(METHODS, { sensor, dates }), name: 'Mine', checks });const api = { post: vi.fn(async (url, body) => {calls.push([url, body]);- if (url.endsWith('/check/plan')) return { tiles: 1, missing: 4 };+ if (url.endsWith('/check/plan')) {+ if (planError) throw new Error(planError);+ return { tiles: 1, missing: 4 };+ }if (url.endsWith('/check')) {const covered = body.check.marks.map((mark) => mark.expect === 'found');return { ready: true, missing: 0, count: 1, covered, size: 512, tiles: [], rules: body.recipe.rules.map(() => ({ share: 0.1, kept: 0.1 })),candidates: [], readings: [] };}return { dates: [{ date: '2026-05-11', cloud: 4, coverage: 1 }, { date: '2026-05-04', cloud: 2, coverage: 1 }], truncated: false };- }) };- bench = new Bench({ api, recipe, limits: { max_checks: 12, max_marks: 20 }, layers: () => layers ?? [],+ }),+ // Letting a drawn rule go clears the draft it was rendered under.+ put: vi.fn(async () => ({ id: 'AZIMUT_DRAFT_ABC123' })),+ del: vi.fn(async () => ({})) };+ bench = new Bench({ api, recipe, limits: { max_checks: 12, max_marks: 60 }, layers: () => layers ?? [],layerState: () => layerState, viewBounds: () => VIEW });target = document.createElement('div');document.body.append(target);@@ -113,6 +119,43 @@ it('arms a pin, says what a click will do, and says how many are down', () => {expect(bench.pinning).toBe(null);});+it('changes only the check display and restores its choices after hiding all overlays', async () => {+ const { recipe } = open({ checks: [made('The plot')] });+ bench.select(bench.checks[0].id); flushSync(); await settle();+ const savedRecipe = JSON.stringify(recipe), before = calls.length;+ click(query('[aria-label="Which overlays"]'));+ await Promise.resolve(); flushSync();+ const rows = [...query('[role="menu"]').querySelectorAll('[role="menuitemcheckbox"]')];+ expect(rows.map((row) => row.textContent.trim())).toEqual(['Markers', 'Outlines', 'Check pins']);+ click(rows[0]); click(rows[2]);+ expect([bench.markers, bench.outlines, bench.checkPins]).toEqual([false, true, false]);+ document.body.dispatchEvent(new Event('pointerdown', { bubbles: true })); flushSync();+ click(query('[aria-label="Hide the check overlays"]'));+ expect(bench.hideOverlays).toBe(true);+ click(query('[aria-label="Hide the check overlays"]'));+ expect(bench.hideOverlays).toBe(false);+ expect([bench.markers, bench.outlines, bench.checkPins]).toEqual([false, true, false]);+ await settle();+ expect(JSON.stringify(recipe)).toBe(savedRecipe);+ expect(calls).toHaveLength(before);+});++it('shows the tile limit error while a pin is armed and blocks Test before fetching', async () => {+ const error = 'these pins reach 21 tiles and a check reads at most 20: start another check';+ open({ checks: [made('The plot')], planError: error });+ bench.select(bench.checks[0].id);+ bench.arm('found'); flushSync();+ await settle();+ expect(bench.pinning).toBe('found');+ expect(query('.note.warn[role="status"]').textContent).toBe(error);+ expect(query('.test').title).toBe(error);+ expect(query('.test').disabled).toBe(true);+ click(query('.test')); await settle();+ expect(calls.some(([url]) => url.endsWith('/check'))).toBe(false);+ bench.arm('found'); flushSync();+ expect(query('.note.warn').textContent).toBe(error);+});+it('says what a test costs before it reads, then that it is done, and draws a chip for each rule', async () => {const { recipe } = open({ checks: [made('The plot')] });recipe.rules = [newRule('index', 'change'), newRule('index', 'a')];@@ -159,7 +202,8 @@ it('shows the passes in the layer the rules read best, or the basemap in their pclick(look);const menu = query('[role="menu"][aria-label="Copernicus layer"]');const rows = [...menu.querySelectorAll('[role="menuitemradio"]')];- expect(rows.map((row) => row.textContent.replace(/\s+/g, ' ').trim())).toEqual(['True colourTRUE_COLOR', 'NDVI (vegetation index)NDVI for rule ★']);+ // the tag names the bands rather than a star that lives at the other end of the screen+ expect(rows.map((row) => row.textContent.replace(/\s+/g, ' ').trim())).toEqual(['True colourTRUE_COLOR', 'NDVI (vegetation index)NDVI shows B08 · B04']);click(rows[1]);expect(bench.layer).toBe('NDVI');expect(look.textContent.trim()).toBe('Display: NDVI');@@ -257,3 +301,29 @@ it('closes the drawer of a check being made by giving the check up, and Escape dexpect(bench.draft).toBe(null);expect(query('.drawer')).toBe(null);});++it('separates what the map shows from what the rules read, where the two are confused', () => {+ open({ checks: [made('The plot')], layers: [{ id: 'TRUE_COLOR', label: 'True colour' }] });+ bench.select(bench.checks[0].id); flushSync();+ click(query('[aria-label="Copernicus layer"][aria-haspopup]'));+ const menu = query('[role="menu"][aria-label="Copernicus layer"]');+ expect(menu.querySelector('.layer-aside').textContent.trim())+ .toBe('What you look at. Rules read the bands themselves.');+});++it('says when a rule is drawn in the display’s place, and gives the display back', async () => {+ const { recipe } = open({ checks: [made('The plot')], layers: [{ id: 'TRUE_COLOR', label: 'True colour' }] });+ recipe.rules = [newRule('nd', 'b', { bands: ['B12', 'B11'] })];+ bench.select(bench.checks[0].id); flushSync();+ // the draft never reaches a picker, so the chip says the rule rather than a layer name+ bench.ruleLayer = { index: 0, id: 'AZIMUT_DRAFT_ABC123', back: 'TRUE_COLOR' };+ flushSync();+ const look = query('[aria-label="Copernicus layer"][aria-haspopup]');+ expect(look.textContent.trim()).toBe('Display: rule 1');+ click(look);+ const back = query('.layer-drawn');+ expect(back.textContent).toContain('Rule 1 is drawn on the map');+ click(back);+ expect(bench.ruleLayer).toBe(null);+ expect(look.textContent.trim()).toBe('Display: True colour');+});diff --git a/frontend/src/tools/detect/DetectPanel.svelte b/frontend/src/tools/detect/DetectPanel.svelteindex 7052bdc..594f3ae 100644--- a/frontend/src/tools/detect/DetectPanel.svelte+++ b/frontend/src/tools/detect/DetectPanel.svelte@@ -50,6 +50,8 @@selectedResult = $bindable(null),/** The review's eye and blink (DetectReview), which only a review holds. */bare = $bindable(false),+ markers = $bindable(true),+ outlines = $bindable(true),blinking = $bindable(false),/** Whether a run's results are open, which holds the map on them. */reviewing = $bindable(false),@@ -801,7 +803,7 @@{#if error}<p class="warn" role="alert">{error}</p>{/if}{#if current}<DetectReview {caseId} run={current} methods={catalogue.methods} active={!collapsed} bind:candidateId- bind:bare bind:blinking {onpair}+ bind:bare bind:markers bind:outlines bind:blinking {onpair}onaccept={afterVerdict} {onfocus} {onshow} onedit={editRun}onadd={(areaId, kind) => {manual = { areaId, kind };diff --git a/frontend/src/tools/detect/DetectPanel.test.js b/frontend/src/tools/detect/DetectPanel.test.jsindex 5a24f5b..9d6f82e 100644--- a/frontend/src/tools/detect/DetectPanel.test.js+++ b/frontend/src/tools/detect/DetectPanel.test.js@@ -1068,7 +1068,7 @@ const rulesMethods = [...methods, { id: 'rules', label: 'Your own rules', singlesizes, measure: '', smoothing_m: 45 }];const rulesCatalogue = (extra = {}) => catalogue({ methods: rulesMethods, rules: {bands: ['B02', 'B03', 'B04', 'B08', 'B11', 'B12'], classes: ['vegetation', 'bare', 'water'],- max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 20, max_check_tiles: 12 }, ...extra });+ max_rules: 6, max_bands: 6, max_around: 300, max_checks: 12, max_marks: 60, max_check_tiles: 20 }, ...extra });const VIEW = { west: 2, south: 48, east: 2.05, north: 48.03 };const debounce = (ms = 320) => new Promise((resolve) => setTimeout(resolve, ms));const phrase = () => [...target.querySelectorAll('.phrase')].map((p) => p.textContent.trim())[0];diff --git a/frontend/src/tools/detect/DetectReview.svelte b/frontend/src/tools/detect/DetectReview.svelteindex 1939617..b3b424b 100644--- a/frontend/src/tools/detect/DetectReview.svelte+++ b/frontend/src/tools/detect/DetectReview.svelte@@ -14,6 +14,7 @@import { isActive, plural } from '../../lib/map/detections.js';import Icon from '../../components/Icon.svelte';import Modal from '../../components/Modal.svelte';+ import OverlayDisplay from './OverlayDisplay.svelte';import {blinkable, candidatePair, candidateSize, comparePairFor, orderCandidates, pinDefaults,} from '../../lib/map/detectReview.js';@@ -29,6 +30,8 @@candidateId = $bindable(null),/** The detection's drawing taken off the map, so the imagery shows bare. */bare = $bindable(false),+ markers = $bindable(true),+ outlines = $bindable(true),/** Pass A flipped against pass B on the map, while the pair has two dates. */blinking = $bindable(false),onaccept = () => {},@@ -146,7 +149,7 @@*/function shortcut(event) {if (!active || !run || run.status !== 'ready' || busy || pin || enlarged || event.ctrlKey || event.metaKey || event.altKey- || event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;+ || event.target?.closest?.('input, textarea, select, [contenteditable="true"], [role="menu"]')) return;const key = event.key.toLowerCase();// Shift and an arrow turn the map, so the queue takes the bare arrows onlyif (event.shiftKey && event.key.startsWith('Arrow')) return;@@ -268,8 +271,8 @@}}>Add candidate</button><button class="btn btn-sm" onclick={onexport}>Export as layer</button><span class="map-acts">- <button class="cmp-icon" class:on={bare} aria-pressed={bare} aria-label="Hide the candidates and areas"- title="Hide the candidates and areas (H)" onclick={() => (bare = !bare)}><Icon name={bare ? 'eyeOff' : 'eye'} size={14} /></button>+ <OverlayDisplay bind:markers bind:outlines bind:hidden={bare}+ what="the candidates and areas" shortcut="H" />{#if canBlink}<button class="cmp-icon" class:on={blinking} aria-pressed={blinking} aria-label="Blink A and B"title="Blink A and B on the map (B)" onclick={() => (blinking = !blinking)}><Icon name="blink" size={14} /></button>diff --git a/frontend/src/tools/detect/OverlayDisplay.svelte b/frontend/src/tools/detect/OverlayDisplay.sveltenew file mode 100644index 0000000..ab8bac5--- /dev/null+++ b/frontend/src/tools/detect/OverlayDisplay.svelte@@ -0,0 +1,110 @@+<script>+ import { tick } from 'svelte';+ import Icon from '../../components/Icon.svelte';++ /**+ * What the map draws over the imagery: the switch and what it switches.+ *+ * The eye and the menu are one control rather than two buttons side by side.+ * Apart, nothing says the eye is the master of the list, and an eye beside a+ * chevron reads as two unrelated things to press.+ */+ let {+ markers = $bindable(true),+ outlines = $bindable(true),+ checkPins = $bindable(null),+ /** All of it off the map at once. */+ hidden = $bindable(false),+ /** What the eye takes off, for its label: "Hide the candidates". */+ what = 'the overlays',+ /** The key that does the same, named in the tooltip. */+ shortcut = '',+ upward = false,+ } = $props();+ let open = $state(false);+ /** Something is off, so the chevron reads as changed even while the menu is shut. */+ const some = $derived(!markers || !outlines || checkPins === false);+ let root = $state(null);+ let trigger = $state(null);++ async function toggle() {+ open = !open;+ if (open) {+ await tick();+ root?.querySelector('[role="menuitemcheckbox"]')?.focus();+ }+ }+ function onOutside(event) {+ if (open && !root?.contains(event.target)) open = false;+ }+ function onKey(event) {+ if (!open) return;+ if (event.key === 'Escape') {+ open = false;+ trigger?.focus();+ } else if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {+ const items = [...root.querySelectorAll('[role="menuitemcheckbox"]')];+ const at = items.indexOf(document.activeElement);+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1+ : (at + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;+ items[next]?.focus();+ } else if (event.key === 'Tab') {+ open = false;+ trigger?.focus();+ return;+ } else return;+ event.preventDefault();+ event.stopPropagation();+ }+</script>++<svelte:document onpointerdown={onOutside} />++<!-- svelte-ignore a11y_no_static_element_interactions -->+<div class="overlay-display" class:upward bind:this={root} onkeydown={onKey}>+ <span class="joined">+ <button type="button" class="cmp-icon eye" class:on={hidden} aria-pressed={hidden}+ aria-label={`Hide ${what}`} title={`${hidden ? 'Show' : 'Hide'} ${what}${shortcut ? ` (${shortcut})` : ''}`}+ onclick={() => (hidden = !hidden)}><Icon name={hidden ? 'eyeOff' : 'eye'} size={14} /></button>+ <button type="button" class="cmp-icon pick" class:on={open || some}+ bind:this={trigger} aria-label="Which overlays" title="Which overlays" aria-haspopup="menu" aria-expanded={open}+ onclick={toggle}><Icon name="chevronDown" size={13} /></button>+ </span>+ {#if open}+ <div class="display-menu cmp-glass" role="menu" aria-label="Overlay display">+ <button type="button" role="menuitemcheckbox" aria-checked={markers} disabled={hidden}+ onclick={() => (markers = !markers)}>+ <Icon name={markers ? 'check' : 'minus'} size={13} /><span>Markers</span></button>+ <button type="button" role="menuitemcheckbox" aria-checked={outlines} disabled={hidden}+ onclick={() => (outlines = !outlines)}>+ <Icon name={outlines ? 'check' : 'minus'} size={13} /><span>Outlines</span></button>+ {#if checkPins !== null}+ <button type="button" role="menuitemcheckbox" aria-checked={checkPins} disabled={hidden}+ onclick={() => (checkPins = !checkPins)}>+ <Icon name={checkPins ? 'check' : 'minus'} size={13} /><span>Check pins</span></button>+ {/if}+ {#if hidden}+ <p class="all-off">The eye has them all off</p>+ {/if}+ </div>+ {/if}+</div>++<style>+ .overlay-display { position: relative; display: inline-flex; flex: 0 0 auto; }+ /* One control, not two: the eye is the switch and the chevron says what it+ switches, so they share a border and sit against each other. */+ .joined { display: inline-flex; border: 1px solid var(--glass-line); border-radius: var(--r-sm); }+ .joined .cmp-icon { border: 0; border-radius: 0; }+ .joined .eye { border-right: 1px solid var(--glass-line); border-radius: var(--r-sm) 0 0 var(--r-sm); }+ .joined .pick { border-radius: 0 var(--r-sm) var(--r-sm) 0; padding-inline: 2px; }+ .display-menu button:disabled { opacity: 0.45; cursor: default; }+ .display-menu button:disabled:hover { color: var(--glass-muted); background: none; }+ .all-off { margin: 2px 0 0; padding: 6px 9px 4px; border-top: 1px solid var(--glass-line);+ color: var(--glass-muted); font-size: var(--fs-xs); }+ .display-menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: 10; min-width: 150px; padding: 4px; }+ .upward .display-menu { top: auto; bottom: calc(100% + 4px); }+ .display-menu button { display: flex; align-items: center; gap: 9px; width: 100%; padding: 7px 9px; border-radius: var(--r-sm); color: var(--glass-muted); text-align: left; font-size: var(--fs-sm); }+ .display-menu button:hover, .display-menu button:focus-visible { color: var(--glass-ink); background: var(--glass-hover); }+ .display-menu button[aria-checked='true'] { color: var(--glass-ink); }+</style>diff --git a/frontend/src/tools/detect/OverlayDisplay.svelte.test.js b/frontend/src/tools/detect/OverlayDisplay.svelte.test.jsnew file mode 100644index 0000000..db1c966--- /dev/null+++ b/frontend/src/tools/detect/OverlayDisplay.svelte.test.js@@ -0,0 +1,72 @@+// @vitest-environment happy-dom+import { afterEach, expect, it } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import OverlayDisplay from './OverlayDisplay.svelte';++let live, target;+afterEach(() => { if (live) unmount(live); target?.remove(); });+const settle = async () => { await Promise.resolve(); flushSync(); await Promise.resolve(); };+async function open(props = {}) {+ target = document.createElement('div'); document.body.append(target);+ live = mount(OverlayDisplay, { target, props }); flushSync();+ // The first button is the eye now; the chevron beside it is what opens the menu.+ chevron().click(); await settle();+}+const chevron = () => target.querySelector('[aria-haspopup="menu"]');+const eye = () => target.querySelector('[aria-pressed]');+const key = (name) => document.activeElement.dispatchEvent(new KeyboardEvent('keydown', { key: name, bubbles: true, cancelable: true }));++it('offers independent marker and outline choices, with check pins only in the maker', async () => {+ await open();+ const rows = [...target.querySelectorAll('[role="menuitemcheckbox"]')];+ expect(rows.map((row) => row.textContent.trim())).toEqual(['Markers', 'Outlines']);+ rows[0].click(); flushSync();+ expect(rows.map((row) => row.getAttribute('aria-checked'))).toEqual(['false', 'true']);+ expect(target.querySelector('[role="menu"]')).not.toBeNull();+ rows[1].click(); flushSync();+ expect(rows.map((row) => row.getAttribute('aria-checked'))).toEqual(['false', 'false']);+});++it('focuses and walks the menu, closes on Escape or outside, and retains the display choices', async () => {+ await open({ checkPins: true, upward: true });+ const trigger = chevron();+ const rows = [...target.querySelectorAll('[role="menuitemcheckbox"]')];+ expect(document.activeElement).toBe(rows[0]);+ key('ArrowDown'); expect(document.activeElement).toBe(rows[1]);+ key('End'); expect(document.activeElement).toBe(rows[2]);+ rows[2].click(); flushSync();+ expect(rows[2].getAttribute('aria-checked')).toBe('false');+ key('ArrowDown'); expect(document.activeElement).toBe(rows[0]);+ key('Escape'); flushSync();+ expect(target.querySelector('[role="menu"]')).toBeNull();+ expect(document.activeElement).toBe(trigger);+ expect(trigger.getAttribute('aria-expanded')).toBe('false');+ trigger.click(); await settle();+ expect(target.querySelectorAll('[role="menuitemcheckbox"]')[2].getAttribute('aria-checked')).toBe('false');+ document.body.dispatchEvent(new Event('pointerdown', { bubbles: true })); flushSync();+ expect(target.querySelector('[role="menu"]')).toBeNull();+});++it('is one control: the eye switches off what the menu lists', async () => {+ // apart, nothing says the eye is the master of the list+ await open({ checkPins: true });+ expect(eye().getAttribute('aria-pressed')).toBe('false');+ const rows = () => [...target.querySelectorAll('[role="menuitemcheckbox"]')];+ expect(rows().every((row) => !row.disabled)).toBe(true);++ eye().click(); flushSync();+ expect(eye().getAttribute('aria-pressed')).toBe('true');+ expect(eye().title).toBe('Show the overlays');+ // with everything off, picking which is off is moot, and the menu says why+ expect(rows().every((row) => row.disabled)).toBe(true);+ expect(target.querySelector('.all-off').textContent).toBe('The eye has them all off');++ eye().click(); flushSync();+ expect(rows().every((row) => !row.disabled)).toBe(true);+});++it('names what it hides, and the key that does the same', async () => {+ await open({ what: 'the candidates and areas', shortcut: 'H' });+ expect(eye().title).toBe('Hide the candidates and areas (H)');+ expect(eye().getAttribute('aria-label')).toBe('Hide the candidates and areas');+});diff --git a/frontend/src/tools/detect/RuleLayers.svelte b/frontend/src/tools/detect/RuleLayers.svelteindex e4a51b8..65c34da 100644--- a/frontend/src/tools/detect/RuleLayers.svelte+++ b/frontend/src/tools/detect/RuleLayers.svelte@@ -13,7 +13,7 @@* After the rules or the pins change the picture is dimmed: it answers for* what they were.*/- import { RULE_COLOURS, sideOf } from '../../lib/map/analyzerRules.js';+ import { RULE_COLOURS, redrawRule, sideOf } from '../../lib/map/analyzerRules.js';import { compose, cssMatrix, imageToMercator, invert, screenToMercator } from '../../lib/map/groundFrame.js';import RuleTile from './RuleTile.svelte';@@ -30,6 +30,12 @@/** Where the split sits, as a percentage of the map from its left edge. */divider = 50,stale = false,+ /**+ * Rules whose reading the engine has sent: `[{ index, reading }]`. Their+ * ground is drawn from the reading rather than from the test's verdict, so+ * their line can move and the picture follows without asking again.+ */+ live = [],} = $props();/** The tint over ground the test measured, out of 255. */@@ -59,6 +65,29 @@return out;}+ /**+ * One rule's reading out of its PNG: sixteen bits split over two channels.+ *+ * A canvas hands back eight-bit RGBA whatever the file held, so the engine+ * writes the high byte on red and the low byte on green rather than a 16-bit+ * greyscale that would be truncated on the way in (`detect_rules._value_png`).+ */+ async function decodeValues(base64, size, { low, high, steps }) {+ const image = new Image();+ image.src = `data:image/png;base64,${base64}`;+ await image.decode();+ const scratch = document.createElement('canvas');+ scratch.width = size;+ scratch.height = size;+ const context = scratch.getContext('2d', { willReadFrequently: true });+ context.drawImage(image, 0, 0);+ const rgba = context.getImageData(0, 0, size, size).data;+ const out = new Float64Array(size * size);+ const step = (high - low) / steps;+ for (let i = 0; i < out.length; i++) out[i] = low + (rgba[i * 4] * 256 + rgba[i * 4 + 1]) * step;+ return out;+ }+$effect(() => {const tiles = detail?.tiles ?? [];const size = detail?.size ?? 0;@@ -69,6 +98,46 @@return () => { cancelled = true; };});+ /** Per rule index, its reading per tile. Decoded once; the line moves, this does not. */+ let readings = $state({});++ $effect(() => {+ const wanted = live;+ let cancelled = false;+ Promise.all(wanted.map(async ({ index, reading }) => [index, Object.fromEntries(+ await Promise.all((reading.tiles ?? []).map(async (tile) => [+ `${tile.x},${tile.y}`, await decodeValues(tile.values, reading.size, reading),+ ])),+ )]))+ .then((pairs) => { if (!cancelled) readings = Object.fromEntries(pairs); })+ .catch(() => { if (!cancelled) readings = {}; });+ return () => { cancelled = true; };+ });++ /**+ * The mask each tile is painted from: the test's, with every live rule's own+ * bit redrawn at the line it sits on now.+ *+ * Its own derivation rather than part of `placed`, which also follows the+ * camera: panning the map must not redraw five million pixels.+ */+ const painted = $derived.by(() => {+ const base = decoded;+ const held = readings;+ const rows = live.filter(({ index }) => held[index] && rules[index]);+ if (!rows.length) return base;+ const out = {};+ for (const [key, bits] of Object.entries(base)) {+ let next = bits;+ for (const { index } of rows) {+ const values = held[index][key];+ if (values) next = redrawRule(next, index, values, rules[index]);+ }+ out[key] = next;+ }+ return out;+ });+const placed = $derived.by(() => {revision;const tiles = detail?.tiles ?? [];@@ -76,9 +145,9 @@const box = element.getBoundingClientRect();const frame = { ...engine.frame(), width: box.width || 1, height: box.height || 1 };const toScreen = invert(screenToMercator(frame));- return tiles.filter((tile) => decoded[`${tile.x},${tile.y}`]).map((tile) => ({+ return tiles.filter((tile) => painted[`${tile.x},${tile.y}`]).map((tile) => ({key: `${tile.x},${tile.y}`,- bits: decoded[`${tile.x},${tile.y}`],+ bits: painted[`${tile.x},${tile.y}`],transform: cssMatrix(compose(toScreen, imageToMercator(tile.box, detail.size, detail.size))),}));});diff --git a/frontend/src/tools/detect/RuleRow.svelte b/frontend/src/tools/detect/RuleRow.svelteindex 81f6b96..77094af 100644--- a/frontend/src/tools/detect/RuleRow.svelte+++ b/frontend/src/tools/detect/RuleRow.svelte@@ -13,6 +13,7 @@directionsFor, formatShare, lineScale, measuresFor, readsOneDate, retarget, ruleProblem, toEngine, whensFor,withAmount, withDirection, ruleBands,} from '../../lib/map/analyzerRules.js';+ import { ruleLayerWords, whyNoLayer } from '../../lib/map/ruleLayer.js';import Icon from '../../components/Icon.svelte';let {@@ -29,6 +30,16 @@ticks = [],/** The last test no longer matches the rules, so what it said of this one is dimmed. */stale = false,+ /** This rule's own arithmetic is the imagery on the map. */+ drawn = false,+ /** Its layer is being fetched. */+ drawing = false,+ onsee = () => {},+ /** Its line is about to move: ask for the reading that lets it move live. */+ onlive = () => {},+ /** A test has run, so there are pixels for the dot to show. Without one the+ * dot is a button that looks live and answers nothing, so it says what it waits for. */+ tested = false,/** What the last test said taking this rule out would change, in a few words, or ''. */effect = '',match = 'all',@@ -66,6 +77,9 @@: rule.on === 'b' ? 'Read on the after pass and painted on the right of the split.': 'Read as after minus before and painted on both sides.');const sentence = $derived(describeRule(rule, { single }));+ /** Why this rule cannot be drawn as imagery, or ''. */+ const noLayer = $derived(whyNoLayer(rule));+ const layerWords = $derived(ruleLayerWords(rule));/** Its own share of the measured ground, then what is left once the rules above it have had theirs. */const shareText = $derived(!reading ? '' : [`${formatShare(reading.share)} of the ground`,@@ -96,8 +110,11 @@<!-- svelte-ignore a11y_no_static_element_interactions --><div class="rule" class:off={!shown} style={`--tint: ${colour}`} onpointerenter={() => onhover(index)} onpointerleave={() => onhover(null)}><div class="head">- <button class="dot" class:off={!shown} aria-pressed={shown} aria-label={`${shown ? 'Hide' : 'Show'} rule ${n} on the map`}- title={shown ? 'Hide its pixels on the map' : 'Show its pixels on the map'} onclick={ontoggle}>{n}</button>+ <button class="dot" class:off={!shown} class:waiting={!tested} aria-pressed={shown}+ aria-label={`${shown ? 'Hide' : 'Show'} rule ${n} on the map`}+ title={!tested ? 'Test to paint what this rule keeps'+ : shown ? 'Hide its pixels on the map' : 'Show its pixels on the map'}+ onclick={ontoggle}>{n}</button><p class="sentence" aria-label={`Rule ${n} says`}>{sentence}</p><button class="star" class:on={signal} disabled={signal || rule.measure === 'class'}aria-label={signal ? `Rule ${n} ranks the candidates` : `Rank candidates by rule ${n}`}@@ -160,7 +177,18 @@{/each}</div>{/if}- <span class="data-source" aria-label={`Rule ${n} data`}>{dataLabel}</span>+ <div class="data-row">+ <span class="data-source" aria-label={`Rule ${n} data`}>{dataLabel}</span>+ <button class="see" class:on={drawn} disabled={!!noLayer || drawing}+ aria-pressed={drawn}+ aria-label={`See rule ${n} as a layer`}+ title={noLayer ? `Cannot be drawn: ${noLayer}`+ : drawn ? 'Put the display layer back'+ : `Draw it on the map: ${layerWords}`}+ onclick={onsee}>+ <Icon name="layers" size={11} /> {drawing ? 'Drawing…' : drawn ? 'Stop drawing' : 'See it'}+ </button>+ </div></div></div>@@ -203,8 +231,11 @@</div>{#if !between}<div class="line" class:stale>+ <!-- Touching the slider is what asks for the reading: before that nobody+ wants it, and after it every nudge is free. --><input class="range" class:above type="range" aria-label={`Rule ${n} line`} min={scale.min} max={scale.max} step={scale.step}style={`--fraction: ${fraction}`} value={Math.min(scale.max, Math.max(scale.min, shownAmount))}+ onpointerdown={() => onlive()} onfocus={() => onlive()}oninput={(event) => setAmount(event.currentTarget.value)} />{#each ticks as tick (tick.pin)}<i class="tick tick-{tick.expect}" class:passes={tick.passes} class:clipped={tick.clipped}@@ -281,6 +312,9 @@box-shadow: 0 0 0 1px rgb(0 0 0 / 0.3);}.dot.off { background: transparent; color: var(--text-2); box-shadow: inset 0 0 0 2px var(--tint); }+ /* Nothing has been painted yet, so the dot is drawn hollow and dashed: it is+ armed for the next test rather than showing anything now. */+ .dot.waiting { background: transparent; color: var(--text-3); box-shadow: inset 0 0 0 1px var(--tint); opacity: 0.7; }.sentence {flex: 1;min-width: 0;@@ -311,6 +345,18 @@}.pair { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: 5px; }.note, .data-source { color: var(--text-3); font-size: 10.5px; line-height: 1.4; }+ /* What the rule reads, and the press that draws that quantity on the map.+ Side by side because the second is the answer to "what does that look like". */+ .data-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+ .data-row .data-source { flex: 1 1 auto; min-width: 0; }+ .see {+ display: inline-flex; align-items: center; gap: 4px;+ padding: 2px 7px; border: 1px solid var(--line); border-radius: var(--r-sm);+ background: none; color: var(--text-2); font-size: 10.5px; cursor: pointer;+ }+ .see:hover:not(:disabled) { border-color: var(--tint); color: var(--text-1); }+ .see.on { border-color: var(--tint); color: var(--tint); }+ .see:disabled { opacity: 0.4; cursor: default; }.value { display: flex; align-items: center; gap: 6px; }.value input[type='number'] { width: 84px; }.minus, .unit { color: var(--text-3); font-size: var(--fs-xs); }diff --git a/frontend/src/tools/detect/RuleRow.svelte.test.js b/frontend/src/tools/detect/RuleRow.svelte.test.jsindex 17c9f63..ecee42d 100644--- a/frontend/src/tools/detect/RuleRow.svelte.test.js+++ b/frontend/src/tools/detect/RuleRow.svelte.test.js@@ -180,3 +180,44 @@ it('names what is wrong with a rule in place of its share', () => {expect(query('.warn').textContent).toBe('Pick two different bands.');expect(query('.share')).toBe(null);});++it('the dot says what it is waiting for while no test has painted anything', () => {+ // it looks live and answers nothing until a test has run, so it says so+ const props = open(newRule('index', 'change'));+ expect(query('.dot').title).toBe('Test to paint what this rule keeps');+ expect(query('.dot').classList.contains('waiting')).toBe(true);+ props.tested = true; flushSync();+ expect(query('.dot').title).toBe('Hide its pixels on the map');+ expect(query('.dot').classList.contains('waiting')).toBe(false);+});++it('offers to draw the rule’s own arithmetic, and says what it would show', () => {+ const props = open(newRule('nd', 'b', { bands: ['B12', 'B11'] }), { onsee: vi.fn() });+ const see = query('.see');+ expect(see.disabled).toBe(false);+ expect(see.title).toContain('(B12 − B11) / (B12 + B11)');+ see.click();+ expect(props.onsee).toHaveBeenCalled();+ props.drawn = true; flushSync();+ expect(query('.see').textContent.trim()).toBe('Stop drawing');+});++it('says why a rule cannot be drawn instead of offering a press that does nothing', () => {+ open(newRule('colour', 'change'));+ expect(query('.see').disabled).toBe(true);+ expect(query('.see').title).toContain('between two dates');+});++it('asks for the reading the moment the slider is touched, not before', () => {+ // nobody wants a megabyte of readings for a rule they never adjust; once it+ // is in hand every further nudge of the line is free+ const props = open(newRule('band', 'b'), { onlive: vi.fn() });+ expect(props.onlive).not.toHaveBeenCalled();+ const slider = query('[aria-label="Rule 1 line"]');+ slider.dispatchEvent(new Event('pointerdown', { bubbles: true }));+ flushSync();+ expect(props.onlive).toHaveBeenCalled();+ // and the keyboard route asks too+ slider.dispatchEvent(new Event('focus', { bubbles: true }));+ expect(props.onlive.mock.calls.length).toBeGreaterThan(1);+});diff --git a/frontend/src/tools/detect/SecondPass.svelte b/frontend/src/tools/detect/SecondPass.svelteindex 325f2ff..654ec1b 100644--- a/frontend/src/tools/detect/SecondPass.svelte+++ b/frontend/src/tools/detect/SecondPass.svelte@@ -115,7 +115,9 @@resetToHome={false} {imperial} {overlays} {armed} chrome={false} controlsTop={108} {onclick} {oncontextmenu} {onusage}{onimageryfallback} errorSide="right" /></div>- <button type="button" class="line" class:dragging class:armed={!!armed} role="slider" aria-label="Split between the before and after passes"+</div>+<div class="split-rail" style:--divider={`${divider}%`}>+ <button type="button" class="line" class:dragging role="slider" aria-label="Split between the before and after passes"aria-valuemin="0" aria-valuemax="100" aria-valuenow={Math.round(divider)} tabindex="0"onpointerdown={press} onpointermove={drag} onpointerup={release} onpointercancel={release} onkeydown={key}><span class="handle" aria-hidden="true">@@ -127,6 +129,10 @@<style>/* Over the first map and under everything the tool draws on the ground. */.second { position: absolute; inset: 0; z-index: 1; pointer-events: none; }+ /* The handle is a control, not ground. Inside `.second` it was trapped in that+ layer's stacking context and every overlay painted over it, so it rides in+ its own rail above them, level with the engine's zoom buttons. */+ .split-rail { position: absolute; inset: 0; z-index: 580; pointer-events: none; }.clip { position: absolute; inset: 0; display: flex; clip-path: inset(0 0 0 var(--divider)); pointer-events: none; }.clip :global(.map-wrap) { pointer-events: auto; }.line {@@ -134,7 +140,6 @@top: 0;bottom: 0;left: var(--divider);- z-index: 2;width: 2px;padding: 0;border: 0;@@ -142,14 +147,16 @@background: rgb(255 255 255 / 0.92);box-shadow: 0 0 5px rgb(0 0 0 / 0.75);cursor: ew-resize;- pointer-events: auto;+ /* The line draws, the handle grabs. From up here beside the engine's controls the line ran a+ column of its own over the ground, and the map is centred on what is being checked, so that+ column fell on the pins: they stayed visible and stopped answering. Letting it through is the+ rule arming a pin already followed — the handle took the drag then too, and nothing was+ missed — so the line follows it all the time rather than only while a pin is armed. */+ pointer-events: none;touch-action: none;}- .line::before { position: absolute; inset: 0 -6px; content: ''; }- /* With a pin armed the line lets the click through, so a pin can be dropped on the ground it runs- over, which is the middle of the map when the map is centred on what is being checked. The- handle still takes the drag. */- .line.armed { pointer-events: none; }+ /* The grab, widened past what it draws so it is easy to catch. */+ .handle::before { position: absolute; inset: -6px; content: ''; }.line:focus-visible { outline: none; }.line:focus-visible .handle { box-shadow: 0 0 0 2px var(--accent), 0 4px 14px rgb(0 0 0 / 0.45); }/* Off the middle of the map, where a click aimed at the place being checked would land on it. */diff --git a/frontend/src/tools/detect/SecondPass.svelte.test.js b/frontend/src/tools/detect/SecondPass.svelte.test.jsindex 6416b7d..343f0aa 100644--- a/frontend/src/tools/detect/SecondPass.svelte.test.js+++ b/frontend/src/tools/detect/SecondPass.svelte.test.js@@ -1,4 +1,7 @@// @vitest-environment happy-dom+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { flushSync, mount, unmount } from 'svelte';@@ -92,10 +95,16 @@ it('hands the cursor mode on to its own map, so a pin can be dropped on either hexpect(target.querySelector('.stub').dataset.armed).toBe('selecting');});-it('lets a click through the line while a pin is armed, and takes it otherwise', () => {- open({ armed: 'selecting' });- expect(slider().classList.contains('armed')).toBe(true);- unmount(live); target.remove();- open();- expect(slider().classList.contains('armed')).toBe(false);+it('lets every click through the line, and grabs only on the handle', () => {+ // The line rides beside the engine's controls (`mapStacking.test.js`), well over+ // the ground the tool paints, and the map is centred on what is being checked —+ // so a line that took clicks took them from the pins sitting under it. The drag+ // lives on the handle, which is why letting the line through costs nothing.+ const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'SecondPass.svelte'), 'utf8');+ const line = source.slice(source.indexOf('.line {'), source.indexOf('.handle::before'));+ expect(line).toMatch(/pointer-events:\s*none/);+ expect(source.slice(source.indexOf('.handle {'))).toMatch(/pointer-events:\s*auto/);+ // and nothing is left behind saying the line ever behaved differently while armed+ expect(source).not.toMatch(/\.line\.armed/);+ expect(source).not.toMatch(/class:armed/);});diff --git a/frontend/src/tools/satellite/CaptureOptions.svelte b/frontend/src/tools/satellite/CaptureOptions.svelteindex ab4d514..7abf0bf 100644--- a/frontend/src/tools/satellite/CaptureOptions.svelte+++ b/frontend/src/tools/satellite/CaptureOptions.svelte@@ -23,6 +23,11 @@scaleNorth = $bindable(),openScreenshot,openExtensionGate,+ /** Build a figure instead of one picture. Absent where there is none to+ * build: a figure is several renderings of one Copernicus acquisition. */+ openFigure = null,+ /** Why a figure cannot be built here, for the row that says so. */+ figureBlocked = '',} = $props();</script>@@ -122,6 +127,26 @@{/if}{/if}+ {#if openFigure}+ <div class="menu-row">+ <span class="menu-label">Figure</span>+ <div class="chips">+ <button+ class="chip"+ disabled={!!figureBlocked}+ onclick={() => { menuOpen = false; openFigure(); }}+ title={figureBlocked || 'Several renderings of this acquisition, laid out and captioned'}+ >+ Build a figure…+ </button>+ </div>+ </div>+ <div class="menu-hint">+ {figureBlocked ||+ 'The same ground through the layers you pick, filed as a Geo Proof ready to annotate.'}+ </div>+ {/if}+{#if widgetBase}<div class="menu-row"><span class="menu-label">Source</span>@@ -235,6 +260,8 @@}.chip:hover { border-color: var(--border-strong); color: var(--text-1); }.chip.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }+ .chip:disabled { opacity: 0.45; cursor: default; }+ .chip:disabled:hover { border-color: var(--border); color: var(--text-2); }.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 switchdiff --git a/frontend/src/tools/satellite/FigureDialog.svelte b/frontend/src/tools/satellite/FigureDialog.sveltenew file mode 100644index 0000000..7790c56--- /dev/null+++ b/frontend/src/tools/satellite/FigureDialog.svelte@@ -0,0 +1,273 @@+<script>+ /**+ * Build a figure: the same ground on one day, through the layers you pick.+ *+ * The figure an analyst publishes is rarely one picture. It is true colour+ * for what a reader recognises, a short-wave composite for the heat, an index+ * for the measurement — each captioned, with one line saying where and when.+ * By hand that is four captures, four drags onto a canvas and a footer typed+ * from memory.+ *+ * It is filed as a Geo Proof, so it opens in the composer with its captions+ * and its credit line already written and takes arrows like any other+ * composition. Each panel is a real capture, with its own provenance.+ *+ * One day for every panel, by design: a figure is about one acquisition seen+ * several ways. Panels of different dates compare two things at once, which+ * is what Compare is for.+ */+ import { untrack } from 'svelte';+ import Modal from '../../components/Modal.svelte';+ import Icon from '../../components/Icon.svelte';+ import { api } from '../../lib/api.js';+ import { toast } from '../../lib/state.svelte.js';+ import { DEFAULT_PER_ROW, MAX_PANELS } from '../../lib/figures.js';++ let {+ caseId,+ /** The acquisition every panel is rendered from. Empty = nothing to build. */+ day,+ maxcc,+ /** Where and how the panels are framed, as the capture would frame them. */+ view,+ width,+ height,+ /** `[{id, label, hint, custom}]` — the layer picker's own list. */+ layers = [],+ scaleNorth = false,+ onclose,+ onbuilt,+ } = $props();++ // What a panel is called defaults to the layer's own label: the analyst's+ // words are what a figure's text refers to, and these are a start, not a rule.+ let chosen = $state(new Map());+ let title = $state('');+ let perRow = $state(DEFAULT_PER_ROW);+ // The capture's own tick is the opening answer; the dialog is mounted fresh+ // each time it opens, so it never needs to follow it afterwards.+ let burn = $state(untrack(() => scaleNorth));+ let busy = $state(false);++ const picked = $derived([...chosen.keys()].filter((id) => layers.some((e) => e.id === id)));+ const full = $derived(picked.length >= MAX_PANELS);++ function toggle(entry) {+ if (chosen.has(entry.id)) {+ chosen.delete(entry.id);+ } else {+ if (full) return;+ chosen.set(entry.id, entry.label || entry.id);+ }+ chosen = new Map(chosen);+ }++ /** Where this layer sits in the figure, which is what its caption is numbered by. */+ const place = (id) => picked.indexOf(id) + 1;++ async function build() {+ if (busy || !picked.length || !title.trim()) return;+ busy = true;+ try {+ const built = await api.post(`/api/cases/${caseId}/satellite/figure`, {+ title: title.trim(),+ lat: view.lat,+ lon: view.lon,+ zoom: Math.round(view.zoom),+ bearing: view.bearing ?? 0,+ width,+ height,+ day,+ maxcc,+ per_row: perRow,+ scale_north: burn,+ panels: picked.map((id) => ({ layer: id, caption: chosen.get(id) ?? '' })),+ });+ toast(`${picked.length} panels filed`, 'ok');+ onbuilt(built);+ } catch (error) {+ toast(error.message, 'danger');+ } finally {+ busy = false;+ }+ }+</script>++<Modal title="Build a figure" {onclose} width="560px" align="top">+ {#if !day}+ <p class="lead warn">+ <Icon name="alert" size={13} />+ Pick a date first. Every panel of a figure is the same acquisition, so an undated map+ has nothing to build from.+ </p>+ {:else}+ <p class="lead">+ The same ground on <strong class="mono">{day}</strong>, through the layers you pick. Each+ panel is filed as its own capture, and the figure opens in Geo Proof ready to annotate.+ </p>++ <label class="field">+ <span>Title</span>+ <!-- svelte-ignore a11y_autofocus -->+ <input+ class="input"+ bind:value={title}+ maxlength="200"+ autofocus+ placeholder="What the figure shows"+ aria-label="Figure title"+ />+ </label>++ <div class="panels">+ <div class="panels-head">+ <span class="label">Panels</span>+ <span class="count">{picked.length}/{MAX_PANELS}</span>+ </div>+ <ul>+ {#each layers as entry (entry.id)}+ {@const on = chosen.has(entry.id)}+ <li class:on>+ <label class="pick" title={entry.hint || entry.id}>+ <input+ type="checkbox"+ checked={on}+ disabled={!on && full}+ onchange={() => toggle(entry)}+ />+ <span class="num mono">{on ? `${place(entry.id)}.` : ''}</span>+ <span class="name">+ {entry.label || entry.id}+ {#if entry.custom}<span class="tag">yours</span>{/if}+ </span>+ </label>+ {#if on}+ <input+ class="input caption"+ value={chosen.get(entry.id)}+ maxlength="120"+ aria-label={`Caption for ${entry.label || entry.id}`}+ placeholder="Caption under this panel"+ oninput={(e) => {+ chosen.set(entry.id, e.currentTarget.value);+ chosen = new Map(chosen);+ }}+ />+ {/if}+ </li>+ {/each}+ </ul>+ <p class="help">+ <Icon name="info" size={12} />+ <span>+ Panels are numbered down the list, so a caption can be referred to as panel 2.+ </span>+ </p>+ </div>++ <div class="row">+ <label class="field narrow">+ <span>Panels per row</span>+ <select class="input" bind:value={perRow} aria-label="Panels per row">+ <option value={1}>1</option>+ <option value={2}>2</option>+ <option value={3}>3</option>+ <option value={4}>4</option>+ </select>+ </label>+ <div class="field narrow">+ <span>Each panel</span>+ <span class="readout mono" title="The capture size, from the menu this opened from">+ {width}×{height}+ </span>+ </div>+ <label class="toggle">+ <input type="checkbox" bind:checked={burn} />+ <span>Scale bar and north arrow</span>+ </label>+ </div>++ <footer class="actions">+ <button+ class="btn btn-primary"+ disabled={busy || !picked.length || !title.trim()}+ onclick={build}+ title={!picked.length+ ? 'Pick at least one layer'+ : !title.trim()+ ? 'Name the figure'+ : `Render ${picked.length} panels and file them`}+ >+ {#if busy}<span class="spinner"></span> Rendering…{:else}Build the figure{/if}+ </button>+ <button class="btn" onclick={onclose}>Cancel</button>+ <span class="cost">{picked.length || 0} panels, {picked.length || 0} renders billed.</span>+ </footer>+ {/if}+</Modal>++<style>+ .lead { margin: 0 0 12px; font-size: var(--fs-sm); color: var(--text-2); line-height: 1.5; }+ /* `.mono` sizes against its parent rather than the scale around it. */+ .lead .mono, .readout { font-size: var(--fs-sm); }+ .lead.warn { display: flex; gap: 7px; align-items: flex-start; color: var(--warn); }+ .lead.warn :global(svg) { flex: none; margin-top: 2px; }++ .field { display: grid; gap: 4px; margin-bottom: 12px; }+ .field > span { font-size: var(--fs-xs); color: var(--text-3); }+ .field.narrow { margin-bottom: 0; min-width: 0; }++ .panels {+ display: grid;+ gap: 7px;+ margin-bottom: 12px;+ padding: 10px 11px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .panels-head { display: flex; align-items: baseline; gap: 8px; }+ .panels-head .label {+ font-size: var(--fs-xs);+ font-weight: 700;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--text-3);+ }+ .panels-head .count { margin-left: auto; font-size: var(--fs-xs); color: var(--text-3); }+ .panels ul { display: grid; gap: 5px; margin: 0; padding: 0; list-style: none; }+ .panels li { display: grid; gap: 4px; padding: 5px 6px; border-radius: var(--r-sm); }+ .panels li.on { background: var(--bg-1); }+ .pick { display: flex; align-items: center; gap: 8px; cursor: pointer; }+ .num { width: 1.4em; font-size: var(--fs-xs); color: var(--accent); }+ .name { font-size: var(--fs-sm); color: var(--text-1); }+ .tag {+ margin-left: 6px;+ padding: 0 4px;+ border: 1px solid var(--border);+ border-radius: 3px;+ font-size: 9px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--text-3);+ }+ .caption { margin-left: 26px; font-size: var(--fs-xs); }++ .row { display: flex; align-items: flex-end; gap: 14px; margin-bottom: 14px; }+ .readout { padding: 5px 0; color: var(--text-2); }+ .toggle { display: flex; align-items: center; gap: 7px; font-size: var(--fs-xs); color: var(--text-2); }++ .help {+ display: flex;+ align-items: flex-start;+ gap: 6px;+ margin: 0;+ font-size: var(--fs-xs);+ line-height: 1.45;+ color: var(--text-3);+ }+ .help :global(svg) { flex: none; margin-top: 2px; opacity: 0.8; }++ .actions { display: flex; align-items: center; gap: 8px; }+ .cost { margin-left: auto; font-size: var(--fs-xs); color: var(--text-3); }+</style>diff --git a/frontend/src/tools/satellite/FigureDialog.test.js b/frontend/src/tools/satellite/FigureDialog.test.jsnew file mode 100644index 0000000..1f68139--- /dev/null+++ b/frontend/src/tools/satellite/FigureDialog.test.js@@ -0,0 +1,193 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';+import { MAX_PANELS } from '../../lib/figures.js';++/**+ * Building a figure from the map: pick the layers, caption them, press once.+ *+ * What matters is that the request says what the figure is — one day, each+ * layer once, captions in the analyst's words — and that the dialog refuses+ * what the route would refuse rather than rendering panels and then failing.+ */++const calls = [];+vi.mock('../../lib/api.js', () => ({+ api: {+ post: vi.fn(async (path, body) => {+ calls.push([path, body]);+ return { proof: { name: 'Fujairah plume' }, panels: body.panels };+ }),+ },+}));+const toast = vi.fn();+vi.mock('../../lib/state.svelte.js', () => ({ toast: (...args) => toast(...args) }));++const FigureDialog = (await import('./FigureDialog.svelte')).default;++let live;+let target;+let built;++const LAYERS = [+ { id: 'TRUE_COLOR', label: 'True colour', hint: 'What the eye would see' },+ { id: 'SWIR', label: 'SWIR', hint: 'Hot ground' },+ { id: 'PLUME_SWIR', label: 'My plume', hint: 'mine', custom: true },+];++function open(props = {}) {+ built = vi.fn();+ target = document.createElement('div');+ document.body.append(target);+ live = mount(FigureDialog, {+ target,+ props: {+ caseId: 'case-1',+ day: '2026-10-04',+ maxcc: 100,+ view: { lat: 26.383333, lon: 56.438333, zoom: 14.2, bearing: 0 },+ width: 900,+ height: 700,+ layers: LAYERS,+ onclose: vi.fn(),+ onbuilt: built,+ ...props,+ },+ });+ flushSync();+ return target;+}++beforeEach(() => {+ calls.length = 0;+ toast.mockClear();+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+ document.body.innerHTML = '';+});++const button = (label) =>+ [...document.querySelectorAll('button')].find((node) =>+ node.textContent.trim().startsWith(label)+ );+const pick = (label) => {+ const row = [...document.querySelectorAll('.pick')].find((node) =>+ node.textContent.includes(label)+ );+ row.querySelector('input').click();+ flushSync();+};+const type = (selector, value) => {+ const field = document.querySelector(selector);+ field.value = value;+ field.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+};++it('says what a figure is, and which acquisition this one is of', () => {+ open();+ expect(document.body.textContent).toContain('2026-10-04');+ expect(document.body.textContent).toContain('filed as its own capture');+});++it('will not build an undated figure, and says why', () => {+ open({ day: '' });+ // every panel is the same acquisition, so there is nothing to build from+ expect(document.body.textContent).toContain('Pick a date first');+ expect(button('Build the figure')).toBeUndefined();+});++it('builds nothing until a layer is picked and the figure is named', () => {+ open();+ expect(button('Build the figure').disabled).toBe(true);+ pick('True colour');+ expect(button('Build the figure').disabled).toBe(true);+ expect(button('Build the figure').title).toContain('Name the figure');+ type('[aria-label="Figure title"]', 'Fujairah plume');+ expect(button('Build the figure').disabled).toBe(false);+});++it('sends one day, the picked layers in order, and the analyst’s captions', async () => {+ open();+ type('[aria-label="Figure title"]', 'Fujairah plume');+ pick('True colour');+ pick('SWIR');+ type('[aria-label="Caption for True colour"]', 'Visible plume (RGB)');++ button('Build the figure').click();+ await vi.waitFor(() => expect(calls.length).toBe(1));+ const [path, body] = calls[0];+ expect(path).toBe('/api/cases/case-1/satellite/figure');+ expect(body.day).toBe('2026-10-04');+ expect(body.zoom).toBe(14); // a zoom is a whole number to the backend+ expect(body.panels).toEqual([+ { layer: 'TRUE_COLOR', caption: 'Visible plume (RGB)' },+ { layer: 'SWIR', caption: 'SWIR' },+ ]);+ expect(body.width).toBe(900);+ expect(body.per_row).toBe(2);+});++it('opens the figure it built, rather than leaving it to be found', async () => {+ open();+ type('[aria-label="Figure title"]', 'Fujairah plume');+ pick('SWIR');+ button('Build the figure').click();+ await vi.waitFor(() => expect(built).toHaveBeenCalled());+ expect(built.mock.calls[0][0].proof.name).toBe('Fujairah plume');+});++it('numbers the panels down the list, so a caption can be referred to', () => {+ open();+ pick('SWIR');+ pick('My plume');+ const numbers = [...document.querySelectorAll('.pick')]+ .map((node) => node.querySelector('.num').textContent.trim())+ .filter(Boolean);+ expect(numbers).toEqual(['1.', '2.']);+});++it('offers a layer written here beside the configured ones, and marks it', () => {+ open();+ const row = [...document.querySelectorAll('.pick')].find((node) =>+ node.textContent.includes('My plume')+ );+ expect(row.textContent).toContain('yours');+});++it('stops at the panel count the route stops at', () => {+ const many = Array.from({ length: MAX_PANELS + 2 }, (_, n) => ({+ id: `L${n}`,+ label: `Layer ${n}`,+ }));+ open({ layers: many });+ for (const entry of many) {+ const row = [...document.querySelectorAll('.pick')].find((node) =>+ node.textContent.includes(entry.label)+ );+ const box = row.querySelector('input');+ if (!box.disabled) box.click();+ flushSync();+ }+ expect(document.body.textContent).toContain(`${MAX_PANELS}/${MAX_PANELS}`);+ expect(calls).toEqual([]);+});++it('unpicking a layer renumbers the rest', () => {+ open();+ pick('True colour');+ pick('SWIR');+ pick('My plume');+ pick('SWIR'); // off again+ const rows = [...document.querySelectorAll('.pick')].map((node) => ({+ text: node.textContent,+ num: node.querySelector('.num').textContent.trim(),+ }));+ expect(rows.find((row) => row.text.includes('True colour')).num).toBe('1.');+ expect(rows.find((row) => row.text.includes('SWIR')).num).toBe('');+ expect(rows.find((row) => row.text.includes('My plume')).num).toBe('2.');+});diff --git a/frontend/src/tools/satellite/MapSurface.svelte b/frontend/src/tools/satellite/MapSurface.svelteindex e149770..b8132c5 100644--- a/frontend/src/tools/satellite/MapSurface.svelte+++ b/frontend/src/tools/satellite/MapSurface.svelte@@ -127,25 +127,29 @@imagery.displayed(providerId, view.zoom, {...(s2?.variant ?? {}),release: wayback?.release ?? null,- pass: s1?.pass ?? null,+ pass: s1?.shownPass ?? null,}));- const radarPass = $derived(shown.provider?.id === RADAR_ID ? s1?.pass ?? null : null);+ const radarPass = $derived(shown.provider?.id === RADAR_ID ? s1?.shownPass ?? null : null);const tileProblem = $derived(tileFailure?.id === shown.id ? tileFailure : null);- /** A pinned Sentinel-2 day *is* the acquisition date — the one provider that- * can answer "when was this taken?" without being asked. */- const pinnedDay = $derived(+ /** The Sentinel-2 day the tiles were rendered from — the window is one+ * acquisition, whether the analyst pinned it or "most recent" resolved it,+ * so the pixels carry that date exactly. Null while no day is known, which+ * is the one case the tiles blend dates and nothing may be claimed. */+ const renderedDay = $derived(shown.provider?.id === SENTINEL_ID && s2?.window.from ? s2.window.from : null);$effect(() => {dated = radarPass? { date: radarPass.date, exact: true, source: 'Sentinel-1' }- : pinnedDay- ? { date: pinnedDay, exact: true, source: 'Sentinel-2' }+ : renderedDay+ ? { date: renderedDay, exact: true, source: 'Sentinel-2' }: shown.provider?.id === SENTINEL_ID- ? s2?.latest ? { date: s2.latest, exact: false, source: 'Sentinel-2' } : null+ // an undated blend has no date to give, and the newest pass over the+ // crosshair is not it: most of the tile may be older+ ? null: imageryDate?.supported && imageryDate.date? { date: imageryDate.date, exact: false, source: imageryDate.source ?? null }: null;@@ -161,7 +165,7 @@* `imageryWhen` is the same date with a radar pass's UTC time when it has one.*/export function provenance() {- return { provider: shown.id, ...pictureDate({ radarPass, pinnedDay, estimated: imageryDate?.date }) };+ return { provider: shown.id, ...pictureDate({ radarPass, day: renderedDay, estimated: imageryDate?.date }) };}// Svelte only honours a cleanup returned from a *synchronous* onMount, and the@@ -349,7 +353,7 @@{#if tileProblem && !grabbing}<div class="tile-trouble" class:right={errorSide === 'right'} role="status" aria-label="Imagery loading error"><strong>Could not load imagery</strong>- <span>{shown.provider?.label}{shown.provider?.id === SENTINEL_ID ? ` · ${s2?.layer ?? DEFAULT_LAYER}` : ''}{pinnedDay ? ` · ${pinnedDay}` : radarPass?.date ? ` · ${radarPass.date}` : ''}</span>+ <span>{shown.provider?.label}{shown.provider?.id === SENTINEL_ID ? ` · ${s2?.layer ?? DEFAULT_LAYER}` : ''}{renderedDay ? ` · ${renderedDay}` : radarPass?.date ? ` · ${radarPass.date}` : ''}</span><p>{tileProblem.message}</p><div class="error-actions"><button class="btn btn-sm" onclick={retryImagery}>Retry imagery</button>@@ -382,22 +386,25 @@reads. -->{#if s2 && shown.provider?.id === SENTINEL_ID}<!-- The date is the picker's chip too, and it is said again here, as the- radar's pass is: one line reading the day, how it was chosen and what- is drawn from it. A pinned day is the window the tiles were rendered- from; otherwise the layer's default renders the most recent pass. -->+ radar's pass is: one line reading the day the window named and whether+ the analyst chose it. Without a day the tiles blend the archive, and+ the pill says that rather than naming the newest pass. --><spanclass="date-pill mono"- class:exact={!!pinnedDay}- title={pinnedDay- ? `Sentinel-2 ${s2.layerLabel} from this exact date`- : s2.latest- ? `Sentinel-2 ${s2.layerLabel}: most recent pass over this point`- : `Sentinel-2 ${s2.layerLabel}: most recent pass (open the picker to date it)`}+ class:exact={!!renderedDay}+ class:undated={!renderedDay && s2.undated}+ title={renderedDay+ ? s2.date+ ? `Sentinel-2 ${s2.layerLabel} from this pass`+ : `The newest Sentinel-2 ${s2.layerLabel} pass over this point`+ : s2.undated+ ? 'No pass could be dated here, so these tiles blend several dates'+ : 'Finding the newest pass over this point'}><Icon name="clock" size={11} />- {pinnedDay ?? s2.latest ?? ''}- {#if !pinnedDay}- <span class="tag">{s2.latest ? 'latest' : 'most recent'}</span>+ {renderedDay ?? (s2.undated ? 'several dates' : 'finding…')}+ {#if renderedDay && !s2.date}+ <span class="tag">latest</span>{/if}{#if s2.layer !== DEFAULT_LAYER}<span class="tag layer">{s2.layerShort}</span>@@ -409,13 +416,19 @@{/if}</span>{:else if s1 && shown.provider?.id === RADAR_ID}- <!-- The pass is the picker's own chip; this says what it means. -->- <span class="date-pill mono" class:exact={!!radarPass}+ <!-- The pass is the picker's own chip; this says what it means. Without one+ the tiles blend every pass over the point, which for radar mixes looks+ from opposite sides of the track, so the pill says so. -->+ <span class="date-pill mono" class:exact={!!radarPass} class:undated={!radarPass && s1.undated}title={radarPass ? `Sentinel-1 pass flying ${radarPass.orbit === 'descending' ? 'south' : 'north'}`- : 'Sentinel-1: most recent pass (open the picker to date it)'}>+ : s1.undated+ ? 'No pass could be dated here, so these tiles blend several passes'+ : 'Finding the newest pass over this point'}><Icon name="clock" size={11} />- {radarPass ? `${radarPass.date} ${radarPass.time.slice(0, 5)} UTC ${orbitMark(radarPass.orbit)}` : ''}- {#if !radarPass}<span class="tag">most recent</span>{/if}+ {radarPass+ ? `${radarPass.date} ${radarPass.time.slice(0, 5)} UTC ${orbitMark(radarPass.orbit)}`+ : s1.undated ? 'several passes' : 'finding…'}+ {#if radarPass && !s1.pass}<span class="tag">latest</span>{/if}<span class="tag layer">radar</span></span>{:else if imageryDate?.supported}@@ -502,12 +515,17 @@backdrop-filter: blur(6px);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 */+ /* a day the window named is a fact about the pixels, pinned or resolved; a+ blend of the archive is the one case there is no date to give, and the two+ must not look identical */.date-pill.exact {color: var(--text-2);box-shadow: 0 0 0 1px color-mix(in srgb, var(--ok, #46a758) 55%, transparent);}+ .date-pill.undated {+ color: var(--warn);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--warn) 45%, transparent);+ }.date-pill .tag {font-family: var(--font-sans);font-size: 9px;diff --git a/frontend/src/tools/satellite/RadarPicker.svelte b/frontend/src/tools/satellite/RadarPicker.svelteindex a57d3f9..b99206a 100644--- a/frontend/src/tools/satellite/RadarPicker.svelte+++ b/frontend/src/tools/satellite/RadarPicker.svelte@@ -15,7 +15,11 @@let { menuEl = $bindable(), s1 } = $props();const peer = $derived(s1.peer);- const shown = $derived(s1.pass);+ /** The pass "most recent" resolved to: being rendered, but not chosen. */+ const resolved = $derived(s1.pass ? null : s1.latest);+ // What the tiles are rendered from: the chosen pass, or the one "most recent"+ // resolved to. The chip reads that pass either way.+ const shown = $derived(s1.shownPass);</script><div class="s1-wrap" bind:this={menuEl}>@@ -64,9 +68,11 @@{#if s1.passes.length}<ul class="passes" aria-label="Sentinel-1 passes">{#each s1.passes as entry (`${entry.date}T${entry.time}`)}- {@const on = shown?.date === entry.date && shown?.time === entry.time}+ {@const on = s1.pass?.date === entry.date && s1.pass?.time === entry.time}+ {@const showing = !s1.pass+ && resolved?.date === entry.date && resolved?.time === entry.time}<li>- <button class="row mono" class:on onclick={() => s1.pick(entry)}+ <button class="row mono" class:on class:showing onclick={() => s1.pick(entry)}title={entry.orbit ? `Flying ${entry.orbit === 'descending' ? 'south' : 'north'}` : undefined}><span>{entry.date} · {entry.time.slice(0, 5)} UTC</span><span class="side">@@ -185,6 +191,11 @@color: var(--accent);background: var(--accent-soft);}+ /* the pass "most recent" landed on: being rendered, but not chosen */+ .row.showing {+ color: var(--accent);+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--accent) 45%, transparent);+ }.side {display: inline-flex;gap: 6px;diff --git a/frontend/src/tools/satellite/SentinelPicker.svelte b/frontend/src/tools/satellite/SentinelPicker.svelteindex c7aff50..82c4467 100644--- a/frontend/src/tools/satellite/SentinelPicker.svelte+++ b/frontend/src/tools/satellite/SentinelPicker.svelte@@ -1,5 +1,16 @@<script>import Icon from '../../components/Icon.svelte';+ import CustomLayerForm from '../../components/CustomLayerForm.svelte';+ import { api } from '../../lib/api.js';+ import { toast } from '../../lib/state.svelte.js';+ import {+ clearPreview,+ dataSources,+ previewLayer,+ readCustomLayers,+ saveCustomLayer,+ startForm,+ } from '../../lib/customLayers.js';/** `s2` is the store from `state/sentinel.svelte.js`: what has been asked,* what came back, and what is still in flight. The label helpers are pure@@ -16,13 +27,112 @@// What the tiles are dated: the pinned pass, or the one "most recent" resolved// to. Blank only while that lookup is out, or where no pass came back at all.- const chipDate = $derived(s2.date || s2.latest || '');+ const chipDate = $derived(s2.day);// The readout tracks the drag; the ceiling only moves on release. Every step// in between would be a provider id of its own, and Sentinel-2 tiles are// billed — you pay for the number you stopped on, not the ones you passed.let dragging = $state(null);const shown = $derived(dragging ?? s2.maxcc);++ /**+ * Writing a layer happens here rather than only in Settings because a script+ * is judged on pixels: Preview renders it on this very map, over the date and+ * the ceiling already chosen, before anything is saved. Settings keeps the+ * list; this is where one is made. Both use the same form.+ *+ * **The draft outlives the panel.** Previewing is the reason to close the+ * form — you close it to look at the map — so closing it must not throw away+ * what was typed. The draft is held here until it is saved or discarded, and+ * reopening the panel hands the same one back.+ */+ let open = $state(false); // is the form showing+ let held = $state(null); // the draft, kept while the form is closed+ let writingBusy = $state(false);+ let writingNote = $state('');+ let mine = $state([]); // the saved scripts, read when the form opens+ let scriptMax = $state(4000);+ let bands = $state([]);+ let radarLayer = $state('');+ let before = ''; // the layer to come back to if nothing is kept++ // A script reads the data of a layer the configuration serves — never another+ // script, and never the radar layer, through which Sentinel-2 bands render+ // nothing at all.+ const bases = $derived(dataSources(s2.layers, radarLayer));+ const resuming = $derived(!!held && !held.editing);++ async function openWriting(ident) {+ try {+ const found = await readCustomLayers(api);+ mine = found.layers;+ scriptMax = found.scriptMax;+ bands = found.bands;+ radarLayer = found.radarLayer;+ } catch (error) {+ toast(`Could not read your layers: ${error.message}`, 'danger');+ return;+ }+ // The draft already in hand is handed back, unless this press is about a+ // different layer — then it is that layer's turn and the old draft is gone.+ if (!held || held.editing !== ident) {+ held = startForm({+ layer: ident ? mine.find((row) => row.id === ident) ?? null : null,+ bases: dataSources(s2.layers, radarLayer),+ bands,+ radarLayer,+ });+ writingNote = '';+ }+ before = s2.draft ? before : s2.layer;+ open = true;+ }++ async function preview(draft) {+ writingBusy = true;+ try {+ s2.layer = await previewLayer(api, draft);+ writingNote = 'Drawn on the map. Nothing is saved yet.';+ } catch (error) {+ writingNote = '';+ toast(error.message, 'danger');+ } finally {+ writingBusy = false;+ }+ }++ async function keep(draft) {+ writingBusy = true;+ try {+ const saved = await saveCustomLayer(api, draft);+ await clearPreview(api).catch(() => {});+ s2.rememberLayer(saved);+ s2.layer = saved.id;+ open = false;+ held = null;+ writingNote = '';+ toast(`${draft.id} saved`, 'ok');+ } catch (error) {+ toast(error.message, 'danger');+ } finally {+ writingBusy = false;+ }+ }++ /** Put the form away, keeping the draft and the preview on the map. */+ function setAside() {+ open = false;+ }++ async function discard() {+ open = false;+ held = null;+ writingNote = '';+ // A preview is a layer only this machine knows; dropping the draft forgets+ // it and the map goes back to what was on it.+ if (before) s2.layer = before;+ await clearPreview(api).catch(() => {});+ }</script><div class="s2-wrap" bind:this={menuEl}>@@ -40,16 +150,50 @@<span class="mono">{chipDate || 'Most recent'}</span></button>{#if s2.menuOpen}- <div class="s2-menu card">+ <div class="s2-menu card" class:writing={open}><div class="menu-row"><span class="menu-label">Layer</span>- <select class="select" bind:value={s2.layer}>+ <select class="select" bind:value={s2.layer} disabled={open}>{#each s2.layers as entry (entry.id)}<option value={entry.id}>{entry.label}</option>{/each}+ {#if s2.draft}+ <option value={s2.layer}>Draft (not saved)</option>+ {/if}</select></div>{#if s2.layerHint}<div class="menu-hint">{s2.layerHint}</div>{/if}++ {#if !open}+ <div class="menu-hint dim write-row">+ <button class="linkish" onclick={() => openWriting('')}>+ {resuming ? 'Keep writing…' : 'Write a layer…'}+ </button>+ {#if s2.layers.some((entry) => entry.custom && entry.id === s2.layer)}+ <button class="linkish" onclick={() => openWriting(s2.layer)}>Edit this one</button>+ {/if}+ {#if resuming}+ <button class="linkish dismiss" onclick={discard} title="Throw the draft away">+ Discard+ </button>+ {/if}+ </div>+ {:else}+ <CustomLayerForm+ form={held}+ {bases}+ {bands}+ taken={s2.layers+ .filter((entry) => !entry.custom && entry.id !== held.editing)+ .map((entry) => entry.id)}+ {scriptMax}+ busy={writingBusy}+ note={writingNote}+ onpreview={preview}+ onsave={keep}+ oncancel={setAside}+ />+ {/if}<!-- Silent when the layers are the configured ones, which is the normalcase and was a line of panel saying so on every open. -->{#if s2.layersSource !== 'instance'}@@ -87,7 +231,14 @@<div class="menu-row"><span class="menu-label">Date</span><div class="chips">- <button class="chip-opt" class:on={!s2.date} onclick={s2.clearDate}>Most recent</button>+ <button+ class="chip-opt"+ class:on={!s2.date}+ onclick={s2.clearDate}+ title={s2.undated+ ? 'No pass could be dated here; the tiles blend several dates'+ : 'Show the newest pass over the crosshair'}+ >Most recent{#if !s2.date && s2.latest}<span class="opt-day mono">{s2.latest}</span>{/if}</button></div></div>@@ -118,6 +269,7 @@class="cal-day {pass ? cloudClass(pass.cloud) : ''}"class:has={!!pass}class:on={s2.date === day}+ class:showing={!s2.date && s2.latest === day}class:unavailableclass:verifyingdisabled={s2.date !== day &&@@ -198,7 +350,12 @@box-shadow: var(--shadow-2);z-index: 700;}+ /* A script needs room to be read; a date picker does not. The menu widens+ only while one is open, and never past the viewport on a narrow screen. */+ .s2-menu.writing { width: min(620px, calc(100vw - 32px)); }.s2-menu .select { max-width: 150px; padding: 4px 6px; font-size: var(--fs-xs); }+ .write-row { display: flex; gap: 10px; }+ .write-row .dismiss { margin-left: auto; color: var(--text-3); }.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; }@@ -247,6 +404,7 @@.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: 1px; }+ .opt-day { margin-left: 6px; font-size: var(--fs-xs); opacity: 0.7; }.cal-day {/* a square cell grew with the panel; a stated height keeps the month thesize of a month whatever else is in here */@@ -271,5 +429,7 @@.cal-day.verifying { opacity: 0.55; animation: pulse 0.8s ease-in-out infinite alternate; }.cal-day.has:hover { border-color: var(--text-1); }.cal-day.on { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 700; }+ /* the pass "most recent" resolved to: being rendered, but not chosen */+ .cal-day.showing { box-shadow: inset 0 0 0 1px var(--accent); font-weight: 700; }@keyframes pulse { to { opacity: 1; } }</style>diff --git a/frontend/src/tools/satellite/SentinelPicker.test.js b/frontend/src/tools/satellite/SentinelPicker.test.jsindex b40a9fa..27c409a 100644--- a/frontend/src/tools/satellite/SentinelPicker.test.js+++ b/frontend/src/tools/satellite/SentinelPicker.test.js@@ -5,32 +5,39 @@ import SentinelPicker from './SentinelPicker.svelte';/** The picker reads one store (`state/sentinel.svelte.js`); this is a stand-in* holding the state a case would be in, with the actions stubbed. */function props({ s2 = {}, ...overrides } = {}) {+ const state = {+ menuOpen: true,+ layer: 'TRUE_COLOR',+ layers: [{ id: 'TRUE_COLOR', label: 'True colour' }],+ layerHint: '',+ layersSource: 'instance',+ date: '',+ latest: '',+ maxcc: 100,+ month: '2026-05',+ passes: { '2026-05-11': { cloud: 4, granules: 1 } },+ passesBusy: false,+ passesNote: '',+ stale: false,+ verifyingDate: '',+ dateStatus: () => undefined,+ filtered: () => false,+ toggleMenu: vi.fn(),+ loadLayers: vi.fn(),+ stepMonth: vi.fn(),+ loadPasses: vi.fn(),+ pickDate: vi.fn(),+ clearDate: vi.fn(),+ setMaxcc: vi.fn(),+ ...s2,+ };+ // The store derives these from the day it resolved; the stand-in derives them+ // the same way so a test only has to set `date` or `latest`.return {s2: {- menuOpen: true,- layer: 'TRUE_COLOR',- layers: [{ id: 'TRUE_COLOR', label: 'True colour' }],- layerHint: '',- layersSource: 'instance',- date: '',- latest: '',- maxcc: 100,- month: '2026-05',- passes: { '2026-05-11': { cloud: 4, granules: 1 } },- passesBusy: false,- passesNote: '',- stale: false,- verifyingDate: '',- dateStatus: () => undefined,- filtered: () => false,- toggleMenu: vi.fn(),- loadLayers: vi.fn(),- stepMonth: vi.fn(),- loadPasses: vi.fn(),- pickDate: vi.fn(),- clearDate: vi.fn(),- setMaxcc: vi.fn(),- ...s2,+ day: state.date || state.latest || '',+ undated: !(state.date || state.latest),+ ...state,},maxccLabel: (v) => (v >= 100 ? 'Any cloud' : `Up to ${v}%`),monthLabel: () => 'May 2026',diff --git a/frontend/src/tools/satellite/SentinelPicker.writing.test.js b/frontend/src/tools/satellite/SentinelPicker.writing.test.jsnew file mode 100644index 0000000..9869299--- /dev/null+++ b/frontend/src/tools/satellite/SentinelPicker.writing.test.js@@ -0,0 +1,179 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++/**+ * Writing a layer from the map, which is the only place a script can be judged:+ * Preview draws it over the date and ceiling already chosen, and nothing is+ * filed until Save. The map must never be left showing a preview the user+ * walked away from, and a save must not spend a request to learn what this+ * machine just wrote.+ */++const calls = [];+let radar = '';+vi.mock('../../lib/api.js', () => ({+ api: {+ get: vi.fn(async (path) => {+ calls.push(['GET', path]);+ return {+ layers: [],+ max: 40,+ max_script: 4000,+ bands: ['B04', 'B08', 'B11', 'B12'],+ radar_layer: radar,+ };+ }),+ put: vi.fn(async (path, body) => {+ calls.push(['PUT', path, body]);+ if (path.endsWith('/draft-layer')) return { id: 'AZIMUT_DRAFT_ABCDEF123456' };+ return { ...body, label: body.label || body.id, hint: body.hint ?? '' };+ }),+ del: vi.fn(async (path) => {+ calls.push(['DELETE', path]);+ return {};+ }),+ },+}));+const toast = vi.fn();+vi.mock('../../lib/state.svelte.js', () => ({ toast: (...args) => toast(...args) }));++const SentinelPicker = (await import('./SentinelPicker.svelte')).default;+const { sentinelStub } = await import('./sentinelStore.fixture.svelte.js');++let live;+let target;+let s2;++beforeEach(() => {+ calls.length = 0;+ radar = '';+ toast.mockClear();+ s2 = sentinelStub();+ target = document.createElement('div');+ document.body.append(target);+ live = mount(SentinelPicker, {+ target,+ props: {+ s2,+ maxccLabel: () => 'Any cloud',+ monthLabel: () => 'May 2026',+ monthGrid: () => [],+ cloudClass: () => 'clear',+ cloudLabel: () => '',+ },+ });+ flushSync();+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+});++const button = (label) =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));++async function openForm() {+ button('Write a layer…').click();+ await vi.waitFor(() => expect(target.querySelector('[aria-label="Red band"]')).toBeTruthy());+ flushSync();+}++it('offers writing one, and reads the saved list only when asked', async () => {+ expect(button('Write a layer…')).toBeDefined();+ expect(target.querySelector('[aria-label="Red band"]')).toBeNull();+ expect(calls).toEqual([]); // opening the picker asks for nothing+ await openForm();+ // the scripts and the budget are read once the form is actually opened+ expect(calls).toEqual([['GET', '/api/satellite/sentinel/custom-layers']]);+});++it('draws a script on this map before anything is saved', async () => {+ await openForm();+ button('Preview').click();+ await vi.waitFor(() => expect(s2.layer).toBe('AZIMUT_DRAFT_ABCDEF123456'));+ const preview = calls.find(([method, path]) => method === 'PUT' && path.endsWith('/draft-layer'));+ expect(preview[2].base).toBe('TRUE_COLOR');+ expect(preview[2].script).toContain('//VERSION=3');+ // and nothing has been filed under a name yet+ expect(calls.some(([method, path]) => method === 'PUT' && path.endsWith('/custom-layers'))).toBe(+ false+ );+ expect(target.textContent).toContain('Nothing is saved yet');+});++it('keeps the draft and the preview when the form is put away', async () => {+ // Previewing is the reason to close the form — you close it to look at the+ // map — so closing it must not throw away what was typed.+ await openForm();+ const label = target.querySelector('[aria-label="Label"]');+ label.value = 'SWIR plume';+ label.dispatchEvent(new Event('input', { bubbles: true }));+ button('Index').click();+ flushSync();+ button('Preview').click();+ await vi.waitFor(() => expect(s2.draft).toBe(true));++ button('Cancel').click();+ flushSync();+ expect(target.querySelector('[aria-label="Red band"]')).toBeNull(); // put away+ expect(s2.draft).toBe(true); // the map still shows it+ expect(button('Keep writing…')).toBeDefined();+ expect(+ calls.some(([method, path]) => method === 'DELETE' && path.endsWith('/draft-layer'))+ ).toBe(false);++ button('Keep writing…').click();+ await vi.waitFor(() => expect(target.querySelector('[aria-label="Band A"]')).toBeTruthy());+ expect(target.querySelector('[aria-label="Label"]').value).toBe('SWIR plume');+});++it('throws the draft away, and the map with it, only when asked', async () => {+ await openForm();+ button('Preview').click();+ await vi.waitFor(() => expect(s2.draft).toBe(true));+ button('Cancel').click();+ flushSync();++ button('Discard').click();+ await vi.waitFor(() => expect(s2.layer).toBe('TRUE_COLOR'));+ // the preview is this machine's scratch work, and it is forgotten+ expect(+ calls.some(([method, path]) => method === 'DELETE' && path.endsWith('/draft-layer'))+ ).toBe(true);+ expect(button('Write a layer…')).toBeDefined();++ // and a form opened after that starts clean+ button('Write a layer…').click();+ await vi.waitFor(() => expect(target.querySelector('[aria-label="Red band"]')).toBeTruthy());+ expect(target.querySelector('[aria-label="Label"]').value).toBe('');+});++it('keeps a named layer, shows it, and does not re-ask the instance', async () => {+ await openForm();+ const name = target.querySelector('input.mono');+ name.value = 'plume swir';+ name.dispatchEvent(new Event('input', { bubbles: true }));+ flushSync();+ button('Save layer').click();+ await vi.waitFor(() => expect(s2.rememberLayer).toHaveBeenCalled());+ expect(s2.rememberLayer.mock.calls[0][0].id).toBe('PLUME_SWIR');+ expect(s2.layer).toBe('PLUME_SWIR');+ expect(s2.loadLayers).not.toHaveBeenCalled();+ expect(target.querySelector('[aria-label="Red band"]')).toBeNull();+});++it('does not offer a configured layer as something to edit', () => {+ // TRUE_COLOR lives in the configuration; its script is not ours to rewrite+ expect(button('Edit this one')).toBeUndefined();+});++it('never offers the radar layer as a Sentinel-2 data source', async () => {+ s2.layers.push({ id: 'RADAR', label: 'Radar' });+ radar = 'RADAR';+ await openForm();+ const source = target.querySelector('[aria-label="Layer to read data from"]');+ expect([...source.options].map((node) => node.value)).toEqual(['TRUE_COLOR', 'SWIR']);+});diff --git a/frontend/src/tools/satellite/sentinelStore.fixture.svelte.js b/frontend/src/tools/satellite/sentinelStore.fixture.svelte.jsnew file mode 100644index 0000000..94b87fd--- /dev/null+++ b/frontend/src/tools/satellite/sentinelStore.fixture.svelte.js@@ -0,0 +1,58 @@+/**+ * A stand-in for `state/sentinel.svelte.js` with the actions stubbed.+ *+ * It lives in a `.svelte.js` file so `layer` is really reactive: the picker+ * binds a select straight to it, and a plain object would make that binding+ * silently one-way in a test while working in the app.+ */+import { vi } from 'vitest';+import { isDraftLayer } from '../../lib/customLayers.js';++export function sentinelStub(overrides = {}) {+ let layer = $state(overrides.layer ?? 'TRUE_COLOR');+ const layers = $state(+ overrides.layers ?? [+ { id: 'TRUE_COLOR', label: 'True colour' },+ { id: 'SWIR', label: 'SWIR' },+ ]+ );+ return {+ get layer() {+ return layer;+ },+ set layer(value) {+ layer = value;+ },+ get layers() {+ return layers;+ },+ get draft() {+ return isDraftLayer(layer);+ },+ menuOpen: true,+ layerHint: '',+ layersSource: 'instance',+ date: '',+ latest: '',+ day: '',+ undated: false,+ maxcc: 100,+ month: '2026-05',+ passes: {},+ passesBusy: false,+ passesNote: '',+ stale: false,+ verifyingDate: '',+ dateStatus: () => undefined,+ filtered: () => false,+ toggleMenu: vi.fn(),+ loadLayers: vi.fn(),+ stepMonth: vi.fn(),+ loadPasses: vi.fn(),+ pickDate: vi.fn(),+ clearDate: vi.fn(),+ setMaxcc: vi.fn(),+ rememberLayer: vi.fn(),+ ...overrides,+ };+}diff --git a/frontend/src/tools/satellite/state/radar.svelte.js b/frontend/src/tools/satellite/state/radar.svelte.jsindex de3bb03..feee961 100644--- a/frontend/src/tools/satellite/state/radar.svelte.js+++ b/frontend/src/tools/satellite/state/radar.svelte.js@@ -10,6 +10,10 @@* failed says so rather than offering a list that claims there was no pass.* - **A pass is a day and a time.** The radar sees a place at dawn flying south* and at dusk flying north, and those are two looks from opposite sides.+ * - **"Most recent" is a lookup, not a layer default.** Sending no window makes+ * Sentinel Hub blend every pass in the archive, pixel by pixel, which for+ * radar means mixing looks from opposite sides. So the newest pass is resolved+ * and *that* pass is the window; where it has no pixels the map shows a hole.** The arithmetic is `lib/radar.js`; this holds what was asked and what came back.*@@ -24,17 +28,68 @@ import { validPass } from '../../../lib/radar.js';import { addMonths, isoDay, monthBounds, monthOf, sentinelPlaceKey } from '../../../lib/sentinel.js';export function createRadarState({ api, place, onBilled = () => {}, peer = () => null }) {- let pass = $state(null); // null = the most recent pass, the layer's default+ let pass = $state(null); // null = whatever "most recent" resolves to herelet menuOpen = $state(false);let month = $state(monthOf(''));let passes = $state([]);let passesFor = $state('');let busy = $state(false);let note = $state('');+ // The newest pass over this point, and the place it answers for.+ let latest = $state(null);+ let latestFor = $state('');let requestId = 0;const cache = new Map();const hereKey = () => `${month}@${sentinelPlaceKey(place().lat, place().lon)}`;+ const placeKey = () => sentinelPlaceKey(place().lat, place().lon);++ /** The passes of one month over this point, or null when the read failed. */+ async function monthPasses(forMonth, at) {+ const key = `${forMonth}@${at}`;+ if (cache.has(key)) return cache.get(key);+ const { lat, lon } = place();+ const { from, to } = monthBounds(forMonth);+ try {+ const answer = await api.get(+ `/api/satellite/sentinel/dates?collection=sentinel1&lat=${lat}&lon=${lon}&start=${from}&end=${to}`+ );+ onBilled();+ const list = (answer.dates ?? []).filter((entry) => entry.time);+ cache.set(key, list);+ return list;+ } catch {+ return null;+ }+ }++ /**+ * Which pass "most recent" is showing. Sentinel-1 revisits every ~6 days from+ * one track, so this month usually answers it and one step back does the rest.+ * Without it the tiles would blend the archive and the map could not say which+ * look it is drawing, which for radar is most of the reading.+ */+ async function resolveLatest(today = isoDay(new Date())) {+ const at = placeKey();+ if (latestFor === at) return;+ for (const forMonth of [monthOf(today), addMonths(monthOf(today), -1)]) {+ const list = await monthPasses(forMonth, at);+ if (list === null) return; // lookup failed — say nothing rather than guess+ const found = list+ .filter((entry) => entry.date <= today)+ .sort((one, other) => `${one.date}T${one.time}`.localeCompare(`${other.date}T${other.time}`))+ .at(-1);+ if (found && validPass(found)) {+ latest = { date: found.date, time: found.time, orbit: found.orbit ?? '' };+ latestFor = at;+ return;+ }+ }+ // No pass in ~2 months. There is no window to send, so the tiles are the+ // archive blend and the map says so rather than naming a pass.+ latest = null;+ latestFor = at;+ }async function loadPasses(force = false) {const key = hereKey();@@ -44,6 +99,7 @@ export function createRadarState({ api, place, onBilled = () => {}, peer = () =>note = passes.length ? '' : 'No Sentinel-1 pass here this month.';return passes;}+ if (force) cache.delete(key);const mine = ++requestId;const { lat, lon } = place();const { from, to } = monthBounds(month);@@ -101,10 +157,29 @@ export function createRadarState({ api, place, onBilled = () => {}, peer = () =>get peer() {return peer();},+ /** The pass the tiles are rendered from: the chosen one, else the one+ * "most recent" resolved to. Null only while that lookup has not answered+ * or found nothing, which is the one case the tiles blend passes. */+ get shownPass() {+ return pass ?? latest;+ },+ get latest() {+ return latest;+ },+ /** Has "most recent" been answered for the place on screen? */+ get resolved() {+ return Boolean(pass) || latestFor === placeKey();+ },+ /** No pass could be put under the crosshair, so the tiles blend the+ * archive. Declared on screen and left out of provenance. */+ get undated() {+ return !this.shownPass && latestFor === placeKey();+ },/** What the provider id carries (`lib/radar.js` `radarId`). */get variant() {- return { pass };+ return { pass: this.shownPass };},+ resolveLatest,toggleMenu() {menuOpen = !menuOpen;if (menuOpen && (!passesFor || this.stale)) void loadPasses();diff --git a/frontend/src/tools/satellite/state/radar.svelte.test.js b/frontend/src/tools/satellite/state/radar.svelte.test.jsindex 112733a..c662eca 100644--- a/frontend/src/tools/satellite/state/radar.svelte.test.js+++ b/frontend/src/tools/satellite/state/radar.svelte.test.js@@ -84,3 +84,78 @@ describe('radar passes', () => {expect(s1.peer.time).toBe('05:42:40');});});++/**+ * With no pass chosen the tiles used to go out without a mosaicking window,+ * which makes Sentinel Hub blend the whole archive pixel by pixel — for radar+ * that mixes looks from opposite sides of the track, which cannot be read. So+ * "most recent" resolves to one pass and that pass is the window.+ */+describe('never showing a blend of passes', () => {+ it('resolves the newest pass and renders that one', async () => {+ const s1 = store();+ expect(s1.shownPass).toBe(null);+ await s1.resolveLatest('2026-05-20');+ // two passes that day, from opposite sides: the later one is the newest+ expect(s1.shownPass).toEqual({ date: '2026-05-14', time: '17:33:02', orbit: 'ascending' });+ expect(s1.variant).toEqual({ pass: s1.shownPass });+ });++ it('prefers a chosen pass over the resolved one', async () => {+ const s1 = store();+ await s1.resolveLatest('2026-05-20');+ s1.pick(PASSES[1]);+ expect(s1.shownPass.time).toBe('05:42:10');+ });++ it('ignores a pass later than the day asked about', async () => {+ get = vi.fn(async () => ({ dates: PASSES }));+ const s1 = store();+ await s1.resolveLatest('2026-05-13');+ // nothing on or before that day in either month, so there is no window+ expect(s1.shownPass).toBe(null);+ expect(s1.undated).toBe(true);+ });++ it('separates "not asked yet" from "there is no pass here"', async () => {+ const s1 = store();+ expect(s1.resolved).toBe(false);+ expect(s1.undated).toBe(false);+ await s1.resolveLatest('2026-05-20');+ expect(s1.resolved).toBe(true);+ expect(s1.undated).toBe(false);+ });++ it('stays silent rather than declaring a blend when the lookup failed', async () => {+ get = vi.fn(async () => { throw new Error('offline'); });+ const s1 = store();+ await s1.resolveLatest('2026-05-20');+ expect(s1.undated).toBe(false);+ expect(s1.resolved).toBe(false);+ });++ it('steps back a month rather than claiming there was no pass', async () => {+ get = vi.fn(async (path) => (+ path.includes('start=2026-05')+ ? { dates: [] }+ : { dates: [{ date: '2026-04-28', time: '05:42:10', orbit: 'descending' }] }+ ));+ const s1 = store();+ await s1.resolveLatest('2026-05-02');+ expect(s1.shownPass.date).toBe('2026-04-28');+ });++ it('resolves once per place, and asks again where the map went', async () => {+ const s1 = store();+ await s1.resolveLatest('2026-05-20');+ const before = get.mock.calls.length;+ await s1.resolveLatest('2026-05-20');+ expect(get).toHaveBeenCalledTimes(before);+ at = { lat: 26.3833, lon: 56.4383 };+ expect(s1.resolved).toBe(false);+ // the pass it resolved holds while the new place is being looked up, so the+ // tiles never fall back to a blend in between+ expect(s1.shownPass.date).toBe('2026-05-14');+ expect(s1.undated).toBe(false);+ });+});diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.js b/frontend/src/tools/satellite/state/sentinel.svelte.jsindex 416054b..d13b08b 100644--- a/frontend/src/tools/satellite/state/sentinel.svelte.js+++ b/frontend/src/tools/satellite/state/sentinel.svelte.js@@ -41,6 +41,7 @@ import {validMaxcc,cloudLabel,} from '../../../lib/sentinel.js';+import { isDraftLayer } from '../../../lib/customLayers.js';export function createSentinelState({ place, onBilled, notify, api }) {let layer = $state(DEFAULT_LAYER);@@ -70,11 +71,15 @@ export function createSentinelState({ place, onBilled, notify, api }) {let passesNote = $state('');let verifyingDate = $state('');let coverageRev = $state(0);- // The newest pass over this point — what "most recent" is actually showing.- // The layer's default window renders the latest acquisition, so naming it is- // the difference between a dated image and an undated one.+ // The newest pass over this point. "Most recent" is a lookup, not a layer+ // default: sending no window makes Sentinel Hub apply the mosaicking order+ // per pixel over the whole archive, which fills a swath edge or a granule gap+ // from an older scene and hands back a picture of several dates. So the+ // resolved day is sent as the window, and where that pass has no pixels the+ // map shows a hole — a hole can be read, a blend of dates cannot.let latest = $state('');- let latestFor = $state(''); // the place `latest` was resolved for+ let latestFor = $state(''); // the place+ceiling `latest` was resolved for+ let latestBusy = $state(false);const passCache = new Map();const passPending = new Map();@@ -83,6 +88,9 @@ export function createSentinelState({ place, onBilled, notify, api }) {let pickRequestId = 0;const placeKey = () => sentinelPlaceKey(place().lat, place().lon);+ // What a resolved "most recent" answers for: move the crosshair or change the+ // ceiling and the newest allowed pass is a different question.+ const latestKey = () => `${placeKey()}@${maxcc}`;const coverageKey = (day, at = placeKey(), forLayer = layer, ceiling = maxcc) =>`${forLayer}@${ceiling}@${day}@${at}`;@@ -210,6 +218,24 @@ export function createSentinelState({ place, onBilled, notify, api }) {loadPasses();}+ /**+ * A layer just written here, offered from now on.+ *+ * The list is re-read from the backend nowhere: asking the instance again+ * would spend a request to learn something this machine already knows, and+ * re-reading the catalogue instead would throw away a verified instance list+ * and grey out every configured layer.+ */+ function rememberLayer(entry) {+ const row = {+ id: entry.id,+ label: entry.label || entry.id,+ hint: entry.hint ?? '',+ custom: true,+ };+ layers = [...layers.filter((known) => known.id !== row.id), row];+ }+/*** Which pass "most recent" is showing. Sentinel-2 revisits every ~5 days, so* this month usually answers it; early in a month it may not, and one step@@ -222,22 +248,28 @@ export function createSentinelState({ place, onBilled, notify, api }) {const ceiling = maxcc;const key = `${at}@${ceiling}`;if (latestFor === key) return;- for (const forMonth of [monthOf(today), addMonths(monthOf(today), -1)]) {- const days = await fetchMonth(forMonth, at);- if (days === null) return; // lookup failed — say nothing rather than guess- // the ceiling drops cloudy passes from the tiles, so "most recent" is the- // newest pass it still allows, not the newest pass there is- const found = latestAllowedPass(days, today, ceiling);- if (found) {- latest = found;- latestFor = key;- return;+ latestBusy = true;+ try {+ for (const forMonth of [monthOf(today), addMonths(monthOf(today), -1)]) {+ const days = await fetchMonth(forMonth, at);+ if (days === null) return; // lookup failed — say nothing rather than guess+ // the ceiling drops cloudy passes from the tiles, so "most recent" is the+ // newest pass it still allows, not the newest pass there is+ const found = latestAllowedPass(days, today, ceiling);+ if (found) {+ latest = found;+ latestFor = key;+ return;+ }}+ // No pass in ~2 months: real (deep polar winter, persistent gaps). There+ // is no date to send, so the tiles are the archive blend and the map says+ // so rather than naming a day it is not showing.+ latest = '';+ latestFor = key;+ } finally {+ if (at === placeKey() && ceiling === maxcc) latestBusy = false;}- // no pass in ~2 months: real (deep polar winter, persistent gaps) — the- // pill falls back to "most recent" rather than inventing a date- latest = '';- latestFor = key;}function clearDate() {@@ -380,19 +412,47 @@ export function createSentinelState({ place, onBilled, notify, api }) {return layers.find((l) => l.id === layer)?.hint ?? '';},get layerLabel() {+ if (isDraftLayer(layer)) return 'draft layer';return (layers.find((l) => l.id === layer)?.label ?? layer.replace(/_/g, ' ').toLowerCase());},/** The pill is small: "false colour (infrared)" doesn't fit, "FALSE COLOR" does. */get layerShort() {- return layer.replace(/_/g, ' ');+ // A draft's name is a digest of its script, which says nothing to anyone+ return isDraftLayer(layer) ? 'draft' : layer.replace(/_/g, ' ');+ },+ /** Showing a script that has not been saved. */+ get draft() {+ return isDraftLayer(layer);},- /** A half-typed date is not a date: it stays "most recent" rather than- * becoming a request the backend would refuse. */+ get latestBusy() {+ return latestBusy;+ },+ /** The day the tiles are rendered from: the pinned one, else the pass+ * "most recent" resolved to. Empty only while that lookup has not answered+ * or found nothing, which is the one case the map draws undated. */+ get day() {+ const pinned = validDay(date) ? date : '';+ return pinned || (validDay(latest) ? latest : '');+ },+ /** Has "most recent" been answered for the place and ceiling on screen?+ * Unanswered and answered-with-nothing both leave `latest` empty, and only+ * the second is a reason to draw a mosaic. */+ get resolved() {+ return validDay(date) || latestFor === latestKey();+ },+ /** The tiles would blend every date in the archive: no pass could be put+ * under the crosshair. Declared on screen and left out of provenance. */+ get undated() {+ return !this.day && latestFor === latestKey();+ },+ /** One day on both ends — one acquisition. Empty until a day is known, so+ * the undated template is never asked for by accident. */get window() {- return validDay(date) ? { from: date, to: date } : { from: '', to: '' };+ const day = this.day;+ return day ? { from: day, to: day } : { from: '', to: '' };},/** What rides on the provider id, so the tiles, the capture and the cache* all key on the same choices. */@@ -417,6 +477,7 @@ export function createSentinelState({ place, onBilled, notify, api }) {stepMonth,toggleMenu,resolveLatest,+ rememberLayer,clearDate,setMaxcc,pickDate,diff --git a/frontend/src/tools/satellite/state/sentinel.svelte.test.js b/frontend/src/tools/satellite/state/sentinel.svelte.test.jsindex b1df247..da816e2 100644--- a/frontend/src/tools/satellite/state/sentinel.svelte.test.js+++ b/frontend/src/tools/satellite/state/sentinel.svelte.test.js@@ -238,6 +238,85 @@ describe('what the pill can claim', () => {});});+/**+ * Sending no window does not render the most recent pass: Sentinel Hub applies+ * the mosaicking order per pixel over the whole archive, so a swath edge or a+ * granule gap in the newest scene comes back filled from an older one and the+ * tile is a blend of dates. "Most recent" therefore resolves to a day, and that+ * day is the window — holes where the pass has no pixels, which can be read.+ */+describe('never showing a blend of dates', () => {+ it('renders the resolved pass as a one-day window, not an open one', async () => {+ const s2 = store();+ expect(s2.window).toEqual({ from: '', to: '' }); // nothing resolved yet+ await s2.resolveLatest('2026-05-20');+ expect(s2.day).toBe('2026-05-16');+ expect(s2.window).toEqual({ from: '2026-05-16', to: '2026-05-16' });+ expect(s2.variant.from).toBe('2026-05-16');+ });++ it('prefers a pinned day over the resolved one', async () => {+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ await s2.loadPasses();+ await s2.pickDate('2026-05-11');+ expect(s2.day).toBe('2026-05-11');+ expect(s2.window).toEqual({ from: '2026-05-11', to: '2026-05-11' });+ });++ it('separates "not asked yet" from "there is no pass here"', async () => {+ const s2 = store();+ // before the lookup the map must not call itself undated: it has not asked+ expect(s2.resolved).toBe(false);+ expect(s2.undated).toBe(false);+ await s2.resolveLatest('2026-05-20');+ expect(s2.resolved).toBe(true);+ expect(s2.undated).toBe(false);+ });++ it('declares the blend when no pass could be dated at all', async () => {+ get = vi.fn(async (path) => (path.includes('/sentinel/dates') ? answer([]) : { available: true }));+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ expect(s2.day).toBe('');+ expect(s2.window).toEqual({ from: '', to: '' });+ // deep polar winter, a persistent gap: real, and said rather than papered over+ expect(s2.undated).toBe(true);+ });++ it('stays silent rather than declaring a blend when the lookup failed', async () => {+ get = vi.fn(async () => {+ throw new Error('offline');+ });+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ // a failed lookup proves nothing about the place, so it claims nothing+ expect(s2.undated).toBe(false);+ expect(s2.resolved).toBe(false);+ });++ it('answers again for a new ceiling, since a different pass may be newest', async () => {+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ expect(s2.day).toBe('2026-05-16');+ s2.setMaxcc(20);+ expect(s2.resolved).toBe(false); // the old answer was for the old ceiling+ await s2.resolveLatest('2026-05-20');+ expect(s2.day).toBe('2026-05-11');+ });++ it('holds the day it resolved while a new place is being looked up', async () => {+ const s2 = store();+ await s2.resolveLatest('2026-05-20');+ at = { lat: 26.3833, lon: 56.4383 };+ // the map has moved and nothing is resolved here yet, but the tiles must+ // not fall back to a blend in the meantime+ expect(s2.resolved).toBe(false);+ expect(s2.day).toBe('2026-05-16');+ expect(s2.undated).toBe(false);+ });+});+describe('which layers are on offer', () => {it('does not mistake the local catalogue for a checked instance and shares concurrent checks', async () => {get = vi.fn(async (path) => ({ source: path.includes('?check=true') ? 'instance' : 'catalogue',@@ -298,3 +377,49 @@ describe('which layers are on offer', () => {expect(s2.layer).toBe('SWIR');});});++/**+ * A layer written here is a name like any other, plus a script. The store's+ * part is small and worth pinning: it must offer a new one without spending a+ * request to learn what this machine just wrote, and it must never read a+ * preview's digest out loud as though it were a layer name.+ */+describe('layers written here', () => {+ it('offers a layer just saved, without asking the instance again', async () => {+ const s2 = store();+ await s2.loadLayers(true, true);+ const asked = get.mock.calls.length;+ s2.rememberLayer({ id: 'PLUME_SWIR', label: 'SWIR plume', hint: 'hot spots' });+ expect(get).toHaveBeenCalledTimes(asked);+ const row = s2.layers.find((entry) => entry.id === 'PLUME_SWIR');+ expect(row).toMatchObject({ label: 'SWIR plume', hint: 'hot spots', custom: true });+ // and the verified instance list is not thrown away to learn it+ expect(s2.layersSource).toBe('instance');+ });++ it('replaces a layer of the same name rather than listing it twice', () => {+ const s2 = store();+ s2.rememberLayer({ id: 'PLUME', label: 'First' });+ s2.rememberLayer({ id: 'PLUME', label: 'Second' });+ const rows = s2.layers.filter((entry) => entry.id === 'PLUME');+ expect(rows).toHaveLength(1);+ expect(rows[0].label).toBe('Second');+ });++ it('reads a layer with no label as its own name', () => {+ const s2 = store();+ s2.rememberLayer({ id: 'NDWI_MINE' });+ expect(s2.layers.at(-1).label).toBe('NDWI_MINE');+ });++ it('calls a script being previewed a draft, not its digest', () => {+ const s2 = store();+ s2.layer = 'AZIMUT_DRAFT_A1B2C3D4E5F6';+ expect(s2.draft).toBe(true);+ expect(s2.layerShort).toBe('draft');+ expect(s2.layerLabel).toBe('draft layer');+ s2.layer = 'PLUME_SWIR';+ expect(s2.draft).toBe(false);+ expect(s2.layerShort).toBe('PLUME SWIR');+ });+});diff --git a/frontend/src/tools/settings/CustomLayers.svelte b/frontend/src/tools/settings/CustomLayers.sveltenew file mode 100644index 0000000..203036e--- /dev/null+++ b/frontend/src/tools/settings/CustomLayers.svelte@@ -0,0 +1,199 @@+<script>+ /**+ * Copernicus layers written here, inside the Copernicus card.+ *+ * Settings keeps the list: renaming, re-reading and removing are things you+ * do without looking at a scene. Writing one is not — a script is judged on+ * pixels — so the map's own picker has the same form with a Preview, and both+ * read `lib/customLayers.js`.+ *+ * Visible without a key and marked, rather than hidden: a layer you cannot+ * render yet is still worth knowing you could write.+ */+ import { api } from '../../lib/api.js';+ import { toast } from '../../lib/state.svelte.js';+ import Icon from '../../components/Icon.svelte';+ import CustomLayerForm from '../../components/CustomLayerForm.svelte';+ import {+ dataSources,+ deleteCustomLayer,+ readCustomLayers,+ saveCustomLayer,+ startForm,+ } from '../../lib/customLayers.js';++ let { keyed = false } = $props();++ let layers = $state([]);+ let max = $state(40);+ let scriptMax = $state(4000);+ let bands = $state([]);+ let radarLayer = $state('');+ let configured = $state([]); // the layers the instance serves, as bases+ let open = $state(false);+ let held = $state(null); // the draft, which the form reads and mutates+ let busy = $state(false);+ let loaded = false;++ // Reading the list is a local file, not a request to Copernicus, so it costs+ // nothing — but it still waits for the card to be worth reading.+ $effect(() => {+ if (loaded) return;+ loaded = true;+ void load();+ });++ async function load() {+ try {+ const found = await readCustomLayers(api);+ layers = found.layers;+ max = found.max;+ scriptMax = found.scriptMax;+ bands = found.bands;+ radarLayer = found.radarLayer;+ // Settings never asks the instance for its layers (that is a request, on+ // the analyst's own press, in the tools). So the bases on offer are the+ // ones already in use plus the layer every configuration is built on.+ configured = [...new Set(['TRUE_COLOR', ...found.layers.map((row) => row.base)])];+ } catch (error) {+ toast(`Could not read your layers: ${error.message}`, 'danger');+ }+ }++ const full = $derived(layers.length >= max);++ function write(ident) {+ held = startForm({+ layer: ident ? layers.find((row) => row.id === ident) ?? null : null,+ bases: dataSources(configured.map((id) => ({ id })), radarLayer),+ bands,+ radarLayer,+ });+ open = true;+ }++ async function save(draft) {+ busy = true;+ try {+ await saveCustomLayer(api, draft);+ await load();+ open = false;+ held = null;+ toast(`${draft.id} saved`, 'ok');+ } catch (error) {+ toast(error.message, 'danger');+ } finally {+ busy = false;+ }+ }++ async function remove(ident) {+ busy = true;+ try {+ await deleteCustomLayer(api, ident);+ await load();+ toast(`${ident} removed`, 'ok');+ } catch (error) {+ toast(error.message, 'danger');+ } finally {+ busy = false;+ }+ }+</script>++<section class="custom-layers" class:locked={!keyed}>+ <header>+ <span class="title">+ <Icon name="layers" size={13} /> Your own layers+ {#if layers.length}<span class="count">{layers.length}/{max}</span>{/if}+ </span>+ {#if !open}+ <button+ class="btn btn-sm"+ disabled={busy || full}+ onclick={() => write('')}+ title={full ? `You can keep ${max} layers; remove one first` : 'Write a layer here'}+ >+ <Icon name="plus" size={12} /> Write one+ </button>+ {/if}+ </header>++ <p class="lead">+ A composite or an index of your own, written here instead of in the Copernicus dashboard.+ {#if !keyed}Save your Sentinel Hub key above to render one.{/if}+ </p>++ {#if open}+ <CustomLayerForm+ form={held}+ bases={dataSources(configured.map((id) => ({ id })), radarLayer)}+ {bands}+ taken={layers.filter((row) => row.id !== held.editing).map((row) => row.id)}+ {scriptMax}+ {busy}+ onsave={save}+ oncancel={() => {+ open = false;+ held = null;+ }}+ note="A script is judged on pixels: the layer picker on the map has this same form with a Preview."+ />+ {:else if layers.length}+ <ul class="rows">+ {#each layers as row (row.id)}+ <li>+ <span class="names">+ <strong class="mono">{row.id}</strong>+ <small>{row.hint || row.label}</small>+ <small class="through mono">reads {row.base}</small>+ </span>+ <span class="row-actions">+ <button class="btn btn-sm" disabled={busy} onclick={() => write(row.id)}>Edit</button>+ <button+ class="btn btn-sm danger"+ disabled={busy}+ onclick={() => remove(row.id)}+ title="Work already saved keeps this name in its provenance, and it stops rendering"+ >+ Remove+ </button>+ </span>+ </li>+ {/each}+ </ul>+ {/if}+</section>++<style>+ .custom-layers {+ display: grid;+ gap: 8px;+ padding: 10px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-2);+ }+ .custom-layers.locked { opacity: 0.62; }+ header { display: flex; align-items: center; gap: 8px; }+ .title { display: inline-flex; align-items: center; gap: 6px; font-weight: 600; font-size: var(--fs-sm); }+ .count { font-size: var(--fs-xs); color: var(--text-3); font-weight: 400; }+ header > .btn { margin-left: auto; }+ .lead { margin: 0; font-size: var(--fs-xs); color: var(--text-3); }+ .rows { display: grid; gap: 6px; margin: 0; padding: 0; list-style: none; }+ .rows > li {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 7px 9px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-1);+ }+ .names { display: grid; gap: 1px; min-width: 0; }+ /* `.mono` sizes against its parent, so a layer name outgrows its own row. */+ .names > .mono { font-size: var(--fs-sm); }+ .names > small { font-size: var(--fs-xs); color: var(--text-3); }+ .through { color: var(--text-3); opacity: 0.8; }+ .row-actions { display: flex; gap: 6px; margin-left: auto; }+</style>diff --git a/frontend/src/tools/settings/CustomLayers.test.js b/frontend/src/tools/settings/CustomLayers.test.jsnew file mode 100644index 0000000..616435b--- /dev/null+++ b/frontend/src/tools/settings/CustomLayers.test.js@@ -0,0 +1,116 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++/**+ * The list half of writing a layer: Settings keeps them, the map writes them.+ * What matters here is that the card is honest without a key — visible and+ * marked, not hidden — and that removing one says what it costs.+ */++let saved = [];+const calls = [];+vi.mock('../../lib/api.js', () => ({+ api: {+ get: vi.fn(async (path) => {+ calls.push(['GET', path]);+ return { layers: saved, max: 40, max_script: 4000 };+ }),+ put: vi.fn(async (path, body) => {+ calls.push(['PUT', path, body]);+ saved = [...saved.filter((row) => row.id !== body.id), body];+ return body;+ }),+ del: vi.fn(async (path) => {+ calls.push(['DELETE', path]);+ saved = saved.filter((row) => !path.endsWith(row.id));+ return {};+ }),+ },+}));+vi.mock('../../lib/state.svelte.js', () => ({ toast: vi.fn() }));++const CustomLayers = (await import('./CustomLayers.svelte')).default;++let live;+let target;++function open(props = {}) {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(CustomLayers, { target, props: { keyed: true, ...props } });+ flushSync();+ return target;+}++const button = (label) =>+ [...target.querySelectorAll('button')].find((node) => node.textContent.trim().startsWith(label));++beforeEach(() => {+ calls.length = 0;+ saved = [];+});++afterEach(() => {+ if (live) unmount(live);+ live = null;+ target?.remove();+});++it('stays visible without a key, and says what is missing', () => {+ const root = open({ keyed: false });+ expect(root.textContent).toContain('Save your Sentinel Hub key above');+ expect(root.querySelector('.custom-layers').classList.contains('locked')).toBe(true);+ // the option is marked, not taken away: it is still worth knowing it exists+ expect(button('Write one')).toBeDefined();+});++it('says nothing about a missing key once there is one', () => {+ expect(open({ keyed: true }).textContent).not.toContain('Sentinel Hub key above');+});++it('lists what is saved, with the layer each script reads through', async () => {+ saved = [{ id: 'PLUME_SWIR', label: 'SWIR plume', base: 'TRUE_COLOR', hint: 'hot spots', script: 'x' }];+ const root = open();+ await vi.waitFor(() => expect(root.textContent).toContain('PLUME_SWIR'));+ expect(root.textContent).toContain('hot spots');+ expect(root.textContent).toContain('reads TRUE_COLOR');+ expect(root.textContent).toContain('1/40');+});++it('reads the list without asking Copernicus anything', async () => {+ open();+ await vi.waitFor(() => expect(calls.length).toBe(1));+ expect(calls[0]).toEqual(['GET', '/api/satellite/sentinel/custom-layers']);+});++it('opens the saved script to edit, and keeps the name', async () => {+ saved = [{ id: 'PLUME_SWIR', label: 'Plume', base: 'SWIR', hint: '', script: '//VERSION=3\nkept\n' }];+ const root = open();+ await vi.waitFor(() => expect(button('Edit')).toBeDefined());+ button('Edit').click();+ flushSync();+ expect(root.querySelector('textarea').value).toBe('//VERSION=3\nkept\n');+ expect(root.querySelector('input.mono').disabled).toBe(true);+});++it('warns that removing one stops rendering work already filed under it', async () => {+ saved = [{ id: 'PLUME_SWIR', label: 'Plume', base: 'TRUE_COLOR', hint: '', script: 'x' }];+ open();+ await vi.waitFor(() => expect(button('Remove')).toBeDefined());+ expect(button('Remove').title).toContain('provenance');+ button('Remove').click();+ await vi.waitFor(() =>+ expect(calls.some(([method]) => method === 'DELETE')).toBe(true)+ );+});++it('stops offering a new one when the list is full', async () => {+ saved = Array.from({ length: 40 }, (_, index) => ({+ id: `L${index}`, label: '', base: 'TRUE_COLOR', hint: '', script: 'x',+ }));+ const root = open();+ await vi.waitFor(() => expect(root.textContent).toContain('40/40'));+ expect(button('Write one').disabled).toBe(true);+ expect(button('Write one').title).toContain('remove one first');+});diff --git a/frontend/src/tools/settings/ImageryTab.svelte b/frontend/src/tools/settings/ImageryTab.svelteindex 19c8c19..7efbbd5 100644--- a/frontend/src/tools/settings/ImageryTab.svelte+++ b/frontend/src/tools/settings/ImageryTab.svelte@@ -15,6 +15,7 @@import { tick } from 'svelte';import Icon from '../../components/Icon.svelte';import RadarLayer from './RadarLayer.svelte';+ import CustomLayers from './CustomLayers.svelte';import CopernicusLayersHelp from '../../components/CopernicusLayersHelp.svelte';import { SENTINEL_ECO_MAX_ZOOM } from '../../lib/usage.js';import {@@ -195,6 +196,9 @@<CopernicusLayersHelp /><RadarLayer bind:layer={radarLayer} onchanged={load} />{/if}+ {#if k.id === 'sentinelhub'}+ <CustomLayers keyed={!!keys[k.id]} />+ {/if}<p class="overage">{k.cost}. {k.overage}</p>diff --git a/src/azimut/api/analyzers.py b/src/azimut/api/analyzers.pyindex 372325c..df1b086 100644--- a/src/azimut/api/analyzers.py+++ b/src/azimut/api/analyzers.py@@ -104,6 +104,11 @@ class ProbeInput(CheckInput):point: tuple[Longitude, Latitude]+class ValuesInput(CheckInput):+ #: Which rule of the recipe to send the reading of, by position.+ rule: int = Field(ge=0, lt=MAX_RULES)++def _rules_only(body: CheckInput) -> None:if body.recipe.method != "rules":raise HTTPException(422, "only an analyzer of your own rules has checks to test")@@ -150,6 +155,18 @@ def probe_rules(body: ProbeInput) -> dict[str, Any]:return _testing(lambda: detect_rules.probe(body.recipe, body.check, body.point))[email protected]("/compare/analyzers/check/values")+def rule_values(body: ValuesInput) -> dict[str, Any]:+ """One rule's reading over the whole ground a check was tested on.++ What the browser needs to move that rule's line and repaint without asking+ again. One rule at a time, and never fetches: a check whose frames are not+ cached is tested first.+ """+ _rules_only(body)+ return _testing(lambda: detect_rules.rule_values(body.recipe, body.check, body.rule))++Kind = Literal["areas", "zones", "followups", "runs"]diff --git a/src/azimut/api/figures.py b/src/azimut/api/figures.pynew file mode 100644index 0000000..3183d2d--- /dev/null+++ b/src/azimut/api/figures.py@@ -0,0 +1,160 @@+"""REST API for figures: the same ground on one day, through several layers.++The figure an analyst publishes is rarely one picture — it is true colour for+what a reader recognises, a short-wave composite for the heat, a single band,+an index — each captioned, with one line underneath saying where and when.+Built by hand that is four captures, four files, four drags onto a canvas and a+footer typed from memory.++Here it is one press, and nothing new underneath: each panel goes through the+ordinary provider variant (so a layer written in Azimut resolves and caches+exactly as it does on the map) and is filed as a real capture with its own+provenance, and the layout is a Geo Proof. The composer lays panels out,+captions them, draws the footer and takes annotations, so the figure opens as a+composition the analyst can put arrows on rather than a picture they can only+accept or redo.++Its own module because it is the one route that writes captures *and* a proof:+``api/proofs`` reads from ``api/satellite``, so the dependency only goes one way.+``engine/figures.py`` holds the layout and the wording.+"""++from __future__ import annotations++from datetime import datetime, timezone+from typing import Any++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, ConfigDict, Field++from .. import config+from ..engine import figures, geo+from ..engine import media as media_engine+from ..engine import satellite as satellite_engine+from ..engine import sentinel, tiles+from . import proofs+from .cases import get_case+from .satellite import locate_on_save, saved_changed, units_preference++router = APIRouter(prefix="/api", tags=["figures"])+++class FigurePanel(BaseModel):+ """One rendering of the figure's ground: a Copernicus layer and its caption."""++ model_config = ConfigDict(extra="forbid")++ #: A layer the configuration serves, or one written here.+ layer: str = Field(pattern=r"^[A-Z0-9_]{1,40}$")+ #: What the panel is called in the figure — the analyst's words, not the+ #: layer id: "SWIR hotspot (B12-B11-B04)" is the caption, SWIR is the layer.+ caption: str = Field(default="", max_length=120)+++class FigureIn(BaseModel):+ """One place, one day, several renderings."""++ title: str = Field(min_length=1, max_length=200)+ lat: float = Field(ge=-90, le=90)+ lon: float = Field(ge=-180, le=180)+ zoom: int = Field(ge=1, le=22)+ width: int = Field(default=900, ge=256, le=tiles.SIZE_MAX)+ height: int = Field(default=700, ge=256, le=tiles.SIZE_MAX)+ bearing: float = Field(default=0.0, ge=0, le=360)+ #: The acquisition every panel is rendered from. One day, because a figure+ #: whose panels are different dates compares two things at once.+ day: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")+ maxcc: int = Field(default=sentinel.DEFAULT_MAXCC, ge=0, le=100)+ panels: list[FigurePanel] = Field(min_length=1, max_length=figures.MAX_PANELS)+ #: Panels per row. Not `columns`: that name means a table the browser+ #: assembled, which the hardening gate holds to a body limit.+ per_row: int = Field(default=figures.DEFAULT_PER_ROW, ge=1, le=figures.MAX_PER_ROW)+ #: Burn a scale bar and a north arrow into each panel, as a capture can.+ scale_north: bool = False++[email protected]("/cases/{case_id}/satellite/figure")+def build_figure(case_id: str, body: FigureIn) -> dict[str, Any]:+ """Build a figure, and return the proof it opens as.++ One day for every panel, by design: a figure is about *one* acquisition seen+ several ways. Panels of different dates would compare two things at once,+ which is what Compare is for.+ """+ case = get_case(case_id)+ if config.usage_blocked("sentinelhub"):+ raise HTTPException(+ status_code=429,+ detail=f"Sentinel Hub is paused: {int(config.BLOCK_SHARE * 100)}% of the monthly "+ "free tier is used; enable the override in Settings to keep going",+ )+ # One name means one panel: the same layer twice is the same picture twice.+ if len({panel.layer for panel in body.panels}) != len(body.panels):+ raise HTTPException(status_code=422, detail="a figure holds each layer once")++ coords_dd = satellite_engine.coords_label(body.lat, body.lon, "dd")+ rendered: list[dict[str, Any]] = []+ for at, panel in enumerate(body.panels):+ variant = sentinel.variant_id("sentinel2", panel.layer, body.day, body.day, body.maxcc)+ try:+ provider = tiles.get_provider(variant)+ except KeyError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ try:+ image, provenance = tiles.fetch_crop(+ body.lat, body.lon, body.zoom, body.width, body.height,+ provider, bearing=body.bearing, marker_style="none",+ scale_north=body.scale_north, units=units_preference(),+ )+ except tiles.TileFetchError as exc:+ raise HTTPException(status_code=422, detail=f"{panel.layer}: {exc}") from exc+ except Exception as exc: # network / provider failure+ raise HTTPException(+ status_code=502, detail=f"{panel.layer}: {tiles.upstream_failure(exc)}"+ ) from exc++ provenance["plus_code"] = geo.plus_code(body.lat, body.lon)+ provenance["dms"] = geo.to_dms(body.lat, body.lon)+ # The pass the window named, which is this panel's own acquisition.+ provenance["imagery_date"] = body.day+ provenance["figure"] = body.title+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")+ filed = media_engine.import_image(+ case,+ image,+ f"figure_{stamp}_{at + 1}_{panel.layer}.png",+ {"type": "satellite", **provenance},+ by="satellite",+ entity_type="capture",+ extra_attrs={+ "coords": coords_dd, "lat": body.lat, "lon": body.lon,+ "plus_code": provenance["plus_code"], "zoom": provenance["zoom"],+ "bearing": body.bearing, "provider": provenance["provider"],+ },+ title=f"{body.title} · {panel.caption or panel.layer}",+ dedupe=False, # a capture is 1:1 with its entity — never collapsed+ )+ locate_on_save(case, filed["entity"]["id"], body.lat, body.lon)+ rendered.append(+ {+ "src": filed["entity"]["attrs"]["path"],+ "label": panel.caption or panel.layer,+ "natural": (image.width, image.height),+ "lat": body.lat,+ "lon": body.lon,+ }+ )++ spec = figures.spec(+ rendered,+ per_row=body.per_row,+ footer=figures.footer_line(body.day, coords_dd),+ )+ # No export: the layout is the composer's canvas, and a second renderer here+ # would drift from it at the first change. The first save there writes one.+ saved = proofs.save_proof(case_id, proofs.ProofIn(title=body.title, spec=spec))+ saved_changed(case)+ return {+ "proof": {"name": saved["name"]},+ "panels": [{"src": entry["src"], "caption": entry["label"]} for entry in rendered],+ }diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex cb2bcfd..e760006 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -21,7 +21,7 @@ import httpxfrom fastapi import APIRouter, Form, HTTPException, Query, UploadFilefrom fastapi.responses import Responsefrom PIL import Image-from pydantic import BaseModel, Field+from pydantic import BaseModel, ConfigDict, Fieldfrom .. import config, errorsfrom ..engine.analysis_models import Zone@@ -150,11 +150,12 @@ def _now() -> str:return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")-def _units() -> str:+def units_preference() -> 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.+ provenance keeps metres whatever the bar says. Shared, because a figure's+ panels carry the same bar as a capture does (``api/figures.py``)."""return config.load_settings().get("units", "metric")@@ -232,20 +233,45 @@ def _sentinel_instance() -> str:return key+def _catalogue_layers() -> list[dict[str, Any]]:+ return [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS]+++def _offered_layers(found: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """The configuration's layers, then the ones written here.++ Layers written in Azimut are appended rather than merged in: the standard+ true-colour layer stays the first entry, which is what every picker falls+ back to. They carry ``custom`` so a picker can offer them even where the+ instance has not been asked — a script on this machine needs no permission+ from GetCapabilities to exist — and so the editor knows which rows it owns.+ """+ customs = sentinel.custom_layers(config.load_settings())+ names = {entry["id"] for entry in customs}+ kept = [+ entry+ for entry in found+ if entry.get("id") not in names and not sentinel.is_draft_layer(entry.get("id", ""))+ ]+ return kept + [+ {"id": entry["id"], "label": entry["label"], "hint": entry["hint"], "custom": True}+ for entry in customs+ ]++@router.get("/satellite/sentinel/layers")def sentinel_layers(check: bool = False) -> dict[str, Any]:- """The Sentinel-2 layers on offer.+ """The Sentinel-2 layers on offer, wherever they were written.Without ``check`` this is the built-in catalogue and touches nothing —opening the Satellite tab must never phone out (local-first). ``check=true``asks the user's own instance what it really serves (GetCapabilities), which- is the only authority: a configuration can rename or drop any of them.+ is the only authority for the layers *it* holds: a configuration can rename+ or drop any of them. Layers written here are read from settings either way,+ so every map tab offers them without a request."""if not check:- return {- "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],- "source": "catalogue",- }+ return {"layers": _offered_layers(_catalogue_layers()), "source": "catalogue"}try:found = sentinel.capabilities_layers(_sentinel_instance())except HTTPException:@@ -253,17 +279,160 @@ def sentinel_layers(check: bool = False) -> dict[str, Any]:except Exception as exc:# the catalogue still works — say why the real list is missing, don't failreturn {- "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],+ "layers": _offered_layers(_catalogue_layers()),"source": "catalogue","detail": f"could not read the instance's layers: {tiles.upstream_failure(exc)}",}if not found:return {- "layers": [{"id": e.id, "label": e.label, "hint": e.hint} for e in sentinel.LAYERS],+ "layers": _offered_layers(_catalogue_layers()),"source": "catalogue","detail": "the instance listed no layers",}- return {"layers": found, "source": "instance"}+ return {"layers": _offered_layers(found), "source": "instance"}+++# -- layers written here -------------------------------------------------------++#: How many a user may keep. A picker is a list you read, not a database.+MAX_CUSTOM_LAYERS = 40+++class CustomLayerForm(BaseModel):+ """How a layer was written, when a form wrote it rather than a person.++ Kept so reopening the layer shows that form instead of its output, and so+ an index can be offered to Detect as the rule it already is. The script+ stays the truth: a memo this build cannot read is dropped, not refused+ (``sentinel.parse_form``).+ """++ model_config = ConfigDict(extra="ignore")++ way: Literal["composite", "index"]+ red: str = ""+ green: str = ""+ blue: str = ""+ gain: float = Field(default=1.0, gt=0, le=20)+ high: str = ""+ low: str = ""+ ramp: str = Field(default="", max_length=32)+ threshold: float | None = Field(default=None, ge=-1, le=1)+++class CustomLayerIn(BaseModel):+ """A Copernicus layer written in Azimut, as the editor sends it."""++ model_config = ConfigDict(extra="forbid")++ id: str = Field(pattern=r"^[A-Z0-9_]{1,40}$")+ label: str = Field(default="", max_length=60)+ #: A layer the instance serves, which supplies the data collection the+ #: script reads. An evalscript replaces a layer's style, never its source.+ base: str = Field(default=sentinel.DEFAULT_LAYER, pattern=r"^[A-Z0-9_]{1,40}$")+ script: str = Field(min_length=1, max_length=sentinel.CUSTOM_SCRIPT_MAX)+ hint: str = Field(default="", max_length=160)+ form: CustomLayerForm | None = None++[email protected]("/satellite/sentinel/custom-layers")+def custom_layers() -> dict[str, Any]:+ """The layers written here, with their scripts, for the editor."""+ settings = config.load_settings()+ return {+ "layers": sentinel.custom_layers(settings),+ "max": MAX_CUSTOM_LAYERS,+ "max_script": sentinel.CUSTOM_SCRIPT_MAX,+ # The bands the Composite and Index forms offer. Sent from here rather+ # than held in the frontend so one list stays the authority.+ "bands": list(sentinel.L2A_BANDS),+ # The configuration's radar layer, if it has one. A script reading+ # Sentinel-2 bands through it would render nothing, so the editor keeps+ # it out of what a layer can read its data from.+ "radar_layer": str(settings.get("sentinel1_layer") or ""),+ }++[email protected]("/satellite/sentinel/custom-layers")+def save_custom_layer(body: CustomLayerIn) -> dict[str, Any]:+ """Save a layer under its name, replacing any layer of that name.++ The name is the identity: it is what a variant id, a tile-cache directory+ and a capture's provenance carry, so saving over a name deliberately+ changes what everything already filed under it renders.+ """+ try:+ entry = sentinel.parse_custom_layer(body.model_dump())+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc++ def update(settings: dict[str, Any]) -> None:+ kept = [+ row+ for row in settings.get("sentinel_layers", []) or []+ if not (isinstance(row, dict) and row.get("id") == entry["id"])+ ]+ if len(kept) >= MAX_CUSTOM_LAYERS:+ raise HTTPException(+ status_code=409,+ detail=f"you can keep {MAX_CUSTOM_LAYERS} layers; remove one first",+ )+ settings["sentinel_layers"] = [*kept, entry]++ config.update_settings(update)+ return entry+++class DraftLayerIn(BaseModel):+ """A layer being written, as the picker's Preview sends it."""++ model_config = ConfigDict(extra="forbid")++ base: str = Field(default=sentinel.DEFAULT_LAYER, pattern=r"^[A-Z0-9_]{1,40}$")+ script: str = Field(min_length=1, max_length=sentinel.CUSTOM_SCRIPT_MAX)++[email protected]("/satellite/sentinel/draft-layer")+def save_draft_layer(body: DraftLayerIn) -> dict[str, str]:+ """Render a script before it is saved, under a name of its own.++ The name carries a digest of the script, because the name is what the disk+ cache keys on: change two numbers, press Preview again, and the tiles have+ to be fetched rather than served from the first attempt. Only one draft is+ kept — the previous one is dropped, not accumulated.+ """+ ident = sentinel.draft_layer_id(body.script)+ try:+ entry = sentinel.parse_custom_layer(+ {"id": ident, "label": "Draft", "base": body.base, "script": body.script}+ )+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ config.update_settings(lambda settings: settings.update(sentinel_draft_layer=entry))+ return {"id": ident}++[email protected]("/satellite/sentinel/draft-layer")+def clear_draft_layer() -> dict[str, bool]:+ """Forget the draft, when the editor closes."""+ config.update_settings(lambda settings: settings.update(sentinel_draft_layer=None))+ return {"cleared": True}++[email protected]("/satellite/sentinel/custom-layers/{ident}")+def delete_custom_layer(ident: str) -> dict[str, bool]:+ """Forget a layer. Work already saved keeps its name in provenance, and that+ name no longer renders — the same as a layer dropped from a configuration."""++ def update(settings: dict[str, Any]) -> None:+ settings["sentinel_layers"] = [+ row+ for row in settings.get("sentinel_layers", []) or []+ if not (isinstance(row, dict) and row.get("id") == ident)+ ]++ config.update_settings(update)+ return {"deleted": True}@router.get("/satellite/sentinel/dates")@@ -398,13 +567,19 @@ def sentinel1_layer(body: RadarLayerQuery) -> dict[str, Any]:def sentinel_coverage(lat: float, lon: float, layer: str, date: str, maxcc: int = sentinel.DEFAULT_MAXCC) -> dict[str, Any]:- """Verify a candidate date against the configured layer at the crosshair.+ """Verify a candidate date against the layer at the crosshair.``maxcc`` is the cloud ceiling the map will render with: above it SentinelHub returns nothing, so a probe run at a different ceiling would answer aquestion the user didn't ask.++ The probe asks for whichever layer carries the data — a layer written here+ is asked for through its base, since the instance has never heard of the+ name. The probe draws its own dataMask script either way, so what the+ analyst's script would paint makes no difference to the answer."""instance = _sentinel_instance()+ layer, _ = sentinel.resolve_layer(layer, sentinel.renderable_layers(config.load_settings()))if config.usage_blocked("sentinelhub"):raise HTTPException(status_code=429,@@ -1337,7 +1512,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(),+ scale_north=body.scale_north, units=units_preference(),)except tiles.TileFetchError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc@@ -1448,7 +1623,7 @@ async def capture_screenshot(img,meters_per_pixel=tiles.meters_per_pixel(lat, zoom) / device_scale,bearing=bearing,- units=_units(),+ units=units_preference(),)if scale_north and framedelse Nonediff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex 873f80b..2c4d937 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -549,7 +549,8 @@ def export_settings() -> Response:local download of secrets that already live in their workspace.Deliberately absent: export destinations (absolute paths chosen on this- machine), ``cookies.txt`` (a live login session), the cases themselves+ machine), the half-written Copernicus layer in the picker,+ ``cookies.txt`` (a live login session), the cases themselves(portable folders already), the extension folder the app owns(``config.extension_dir()`` — those are this build's own bundled bytes, andthe new machine's Install button writes its own copy, which the browser has@@ -558,6 +559,9 @@ def export_settings() -> Response:"""portable_settings = config.load_settings()portable_settings.pop("export_dirs", None)+ # A layer half-written in the picker is this machine's scratch work, replaced+ # by the next preview. The saved ones travel, in sentinel_layers.+ portable_settings.pop("sentinel_draft_layer", None)# A machine that never paired has no token to carry, and an empty one would# unpair the machine this backup is restored on.if not portable_settings.get("ingest_token"):@@ -597,6 +601,27 @@ class ImportedTileProvider(BaseModel):tile_size: Literal[256, 512] = 256+class ImportedSentinelLayer(BaseModel):+ """Canonical shape of a Copernicus layer written in Azimut, in a backup.++ The analyst's own work, and no credential: a script is carried across+ machines like an analyzer recipe is. The instance it reads through is+ named by `base`, which the receiving configuration must also serve.+ """++ model_config = ConfigDict(extra="ignore", strict=True)++ id: str = Field(pattern=r"^[A-Z0-9_]{1,40}$")+ label: str = Field(default="", max_length=60)+ base: str = Field(default="TRUE_COLOR", pattern=r"^[A-Z0-9_]{1,40}$")+ script: str = Field(min_length=1, max_length=sentinel.CUSTOM_SCRIPT_MAX)+ hint: str = Field(default="", max_length=160)+ #: How a form wrote it, if one did. Typed loosely and re-read through+ #: `sentinel.parse_form` on load: a memo a newer build wrote travels+ #: without this one having to understand it.+ form: dict[str, Any] | None = None++class ImportedProviderStatus(BaseModel):model_config = ConfigDict(extra="ignore", strict=True)@@ -662,6 +687,7 @@ class ImportedSettings(BaseModel):ge=config.SETTINGS_SCHEMA,le=config.SETTINGS_SCHEMA,)+ sentinel_layers: list[ImportedSentinelLayer] = Field(default_factory=list, max_length=40)tile_providers: list[ImportedTileProvider] = Field(default_factory=list, max_length=100)api_keys: dict[ShortId, SecretValue] = Field(default_factory=dict, max_length=128)usage: dict[ShortId, dict[UsageMonth, UsageCount]] = Field(default_factory=dict, max_length=128)diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 0f38330..6a9e889 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -58,6 +58,17 @@ DEFAULT_SETTINGS: dict[str, Any] = {# Schema version this build writes. Read back through _settings_schema() so# a future breaking rename is migrated rather than silently dropped."schema": SETTINGS_SCHEMA,+ # Copernicus layers written here rather than in the Copernicus dashboard, in+ # the order they were saved. Each: {"id" (the name every variant id, cache+ # directory and capture carries), "label", "base" (a layer the instance+ # serves, which supplies the data collection), "script" (the evalscript),+ # "hint"}. engine/sentinel.py owns the shape; they reach every map tab+ # through /api/satellite/sentinel/layers.+ "sentinel_layers": [],+ # The layer being written on this machine right now, so the map can render+ # it before it is saved: {"id" (AZIMUT_DRAFT_<digest>), "base", "script"}.+ # Replaced by the next preview, and never offered in a picker.+ "sentinel_draft_layer": None,# Extra XYZ tile providers added by the user (spec §6 v1 notes).# Each: {"id", "label", "url" ({x}/{y}/{z} template), "attribution", "max_zoom"}"tile_providers": [],diff --git a/src/azimut/engine/analysis_models.py b/src/azimut/engine/analysis_models.pyindex eddead4..0151e52 100644--- a/src/azimut/engine/analysis_models.py+++ b/src/azimut/engine/analysis_models.py@@ -367,7 +367,7 @@ def ordered_pair(a: Source, b: Source) -> bool:#: How many checks one analyzer keeps, and how many marks one check holds.MAX_CHECKS = 12-MAX_MARKS = 20+MAX_MARKS = 60Longitude = Annotated[float, Field(ge=-180, le=180)]Latitude = Annotated[float, Field(ge=-85, le=85)]diff --git a/src/azimut/engine/analyzers.py b/src/azimut/engine/analyzers.pyindex 3ff372a..290b2d9 100644--- a/src/azimut/engine/analyzers.py+++ b/src/azimut/engine/analyzers.py@@ -755,18 +755,26 @@ def frame(case: Case, run: dict[str, Any], source: Source, x: int, y: int,# A day is read whole, whatever its tile's cloud cover: the ceiling# chose the day, and passed on as MAXCC it would blank a day the analyst# picked over it. The sky byte masks the clouds pixel by pixel.+ # A layer written in Azimut is a script over a base layer; the instance+ # has never heard of the name. A band product reads through the base and+ # ignores the script (our evalscript replaces it), while the review+ # picture is what the analyst wrote, so it carries it.+ asked, script = sentinel.resolve_layer(+ source.layer, sentinel.renderable_layers(config.load_settings())+ )if product or radar:# A radar picture is ours too: there is no true colour to borrow,# so the review composite is rendered like a product, unpadded.try:raw = sentinel.band_frame(instance, _box(z, x, y, PAD if product else 0), edge, edge,source.date, product or "sar-picture",- sentinel.DEFAULT_MAXCC, layer=source.layer,+ sentinel.DEFAULT_MAXCC, layer=asked,time=source.time)finally:config.record_usage("sentinelhub", 1)else:- url = sentinel.wmts_url(source.layer, source.date, source.date, sentinel.DEFAULT_MAXCC)+ url = sentinel.wmts_url(asked, source.date, source.date, sentinel.DEFAULT_MAXCC,+ script=script)url = url.replace("{key}", instance)with httpx.stream("GET", tiles.tile_url(url, z, x, y, 1), timeout=30) as response:if response.status_code == 404:diff --git a/src/azimut/engine/detect_rules.py b/src/azimut/engine/detect_rules.pyindex ebe3f0a..2608101 100644--- a/src/azimut/engine/detect_rules.py+++ b/src/azimut/engine/detect_rules.py@@ -56,7 +56,7 @@ REFLECTANCE = frozenset({"band", "brightness", "colour"})#: How many grid tiles one check may read, the ones beside a pin near an edge#: included. Past that the frames to fetch stop being a figure an analyst can#: weigh before pressing Test.-MAX_CHECK_TILES = 12+MAX_CHECK_TILES = 20#: How near to its tile's edge a pin may come, in pixels, before the tile across#: the edge is read as well. The examples keep their marks at least 64 pixels#: inside, so each of them reads one tile.@@ -616,6 +616,83 @@ def _reading(recipe: Recipe, evaluation: Evaluation, px: int, py: int) -> dict[sfor i in range(len(recipe.rules))]}+#: Steps a rule's value is quantised to on its way to the browser. Sixteen bits+#: across the span actually measured puts the rounding orders of magnitude below+#: any line an analyst can set, so the ground the browser paints while the slider+#: moves is the ground the next test will keep, not an approximation of it.+VALUE_STEPS = 65535+++def _value_png(values: Any, seen: Any, low: float, span: float) -> str:+ """One rule's reading over a tile, as a PNG the browser can read exactly.++ Sixteen bits split over two channels, because a canvas hands back eight-bit+ RGBA whatever the file held: a 16-bit greyscale PNG would be truncated on+ the way in and the line would land in the wrong place.+ """+ import numpy as np++ scaled = (np.nan_to_num(values, nan=0.0, posinf=0.0, neginf=0.0) - low) / span+ steps = np.clip(np.rint(scaled * VALUE_STEPS), 0, VALUE_STEPS).astype(np.uint16)+ # Unmeasured ground carries no reading; the browser has the measured bit and+ # leaves it alone, so what sits here only has to be defined.+ steps = np.where(seen, steps, 0).astype(np.uint16)+ rgb = np.dstack([(steps >> 8).astype(np.uint8), (steps & 0xFF).astype(np.uint8),+ np.zeros(steps.shape, np.uint8)])+ out = io.BytesIO()+ Image.fromarray(rgb, "RGB").save(out, "PNG", compress_level=6)+ return base64.b64encode(out.getvalue()).decode("ascii")+++def rule_values(recipe: Recipe, check: Check, index: int) -> dict[str, Any]:+ """What one rule read at every pixel of a tested check's ground.++ A test sends a verdict: the ground each rule kept. That answers whether the+ line is crossed, never where it should be. This sends the quantity itself,+ so the line can be moved and the ground repainted without asking again — the+ reading is the same one the test made, and the browser applies the same+ comparison (`_passes`) to it.++ One rule at a time, and only when asked: every rule of every tile at once+ would be tens of megabytes on a press nobody made. Never fetches — a check+ whose frames are not cached is tested first.+ """+ import numpy as np++ _satellite(recipe, check)+ if not 0 <= index < len(recipe.rules):+ raise ValueError("no such rule")+ if recipe.rules[index].measure == "class":+ raise ValueError("a ground class is a classification, not a quantity with a line")+ a, b = check_sources(recipe, check.a, check.b)+ tiles = check_tiles(check)+ lacking = missing(recipe, a, b, tiles)+ if lacking:+ return {"ready": False, "missing": len(lacking)}++ read = {tile: _measure_tile(recipe, a, b, *tile) for tile in tiles}+ cropped = {}+ for tile, measured in read.items():+ core = measured.core+ values = measured.values[index]+ if values is None:+ raise ValueError("that rule reads no quantity")+ cropped[tile] = (values[core], measured.measured[core] & np.isfinite(values[core]))++ # One span over the whole ground, so a value means the same on every tile.+ seen = [values[ok] for values, ok in cropped.values() if ok.any()]+ low = float(min(part.min() for part in seen)) if seen else 0.0+ high = float(max(part.max() for part in seen)) if seen else 0.0+ span = high - low or 1.0++ _, size = analyzers.GRID+ return {"ready": True, "missing": 0, "size": size, "rule": index,+ "low": round(low, 6), "high": round(low + span, 6), "steps": VALUE_STEPS,+ "tiles": [{"x": x, "y": y, "box": tile_box(x, y),+ "values": _value_png(cropped[(x, y)][0], cropped[(x, y)][1], low, span)}+ for x, y in tiles]}++def probe(recipe: Recipe, check: Check, point: tuple[float, float]) -> dict[str, Any]:"""What every rule read at one point of the ground a check was tested on."""a, b = check_sources(recipe, check.a, check.b)diff --git a/src/azimut/engine/figures.py b/src/azimut/engine/figures.pynew file mode 100644index 0000000..29290b3--- /dev/null+++ b/src/azimut/engine/figures.py@@ -0,0 +1,114 @@+"""A figure: one place, one day, several renderings, laid out for publication.++The figure an analyst actually publishes is rarely one picture. It is the same+ground four times — true colour for what a reader recognises, a short-wave+composite for the heat, a single band for the same thing without the colour, an+index for the measurement — each captioned, with one line underneath saying+where and when. Building that by hand means four captures, four files, four+drags onto a canvas and a footer typed from memory.++So it is one press. Each panel is a real capture, filed with its own provenance+(the ``/satellite/figure`` route), and the layout is a Geo Proof spec: the composer already+lays panels out in a grid, captions them, draws the footer and takes+annotations, so a figure opens as an ordinary composition the analyst can put+arrows on rather than as a picture they can only accept or redo.++Nothing here reaches the network or the disk — it is the arithmetic of the+layout and the wording of the footer, which is why it can be read on its own.+"""++from __future__ import annotations++import uuid+from typing import Any++#: Panels per row, and the ceiling. Two across is what the figures this was+#: built for use, and a figure nobody can read the captions of is not a figure:+#: past eight panels it is a contact sheet.+#:+#: "Per row" rather than "columns" because a body field named `columns` is a+#: table the browser assembled, which the hardening gate holds to a size limit+#: (`tests/test_hardening.py`). This is a count from one to four.+#:+#: "Figure" rather than "plate" on purpose: a plate is already the SVG a Graph+#: or a Timeline is written out as (``api/plates.py``), and the canvas a Geo+#: Proof composes on (``lib/composer.js``). A third meaning would cost more+#: than the word is worth.+DEFAULT_PER_ROW = 2+MAX_PANELS = 8+MAX_PER_ROW = 4++#: What every panel is drawn from, said once under the figure.+CREDIT = "Copernicus Sentinel-2 L2A"+RADAR_CREDIT = "Copernicus Sentinel-1 GRD"+++def caption_for(label: str, at: int, total: int, numbered: bool = True) -> str:+ """A panel's caption. Numbered, because a figure's text refers to panel 2."""+ text = " ".join(str(label or "").split())+ if not numbered or total < 2:+ return text+ return f"{at + 1}. {text}" if text else f"{at + 1}."+++def footer_line(day: str, coords: str, credit: str = CREDIT) -> str:+ """The one line under the figure: when, where, and from what.++ Each part only when it is known. An undated figure says nothing about a date+ rather than printing an empty field — the same rule the date pill follows.+ """+ parts = []+ if day:+ parts.append(f"Date: {day}")+ if coords:+ parts.append(f"Coordinates: {coords}")+ if credit:+ parts.append(f"Source: {credit}")+ return " · ".join(parts)+++def spec(+ panels: list[dict[str, Any]],+ *,+ per_row: int = DEFAULT_PER_ROW,+ footer: str = "",+ numbered: bool = True,+) -> dict[str, Any]:+ """The Geo Proof a figure is saved as.++ ``panels`` is one entry per rendering, in the order they were asked for:+ ``{"src", "label", "natural", "lat", "lon"}``. Everything the composer can+ decide for itself is left out, so a figure opens as a plain composition+ rather than one frozen into whatever this module thought a figure should+ look like — the one exception being the footer, which states the figure's+ own provenance and is the reason it is worth pressing one button for.+ """+ across = max(1, min(int(per_row), MAX_PER_ROW))+ total = len(panels)+ return {+ "azimut_proof": 1,+ "panels": [+ {+ "id": f"p{uuid.uuid4().hex[:8]}",+ "src": entry["src"],+ "caption": caption_for(entry.get("label", ""), at, total, numbered),+ "row": at // across,+ "scale": 1,+ "natural": [int(entry["natural"][0]), int(entry["natural"][1])],+ # The composer reads the point off a panel for the coordinates+ # it offers; `aimed` says an analyst put the crosshair there,+ # which a figure's centre is.+ "meta": {"lat": entry["lat"], "lon": entry["lon"], "aimed": True},+ }+ for at, entry in enumerate(panels)+ ],+ "pastes": [],+ "shapes": [],+ "notes": {},+ "legendOrder": [],+ "material": [],+ "sources": [],+ # Said once, in the credit line. The composer's own coordinate footer+ # stays off so the figure does not print the point twice.+ "footer": footer,+ }diff --git a/src/azimut/engine/sentinel.py b/src/azimut/engine/sentinel.pyindex c1811c0..efe44c8 100644--- a/src/azimut/engine/sentinel.py+++ b/src/azimut/engine/sentinel.py@@ -19,6 +19,7 @@ instance itself, which is the only authority (user-triggered — local-first).from __future__ import annotationsimport base64+import hashlibimport ioimport mathimport re@@ -120,13 +121,25 @@ def wmts_url(start: str | None = None,end: str | None = None,maxcc: int = DEFAULT_MAXCC,+ *,+ script: str = "",) -> str:"""The WMTS GetTile template for one layer and window: ``{key}``/``{z}``/``{x}``/``{y}``.``start``/``end`` (YYYY-MM-DD) become the ``TIME`` mosaicking window, which- is inclusive of both days. Omitted, no TIME is sent and the layer's own- default applies — "most recent", the honest default for "just show me it".+ is inclusive of both days. The same day on both ends is one acquisition,+ which is what callers ask for: a picture an analyst can point at and date.``maxcc`` is the cloud ceiling in percent; scenes above it are not rendered.+ ``script`` renders the layer's *data* through an evalscript of ours or the+ analyst's instead of the layer's own style (see ``resolve_layer``).++ Omitted, no TIME is sent, and that is *not* "the most recent pass": the+ mosaicking order runs per pixel over the whole archive, so wherever the+ newest scene has nodata — a swath edge, a granule gap — the pixel comes+ from an older one and the tile is a blend of dates that cannot be dated.+ A dated window leaves holes there instead, which is the trade this tool+ makes. The undated template stands only for the declared fallback, where+ no pass could be resolved at all."""url = (f"{BASE}/wmts/{{key}}"@@ -135,11 +148,22 @@ def wmts_url("&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}&FORMAT=image/jpeg"f"&MAXCC={int(maxcc)}")+ if script:+ url += f"&EVALSCRIPT={evalscript_param(script)}"if start and end:url += f"&TIME={start}/{end}"return url+def evalscript_param(script: str) -> str:+ """An evalscript as the ``EVALSCRIPT`` query value: base64, then URL-escaped.++ The radar basemap has sent ours this way since it shipped; a layer written+ in Azimut is the same request with the analyst's script instead of ours.+ """+ return quote(base64.b64encode(script.encode("utf-8")).decode("ascii"), safe="")++def variant_id(base_id: str, layer: str | None = None, start: str | None = None,end: str | None = None, maxcc: int | None = None) -> str:"""Pack a layer + window + cloud ceiling into a provider id. Mirror of@@ -212,12 +236,201 @@ def variant_label(window = start if start == end else f"{start} → {end}"label = f"{known} · {window}"else:- label = f"{known} · most recent"+ label = f"{known} · undated mosaic"if maxcc != DEFAULT_MAXCC:label += f" · ≤{int(maxcc)}% cloud"return label+# -- layers written here -------------------------------------------------------++# How much JavaScript a layer may carry. EVALSCRIPT rides on the GET as base64,+# a third longer than its source, and a proxy refuses a long URL well before+# Sentinel Hub does. 4 kB holds a generous composite or index and keeps the+# whole request inside the 8 kB every server in the way accepts.+CUSTOM_SCRIPT_MAX = 4000+_CUSTOM_LABEL_MAX = 60+_CUSTOM_HINT_MAX = 160+++#: The forms that write a script, as opposed to a script written by hand.+FORM_WAYS = ("composite", "index")+_RAMP_RE = re.compile(r"^[a-z0-9_-]{1,32}$")+++def parse_form(raw: Any) -> dict[str, Any] | None:+ """How a layer was written, when a form wrote it, or None.++ A memo, not the truth: the script is what renders, and a layer whose memo is+ unreadable still works. It is kept for two things the script cannot answer.++ Reopening the layer shows the form that wrote it rather than its output —+ without this, every saved layer opens as JavaScript, including the ones+ nobody typed.++ And an index *is* a quantity Detect already measures: a normalised+ difference of two bands (``analysis_models.Rule``, ``measure="nd"``), so the+ same arithmetic the layer paints can be read as a rule. A composite is three+ channels and no single quantity, which is why only one of the two carries+ over.+ """+ if not isinstance(raw, dict):+ return None+ way = str(raw.get("way", ""))+ if way not in FORM_WAYS:+ return None++ def band(name: str) -> str | None:+ value = str(raw.get(name, ""))+ return value if value in L2A_BANDS else None++ if way == "composite":+ red, green, blue = band("red"), band("green"), band("blue")+ if not (red and green and blue):+ return None+ try:+ gain = float(raw.get("gain", 1))+ except (TypeError, ValueError):+ return None+ if not 0 < gain <= 20:+ return None+ return {"way": way, "red": red, "green": green, "blue": blue, "gain": gain}++ high, low = band("high"), band("low")+ if not (high and low):+ return None+ ramp = str(raw.get("ramp", "") or "")+ if ramp and not _RAMP_RE.match(ramp):+ return None+ threshold: float | None = None+ stated = raw.get("threshold")+ if stated not in (None, ""):+ try:+ threshold = float(stated)+ except (TypeError, ValueError):+ return None+ if not -1 <= threshold <= 1:+ return None+ return {"way": way, "high": high, "low": low, "ramp": ramp, "threshold": threshold}+++def parse_custom_layer(entry: Any) -> dict[str, Any]:+ """One layer written in Azimut, validated. Raises ValueError on anything else.++ ``id`` is the name everything downstream sees — a variant id, a URL path+ segment, a cache directory, a capture's provenance — so it is held to the+ same allowlist as a configured layer's (``_LAYER_RE``).++ ``base`` is a layer the *instance* serves. An evalscript replaces a layer's+ style, never its data collection, so a script needs an existing layer to+ read through: the same arrangement the radar basemap has always used, where+ our picture is drawn from the user's own Sentinel-1 layer.+ """+ if not isinstance(entry, dict):+ raise ValueError("a custom layer is an object")+ ident = str(entry.get("id", "")).strip()+ if not _LAYER_RE.match(ident):+ raise ValueError(+ f"malformed custom layer name '{ident}' "+ "(capitals, digits and underscores, up to 40)"+ )+ base = str(entry.get("base", "") or DEFAULT_LAYER).strip()+ if not _LAYER_RE.match(base):+ raise ValueError(f"malformed base layer '{base}'")+ script = str(entry.get("script", ""))+ if not script.strip():+ raise ValueError("a custom layer needs a script")+ if len(script) > CUSTOM_SCRIPT_MAX:+ raise ValueError(f"a script is at most {CUSTOM_SCRIPT_MAX} characters")+ label = str(entry.get("label", "") or ident).strip()[:_CUSTOM_LABEL_MAX]+ hint = str(entry.get("hint", "")).strip()[:_CUSTOM_HINT_MAX]+ kept: dict[str, Any] = {+ "id": ident, "label": label, "base": base, "script": script, "hint": hint,+ }+ form = parse_form(entry.get("form"))+ if form:+ kept["form"] = form+ return kept+++def custom_layers(settings: dict[str, Any]) -> list[dict[str, Any]]:+ """The layers written here, in the order they were saved.++ A malformed entry is skipped rather than allowed to break the layer list:+ the app must still open on a settings file an older or newer build wrote.+ """+ found: list[dict[str, Any]] = []+ seen: set[str] = set()+ for entry in settings.get("sentinel_layers", []) or []:+ try:+ parsed = parse_custom_layer(entry)+ except ValueError:+ continue+ if parsed["id"] in seen:+ continue # a name means one layer, and the first one saved keeps it+ seen.add(parsed["id"])+ found.append(parsed)+ return found+++# A layer being written, as opposed to one that was saved. Its name carries a+# digest of the script because the name is the cache key: an analyst presses+# Preview, changes two numbers and presses it again, and the second press has to+# fetch tiles rather than serve the first one's.+DRAFT_PREFIX = "AZIMUT_DRAFT_"+++def draft_layer_id(script: str) -> str:+ """The name a draft of this script renders under."""+ digest = hashlib.sha256(script.encode("utf-8")).hexdigest()[:12].upper()+ return f"{DRAFT_PREFIX}{digest}"+++def is_draft_layer(layer: str) -> bool:+ return layer.startswith(DRAFT_PREFIX)+++def draft_layer(settings: dict[str, Any]) -> dict[str, Any] | None:+ """The layer being written on this machine, if there is one."""+ raw = settings.get("sentinel_draft_layer") or None+ if not isinstance(raw, dict):+ return None+ try:+ return parse_custom_layer(raw)+ except ValueError:+ return None+++def renderable_layers(settings: dict[str, Any]) -> list[dict[str, Any]]:+ """Every layer a request may be asked for: the saved ones and the draft.++ The pickers and the editor read ``custom_layers``, which is the saved list.+ Anything that turns a name into a request reads this one, so a draft renders+ exactly like a saved layer without being offered as one.+ """+ draft = draft_layer(settings)+ return [*custom_layers(settings), *([draft] if draft else [])]+++def resolve_layer(+ layer: str, customs: list[dict[str, Any]] | None = None+) -> tuple[str, str]:+ """``layer`` as a request can carry it: the layer to ask for, and the script.++ A configured layer answers for itself and needs no script. A layer written+ here answers through its base layer, which supplies the data collection,+ with the analyst's script in place of that layer's style.++ A name written here wins over a configured one, so a layer later added to+ the configuration under the same name cannot quietly change what a saved+ capture renders.+ """+ for entry in customs or []:+ if entry["id"] == layer:+ return str(entry["base"]), str(entry["script"])+ return layer, ""++# -- date discovery (WFS) ------------------------------------------------------# How wide a box around the point to ask about, in degrees (~1 km): big enough@@ -575,6 +788,10 @@ def radar_wmts_url(layer: str, day: str = "", time: str = "") -> str:The layer is the user's Sentinel-1 layer; its own style is replaced by thepicture Detect reviews radar candidates on, so the map and the evidenceread alike. JPEG like the optical basemap: speckle costs PNG a fortune.++ ``day`` names one pass and is what callers send. Without it no TIME goes+ out and the tile blends every pass in the archive, exactly as the optical+ template does (see ``wmts_url``) — kept for the declared fallback only."""if not _LAYER_RE.match(layer or ""):raise ValueError(f"malformed layer '{layer}'")@@ -591,9 +808,9 @@ def radar_wmts_url(layer: str, day: str = "", time: str = "") -> str:def radar_label(day: str, time: str) -> str:- """How a radar variant reads: "2026-05-14 05:42 UTC", a day, or the latest."""+ """How a radar variant reads: "2026-05-14 05:42 UTC", a day, or undated."""if not day:- return "most recent pass"+ return "undated mosaic"return f"{day} {time[:5]} UTC" if time else daydiff --git a/src/azimut/engine/tiles.py b/src/azimut/engine/tiles.pyindex 620b56d..6828dcc 100644--- a/src/azimut/engine/tiles.py+++ b/src/azimut/engine/tiles.py@@ -94,8 +94,10 @@ GOOGLE_JS_LOADER_URL = "https://maps.googleapis.com/maps/api/js?key={key}&v=week# configuration-instance UUID, which is the whole credential — no token to mint.# The layer, the mosaicking window and the cloud ceiling are choices, not# constants, so the template is built per variant in engine/sentinel.py; this is-# the plain one (TRUE_COLOR, the layer's own default window = most recent, and-# no cloud filter — the instance's own would silently drop cloudy passes).+# the plain one: TRUE_COLOR, no cloud filter (the instance's own would silently+# drop cloudy passes) and no window, which blends the whole archive per pixel+# rather than showing the newest pass. It is the undated fallback the UI falls+# to when it cannot resolve a pass, and it says so on screen when it does.SENTINELHUB_WMTS_URL = sentinel.wmts_url()# Default eco threshold for both Sentinel layers; Settings can override it.SENTINEL_ECO_MAX_ZOOM = 7@@ -333,11 +335,18 @@ def get_provider(provider_id: str) -> Provider:layer, start, end, maxcc = sentinel.parse_variant(spec)except ValueError as exc:raise KeyError(str(exc)) from exc+ # A layer written in Azimut is its base layer plus a script; one the+ # configuration serves answers for itself. Either way the id keeps+ # the name the analyst chose, so the cache and provenance are keyed+ # on what they asked for, not on how it was rendered.+ asked, script = sentinel.resolve_layer(+ layer, sentinel.renderable_layers(config.load_settings())+ )return replace(provider,id=provider_id,label=f"{provider.label} · {sentinel.variant_label(layer, start, end, maxcc)}",- url=sentinel.wmts_url(layer, start, end, maxcc).replace(+ url=sentinel.wmts_url(asked, start, end, maxcc, script=script).replace("{key}", _sentinel_key_from(provider.url)),)diff --git a/src/azimut/server.py b/src/azimut/server.pyindex 946746d..8304888 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -311,9 +311,9 @@ def create_app() -> FastAPI:)from .api import (- analysis_views, analyzers, cases, compare, drafts, events, files, folders, ingest, inspect,- maplayers, media, notes, plates, proofimports, proofs, proposals, satellite, settings,- sheetproofs, sheets, templates,+ analysis_views, analyzers, cases, compare, drafts, events, figures, files, folders, ingest,+ inspect, maplayers, media, notes, plates, proofimports, proofs, proposals, satellite,+ settings, sheetproofs, sheets, templates,)from .engine import sheets as sheet_engine@@ -322,6 +322,7 @@ def create_app() -> FastAPI:app.include_router(analysis_views.router)app.include_router(notes.router)app.include_router(plates.router)+ app.include_router(figures.router)app.include_router(sheets.router)# The one sheet road that fetches bytes, so its own module and its own job.app.include_router(sheetproofs.router)diff --git a/tests/test_detect_rules.py b/tests/test_detect_rules.pyindex eb7dd92..9a2912f 100644--- a/tests/test_detect_rules.py+++ b/tests/test_detect_rules.py@@ -517,6 +517,8 @@ def test_the_catalogue_offers_the_rules_vocabulary_and_the_convertible_built_inscatalogue = client.get("/api/compare/analyzers").json()assert catalogue["rules"]["bands"] == list(sentinel.L2A_BANDS)assert "water" in catalogue["rules"]["classes"]+ assert catalogue["rules"]["max_marks"] == 60+ assert catalogue["rules"]["max_check_tiles"] == 20assert catalogue["rules"]["max_check_tiles"] == detect_rules.MAX_CHECK_TILESassert set(catalogue["as_rules"]) == {"burn-scars", "vegetation-loss", "new-water"}assert any(method["id"] == "rules" and method["rules"] for method in catalogue["methods"])@@ -595,10 +597,10 @@ def test_a_check_reads_the_tiles_under_its_marks_and_beside_a_mark_near_an_edge(detect_rules.check_tiles(Check.model_validate(check_body([])))-def test_a_check_may_not_reach_more_tiles_than_a_handful():+def test_a_check_may_not_reach_more_than_twenty_tiles():z, x, y = SENTINEL_TILEwide = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(detect_rules.MAX_CHECK_TILES + 1)]- with pytest.raises(ValueError, match="at most 12"):+ with pytest.raises(ValueError, match="at most 20"):detect_rules.check_tiles(Check.model_validate(check_body(wide)))@@ -617,13 +619,72 @@ def test_a_check_asks_what_testing_it_costs_before_anything_is_fetched(client, oempty = client.post("/api/compare/analyzers/check/plan", json={**body, "check": check_body([])})assert empty.status_code == 422 and "drop a pin" in empty.textz, x, y = SENTINEL_TILE- wide = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(13)]+ wide = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(21)]refused = client.post("/api/compare/analyzers/check/plan", json={**body, "check": check_body(wide)})- assert refused.status_code == 422 and "at most 12" in refused.text+ assert refused.status_code == 422 and "at most 20" in refused.textbuiltin = next(r for r in BUILTINS if r.id == "large-change").model_dump()assert client.post("/api/compare/analyzers/check/plan", json={**body, "recipe": builtin}).status_code == 422+def test_sixty_pins_share_their_tile_and_keep_all_results_when_saved(client, offline):+ built = recipe(LOSS, GREEN_BEFORE)+ marks = [{"point": pixel_point(155 + i % 10, 155 + i // 10), "expect": "found"} for i in range(30)]+ marks += [{"point": pixel_point(300 + i % 10, 300 + i // 10), "expect": "empty"} for i in range(30)]+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)+ body = {"recipe": built.model_dump(), "check": check_body(marks)}+ assert client.post("/api/compare/analyzers/check/plan", json=body).json() == {"tiles": 1, "missing": 0}+ tested = client.post("/api/compare/analyzers/check", json={**body, "detail": True})+ assert tested.status_code == 200, tested.text+ answer = tested.json()+ assert answer["covered"] == [True] * 30 + [False] * 30+ assert len(answer["readings"]) == 60+ assert all(len(row["covered"]) == 60 for row in answer["without"])+ result = {"signature": "abc", "count": answer["count"], "covered": answer["covered"]}+ saved = client.post("/api/compare/analyzers", json={**body["recipe"], "checks": [check_body(marks, result=result)]})+ assert saved.status_code == 200, saved.text+ loaded = next(row for row in client.get("/api/compare/analyzers").json()["custom"] if row["id"] == saved.json()["id"])+ assert loaded["checks"][0]["marks"] == marks+ assert loaded["checks"][0]["result"] == result+ overflow = {**body, "check": check_body(marks + [marks[0]])}+ assert client.post("/api/compare/analyzers/check/plan", json=overflow).status_code == 422+ with pytest.raises(ValidationError):+ Check.model_validate(check_body(marks, result={**result, "covered": [True] * 61}))+++def test_a_check_can_plan_and_test_twenty_cached_tiles(client, offline):+ built = recipe(LOSS)+ z, x, y = SENTINEL_TILE+ tiles = [(z, x + 2 * i, y) for i in range(20)]+ before, after = cleared()+ for tile in tiles:+ seed_frames(sweep_body(built, maxcc=100), before, after, tile=tile, pictures=False)+ marks = [{"point": pixel_point(165, 165, tile), "expect": "found"} for tile in tiles]+ body = {"recipe": built.model_dump(), "check": check_body(marks)}+ assert client.post("/api/compare/analyzers/check/plan", json=body).json() == {"tiles": 20, "missing": 0}+ tested = client.post("/api/compare/analyzers/check", json={**body, "detail": True})+ assert tested.status_code == 200, tested.text+ answer = tested.json()+ assert answer["ready"] and answer["count"] == 20+ assert answer["covered"] == [True] * 20+ assert len(answer["tiles"]) == len(answer["readings"]) == 20+++def test_a_twenty_first_tile_is_refused_before_fetching_with_an_actionable_error(client, offline, monkeypatch):+ asked = []+ monkeypatch.setattr(detect_rules, "fetch", lambda frames: asked.extend(frames))+ z, x, y = SENTINEL_TILE+ marks = [{"point": pixel_point(256, 256, (z, x + 2 * i, y)), "expect": "found"} for i in range(21)]+ body = {"recipe": recipe(LOSS).model_dump(), "check": check_body(marks)}+ for endpoint, options in (("/check/plan", {}), ("/check", {"read": True})):+ refused = client.post(f"/api/compare/analyzers{endpoint}", json={**body, **options})+ assert refused.status_code == 422+ assert refused.json()["detail"] == (+ "these pins reach 21 tiles and a check reads at most 20: "+ "keep the pins of one place in a check and start another for ground further away"+ )+ assert asked == []++def test_a_check_reads_the_cache_then_what_it_lacks_and_says_what_came_out_on_each_mark(client, offline, monkeypatch):built = recipe(LOSS, GREEN_BEFORE)marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]@@ -897,3 +958,90 @@ def test_an_example_copied_into_the_library_keeps_its_checks_and_the_backup_carrassert listed[0]["checks"][0]["name"] == example["recipe"]["checks"][0]["name"]exported = client.get("/api/settings/export").json()assert example["recipe"]["checks"][0]["name"] in str(exported)+++# -- a rule's reading, for moving its line without asking again ------------------------+++def decode_values(answer, at=0):+ """One tile's reading back out of the PNG, as the browser reads it."""+ tile = answer["tiles"][at]+ raw = np.frombuffer(base64.b64decode(tile["values"]), np.uint8)+ bgr = cv2.imdecode(raw, cv2.IMREAD_COLOR)+ steps = bgr[..., 2].astype(np.float64) * 256 + bgr[..., 1].astype(np.float64)+ return answer["low"] + steps / answer["steps"] * (answer["high"] - answer["low"])+++def test_a_rule_sends_its_reading_so_its_line_can_move_without_another_test(client, offline):+ built = recipe(LOSS, GREEN_BEFORE)+ marks = [{"point": PLOT, "expect": "found"}, {"point": STANDING, "expect": "empty"}]+ body = {"recipe": built.model_dump(), "check": check_body(marks)}+ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)++ answer = client.post("/api/compare/analyzers/check/values", json={**body, "rule": 0})+ assert answer.status_code == 200, answer.text+ got = answer.json()+ assert got["ready"] is True and got["rule"] == 0 and got["size"] == 512+ assert len(got["tiles"]) == 1++ # the reading is the one the probe gives at the same pixel, to the step+ probed = client.post("/api/compare/analyzers/probe", json={**body, "point": PLOT}).json()+ values = decode_values(got)+ assert values[165, 165] == pytest.approx(probed["rules"][0]["value"], abs=1e-3)+ standing = client.post("/api/compare/analyzers/probe", json={**body, "point": STANDING}).json()+ assert values[400, 400] == pytest.approx(standing["rules"][0]["value"], abs=1e-3)+++def test_the_browser_can_redraw_a_rule_from_it_exactly_as_a_test_would(client, offline):+ """The point of the whole thing: the same comparison on the same numbers.++ If this drifts, the ground painted while the slider moves is not the ground+ the next test keeps, and the line gets set against a picture that lies.+ """+ built = recipe(LOSS, GREEN_BEFORE)+ body = {"recipe": built.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}])}+ # Two clearings, not one: a plot taken to bare soil, and a patch only half+ # cleared. Without the second, every line between them keeps the same ground+ # and the test would pass on a picture that never moved.+ before, after = cleared()+ after = paint(after, 300, 300, 24, 24, B04=0.08, B08=0.30)+ seed_frames(sweep_body(built, maxcc=100), before, after, pictures=False)++ def rule_mask(at_line):+ """What a test says rule 0 keeps with its line set there."""+ moved = {**body, "recipe": recipe({**LOSS, "value": at_line}, GREEN_BEFORE).model_dump()}+ answer = client.post("/api/compare/analyzers/check", json={**moved, "detail": True}).json()+ mask = cv2.imdecode(np.frombuffer(base64.b64decode(answer["tiles"][0]["mask"]), np.uint8),+ cv2.IMREAD_UNCHANGED)+ return (mask & 1) > 0, (mask & (1 << detect_rules.MEASURED_BIT)) > 0++ _, seen = rule_mask(LOSS["value"])+ values = decode_values(client.post("/api/compare/analyzers/check/values",+ json={**body, "rule": 0}).json())++ # Rule 0 is `ndvi dropped by so much`: op "le" against a negative line. Three+ # lines, each keeping different ground: the cleared plot alone, both patches,+ # and nothing at all.+ for line in (-0.2, -0.5, -0.75):+ redrawn = seen & (values <= line)+ kept, _ = rule_mask(line)+ assert (redrawn == kept).all(), f"the slider and the engine disagree at {line}"+ assert (seen & (values <= -0.2)).sum() > (seen & (values <= -0.5)).sum() > 0+ assert (seen & (values <= -0.75)).sum() == 0+++def test_a_reading_is_never_fetched_and_a_ground_class_has_no_line(client, offline):+ built = recipe(LOSS)+ body = {"recipe": built.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}])}+ # nothing cached: it says so rather than reaching for Copernicus+ waiting = client.post("/api/compare/analyzers/check/values", json={**body, "rule": 0}).json()+ assert waiting == {"ready": False, "missing": 2}++ seed_frames(sweep_body(built, maxcc=100), *cleared(), pictures=False)+ classes = recipe({"measure": "class", "classes": ["water"], "on": "b", "op": "is"})+ refused = client.post("/api/compare/analyzers/check/values",+ json={"recipe": classes.model_dump(), "check": check_body([{"point": PLOT, "expect": "found"}]),+ "rule": 0})+ assert refused.status_code == 422 and "classification" in refused.json()["detail"]+ # and a rule that is not there at all+ assert client.post("/api/compare/analyzers/check/values", json={**body, "rule": 3}).status_code == 422diff --git a/tests/test_figures.py b/tests/test_figures.pynew file mode 100644index 0000000..0259ba4--- /dev/null+++ b/tests/test_figures.py@@ -0,0 +1,217 @@+"""Figures: one place, one day, several renderings, laid out for publication.++The figure an analyst publishes is the same ground three or four times — true+colour for what a reader recognises, a short-wave composite for the heat, an+index for the measurement — each captioned, with one line saying where and+when. What these tests hold is what makes that evidence rather than a picture:+every panel is a real capture with its own provenance, every panel is the *same*+acquisition, and the figure opens as a composition that can still be annotated.+"""++from __future__ import annotations++from pathlib import Path++from PIL import Image++from azimut import config+from azimut.engine import figures, tiles+++def _fake_tile(client, url): # offline: every tile is a solid square+ return Image.new("RGB", (256, 256), (10, 120, 10))+++def keyed(client) -> str:+ config.update_settings(lambda settings: settings.update(api_keys={"sentinelhub": "inst-uuid"}))+ return client.post("/api/cases", json={"name": "Figure"}).json()["id"]+++def build(client, cid, **over):+ body = {+ "title": "Fujairah plume",+ "lat": 26.383333,+ "lon": 56.438333,+ "zoom": 14,+ "width": 512,+ "height": 512,+ "day": "2026-10-04",+ "panels": [+ {"layer": "TRUE_COLOR", "caption": "Visible plume (RGB)"},+ {"layer": "SWIR", "caption": "SWIR hotspot (B12-B11-B04)"},+ ],+ **over,+ }+ return client.post(f"/api/cases/{cid}/satellite/figure", json=body)+++# -- the layout, on its own ----------------------------------------------------+++def test_captions_are_numbered_so_the_text_can_refer_to_panel_two():+ assert figures.caption_for("SWIR hotspot", 1, 4) == "2. SWIR hotspot"+ # one panel is not a numbered figure, it is a picture+ assert figures.caption_for("SWIR hotspot", 0, 1) == "SWIR hotspot"+ assert figures.caption_for("SWIR hotspot", 0, 4, numbered=False) == "SWIR hotspot"+ # a panel with no caption still carries its number+ assert figures.caption_for("", 2, 4) == "3."+++def test_the_footer_says_when_where_and_from_what():+ line = figures.footer_line("2026-10-04", "26.383333, 56.438333")+ assert "Date: 2026-10-04" in line+ assert "Coordinates: 26.383333, 56.438333" in line+ assert "Copernicus Sentinel-2 L2A" in line+++def test_the_footer_states_only_what_it_knows():+ # an undated figure says nothing about a date rather than printing a blank+ assert "Date" not in figures.footer_line("", "1, 2")+ assert figures.footer_line("", "", "") == ""+++def test_panels_fill_rows_across_the_chosen_width():+ entries = [+ {"src": f"media/{n}.png", "label": f"L{n}", "natural": (512, 512), "lat": 1.0, "lon": 2.0}+ for n in range(4)+ ]+ rows = [panel["row"] for panel in figures.spec(entries, per_row=2)["panels"]]+ assert rows == [0, 0, 1, 1]+ assert [panel["row"] for panel in figures.spec(entries, per_row=1)["panels"]] == [0, 1, 2, 3]+ # a nonsense count is clamped rather than allowed to divide by zero+ assert [panel["row"] for panel in figures.spec(entries, per_row=0)["panels"]] == [0, 1, 2, 3]+++def test_the_spec_leaves_the_look_to_the_composer():+ entries = [{"src": "media/a.png", "label": "A", "natural": (8, 8), "lat": 1.0, "lon": 2.0}]+ built = figures.spec(entries, footer="x")+ # everything the composer fills from its own defaults stays absent+ assert set(built) == {+ "azimut_proof", "panels", "pastes", "shapes", "notes",+ "legendOrder", "material", "sources", "footer",+ }+ assert built["shapes"] == [] # so the analyst's arrows are the only ones+++# -- the route -----------------------------------------------------------------+++def test_a_figure_files_every_panel_as_a_dated_capture(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)++ built = build(client, cid)+ assert built.status_code == 200+ body = built.json()+ assert [panel["caption"] for panel in body["panels"]] == [+ "Visible plume (RGB)",+ "SWIR hotspot (B12-B11-B04)",+ ]++ captures = client.get(f"/api/cases/{cid}/satellite").json()+ assert len(captures) == 2+ for capture in captures:+ # each panel answers for itself: which layer, which pass, which point+ assert capture["provider"].startswith("sentinel2~")+ assert capture["zoom"] == 14+ layers = sorted(capture["provider"] for capture in captures)+ assert layers[0].startswith("sentinel2~SWIR~2026-10-04~2026-10-04")+ assert layers[1].startswith("sentinel2~TRUE_COLOR~2026-10-04~2026-10-04")+++def test_the_figure_opens_as_a_composition_with_its_credit_line_written(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)+ name = build(client, cid).json()["proof"]["name"]++ spec = client.get(f"/api/cases/{cid}/proofs/{name}").json()+ assert [panel["caption"] for panel in spec["panels"]] == [+ "1. Visible plume (RGB)",+ "2. SWIR hotspot (B12-B11-B04)",+ ]+ assert spec["panels"][0]["row"] == 0 and spec["panels"][1]["row"] == 0+ assert "Date: 2026-10-04" in spec["footer"]+ assert "26.383333, 56.438333" in spec["footer"]+ # the point rides on each panel, so the composer can offer the coordinates+ assert spec["panels"][0]["meta"]["lat"] == 26.383333+ # and nothing is drawn on it yet+ assert spec["shapes"] == []+++def test_every_panel_is_the_same_acquisition(client, monkeypatch):+ """A figure is one pass seen several ways. Panels of different dates would+ compare two things at once, which is what Compare is for."""+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)+ build(client, cid)+ dates = {+ capture["provider"].split("~")[2]+ for capture in client.get(f"/api/cases/{cid}/satellite").json()+ }+ assert dates == {"2026-10-04"}+++def test_a_figure_holds_each_layer_once(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)+ twice = build(+ client, cid,+ panels=[{"layer": "SWIR", "caption": "one"}, {"layer": "SWIR", "caption": "again"}],+ )+ assert twice.status_code == 422+ assert "each layer once" in twice.json()["detail"]+++def test_a_panel_captioned_by_nothing_reads_as_its_layer(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)+ name = build(client, cid, panels=[{"layer": "SWIR"}]).json()["proof"]["name"]+ spec = client.get(f"/api/cases/{cid}/proofs/{name}").json()+ # one panel is not numbered, and the layer id is better than an empty bar+ assert spec["panels"][0]["caption"] == "SWIR"+++def test_a_layer_written_here_can_be_a_panel(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = keyed(client)+ client.put(+ "/api/satellite/sentinel/custom-layers",+ json={"id": "PLUME_SWIR", "base": "TRUE_COLOR", "script": "//VERSION=3\\nx\\n"},+ )+ built = build(+ client, cid,+ panels=[{"layer": "PLUME_SWIR", "caption": "My plume"}],+ )+ assert built.status_code == 200+ capture = client.get(f"/api/cases/{cid}/satellite").json()[0]+ # the capture is filed under the name the analyst chose, not its base+ assert capture["provider"].startswith("sentinel2~PLUME_SWIR~")+++def test_an_undated_figure_is_refused_at_the_edge(client):+ cid = keyed(client)+ assert build(client, cid, day="").status_code == 422+ assert build(client, cid, day="most recent").status_code == 422+++def test_a_figure_needs_a_panel_and_stops_at_eight(client):+ cid = keyed(client)+ assert build(client, cid, panels=[]).status_code == 422+ too_many = [{"layer": f"L{n}"} for n in range(figures.MAX_PANELS + 1)]+ assert build(client, cid, panels=too_many).status_code == 422+++def test_a_layer_the_app_cannot_render_is_named_in_the_refusal(client, monkeypatch):+ monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)+ cid = client.post("/api/cases", json={"name": "No key"}).json()["id"]+ # no Copernicus key, so sentinel2 is not a provider this app can serve+ refused = build(client, cid)+ assert refused.status_code == 404+++def test_the_browser_holds_the_same_caps_as_the_engine():+ """The dialog stops a figure the route would refuse, so its numbers are+ this module's. They are written out twice, and must not drift."""+ source = Path("frontend/src/lib/figures.js").read_text(encoding="utf-8")+ assert f"MAX_PANELS = {figures.MAX_PANELS};" in source+ assert f"DEFAULT_PER_ROW = {figures.DEFAULT_PER_ROW};" in sourcediff --git a/tests/test_sentinel.py b/tests/test_sentinel.pyindex c99cfb1..982d724 100644--- a/tests/test_sentinel.py+++ b/tests/test_sentinel.py@@ -27,12 +27,20 @@ def _response(url, payload=None, text=None, status=200):def test_wmts_url_omits_time_by_default():url = sentinel.wmts_url()assert "LAYER=TRUE_COLOR" in url- # no TIME = the layer's own default window (most recent), which is the- # honest answer to "just show me it"+ # No TIME is the undated fallback, not "most recent": Sentinel Hub applies+ # the mosaicking order per pixel over the whole archive, so a swath edge in+ # the newest scene comes back filled from an older one. Callers send a day.assert "TIME=" not in urlassert "{key}" in url and "{z}" in url and "{x}" in url and "{y}" in url+def test_wmts_url_dates_one_acquisition_when_both_ends_are_the_same_day():+ # the shape every caller asks for: one pass, which can be pointed at and+ # dated, with holes where that pass has no pixels+ url = sentinel.wmts_url("TRUE_COLOR", "2026-05-11", "2026-05-11")+ assert "TIME=2026-05-11/2026-05-11" in url++def test_wmts_url_carries_the_layer_and_the_window():url = sentinel.wmts_url("SWIR", "2026-05-01", "2026-05-31")assert "LAYER=SWIR" in url@@ -131,7 +139,9 @@ def test_parse_variant_refuses_an_impossible_ceiling(spec):def test_variant_label_reads_like_a_human_wrote_it():- assert sentinel.variant_label("SWIR", None, None).endswith("most recent")+ # no window sends no TIME, which blends the archive per pixel rather than+ # rendering the newest pass — the label must not promise a date+ assert sentinel.variant_label("SWIR", None, None).endswith("undated mosaic")assert "2026-05-01 → 2026-05-31" in sentinel.variant_label("SWIR", "2026-05-01", "2026-05-31")# a single-day window is a day, not a range from a day to itselfassert sentinel.variant_label("SWIR", "2026-05-01", "2026-05-01").endswith("2026-05-01")@@ -731,3 +741,18 @@ def test_band_frame_refuses_a_product_it_has_no_evalscript_for():*(f"index-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),*(f"change-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),}+++def test_radar_label_names_a_pass_and_says_so_when_there_is_none():+ assert sentinel.radar_label("2026-05-14", "05:42:10") == "2026-05-14 05:42 UTC"+ assert sentinel.radar_label("2026-05-14", "") == "2026-05-14"+ # same defect as the optical label: without a day the tiles blend every pass+ # over the point, which mixes looks from opposite sides of the track+ assert sentinel.radar_label("", "") == "undated mosaic"+++def test_radar_wmts_url_sends_no_time_only_when_it_has_no_pass():+ dated = sentinel.radar_wmts_url("S1_VV", "2026-05-14", "05:42:10")+ assert "TIME=" in dated+ assert "EVALSCRIPT=" in dated+ assert "TIME=" not in sentinel.radar_wmts_url("S1_VV")diff --git a/tests/test_sentinel_custom_layers.py b/tests/test_sentinel_custom_layers.pynew file mode 100644index 0000000..50b7e54--- /dev/null+++ b/tests/test_sentinel_custom_layers.py@@ -0,0 +1,487 @@+"""Copernicus layers written in Azimut rather than in the Copernicus dashboard.++A layer is a name the whole app already knows how to carry — a variant id, a+URL path segment, a tile-cache directory, a line of provenance. What is new is+where the *rendering* comes from: an evalscript saved here, sent with a base+layer that supplies the data collection. So these tests are about the seam:+that the name survives everything downstream, that the request asks the+instance for a layer it actually serves, and that one list reaches every tab.+"""++from __future__ import annotations++import base64+import re+from pathlib import Path+from urllib.parse import parse_qs, urlparse++import pytest++from azimut import config+from azimut.api import satellite as api+from azimut.engine import sentinel, tiles++PLUME = {+ "id": "PLUME_SWIR",+ "label": "SWIR plume",+ "base": "TRUE_COLOR",+ "script": "//VERSION=3\nfunction setup(){}\n",+ "hint": "B12/B11/B04 for hot spots",+}+++def script_of(url: str) -> str:+ """The evalscript a request carries, back as its source."""+ value = parse_qs(urlparse(url).query)["EVALSCRIPT"][0]+ return base64.b64decode(value).decode("utf-8")+++# -- the shape of one ----------------------------------------------------------+++def test_a_custom_layer_is_named_like_any_other_layer():+ entry = sentinel.parse_custom_layer(PLUME)+ assert entry["id"] == "PLUME_SWIR"+ assert entry["base"] == "TRUE_COLOR"+ # the name has to survive being a variant id and a directory name+ assert sentinel.parse_variant(f"{entry['id']}~2026-05-11~2026-05-11~CC20")[0] == "PLUME_SWIR"+++ "bad",+ [+ {"id": "plume", "script": "x"}, # lower case would not parse as a variant+ {"id": "PLUME SWIR", "script": "x"}, # a space in a path segment+ {"id": "PLUME~SWIR", "script": "x"}, # the variant separator itself+ {"id": "../ESCAPE", "script": "x"}, # traversal, as a directory name+ {"id": "P" * 41, "script": "x"},+ {"id": "PLUME", "script": " "}, # a layer that renders nothing+ {"id": "PLUME", "script": "x", "base": "true_color"},+ "not an object",+ ],+)+def test_a_malformed_custom_layer_is_refused(bad):+ with pytest.raises(ValueError):+ sentinel.parse_custom_layer(bad)+++def test_a_script_is_bounded_so_the_request_stays_sendable():+ too_long = {"id": "BIG", "script": "x" * (sentinel.CUSTOM_SCRIPT_MAX + 1)}+ with pytest.raises(ValueError):+ sentinel.parse_custom_layer(too_long)+ fits = {"id": "BIG", "script": "x" * sentinel.CUSTOM_SCRIPT_MAX}+ assert sentinel.parse_custom_layer(fits)["id"] == "BIG"+++def test_a_layer_with_no_label_reads_as_its_name():+ assert sentinel.parse_custom_layer({"id": "NDWI_MINE", "script": "x"})["label"] == "NDWI_MINE"+++# -- the list ------------------------------------------------------------------+++def test_the_list_skips_what_it_cannot_read_rather_than_breaking():+ settings = {"sentinel_layers": [PLUME, {"id": "nope"}, {"script": "x"}, 7]}+ assert [entry["id"] for entry in sentinel.custom_layers(settings)] == ["PLUME_SWIR"]+++def test_a_name_means_one_layer():+ settings = {"sentinel_layers": [PLUME, {**PLUME, "script": "//VERSION=3\nother\n"}]}+ found = sentinel.custom_layers(settings)+ assert len(found) == 1+ assert found[0]["script"] == PLUME["script"]+++def test_no_layers_is_not_an_error():+ assert sentinel.custom_layers({}) == []+ assert sentinel.custom_layers({"sentinel_layers": None}) == []+++# -- how a name becomes a request ----------------------------------------------+++def test_a_configured_layer_answers_for_itself():+ assert sentinel.resolve_layer("SWIR", []) == ("SWIR", "")+++def test_a_layer_written_here_is_asked_for_through_its_base():+ customs = sentinel.custom_layers({"sentinel_layers": [PLUME]})+ asked, script = sentinel.resolve_layer("PLUME_SWIR", customs)+ # the instance has never heard of PLUME_SWIR; it knows TRUE_COLOR+ assert asked == "TRUE_COLOR"+ assert script == PLUME["script"]+++def test_a_name_written_here_wins_over_a_configured_one():+ # otherwise a layer later added to the configuration under the same name+ # would quietly change what everything already filed under it renders+ customs = sentinel.custom_layers({"sentinel_layers": [{**PLUME, "id": "TRUE_COLOR"}]})+ asked, script = sentinel.resolve_layer("TRUE_COLOR", customs)+ assert (asked, script) == ("TRUE_COLOR", PLUME["script"])+++def test_the_url_carries_the_script_as_base64_beside_the_window():+ url = sentinel.wmts_url("TRUE_COLOR", "2026-05-11", "2026-05-11", script=PLUME["script"])+ assert "LAYER=TRUE_COLOR" in url+ assert "TIME=2026-05-11/2026-05-11" in url+ assert script_of(url) == PLUME["script"]+++def test_a_script_with_an_accent_in_a_comment_still_sends():+ # the radar script is ASCII, a person's notes are not+ script = "//VERSION=3\n// zone brûlée\n"+ assert script_of(sentinel.wmts_url("TRUE_COLOR", script=script)) == script+++def test_no_script_sends_no_evalscript():+ assert "EVALSCRIPT=" not in sentinel.wmts_url("TRUE_COLOR", "2026-05-11", "2026-05-11")+++# -- the seam with everything downstream ---------------------------------------+++def test_the_variant_keeps_the_name_and_renders_the_script(client):+ config.update_settings(+ lambda settings: settings.update(+ api_keys={"sentinelhub": "inst-uuid"}, sentinel_layers=[PLUME]+ )+ )+ provider = tiles.get_provider("sentinel2~PLUME_SWIR~2026-05-11~2026-05-11")+ # the id is what the analyst asked for, so the cache and provenance key on it+ assert provider.id == "sentinel2~PLUME_SWIR~2026-05-11~2026-05-11"+ # the request is what the instance can answer+ assert "LAYER=TRUE_COLOR" in provider.url+ assert script_of(provider.url) == PLUME["script"]+ assert "TIME=2026-05-11/2026-05-11" in provider.url+++def test_two_custom_layers_cache_apart(client):+ config.update_settings(+ lambda settings: settings.update(+ api_keys={"sentinelhub": "inst-uuid"},+ sentinel_layers=[PLUME, {**PLUME, "id": "PLUME_NBR", "script": "//VERSION=3\nnbr\n"}],+ )+ )+ one = tiles.get_provider("sentinel2~PLUME_SWIR~2026-05-11~2026-05-11")+ other = tiles.get_provider("sentinel2~PLUME_NBR~2026-05-11~2026-05-11")+ assert one.id != other.id # the disk cache keys on the id+ assert script_of(one.url) != script_of(other.url)+++# -- one list, every tab -------------------------------------------------------+++def test_every_tab_is_offered_them_without_a_request(client):+ """Satellite, both Compare sides, Detect and the analyzer builder all read+ this one route, so a layer written here reaches them by existing."""+ config.update_settings(lambda settings: settings.update(sentinel_layers=[PLUME]))+ body = client.get("/api/satellite/sentinel/layers").json()+ assert body["source"] == "catalogue" # nothing phoned out+ mine = [entry for entry in body["layers"] if entry.get("custom")]+ assert [entry["id"] for entry in mine] == ["PLUME_SWIR"]+ assert mine[0]["label"] == "SWIR plume"+ assert mine[0]["hint"] == "B12/B11/B04 for hot spots"+ # and the standard layer is still the first entry every picker falls back to+ assert body["layers"][0]["id"] == sentinel.DEFAULT_LAYER+++def test_a_layer_written_here_replaces_the_configured_row_of_that_name(client):+ config.update_settings(+ lambda settings: settings.update(sentinel_layers=[{**PLUME, "id": "TRUE_COLOR"}])+ )+ layers = client.get("/api/satellite/sentinel/layers").json()["layers"]+ rows = [entry for entry in layers if entry["id"] == "TRUE_COLOR"]+ assert len(rows) == 1 # one name, one row+ assert rows[0]["custom"] is True+++def test_the_list_is_empty_until_something_is_written(client):+ layers = client.get("/api/satellite/sentinel/layers").json()["layers"]+ assert not [entry for entry in layers if entry.get("custom")]+++# -- keeping them --------------------------------------------------------------+++def test_saving_reading_and_forgetting_one(client):+ saved = client.put("/api/satellite/sentinel/custom-layers", json=PLUME)+ assert saved.status_code == 200+ assert saved.json()["id"] == "PLUME_SWIR"++ listed = client.get("/api/satellite/sentinel/custom-layers").json()+ assert listed["layers"][0]["script"] == PLUME["script"]+ assert listed["max_script"] == sentinel.CUSTOM_SCRIPT_MAX++ assert client.delete("/api/satellite/sentinel/custom-layers/PLUME_SWIR").json() == {+ "deleted": True+ }+ assert client.get("/api/satellite/sentinel/custom-layers").json()["layers"] == []+++def test_saving_over_a_name_replaces_that_layer(client):+ client.put("/api/satellite/sentinel/custom-layers", json=PLUME)+ client.put(+ "/api/satellite/sentinel/custom-layers",+ json={**PLUME, "script": "//VERSION=3\nsecond\n"},+ )+ layers = client.get("/api/satellite/sentinel/custom-layers").json()["layers"]+ assert len(layers) == 1+ assert layers[0]["script"] == "//VERSION=3\nsecond\n"+++ "body",+ [+ {"id": "plume", "script": "x"},+ {"id": "PLUME", "script": ""},+ {"id": "PLUME"},+ {"id": "PLUME", "script": "x", "nonsense": 1},+ ],+)+def test_the_editor_cannot_save_a_layer_the_app_could_not_render(client, body):+ assert client.put("/api/satellite/sentinel/custom-layers", json=body).status_code == 422+++def test_forgetting_a_layer_that_is_not_there_is_not_an_error(client):+ assert client.delete("/api/satellite/sentinel/custom-layers/NOPE").status_code == 200+++def test_the_library_has_a_ceiling(client):+ from azimut.api import satellite as api++ for index in range(api.MAX_CUSTOM_LAYERS):+ kept = client.put(+ "/api/satellite/sentinel/custom-layers", json={**PLUME, "id": f"L{index}"}+ )+ assert kept.status_code == 200+ full = client.put("/api/satellite/sentinel/custom-layers", json={**PLUME, "id": "ONE_MORE"})+ assert full.status_code == 409+ # a name already kept is still savable: it replaces, it does not grow the list+ assert client.put(+ "/api/satellite/sentinel/custom-layers", json={**PLUME, "id": "L0"}+ ).status_code == 200+++def test_a_backup_carries_them(client):+ client.put("/api/satellite/sentinel/custom-layers", json=PLUME)+ blob = client.get("/api/settings/export").json()+ assert blob["settings"]["sentinel_layers"][0]["script"] == PLUME["script"]++ client.delete("/api/satellite/sentinel/custom-layers/PLUME_SWIR")+ assert client.get("/api/satellite/sentinel/custom-layers").json()["layers"] == []++ restored = client.post("/api/settings/import", json=blob)+ assert restored.status_code == 200+ back = client.get("/api/satellite/sentinel/custom-layers").json()["layers"]+ assert back[0]["id"] == "PLUME_SWIR"+ assert back[0]["script"] == PLUME["script"]+++# -- a layer being written -----------------------------------------------------+++def test_a_draft_renders_before_it_is_saved(client):+ config.update_settings(lambda settings: settings.update(api_keys={"sentinelhub": "inst-uuid"}))+ draft = client.put(+ "/api/satellite/sentinel/draft-layer",+ json={"base": "TRUE_COLOR", "script": "//VERSION=3\nfirst\n"},+ ).json()+ assert draft["id"].startswith(sentinel.DRAFT_PREFIX)++ provider = tiles.get_provider(f"sentinel2~{draft['id']}~2026-05-11~2026-05-11")+ assert "LAYER=TRUE_COLOR" in provider.url+ assert script_of(provider.url) == "//VERSION=3\nfirst\n"+++def test_a_changed_draft_renders_under_a_new_name(client):+ """The name is the disk cache's key, so two attempts must not share one."""+ first = client.put(+ "/api/satellite/sentinel/draft-layer", json={"script": "//VERSION=3\nfirst\n"}+ ).json()["id"]+ second = client.put(+ "/api/satellite/sentinel/draft-layer", json={"script": "//VERSION=3\nsecond\n"}+ ).json()["id"]+ assert first != second+ # and only one draft is kept, not a pile of them+ assert config.load_settings()["sentinel_draft_layer"]["id"] == second+++def test_the_same_draft_twice_is_the_same_name(client):+ body = {"script": "//VERSION=3\nsame\n"}+ first = client.put("/api/satellite/sentinel/draft-layer", json=body).json()["id"]+ second = client.put("/api/satellite/sentinel/draft-layer", json=body).json()["id"]+ assert first == second+++def test_a_draft_is_never_offered_as_a_layer(client):+ client.put("/api/satellite/sentinel/draft-layer", json={"script": "//VERSION=3\nx\n"})+ layers = client.get("/api/satellite/sentinel/layers").json()["layers"]+ assert not [entry for entry in layers if sentinel.is_draft_layer(entry["id"])]+ # nor among the layers the editor manages+ kept = client.get("/api/satellite/sentinel/custom-layers").json()["layers"]+ assert kept == []+++def test_closing_the_editor_forgets_the_draft(client):+ client.put("/api/satellite/sentinel/draft-layer", json={"script": "//VERSION=3\nx\n"})+ assert client.delete("/api/satellite/sentinel/draft-layer").json() == {"cleared": True}+ assert config.load_settings()["sentinel_draft_layer"] is None+++def test_a_draft_does_not_travel_in_a_backup(client):+ client.put("/api/satellite/sentinel/draft-layer", json={"script": "//VERSION=3\nx\n"})+ client.put("/api/satellite/sentinel/custom-layers", json=PLUME)+ blob = client.get("/api/settings/export").json()+ # the saved layer travels; this machine's scratch work does not+ assert blob["settings"]["sentinel_layers"][0]["id"] == "PLUME_SWIR"+ assert "sentinel_draft_layer" not in blob["settings"]+++def test_the_editor_is_told_which_layer_is_the_radar_one(client):+ """A script reading Sentinel-2 bands through the radar layer renders+ nothing, so the editor has to be able to keep it off the list."""+ body = client.get("/api/satellite/sentinel/custom-layers").json()+ assert body["radar_layer"] == ""+ assert "B12" in body["bands"] and "B10" not in body["bands"]++ config.update_settings(lambda settings: settings.update(sentinel1_layer="RADAR"))+ assert client.get("/api/satellite/sentinel/custom-layers").json()["radar_layer"] == "RADAR"+++def test_the_route_takes_exactly_the_body_the_editor_sends(client):+ """The editor's draft holds more than a layer, and this route forbids what+ it does not know. The two lists are written out separately, so they are+ checked against each other rather than trusted."""+ source = Path("frontend/src/lib/customLayers.js").read_text(encoding="utf-8")+ sent = re.search(r"export function layerPayload\(form, script\) \{\s*return \{(.+?)\};",+ source, re.S).group(1)+ # `key: value` and the shorthand `key,` are both a key being sent+ keys = set(re.findall(r"^\s*(\w+)\s*[:,]", sent, re.M))+ assert keys == set(api.CustomLayerIn.model_fields)++ # and that body really is accepted, memo and all+ kept = client.put(+ "/api/satellite/sentinel/custom-layers",+ json={**{key: "" for key in keys if key not in ("form",)},+ "id": "PLUME_SWIR", "base": "TRUE_COLOR", "script": "//VERSION=3\n",+ "form": {"way": "index", "high": "B12", "low": "B11",+ "ramp": "heat", "threshold": 0.15}},+ )+ assert kept.status_code == 200+ assert kept.json()["form"] == {+ "way": "index", "high": "B12", "low": "B11", "ramp": "heat", "threshold": 0.15,+ }+++# -- what a form wrote ---------------------------------------------------------+++def test_a_layer_remembers_the_form_that_wrote_it(client):+ client.put(+ "/api/satellite/sentinel/custom-layers",+ json={"id": "PLUME", "base": "TRUE_COLOR", "script": "//VERSION=3\n",+ "form": {"way": "composite", "red": "B12", "green": "B11",+ "blue": "B04", "gain": 2.5}},+ )+ kept = client.get("/api/satellite/sentinel/custom-layers").json()["layers"][0]+ # without this, every saved layer reopens as JavaScript — the ones nobody typed too+ assert kept["form"]["way"] == "composite"+ assert kept["form"]["red"] == "B12"+++def test_a_script_somebody_typed_remembers_nothing(client):+ client.put(+ "/api/satellite/sentinel/custom-layers",+ json={"id": "BYHAND", "base": "TRUE_COLOR", "script": "//VERSION=3\n"},+ )+ kept = client.get("/api/satellite/sentinel/custom-layers").json()["layers"][0]+ assert "form" not in kept+++ "memo",+ [+ {"way": "nonsense", "high": "B08", "low": "B04"},+ {"way": "index", "high": "B99", "low": "B04"}, # not a band+ {"way": "index", "high": "B08"}, # half an index+ {"way": "index", "high": "B08", "low": "B04", "threshold": 4}, # off the scale+ {"way": "index", "high": "B08", "low": "B04", "ramp": "../escape"},+ {"way": "composite", "red": "B12", "green": "B11"}, # two of three channels+ {"way": "composite", "red": "B12", "green": "B11", "blue": "B04", "gain": 0},+ "not an object",+ None,+ ],+)+def test_a_memo_this_build_cannot_read_is_dropped_not_refused(memo):+ """The script is what renders. A layer whose memo is nonsense still works —+ it just reopens as the script, which is all anyone could say about it."""+ entry = sentinel.parse_custom_layer(+ {"id": "PLUME", "base": "TRUE_COLOR", "script": "//VERSION=3\n", "form": memo}+ )+ assert entry["script"] == "//VERSION=3\n"+ assert "form" not in entry+++def test_a_backup_carries_how_a_layer_was_written(client):+ client.put(+ "/api/satellite/sentinel/custom-layers",+ json={"id": "PLUME", "base": "TRUE_COLOR", "script": "//VERSION=3\n",+ "form": {"way": "index", "high": "B12", "low": "B11", "threshold": 0.15}},+ )+ blob = client.get("/api/settings/export").json()+ client.post("/api/settings/import", json=blob)+ back = client.get("/api/satellite/sentinel/custom-layers").json()["layers"][0]+ assert back["form"]["threshold"] == 0.15+++def test_an_index_layer_is_already_a_rule_this_engine_measures():+ """The bridge the builder offers rests on `nd` existing: a normalised+ difference of two bands is a quantity a rule reads, so the arithmetic an+ analyst settled on looking at the map does not have to be typed twice."""+ from azimut.engine.analysis_models import Rule++ rule = Rule(measure="nd", bands=("B12", "B11"), on="b", op="ge", value=0.15)+ assert set(rule.bands_read()) == {"B12", "B11"}+ # and the threshold an index layer paints with is the line a rule crosses+ assert rule.value == 0.15+++# -- in Detect -----------------------------------------------------------------+++def test_detect_reviews_a_run_on_a_layer_written_here(client):+ """A run records the layer its pictures were drawn from, and a name written+ here is a layer name like any other — so a detection can be reviewed over+ the analyst's own composite."""+ from azimut.engine.analysis_models import Source++ source = Source(provider="sentinel2", date="2026-10-04", layer="PLUME_SWIR")+ assert source.layer == "PLUME_SWIR"+ # and that is what the picture is fetched through, resolved to base + script+ config.update_settings(lambda settings: settings.update(sentinel_layers=[PLUME]))+ customs = sentinel.renderable_layers(config.load_settings())+ asked, script = sentinel.resolve_layer(source.layer, customs)+ assert (asked, script) == ("TRUE_COLOR", PLUME["script"])+++def test_a_rule_still_reads_bands_whatever_the_picture_is(client):+ """The division the whole feature rests on: a layer is the picture, a rule is+ the measurement. Changing the display must not change what is measured."""+ from azimut.engine.analysis_models import Recipe, Rule, recipe_products++ recipe = Recipe(+ id="mine", name="Mine", method="rules", phenomenon="x",+ rules=[Rule(measure="nd", bands=("B12", "B11"), on="b", op="ge", value=0.15)],+ )+ # the products are named by the rule's bands, never by the layer on screen+ assert recipe_products(recipe) == ["bands-B11-B12"]+++def test_the_display_a_frame_is_drawn_through_is_not_the_data_it_reads(client):+ """`band_frame` renders our evalscript through a layer, so a custom layer's+ base is enough: the script the analyst wrote paints nothing a rule reads."""+ config.update_settings(lambda settings: settings.update(sentinel_layers=[PLUME]))+ customs = sentinel.renderable_layers(config.load_settings())+ asked, _ = sentinel.resolve_layer("PLUME_SWIR", customs)+ # a band product asks the instance for a layer it serves, and nothing else+ assert asked == "TRUE_COLOR"diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pyindex 020af52..a5dde0f 100644--- a/tests/test_settings_backup.py+++ b/tests/test_settings_backup.py@@ -27,6 +27,8 @@ def bundle_of(client) -> dict:# the gate below is an oversight, not a policy.NOT_EXPORTED: dict[str, str] = {"export_dirs": "absolute export paths belong to the machine that selected them",+ "sentinel_draft_layer": "a layer half-written in the picker, replaced by the next "+ "preview; the saved ones travel in sentinel_layers",}