The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
Export a point's evolution as a GIF or a sheet, sign Compare exports, and let added-layer pins give their point (#88)
OsintMeThat1dbdfe5079a0
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.mdindex 0030588..6cd0cce 100644--- a/docs/RELEASE_NOTES.md+++ b/docs/RELEASE_NOTES.md@@ -8,204 +8,125 @@ maps made elsewhere on yours.## Detect-- **Detect** is a new tab under Map. Draw one or more areas on- Sentinel-2 and it sweeps them at full resolution for vessels, fires and gas- flares, construction, small spots, any surface change, burn scars, vegetation- loss or new water.-- Five radar analyzers read Sentinel-1 through cloud and at night: vessels, any- change, damaged or razed buildings, new structures and vehicles, and floods.- They use a Sentinel-1 layer you add to your Copernicus configuration, and- Settings → Imagery walks you through it.-- **New analyzer** builds your own from up to six rules on a band, an index, a- ground class or radar, and shows on the map what each rule keeps as you change it.- Checks are places you trust, pinned as "should be found" or "should stay- empty", and they turn red when a rule stops holding. Five examples ship with- their checks: Lahaina, Grünheide, Kakhovka, Dubai and Fujairah.-- Ask for a small, medium or large target instead of setting thresholds. The- areas are priced in Copernicus requests before anything is fetched.-- **Find passes** lists the dates your areas really have, with how much of them- each pass covered and how cloudy it was. A finished run says how much it read,- so "nothing found" and "never looked" stay apart.-- Candidates come strongest first, one at a time, sized along their footprint.- **Pin** files one with its own evidence crop and a claim dated by the passes- that found it; **Keep** leaves it in the run. Nothing else reaches the case.-- A candidate opens in Compare on the passes that found it.-- Areas can be saved with the case. A routine keeps an analyzer, its areas and a- date rule together, and **Run routine** repeats the sweep.+- **Detect** is a new tab under Map. Draw areas and it sweeps them on Sentinel-2+ at full resolution for vessels, fires, construction, burn scars, vegetation+ loss, new water or any change.+- Radar analyzers read Sentinel-1 through cloud and at night: vessels, damaged+ buildings, new structures, floods. Settings → Imagery shows how to add the+ Sentinel-1 layer they need.+- **New analyzer** builds your own from rules on bands, indices, ground classes+ or radar. Checks on places you trust turn red when a rule stops holding. Five+ examples ship with their checks.+- **Find passes** lists the dates your areas really have, with coverage and+ cloud. The cost in Copernicus requests shows before anything is fetched.+- Candidates come strongest first. **Pin** files one in the case with its+ evidence crop and a dated claim, or open it in Compare.+- A routine keeps an analyzer, its areas and a date rule, and **Run routine**+ repeats the sweep.- Detect needs Copernicus credentials in Settings.## Compare-- Compare opens on a Wayback release from a year ago against today's World- Imagery, with no key needed. **New** offers the other starting pairs.-- **All dates** lists every dated picture of the point and narrows down, a- question at a time, between which two a change appeared.-- Sentinel-1 radar passes are a basemap in Satellite, Compare and Detect, named- by day, UTC time and direction.-- A saved comparison stands on the map beside the captures, dated A → B, and- reopens in Compare.-- "Change assist" is now **Difference**. Its cloud switch uses the same- Sentinel-2 cloud and shadow mask as Detect instead of guessing from the- picture, so a white roof is no longer taken for a cloud.-- MNDWI and BSI join the spectral indices. An index draws its line at a stated- change, so panning no longer moves it.-- Tone matching is off by default on a Sentinel-2 pair.-- Difference is a switch beside the four views rather than a view of its own:- its highlights lie over side by side, swipe, fade or blink, on A, B or both.- They can blink.-- Right-click the ground, or a shape drawn on it, for the point menu. A drag- inside a box, an ellipse or a polygon moves the map; a shape is picked by its- outline.-- Right-click a point on the Satellite map to open Compare on its last two- Wayback pictures or its last two Copernicus passes.-- An export frame sets what an export shows. Numbered markers and blur boxes can- be stamped on the ground.-- On a turned map, boxes and ellipses are drawn along the screen, and any shape- turns from the grip above it. The export frame keeps its shape when the- camera turns, and exports upright as drawn.-- Difference's settings stay put through a read, lie over the highlights, and- close on a click outside them.+- Compare opens on Wayback a year back against today's World Imagery, with no+ key needed.+- **All dates** lists every dated picture of a point and narrows down when a+ change appeared.+- Sentinel-1 radar passes are a basemap in Satellite, Compare and Detect.+- A saved comparison stands on the map, dated A → B, and reopens in Compare.+- "Change assist" is now **Difference**, a switch over any of the four views.+ It masks clouds with Detect's Sentinel-2 mask, so a white roof no longer+ counts as one, and tone matching starts off on a Sentinel-2 pair.+- New MNDWI and BSI indices, an export frame, numbered markers and blur boxes.+- Right-click a point on the Satellite map to compare its last two Wayback+ pictures or Copernicus passes.## One camera for the maps-- Satellite, Compare and Detect show the same ground: pan one and the others are- there when you switch. A link carries it to other windows. A Detect review and- an open saved comparison keep their own view, and Settings → General turns- the sharing off.-- A middle-drag turns any map, or an Inspect frame, about the point you grabbed,- in 15° steps with Ctrl. A middle click or Shift+↑ puts north back.+- Satellite, Compare and Detect show the same ground: pan one and the others+ follow. Settings → General turns it off.+- A middle-drag turns any map or Inspect frame; a middle click puts north back.## Layers from elsewhere- Open a KML, KMZ, GeoJSON or GPX file as a map layer, or follow a public Google- My Maps or map URL. It keeps its own colours and, if you ask, its own icons,- with a legend that filters and a search that jumps to a feature. A layer lives- in the case and travels in bundles; its features never become case entities.-- Add a **GeoConfirmed** conflict over a span of days or dates, or its whole- history, optionally only the current view. Events carry GeoConfirmed's own- icons, are grouped by faction, and link to their sources and geolocation.-- Narrow a dated layer (GeoConfirmed, timestamped KML, GPX waypoints) to a period- dragged on a strip of its events or picked on a calendar.-- Added layers start switched off after a reload, so a layer heavy enough to- crash the tab cannot do it twice.-- The map panel opens on its Layers tab. Its Saved tab shows one position at a- time: Media, then Places, then Captures. Media draws the case's photos and- videos where a relation, a GPS reading or a proof places them, and plays them- beside the imagery.+ My Maps URL. It keeps its own colours and icons and travels in bundles.+- Add **GeoConfirmed** events over a span of dates, grouped by faction and+ linked to their sources.+- Narrow a dated layer to a period on a strip of its events or a calendar.+- A pin's card gives its coordinates to copy. Right-click the pin to compare its+ exact point or open its imagery history.+- The map panel's Saved tab shows Media, Places or Captures. Media places the+ case's photos and videos and plays them beside the imagery.## Proofs-- Turn or crop a panel or an overlay without touching its source. Annotations- stay on the same pixels.-- Stamp numbered markers, counted per colour, and blur boxes that hide what is- under them.-- A proof can carry one sentence, used as its notes and to write the post, and- the date its material was taken. That date shows on the Timeline and is stated- for the original footage, never for a frame cut from it.-- Place any point of a proof on a map instead of typing it. Each panel keeps its- own point.+- Turn or crop a panel or an overlay without touching its source.+- Stamp numbered markers and blur boxes.+- A proof can carry one sentence and the date its material was taken, shown on+ the Timeline.+- Place a proof's point on a map instead of typing it.## Inspect and Collage-- Inspect keeps one work per file, saved as you go, with its frames on a strip.- There are no sessions to open or save. **Save to case** is still the only step- that files a frame or an adjusted video as media.-- **Collage** is a tab of its own. It lays out frames and images from any number- of files, and the picture it exports is case media.-- The file name in Inspect's header renames the media itself.-- The first time a case opens, its 0.3.0 Inspect sessions of one file become one- work: the latest is kept, and the others' notes and names are carried into it.+- Inspect keeps one work per file, saved as you go. There are no sessions to+ open or save.+- **Collage** is a tab of its own and lays out frames from any number of files.+- The first time a case opens, its 0.3.0 Inspect sessions of one file become+ one work: the latest is kept, with the others' notes and names.## Elsewhere-- **To-do lists** on Home: named lists of tasks with a progress count, saved with- the case and carried in bundles.-- One date field across the app. Type a day, a month, a year, a time or a range,- or build it from a calendar with how sure you are. It says what it understood.-- File a claim straight from Details, a Board row or a Graph node, with that- entity already filled in.-- Send a picture to Reverse Search from a Media Library row (**Open in…**), or an- Inspect frame as cropped, saved or not.-- A claim is called a claim everywhere. Every icon button has a tooltip, a layer- that cannot be switched on says why, Home lists recent work first, and Coords &- Sky opens on the point the map is showing.-- Over another map site, the extension's points tool draws one position at a- time, like the app. Its media windows take files up to 512 MB.+- **To-do lists** on Home, saved with the case.+- One date field across the app: type a day, a month, a year or a range, or+ pick it on a calendar with how sure you are.+- File a claim straight from Details, a Board row or a Graph node.+- Send a picture to Reverse Search from the Media Library or an Inspect frame.+- Every icon button has a tooltip.## Security and privacy-- A case file opened in a tab, such as an SVG or a web page from a received- bundle, is shown without running its script.-- A web page open in your browser can no longer make Azimut fetch tiles or run- lookups on your keys: a request from another site is refused.-- A bundle no longer carries folder paths of the machine that exported it, nor- the database journal of a save in progress.-- Over another map site, the extension's panel is out of that site's reach: it- can neither read the panel nor press its buttons.-- A key a provider refuses no longer appears in the error message.-- A followed map layer received in a bundle reads its source only when you press- Refresh, and a refresh never asks an icon host again. Stored icons are checked- before they are shown.-- Home and the Guide say what the startup check asks: GitHub for a new release,- PyPI for the downloaders.+- A case file opened in a tab, such as an SVG from a received bundle, no longer+ runs its script.+- Another website can no longer make Azimut fetch tiles or run lookups on your+ keys.+- A bundle no longer carries the exporting machine's folder paths or a database+ journal.+- A map site can no longer read or press the extension's panel.+- A key a provider refuses no longer shows in the error message.## Fixes-- Changing only the case of a collage, comparison, draft or proof name renames it- on Windows and macOS, where it used to delete the collage or be refused.-- Two names that differ only by case can no longer sit side by side on Linux and- block a bundle export. When an export does refuse, it names both files.-- A layer, proof, draft or grid with "#" in its name opens and deletes itself, not- the one whose name stops before it.-- A proof date or description cleared in Details stays cleared.-- A layer refresh keeps a legend or title change made while it was reading, and a- layer deleted meanwhile stays deleted.-- Undoing a Detect pin takes its evidence picture to the Trash with it.-- A routine whose area is in the Trash asks for the area back first. One whose- area is gone for good still opens and says so.-- A new comparison no longer picks up the kept images of a deleted one with the- same name.-- A damaged KMZ or a deeply nested GeoJSON is refused with a reason instead of a- server error.-- Notes, proofs, drafts and layer settings are written whole, so a save cut- short keeps the previous version.-- The tile cache clears tiles older than 30 days at startup, including those- Detect read.-- Copies of 0.3.0 Inspect sessions stay out of bundles and go with their file- once it leaves the Trash.-- Geo Report's map links read as site names, in the app and in the saved- Markdown note, instead of internal ids.-- A tab left open across an update no longer asks for interface files that are- gone.-- A video's thumbnail no longer goes missing when the background worker reaches- it before the file's details are written.-- The Guide describes Inspect's actual tabs, and sends you to the Layers tab for- overlays.+- Changing only the case of a name renames it on Windows and macOS, where it+ used to delete a collage or be refused.+- Two names differing only by case no longer block a bundle export on Linux.+- A proof, draft or grid with "#" in its name opens and deletes the right one.+- Notes, proofs and drafts are written whole, so an interrupted save keeps the+ previous version.+- The Wayback map no longer slows down while you pan, and its picker lists every+ release.+- A video's thumbnail no longer goes missing on import.+- Geo Report's map links read as site names instead of internal ids.- On Windows, moving the workspace or saving settings no longer fails when an- antivirus or the search indexer briefly holds the file.-- The Wayback map no longer slows down while you pan. Its picker lists every- release, and **Changes here** reads a point's history only when you press it.+ antivirus briefly holds the file.+- A tab left open across an update no longer asks for files that are gone.## Install or upgradeDownload the ready-to-run file for Windows x86_64, Linux x86_64 or Apple-Silicon macOS and run it. Each one includes the interface, `ffmpeg` and the-fonts used for PDF export. The Linux file needs glibc 2.38 or newer (Ubuntu-24.04, Debian 13, Fedora 39 or later); on an older distribution, install with-`pipx install azimut`.+Silicon macOS and run it. It includes the interface, `ffmpeg` and the PDF+fonts. The Linux file needs glibc 2.38 or newer (Ubuntu 24.04, Debian 13,+Fedora 39 or later); on an older distribution, use `pipx install azimut`.On Intel Macs (macOS 14 or newer), install the Python package instead:`pipx install azimut` or `pip install azimut`.-The downloads are unsigned, so your system will warn you the first time. On-macOS, make the file executable with `chmod +x` before opening it. The README-gives the steps for each platform.+The downloads are unsigned, so your system warns you the first time. On macOS,+run `chmod +x` on the file first. The README gives the steps for each platform.-The capture extension changed in this release. Chrome, Edge and Brave users-update it from Settings → Capture extension. Firefox updates the signed add-on by-itself; a new install uses `azimut-capture-0.3.1.xpi` attached to this release,-opened from `about:addons` → gear menu → **Install Add-on From File**.+The capture extension changed. Chrome, Edge and Brave update it from Settings →+Capture extension. Firefox updates the signed add-on by itself; for a new+install, open `azimut-capture-0.3.1.xpi` from this release in `about:addons` →+gear menu → **Install Add-on From File**.-Your existing cases open as they are. Apart from Inspect sessions becoming one-work per file, nothing changes in them, no export or manual step is needed, and-older case bundles still import.+Your cases open as they are and older bundles still import. The Inspect merge+above is the only change to them.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 943272b..235d6e8 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -207,6 +207,8 @@ proof for publication.| ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review and a saved comparison keep theirs, and Settings turns it off. || ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, at its frame's centre with the frame outlined, dated A → B, and reopens in Compare; an export can also be kept in the case under it. || ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin (a change between two passes, or a thing seen on one); comparisons and pinned evidence carry each picture's date, estimates marked; Detect layers filter a change by its span; exports are named by their pictures' dates. |+| ✅ **An evolution of one point** | Exports Sentinel-2 passes or Wayback pictures ticked by hand on their previews, back to 2015, as one GIF or one sheet drawn from the tile proxy on the same ground, repeats and empty pictures left out and counted. |+| ✅ **Signed exports, marks in their colours** | Compare exports close their credits line with the Azimut logo and name unless unticked, and a GIF keeps every mark's colour exact. || ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame like a wheel about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back, Shift+← / → steps. |---diff --git a/docs/UI.md b/docs/UI.mdindex 5f1f66c..388c776 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -1434,11 +1434,36 @@ shared Views destination, named by the comparison and its two pictures' dates, anever over an earlier file. **Also keep it in this case** files the same image in Mywork under the comparison, stamped with the reading on screen and never replaced by alater save; asked on a comparison never saved, it asks for a name first. An optional-ground-anchored frame cuts any of the three to the+ground-anchored frame cuts any export to thechosen area, while Full view remains the default. The frame keeps the bearing it wasdrawn at: turning the camera turns it with the ground rather than reshaping it, andthe export comes out upright as it was drawn, once all four corners are in view. Copy current PNG uses the clipboard.-Exports include projected annotations, a scale bar and north arrow. Tile captures wait+Exports include projected annotations, a scale bar and north arrow. **Sign it Azimut**,+ticked by default, closes the credits line under the imagery with the logo and the+wordmark of the app's corner. A GIF keeps the colour of every mark exactly: the+palette of each frame is built around them, and the imagery gets the rest.++**GIF · Evolution** and **PNG · Evolution sheet** play the pictures of one archive in+order, on Sentinel-2 or Wayback on both sides, or Wayback against World Imagery.+Choosing one reads the crosshair's pictures, each shown as a card with its picture of+the export's ground to tick by hand. Wayback lists the whole history at once, in the+order the pictures were taken with each release beside its date, and opens on A to B+(a release that republished an older picture counts as that picture); **One a+month**, **One a year** and **All** retick it. Sentinel-2 is read a month at a time,+one Copernicus request each: it opens on A's month and B's with both passes ticked,+and the arrows or the month field go back to any month since June 2015. A pass over+the cloud ceiling is shown and can still be ticked, **Clearest of the month** ticks+the least cloudy, and the chosen passes stay listed as chips across months. One export+holds 2 to 40 pictures, and the price in Copernicus requests is stated before it runs.+Each picture is drawn from the tile proxy on the export frame's ground, or A's view,+so A and B stay as they are and every picture covers the same ground at one scale; it+may lie off screen. A frame carries its date on the imagery and a line of dates in its+footer, the last one held three times as long, at the pace chosen; a sheet lays the+pictures out in rows under one scale bar. Only the marks set on both sides are drawn,+reference layers and the Difference stay out, and the tones are the archive's. A+picture with no imagery, or with the same pixels as the one before, is left out and+the toast counts it. **Stop** ends it between two tiles. An evolution is written to the+Views destination only, never kept in the case. Tile captures waitfor loaded frames and reject incomplete tiles. Google Maps JS uses theuser-triggered Azimut Capture extension and retains its on-map credits.@@ -1651,7 +1676,14 @@ or GPX file opened from the computer, a public My Maps or map URL followed, or aGeoConfirmed conflict. All of them land in the same section, because the question the row answers is who putthis on my map. **A layer is drawn and never adopted** — clicking a feature openswhat the source says about it, its name, its group and its description, with-nothing to confirm and no way from there into the case. A description written as+nothing to confirm and no way from there into the case. A pin's card also states+its point in the analyst's format, pressed to copy: read from the file rather+than from what the map drew, which a tile rounds by tens of metres far out. A+right-click on a pin opens the map's own point menu on that point, headed by the+pin's name and its layer, since the pin is pressed on its head, well above the+ground it names. On a line or inside an area it opens on the ground pressed. A+place saved from that menu is the analyst's and carries nothing of the feature.+A description written ascolumns is drawn as columns, one label and its value per row, because a My Mapskeeps its fields in a table and a table flattened into a paragraph is unreadable.Addresses in it are links, and they open in a new tab: a feature sourced from a@@ -1870,7 +1902,8 @@ is there, answered inside the menu; save a place there; start a distance fromit; anchor the sun and moon on it; open its Wayback history; centre the mapon it; compare it across time; or open it in Compare, in Detect or in anothermap site. A right-click on a shape that answers-its own (a search-grid cell) stays that shape's. The menu flips away from the+its own (a search-grid cell) stays that shape's; on a pin of an added layer the+menu is on the pin's point (see **Added map layers**). The menu flips away from themap's edges, walks with the arrow keys, and closes on Escape, a press outside,or a zoom that moves the ground from under it.diff --git a/frontend/e2e/satellite-added-layers.spec.js b/frontend/e2e/satellite-added-layers.spec.jsnew file mode 100644index 0000000..12bf67c--- /dev/null+++ b/frontend/e2e/satellite-added-layers.spec.js@@ -0,0 +1,112 @@+import { test, expect } from '@playwright/test';+import { awaitMapReady, CASE_ID, installAppFixture, mapPicture, repainted } from './app.fixture.js';++/**+ * A feature of an added layer, pressed on the real engine.+ *+ * The features claim their clicks, and the map's right-click relay honoured+ * that claim too: a right-click on a pin, or anywhere inside an area, opened+ * nothing. Only a browser can say what the pointer actually lands on, since+ * a pin is pressed on its head, well above the point it names.+ */++const LAYER = {+ name: 'checkpoints',+ title: 'Checkpoints map',+ source: { kind: 'file', format: 'geojson', filename: 'checkpoints.geojson' },+ hidden: [],+ period: null,+ refresh: {},+ features: 2,+ categories: [{ name: 'checkpoints', count: 2, colour: '#e04040' }],+ bbox: [2.345, 48.848, 2.35, 48.852],+ format: 'geojson',+ icons: 0,+ sha256: 'a'.repeat(64),+ bytes: 512,+ fetched_at: '2026-09-20T10:00:00Z',+ checked_at: '2026-09-20T10:00:00Z',+ stale: false,+ created_at: '2026-09-20T10:00:00Z',+ updated_at: '2026-09-20T10:00:00Z',+ spec: '.layers/checkpoints/layer.json',+};++const FEATURES = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ geometry: { type: 'Point', coordinates: [2.35, 48.85] },+ properties: { name: 'North gate', category: 'checkpoints', colour: '#e04040', index: 0 },+ },+ {+ type: 'Feature',+ // west of the pin, far enough that a press inside it is not on the pin+ geometry: {+ type: 'Polygon',+ coordinates: [[[2.345, 48.848], [2.348, 48.848], [2.348, 48.852], [2.345, 48.852], [2.345, 48.848]]],+ },+ properties: { name: 'Depot', category: 'checkpoints', colour: '#e04040', index: 1 },+ },+ ],+};++/** Satellite centred on the pin, with the layer drawn. */+async function openOnThePin(page) {+ await installAppFixture(page);+ await page.route(`**/api/cases/${CASE_ID}/map-layers`, (route) =>+ route.request().method() === 'GET' ? route.fulfill({ json: [LAYER] }) : route.fallback()+ );+ await page.route(`**/api/cases/${CASE_ID}/map-layers/${LAYER.name}/data`, (route) =>+ route.fulfill({ json: FEATURES })+ );+ await page.goto('/#satellite?ll=48.85,2.35&z=16');+ await awaitMapReady(page);+ const bare = await mapPicture(page);+ await page.getByRole('button', { name: LAYER.title, exact: true }).click();+ // painted a frame after it is declared, so nothing is under the pointer before+ await expect.poll(async () => repainted(bare, await mapPicture(page))).toBe(true);+ const box = await page.locator('.map').boundingBox();+ // the pin stands on the centre and is pressed on its head+ return { box, head: { x: box.x + box.width / 2, y: box.y + box.height / 2 - 14 } };+}++const menu = (page) => page.getByRole('menu', { name: 'This point' });++test("a right-click on a pin opens the point menu on the pin's own point", async ({ page }) => {+ const { head } = await openOnThePin(page);++ await page.mouse.click(head.x, head.y, { button: 'right' });++ await expect(menu(page)).toBeVisible();+ await expect(menu(page).locator('.snap')).toContainText('North gate');+ await expect(menu(page).locator('.snap')).toContainText(LAYER.title);+ // the file's point to the digit, not the ground under the pin's head+ await expect(menu(page).getByRole('menuitem', { name: /^DD/ })).toContainText('48.850000, 2.350000');+ await expect(menu(page).getByRole('menuitem', { name: 'Save place here…' })).toBeVisible();+});++test('a right-click inside an area opens the point menu on the ground there', async ({ page }) => {+ const { box } = await openOnThePin(page);++ await page.mouse.click(box.x + box.width / 2 - 150, box.y + box.height / 2, { button: 'right' });++ await expect(menu(page)).toBeVisible();+ await expect(menu(page).locator('.snap')).toHaveCount(0);+ await expect(menu(page).getByRole('menuitem', { name: /^DD/ })).not.toContainText('2.350000');+});++test("the pin's card states its point and copies it", async ({ page, context, browserName }) => {+ const { head } = await openOnThePin(page);++ await page.mouse.click(head.x, head.y);++ const where = page.locator('.layer-card-where');+ await expect(where).toHaveText('48.850000, 2.350000');+ test.skip(browserName !== 'chromium', 'only Chromium lets a test grant the clipboard');+ await context.grantPermissions(['clipboard-read', 'clipboard-write']);+ await where.click();+ await expect(page.getByText('Coordinates copied')).toBeVisible();+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('48.850000, 2.350000');+});diff --git a/frontend/src/components/brandAssets.test.js b/frontend/src/components/brandAssets.test.jsindex 31bf59f..414291c 100644--- a/frontend/src/components/brandAssets.test.js+++ b/frontend/src/components/brandAssets.test.js@@ -43,6 +43,15 @@ describe('brand assets', () => {}});+ it('the canvas signature exports sign with draws the same mark and letters', async () => {+ const { LETTERS, MARK } = await import('../lib/brandMark.js');+ expect([`d="${MARK.west}"`, `d="${MARK.east}"`]).toEqual([WEST, EAST]);+ expect(LETTERS.map((letter) => letter.d)).toEqual(paths(read('./Wordmark.svelte')));+ const shifts = [...read('./Wordmark.svelte').matchAll(/<path(?: transform="translate\(([\d.]+) 0\)")? d=/g)]+ .map((match) => Number(match[1] ?? 0));+ expect(LETTERS.map((letter) => letter.dx)).toEqual(shifts);+ });+it('each lockup carries the ink of the background it is served on', () => {// A file fetched outside the app has no theme to read, so the pair exists// precisely to spell the ink out: the light one dark, the dark one light.diff --git a/frontend/src/lib/brandMark.js b/frontend/src/lib/brandMark.jsnew file mode 100644index 0000000..7600872--- /dev/null+++ b/frontend/src/lib/brandMark.js@@ -0,0 +1,82 @@+/**+ * The Azimut lockup drawn on a canvas, for exports that sign their pictures.+ *+ * The same two flanks as `components/Logo.svelte` and the same seven letter paths+ * as `components/Wordmark.svelte`, laid out as the app's top-left corner shows+ * them: the mark 27 px high, 11 px of air, then AZIMUT 13 px high.+ * `components/brandAssets.test.js` holds them together.+ */++export const MARK = Object.freeze({+ west: 'M12 1.8 5.8 21.4 12 16.4Z',+ east: 'M12 1.8 18.2 21.4 12 16.4Z',+});++/** Each letter's path and its shift along the line, in wordmark units. */+export const LETTERS = Object.freeze([+ { d: 'M0 100 25 0h13.3l25 100', dx: 0 },+ { d: 'M13 69h37.3', dx: 0 },+ { d: 'M0 7.5h58L0 92.5h58', dx: 96.3 },+ { d: 'M0 0v100', dx: 193.3 },+ { d: 'M0 100V0l38 58 38-58v100', dx: 232.3 },+ { d: 'M0 0v69a31 31 0 0 0 62 0V0', dx: 347.3 },+ { d: 'M0 7.5h58M29 7.5V100', dx: 430.3 },+]);++/** The wordmark's box, stroke included: `viewBox="-7.5 -7.5 503.3 115"`. */+const WORD_BOX = { x: -7.5, y: -7.5, width: 503.3, height: 115 };+/** The app's corner, in CSS px: mark, gap, wordmark. */+const MARK_SIZE = 27;+const GAP = 11;+const WORD_HEIGHT = 13;++export const INK_ON_DARK = '#e3e3e3';+export const AMBER = '#e8a33d';++/** How wide the lockup is when drawn `height` px high. */+export function signatureWidth(height) {+ const unit = height / MARK_SIZE;+ return (MARK_SIZE + GAP + (WORD_HEIGHT * WORD_BOX.width) / WORD_BOX.height) * unit;+}++/**+ * Draw the lockup with its right edge at `right`, centred on `middle`.+ *+ * Nothing is drawn where the canvas has no `Path2D` to trace the paths with,+ * so a signature never costs an export its picture.+ *+ * @returns {number} the width drawn, 0 when nothing was+ */+export function drawSignature(ctx, right, middle, { height, ink = INK_ON_DARK, makePath } = {}) {+ const pathOf = makePath ?? (typeof Path2D === 'function' ? (d) => new Path2D(d) : null);+ if (!pathOf || !(height > 0)) return 0;+ const unit = height / MARK_SIZE;+ const width = signatureWidth(height);+ const left = right - width;+ ctx.save();+ // The mark: a 24-unit viewBox drawn MARK_SIZE px square.+ ctx.translate(left, middle - height / 2);+ ctx.scale(height / 24, height / 24);+ ctx.fillStyle = ink;+ ctx.fill(pathOf(MARK.west));+ ctx.fillStyle = AMBER;+ ctx.fill(pathOf(MARK.east));+ ctx.restore();++ ctx.save();+ const wordScale = (WORD_HEIGHT * unit) / WORD_BOX.height;+ ctx.translate(left + (MARK_SIZE + GAP) * unit - WORD_BOX.x * wordScale, middle - (WORD_HEIGHT * unit) / 2 - WORD_BOX.y * wordScale);+ ctx.scale(wordScale, wordScale);+ ctx.strokeStyle = ink;+ ctx.lineWidth = 15;+ ctx.lineCap = 'butt';+ ctx.lineJoin = 'miter';+ for (const letter of LETTERS) {+ ctx.save();+ ctx.translate(letter.dx, 0);+ ctx.stroke(pathOf(letter.d));+ ctx.restore();+ }+ ctx.restore();+ return width;+}diff --git a/frontend/src/lib/map/addedLayer.js b/frontend/src/lib/map/addedLayer.jsindex 1eefb41..caa106f 100644--- a/frontend/src/lib/map/addedLayer.js+++ b/frontend/src/lib/map/addedLayer.js@@ -39,6 +39,7 @@*/import { Popup } from 'maplibre-gl';import { paths } from '../../components/Icon.svelte';+import { wrapLon } from '../coords.js';import { categoryColour } from './addedLayers.js';/** The pictogram per geometry kind. Three shapes is the whole vocabulary, and@@ -286,17 +287,23 @@ export function periodFilter(period = null) {/*** @param {object} engine the façade from `engine.js`* @param {object} [opts]- * @param {(feature: object) => HTMLElement} [opts.card] the read-only popup's body+ * @param {(properties: object, point: { lat: number, lon: number } | null) => HTMLElement} [opts.card]+ * the read-only popup's body, handed the feature's own point when it has one* @param {(offset: number) => object} [opts.popup] the card itself, swappable so* the click path can be read off a test without standing up the engine's own popup* @param {(key: string) => string} [opts.iconUrl] where this case keeps the* source's composed icons. Absent — a layer added without the box ticked, or one* whose icons could not be made — and every point draws the app's own pictogram.* @param {(map: object, url: string) => Promise<object|null>} [opts.loadIcon]+ * @param {(at: { lat: number, lon: number, x: number, y: number }, properties: object | null) => void} [opts.menu]+ * what a right-click on a feature opens: the map's own point menu, on the+ * feature's point when it is a pin (with its properties), on the ground under+ * the cursor for a line or an area (with none). The features claim their+ * clicks, so without this a right-click on one opens nothing at all.*/export function createAddedLayer(engine,- { card, popup = defaultPopup, iconUrl = null, loadIcon = defaultLoadIcon } = {}+ { card, popup = defaultPopup, iconUrl = null, loadIcon = defaultLoadIcon, menu = null } = {}) {const map = engine.impl;const prefix = `added-${++layers}`;@@ -422,10 +429,28 @@ export function createAddedLayer(}/**- * The card, and the only thing a feature answers.+ * Where a pin stands, as the source wrote it, or null for a line or an area.*- * Read-only by construction: it is given what the source states and offers no- * way out of itself. Nothing in an added layer enters the case.+ * Read off the collection rather than off the feature the engine hands back:+ * that one is rebuilt out of a tile, its position rounded to the tile's grid,+ * which far out is tens of metres. The number the backend gave every feature+ * finds the original.+ */+ function pointOf(feature) {+ const original = featureAt(collection, feature?.properties?.index);+ const geometry = original?.geometry ?? feature?.geometry;+ if (geometry?.type !== 'Point') return null;+ const [lon, lat] = geometry.coordinates ?? [];+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;+ return { lat, lon: wrapLon(lon) };+ }++ /**+ * The card and the point menu, the only two things a feature answers.+ *+ * The card is read-only by construction: it is given what the source states,+ * and copying its point is the one thing it does. The menu is the map's own,+ * moved onto the pin's point. Nothing in an added layer enters the case.*/function bindHandlers() {const bind = (type, handler) => {@@ -437,6 +462,16 @@ export function createAddedLayer(if (!feature) return;showCard(feature, event.lngLat);});+ bind('contextmenu', (event) => {+ if (!menu) return;+ const features = event.features ?? [];+ // a pin drawn over an area is the pin that was meant+ const feature = features.find((one) => pointOf(one)) ?? features[0];+ if (!feature) return;+ const point = pointOf(feature);+ const at = point ?? { lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) };+ menu({ ...at, x: event.point.x, y: event.point.y }, point ? (feature.properties ?? {}) : null);+ });bind('mouseenter', () => {map.getCanvas().style.cursor = 'pointer';});@@ -459,10 +494,10 @@ export function createAddedLayer(function showCard(feature, at) {if (!card) return;closeCard();- const point = feature.geometry?.type === 'Point' ? feature.geometry.coordinates : null;+ const point = pointOf(feature);open = popup(point ? PIN_CARD_OFFSET : EDGE_CARD_OFFSET)- .setLngLat(point ?? at)- .setDOMContent(card(feature.properties ?? {}))+ .setLngLat(point ? [point.lon, point.lat] : at)+ .setDOMContent(card(feature.properties ?? {}, point)).addTo(map);open.on('close', () => {open = null;@@ -601,7 +636,7 @@ export function createAddedLayer(** The second way into this layer, and deliberately the same one: it ends at* the card a click ends at, which states what the source says and offers no- * route out of itself. Finding a feature is not adopting it.+ * route from it into the case. Finding a feature is not adopting it.** False when the number names nothing here, which is what a card opened on* the wrong feature would otherwise be.diff --git a/frontend/src/lib/map/addedLayer.test.js b/frontend/src/lib/map/addedLayer.test.jsindex 9acc7f8..2e4f701 100644--- a/frontend/src/lib/map/addedLayer.test.js+++ b/frontend/src/lib/map/addedLayer.test.js@@ -110,6 +110,13 @@ const DRESSED = {],};+/** The first feature as the engine hands it back: rebuilt out of a tile, so its+ * position is the tile grid's, a little off the file's. */+const ROUNDED_PIN = {+ ...COLLECTION.features[0],+ geometry: { type: 'Point', coordinates: [2.3507, 48.8503] },+};+/** Which symbol layer is which, told apart by the image each one draws. */function symbolLayers(engine) {const symbols = [...engine.map.layers.values()].filter((layer) => layer.type === 'symbol');@@ -485,7 +492,7 @@ describe('an added layer on the map', () => {const [, , click] = engine.map.handlers.find(([type]) => type === 'click');click({ lngLat: [2.35, 48.85], features: [COLLECTION.features[0]] });- expect(card).toHaveBeenCalledWith(COLLECTION.features[0].properties);+ expect(card).toHaveBeenCalledWith(COLLECTION.features[0].properties, { lat: 48.85, lon: 2.35 });// nothing to confirm, nothing to save, no path out of it into the caseexpect(popup.body.querySelectorAll('button, a, input, form')).toHaveLength(0);});@@ -512,6 +519,94 @@ describe('an added layer on the map', () => {expect(popup.at).toEqual([2.05, 48.05]);expect(popup.offset).toBeLessThan(22);});++ it("hands the card the pin's point as the file wrote it, not as a tile rounded it", async () => {+ // A rendered feature is rebuilt out of a tile, its position snapped to the+ // tile's grid: far out that is tens of metres, and it is what gets copied.+ const engine = stubEngine();+ const { card, popup, opts } = stubCard();+ await createAddedLayer(engine, opts).set(COLLECTION, { categories: CATEGORIES });+ const [, , click] = engine.map.handlers.find(([type]) => type === 'click');++ click({ lngLat: [2.3511, 48.8511], features: [ROUNDED_PIN] });++ expect(card).toHaveBeenCalledWith(ROUNDED_PIN.properties, { lat: 48.85, lon: 2.35 });+ expect(popup.at).toEqual([2.35, 48.85]);+ });+});++/**+ * The right-click, which the features claim along with their clicks.+ *+ * Claimed and answered by nobody, it opened nothing at all: not on a pin, not+ * anywhere inside an area. It opens the map's own point menu instead, on the+ * pin's point, since the pin's head is clicked some twenty pixels above it.+ */+describe('a right-click on an added layer', () => {+ /** The right-click the engine would deliver, and what the layer made of it. */+ async function rightClick(event, { menu = vi.fn() } = {}) {+ const engine = stubEngine();+ const { opts } = stubCard();+ await createAddedLayer(engine, { ...opts, menu }).set(COLLECTION, { categories: CATEGORIES });+ const handler = engine.map.handlers.find(([type]) => type === 'contextmenu');+ handler?.[2](event);+ return { menu, engine, handler };+ }++ it("opens the point menu on the pin's own point, not the ground under its head", async () => {+ const { menu } = await rightClick({+ lngLat: { lat: 48.8511, lng: 2.3511 },+ point: { x: 140, y: 90 },+ features: [ROUNDED_PIN],+ });++ expect(menu).toHaveBeenCalledWith(+ { lat: 48.85, lon: 2.35, x: 140, y: 90 },+ COLLECTION.features[0].properties+ );+ });++ it('opens it where it was pressed inside an area, which has no one point', async () => {+ // a world copy away, as the map counts past the antimeridian+ const { menu } = await rightClick({+ lngLat: { lat: 48.05, lng: 362.05 },+ point: { x: 300, y: 200 },+ features: [COLLECTION.features[1]],+ });++ const [at, named] = menu.mock.calls[0];+ expect(at.lat).toBe(48.05);+ expect(at.lon).toBeCloseTo(2.05, 9);+ expect([at.x, at.y]).toEqual([300, 200]);+ // nothing to name: the menu is on the ground, not on a feature's point+ expect(named).toBeNull();+ });++ it('takes the pin over the area it stands in', async () => {+ const { menu } = await rightClick({+ lngLat: { lat: 48.05, lng: 2.05 },+ point: { x: 10, y: 10 },+ features: [COLLECTION.features[1], COLLECTION.features[0]],+ });++ expect(menu.mock.calls[0][0]).toMatchObject({ lat: 48.85, lon: 2.35 });+ });++ it('is claimed from the map, so the ground menu does not open a second time behind it', async () => {+ const { engine } = await rightClick({ lngLat: { lat: 0, lng: 0 }, point: { x: 0, y: 0 }, features: [] });+ expect(engine.claimClicks).toHaveBeenCalled();+ });++ it('opens nothing when nobody asked for a menu, and does not throw', async () => {+ const engine = stubEngine();+ const { opts } = stubCard();+ await createAddedLayer(engine, opts).set(COLLECTION, { categories: CATEGORIES });+ const [, , handler] = engine.map.handlers.find(([type]) => type === 'contextmenu');++ expect(() =>+ handler({ lngLat: { lat: 48.85, lng: 2.35 }, point: { x: 1, y: 1 }, features: [COLLECTION.features[0]] })+ ).not.toThrow();+ });});/**@@ -579,7 +674,8 @@ describe('going to one feature', () => {{ west: 2, east: 2.1, south: 48, north: 48.1 },expect.objectContaining({ maxZoom: 17, animate: true }));- expect(card).toHaveBeenCalledWith(COLLECTION.features[1].properties);+ // an area has no one point to state+ expect(card).toHaveBeenCalledWith(COLLECTION.features[1].properties, null);// nothing to confirm, nothing to save: a found feature is not an adopted oneexpect(popup.body.querySelectorAll('button, a, input, form')).toHaveLength(0);});diff --git a/frontend/src/lib/map/compareExport.js b/frontend/src/lib/map/compareExport.jsindex 2a5e44f..9dd48d3 100644--- a/frontend/src/lib/map/compareExport.js+++ b/frontend/src/lib/map/compareExport.js@@ -12,7 +12,8 @@* a change mask computed for an earlier camera is laid where its ground is.*/-import { drawAnnotations, onSide } from './compareAnnotations.js';+import { comparisonAnnotations, drawAnnotations, onSide, stampInk } from './compareAnnotations.js';+import { AMBER, INK_ON_DARK, drawSignature, signatureWidth } from '../brandMark.js';import {apply,compose,@@ -34,6 +35,45 @@ const ACCENT = '#e8a33d';const FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';const MONO = 'ui-monospace, "SF Mono", "Cascadia Code", monospace';+/** The inks an export is laid out in, for the other composers to share. */+export const EXPORT_STYLE = Object.freeze({ INK, MUTED, BAND, ACCENT, FONT, MONO });++/** The plate a mark's label sits on, and the ink written on it (`compareAnnotations.js`). */+const LABEL_INKS = ['#f5f6f7'];++/**+ * The colours a GIF must keep exactly, as the `keep` form field: every mark's+ * colour and the ink of its numeral, then the export's own inks and the+ * signature's. The server builds each frame's palette around them; the imagery+ * gets the rest.+ */+export function gifColours(annotations = [], { signed = false } = {}) {+ const colours = [];+ for (const mark of comparisonAnnotations(annotations)) {+ colours.push(mark.colour);+ if (mark.kind === 'number') colours.push(stampInk(mark));+ }+ colours.push(ACCENT, INK, MUTED, BAND, ...LABEL_INKS);+ if (signed) colours.push(INK_ON_DARK, AMBER);+ const kept = [];+ for (const colour of colours) {+ const hex = String(colour).toLowerCase();+ if (/^#[0-9a-f]{6}$/.test(hex) && !kept.includes(hex)) kept.push(hex);+ }+ return kept.slice(0, 32).join(',');+}++/**+ * Sign a footer band: the Azimut lockup at its right end, centred on `middle`.+ * Answers the width it took, so the credits beside it can stop short.+ */+export function signFooter(ctx, right, middle, scale) {+ return drawSignature(ctx, right, middle, { height: 15 * scale });+}++/** How much of a footer row the signature takes, gap included. */+export const signatureRoom = (scale) => signatureWidth(15 * scale) + 18 * scale;+/*** What an exported comparison is called: its title, then the dates of its two* pictures, which say what the file shows. When neither picture is dated, the@@ -104,7 +144,8 @@ export function scaleBarLength(metresPerPixel, target = 120) {const readableLength = (metres) =>metres >= 1000 ? `${metres / 1000} km` : `${metres} m`;-function drawTag(ctx, text, x, y, { scale, accent = false, align = 'left' }) {+/** A label on a dark rounded plate, as the corners of an export carry them. */+export function drawTag(ctx, text, x, y, { scale, accent = false, align = 'left' }) {ctx.font = `700 ${Math.round(12 * scale)}px ${FONT}`;const padX = 8 * scale;const height = 22 * scale;@@ -120,8 +161,13 @@ function drawTag(ctx, text, x, y, { scale, accent = false, align = 'left' }) {ctx.textBaseline = 'alphabetic';}-function drawScaleAndNorth(ctx, frame, x, y, { scale, bearing, units }) {- const perPixel = groundPerPixel(frame) / scale;+/**+ * The scale bar and north needle, bottom-aligned at `y`. `pixelScale` is how many+ * output pixels one CSS pixel of `frame` became, when the marks are drawn at+ * another size than the picture was.+ */+export function drawScaleAndNorth(ctx, frame, x, y, { scale, bearing, units, pixelScale = scale }) {+ const perPixel = groundPerPixel(frame) / pixelScale;let { metres, pixels } = scaleBarLength(perPixel, 120 * scale);let label = readableLength(metres);if (units === 'imperial') {@@ -213,6 +259,7 @@ export function composeComparison({view,bearing = 0,units = 'metric',+ signed = false,makeCanvas,}) {if (!a?.canvas?.width || !b?.canvas?.width || !a?.frame || !b?.frame) {@@ -404,7 +451,13 @@ export function composeComparison({ctx.fillStyle = MUTED;ctx.font = `${Math.round(10 * s)}px ${FONT}`;const credits = `A: ${attributionA || labelA} | B: ${attributionB || labelB}`;- ctx.fillText(credits, left, output.height - 9 * s, Math.max(0, mapWidth - 32 * s));+ // The signature closes the credits row, off the imagery and clear of the scale bar.+ const signature = signed && signFooter(ctx, mapWidth - 14 * s, output.height - 13 * s, s)+ ? signatureRoom(s)+ : 0;+ ctx.fillStyle = MUTED;+ ctx.font = `${Math.round(10 * s)}px ${FONT}`;+ ctx.fillText(credits, left, output.height - 9 * s, Math.max(0, mapWidth - 32 * s - signature));return output;}diff --git a/frontend/src/lib/map/compareExport.test.js b/frontend/src/lib/map/compareExport.test.jsindex e78f6e7..472f4e4 100644--- a/frontend/src/lib/map/compareExport.test.js+++ b/frontend/src/lib/map/compareExport.test.js@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {blobBase64,canvasBlob,@@ -6,6 +6,7 @@ import {comparisonFilename,pictureDateFields,composeComparison,+ gifColours,scaleBarLength,} from './compareExport.js';@@ -47,6 +48,7 @@ function fakeCanvas() {closePath: record('closePath'),translate: record('translate'),rotate: record('rotate'),+ scale: record('scale'),transform: record('transform'),setTransform: record('setTransform'),setLineDash: record('setLineDash'),@@ -253,3 +255,49 @@ describe('comparison image encoding', () => {await expect(canvasBlob(canvas)).rejects.toThrow('cannot be exported');});});++describe('keeping colours in a GIF', () => {+ it('names every mark colour, the numeral inks and the export inks, each once', () => {+ const marks = [+ { id: 'a', kind: 'rect', colour: '#EF4444', points: [[0, 0], [1, 1]] },+ { id: 'b', kind: 'number', colour: '#f6a81a', number: 1, points: [[0, 0]] },+ { id: 'c', kind: 'line', colour: '#ef4444', points: [[0, 0], [1, 1]] },+ ];+ const kept = gifColours(marks).split(',');+ expect(kept.slice(0, 3)).toEqual(['#ef4444', '#f6a81a', '#14161a']);+ expect(kept).toEqual(expect.arrayContaining(['#e8a33d', '#f3f4f6', '#0f1114']));+ expect(new Set(kept).size).toBe(kept.length);+ expect(kept).not.toContain('#e3e3e3');+ expect(gifColours([], { signed: true }).split(',')).toContain('#e3e3e3');+ });++ it('stays inside what the server reads', () => {+ const marks = Array.from({ length: 60 }, (_, index) => ({+ id: `m${index}`, kind: 'line', colour: `#${index.toString(16).padStart(6, '0')}`, points: [[0, 0], [1, 1]],+ }));+ const field = gifColours(marks, { signed: true });+ expect(field.split(',')).toHaveLength(32);+ expect(field).toMatch(/^(#[0-9a-f]{6})(,#[0-9a-f]{6})*$/);+ });+});++describe('signing an export', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('closes the credits line with the lockup, and shortens the credits to make room', () => {+ const paths = [];+ vi.stubGlobal('Path2D', class { constructor(d) { paths.push(d); } });+ const plain = composeComparison({ ...BASE, mode: 'side' });+ expect(paths).toHaveLength(0);+ const signed = composeComparison({ ...BASE, mode: 'side', signed: true });+ expect(paths).toHaveLength(9);+ const credits = (out) => out.context.calls.filter(([name, text]) => name === 'fillText' && String(text).startsWith('A: '));+ expect(credits(signed)[0][4]).toBeLessThan(credits(plain)[0][4]);+ expect([signed.width, signed.height]).toEqual([plain.width, plain.height]);+ });++ it('leaves the picture whole where the browser cannot trace the lockup', () => {+ vi.stubGlobal('Path2D', undefined);+ expect(() => composeComparison({ ...BASE, mode: 'side', signed: true })).not.toThrow();+ });+});diff --git a/frontend/src/lib/map/evolution.js b/frontend/src/lib/map/evolution.jsnew file mode 100644index 0000000..68a1a26--- /dev/null+++ b/frontend/src/lib/map/evolution.js@@ -0,0 +1,301 @@+/**+ * An evolution: the dated pictures of one point, played in order.+ *+ * A comparison reads two pictures. An evolution reads every picture the archive+ * A and B share holds between them, so a building going up or a burn greening+ * again shows as it happened rather than as two ends. The list is the one the+ * pictures strip reads (`passStrip.js`); this module chooses among its rows and+ * lays each picture out on the ground.+ *+ * Each picture is drawn from the tile proxy, not from the maps on screen: A and+ * B keep what they show while the export runs, and every picture of one export+ * covers exactly the same ground at the same scale. The pixels are kept as the+ * archive gives them, tones unmatched, since matching them can erase the change+ * being shown. Only reference layers are left out: the export is the imagery,+ * its date and the marks pinned to the ground.+ *+ * Everything here is pure; `evolutionExport.js` fetches and draws.+ */++import { SENTINEL_ID } from '../sentinel.js';+import { WAYBACK_ID } from '../wayback.js';+import { entryOf } from './passStrip.js';+import {+ apply, compassAngle, compose, fromMercator, invert, mercatorPerPixel, scale,+ screenToMercator, turnedBox,+} from './groundFrame.js';++export const EVOLUTION_ARCHIVES = Object.freeze([SENTINEL_ID, WAYBACK_ID]);+export const WORLD_IMAGERY_ID = 'esri-world-imagery';+/** The first month Sentinel-2 imaged the ground: Sentinel-2A began in June 2015. */+export const SENTINEL2_FIRST_MONTH = '2015-06';++/** A month the Sentinel-2 picker can open, `YYYY-MM`, held between 2015 and `today`; null for no month. */+export function pickerMonth(month, today) {+ if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(String(month ?? ''))) return null;+ if (month < SENTINEL2_FIRST_MONTH) return SENTINEL2_FIRST_MONTH;+ return month > today ? today : month;+}++/** The most pictures one export holds; `MAX_SEQUENCE_FRAMES` in `api/compare.py`. */+export const MAX_EVOLUTION_FRAMES = 40;+/** The widest a GIF frame is drawn; `MAX_GIF_EDGE` in `api/compare.py`. */+export const GIF_EDGE = 1280;+/** The width a contact sheet aims at, gaps included. */+export const SHEET_WIDTH = 2400;+/** The most pixels the pictures of a sheet add up to. */+export const SHEET_PIXELS = 8_000_000;+/** A picture needing more tiles than this is refused rather than fetched. */+export const MAX_PICTURE_TILES = 128;+/** How long each picture of a GIF stays up by default, in ms. */+export const DEFAULT_INTERVAL = 800;++const WORLD = mercatorPerPixel(0) * 512;+const HALF = WORLD / 2;++/**+ * The archive an evolution plays, when A and B allow one: Sentinel-2 or Wayback+ * on both sides, or Wayback against World Imagery, whose history Wayback is.+ */+export function evolutionArchive(a, b) {+ if (!a?.present || !b?.present) return null;+ if (a.provider === b.provider) return EVOLUTION_ARCHIVES.includes(a.provider) ? a.provider : null;+ const pair = [a.provider, b.provider];+ return pair.includes(WAYBACK_ID) && pair.includes(WORLD_IMAGERY_ID) ? WAYBACK_ID : null;+}++/**+ * The row a side shows. World Imagery stands for the newest Wayback release.+ *+ * The Wayback list holds only the releases that first published a picture of+ * the point, and a side usually shows a release that republished one: it shows+ * the picture of the last listed release published on or before its own, so+ * the side carries its release's date as `wayback_date`.+ */+export function sideEntry(entries, archive, side) {+ if (!side) return null;+ if (archive !== WAYBACK_ID) return entryOf(entries, archive, side);+ if (side.provider !== WAYBACK_ID || side.wayback_release == null) return entries.at(-1) ?? null;+ const exact = entryOf(entries, archive, side);+ if (exact) return exact;+ const day = side.wayback_date;+ if (!day) return null;+ return entries.filter((entry) => entry.released && entry.released <= day).at(-1) ?? null;+}++/**+ * The rows in the order an evolution plays them: by the day each picture was+ * taken. The Wayback list comes in release order, and a later release can carry+ * an older picture; a row with no acquisition date stands at its release's.+ */+export function playOrder(entries) {+ return entries+ .map((entry, index) => [entry, index])+ .sort(([x, i], [y, j]) => (x.date < y.date ? -1 : x.date > y.date ? 1 : i - j))+ .map(([entry]) => entry);+}++/** Evenly spaced keys, both ends kept, when there are more than `max`. */+export function spreadKeys(keys, max = MAX_EVOLUTION_FRAMES) {+ if (keys.length <= max) return [...keys];+ if (max < 2) return keys.slice(0, Math.max(0, max));+ const picked = [];+ for (let index = 0; index < max; index += 1) {+ picked.push(keys[Math.round((index * (keys.length - 1)) / (max - 1))]);+ }+ return picked;+}++/**+ * The usable rows from A's picture to B's, both included, in the list's order+ * (release order for Wayback). A side the list does not hold (a Sentinel-2 side+ * on its latest pass) stands at that end.+ */+export function rangeKeys(entries, first, last) {+ if (!entries.length) return [];+ let from = first ? entries.indexOf(first) : 0;+ let to = last ? entries.indexOf(last) : entries.length - 1;+ if (from < 0) from = 0;+ if (to < 0) to = entries.length - 1;+ if (from > to) [from, to] = [to, from];+ return entries.slice(from, to + 1).filter((entry) => entry.usable).map((entry) => entry.key);+}++/** Every usable row. */+export const allKeys = (entries) => entries.filter((entry) => entry.usable).map((entry) => entry.key);++/**+ * What an export starts on: A to B, or every usable picture when A and B are one+ * row, spread down to the most one export holds.+ */+export function defaultKeys(entries, first, last) {+ const range = rangeKeys(entries, first, last);+ return spreadKeys(range.length >= 2 ? range : allKeys(entries));+}++const cloudOf = (entry) => (Number.isFinite(entry.cloud) ? entry.cloud : 101);++/**+ * One picture per calendar month or year among `keys`: the clearest, or the+ * earliest of equally clear ones. Wayback states no cloud, so it keeps the first.+ */+export function thinKeys(entries, keys, period) {+ const chosen = new Set(keys);+ const best = new Map();+ for (const entry of entries) {+ if (!chosen.has(entry.key)) continue;+ const bucket = String(entry.date).slice(0, period === 'year' ? 4 : 7);+ const held = best.get(bucket);+ if (!held || cloudOf(entry) < cloudOf(held)) best.set(bucket, entry);+ }+ const kept = new Set([...best.values()].map((entry) => entry.key));+ return entries.filter((entry) => kept.has(entry.key)).map((entry) => entry.key);+}++/** The chosen rows, in the order they play whatever order they were ticked in. */+export function chosenEntries(entries, keys) {+ const chosen = new Set(keys);+ return playOrder(entries).filter((entry) => chosen.has(entry.key));+}++/**+ * How a picture is dated on the export. A Wayback date is Esri's estimate of when+ * the pixels were taken, or only the release date when it has none.+ */+export function pictureLabel(archive, entry) {+ if (archive !== WAYBACK_ID) return entry.date;+ if (entry.note === 'taken') return `~${entry.date}`;+ return entry.date ? `Release ${entry.date}` : 'Release, undated';+}++/**+ * The ground an evolution shows, as a frame in CSS pixels: the view, or the+ * export frame at the view's scale, upright at the bearing it was drawn at.+ * Nothing needs to be on screen, since every picture is fetched for it.+ */+export function evolutionFrame(view, exportFrame) {+ if (!exportFrame?.points) return { ...view };+ const angle = compassAngle(exportFrame.angle);+ const box = turnedBox(exportFrame.points, angle);+ const perPixel = mercatorPerPixel(view.zoom);+ const [lng, lat] = fromMercator(...box.centre);+ return {+ ...view,+ lng,+ lat,+ width: Math.max(1, Math.round(Math.abs(box.width) / perPixel)),+ height: Math.max(1, Math.round(Math.abs(box.height) / perPixel)),+ bearing: angle,+ };+}++/**+ * How many output pixels one CSS pixel of the frame becomes: the screen's density,+ * held under `edge` on the longer side.+ */+export function pictureScale(frame, edge, density = 1) {+ const most = edge / Math.max(1, frame.width, frame.height);+ return Math.max(Number.EPSILON, Math.min(Math.max(1, density), most));+}++/**+ * The tiles that draw one picture of `frame` at `pixelScale`, each with the+ * matrix that lays its pixels on the output.+ *+ * The level holds about one tile pixel per output pixel, capped at the+ * provider's native level so nothing is bought that is only upsampled; the proxy+ * magnifies past it for free. Only tiles that touch the output are listed, which+ * matters on a turned frame. The matrices are composed in doubles here and handed+ * to the canvas in output pixels, never as Mercator metres.+ */+export function pictureTiles(frame, provider, pixelScale) {+ const size = provider?.tile_size ?? 256;+ const shift = Math.log2(size / 256);+ const native = Math.floor((provider?.max_native_zoom ?? provider?.max_zoom ?? 18) - shift);+ const perOutputPixel = mercatorPerPixel(frame.zoom) / pixelScale;+ const wanted = Math.round(Math.log2(WORLD / (size * perOutputPixel)));+ const z = Math.max(0, Math.min(native, wanted));+ const count = 2 ** z;+ const span = WORLD / count;+ const width = Math.max(1, Math.round(frame.width * pixelScale));+ const height = Math.max(1, Math.round(frame.height * pixelScale));+ const toGround = compose(screenToMercator(frame), scale(1 / pixelScale));+ const toOutput = invert(toGround);+ const corners = [[0, 0], [width, 0], [0, height], [width, height]];+ const ground = corners.map(([x, y]) => apply(toGround, x, y));+ const columns = ground.map(([x]) => (x + HALF) / span);+ const rows = ground.map(([, y]) => (HALF - y) / span);+ const tiles = [];+ const firstRow = Math.max(0, Math.floor(Math.min(...rows)));+ const lastRow = Math.min(count - 1, Math.floor(Math.max(...rows)));+ for (let ty = firstRow; ty <= lastRow; ty += 1) {+ for (let tx = Math.floor(Math.min(...columns)); tx <= Math.floor(Math.max(...columns)); tx += 1) {+ const matrix = compose(toOutput, {+ a: span / size, b: 0, c: 0, d: -span / size, e: tx * span - HALF, f: HALF - ty * span,+ });+ if (!touches(matrix, size, width, height)) continue;+ tiles.push({ z, x: ((tx % count) + count) % count, y: ty, size, matrix });+ }+ }+ return { width, height, z, tiles };+}++/**+ * Whether a tile laid by `matrix` overlaps the output. Two rectangles are apart+ * only along one of their own sides, so it is enough to look from each.+ */+function touches(matrix, size, width, height) {+ const square = [[0, 0], [size, 0], [0, size], [size, size]].map(([x, y]) => apply(matrix, x, y));+ if (!overlaps(square, width, height)) return false;+ const back = invert(matrix);+ const output = [[0, 0], [width, 0], [0, height], [width, height]].map(([x, y]) => apply(back, x, y));+ return overlaps(output, size, size);+}++function overlaps(points, width, height) {+ const xs = points.map(([x]) => x);+ const ys = points.map(([, y]) => y);+ return Math.max(...xs) > 0 && Math.min(...xs) < width && Math.max(...ys) > 0 && Math.min(...ys) < height;+}++/** Whether two pictures hold the same pixels: one Wayback release can repeat another. */+export function samePixels(first, second) {+ if (!first || !second || first.length !== second.length) return false;+ for (let index = 0; index < first.length; index += 1) {+ if (first[index] !== second[index]) return false;+ }+ return true;+}++/** How many columns a contact sheet of `count` pictures is laid in. */+export function sheetColumns(count) {+ return Math.max(1, Math.min(6, Math.ceil(Math.sqrt(count))));+}++/**+ * The output scale of one sheet cell: the sheet's width shared out, never finer+ * than the screen, and small enough that the whole sheet stays a PNG the plates+ * route takes (24 MB) when a tall frame stacks its rows.+ */+export function sheetCellScale(frame, count, density = 1, gap = 8) {+ const columns = sheetColumns(count);+ const rows = Math.ceil(Math.max(1, count) / columns);+ const width = Math.max(1, frame.width);+ const height = Math.max(1, frame.height);+ const byWidth = (SHEET_WIDTH - gap * (columns + 1)) / columns / width;+ const byArea = Math.sqrt(SHEET_PIXELS / (columns * rows * width * height));+ return Math.max(Number.EPSILON, Math.min(Math.max(1, density), byWidth, byArea));+}++/** Where each picture's day sits on a line from the first to the last, 0 to 1. */+export function timelinePositions(dates) {+ const times = dates.map((date) => Date.parse(`${String(date).slice(0, 10)}T00:00:00Z`));+ const known = times.filter(Number.isFinite);+ if (!known.length) return dates.map((_, index) => (dates.length > 1 ? index / (dates.length - 1) : 0));+ const first = Math.min(...known);+ const last = Math.max(...known);+ return times.map((time, index) => {+ if (!Number.isFinite(time)) return dates.length > 1 ? index / (dates.length - 1) : 0;+ return last > first ? (time - first) / (last - first) : 0;+ });+}diff --git a/frontend/src/lib/map/evolution.test.js b/frontend/src/lib/map/evolution.test.jsnew file mode 100644index 0000000..3bf7ad5--- /dev/null+++ b/frontend/src/lib/map/evolution.test.js@@ -0,0 +1,229 @@+import { describe, expect, it } from 'vitest';+import {+ GIF_EDGE,+ MAX_EVOLUTION_FRAMES,+ SHEET_PIXELS,+ allKeys,+ chosenEntries,+ defaultKeys,+ evolutionArchive,+ evolutionFrame,+ pickerMonth,+ pictureLabel,+ pictureScale,+ pictureTiles,+ playOrder,+ rangeKeys,+ samePixels,+ sheetCellScale,+ sheetColumns,+ sideEntry,+ spreadKeys,+ thinKeys,+ timelinePositions,+} from './evolution.js';+import { apply, invert, screenToMercator, scale, compose, toMercator } from './groundFrame.js';++const side = (provider, extra = {}) => ({ present: true, provider, ...extra });+const row = (key, date, extra = {}) => ({ key, date, usable: true, ...extra });++const ROWS = [+ row('2025-01-03', '2025-01-03', { cloud: 40 }),+ row('2025-01-20', '2025-01-20', { cloud: 5 }),+ row('2025-02-11', '2025-02-11', { cloud: 90, usable: false }),+ row('2025-03-02', '2025-03-02', { cloud: 12 }),+ row('2026-04-09', '2026-04-09', { cloud: 3 }),+];++describe('evolution archive', () => {+ it('plays an archive both sides share, and Wayback against World Imagery', () => {+ expect(evolutionArchive(side('sentinel2'), side('sentinel2'))).toBe('sentinel2');+ expect(evolutionArchive(side('esri-wayback'), side('esri-wayback'))).toBe('esri-wayback');+ expect(evolutionArchive(side('esri-wayback'), side('esri-world-imagery'))).toBe('esri-wayback');+ expect(evolutionArchive(side('esri-world-imagery'), side('esri-wayback'))).toBe('esri-wayback');+ });++ it('plays nothing on a pair with no shared history', () => {+ expect(evolutionArchive(side('sentinel1'), side('sentinel1'))).toBeNull();+ expect(evolutionArchive(side('esri-world-imagery'), side('esri-world-imagery'))).toBeNull();+ expect(evolutionArchive(side('sentinel2'), side('esri-wayback'))).toBeNull();+ expect(evolutionArchive(side('sentinel2'), { ...side('sentinel2'), present: false })).toBeNull();+ });++ it('reads World Imagery as the newest release, whatever release its side last held', () => {+ const rows = [row('r1', '2020-01-01', { release: 1 }), row('r2', '2024-01-01', { release: 2 })];+ expect(sideEntry(rows, 'esri-wayback', side('esri-world-imagery', { wayback_release: 1 }))).toBe(rows[1]);+ expect(sideEntry(rows, 'esri-wayback', side('esri-wayback', { wayback_release: 1 }))).toBe(rows[0]);+ expect(sideEntry(rows, 'esri-wayback', side('esri-wayback', { wayback_release: null }))).toBe(rows[1]);+ });++ it('reads a release that republished a picture as the release that first published it', () => {+ const rows = [+ row('r5', '2009-06-01', { release: 5, released: '2012-01-01', note: 'taken' }),+ row('r15', '2020-01-01', { release: 15, released: '2020-01-01' }),+ row('r30', '2026-09-01', { release: 30, released: '2026-09-01' }),+ ];+ const at = (day) => sideEntry(rows, 'esri-wayback', side('esri-wayback', { wayback_release: 20, wayback_date: day }));+ expect(at('2025-06-01')).toBe(rows[1]);+ expect(at('2020-01-01')).toBe(rows[1]);+ expect(at('2015-03-03')).toBe(rows[0]);+ expect(at('2011-01-01')).toBeNull();+ expect(at('')).toBeNull();+ });+});++describe('choosing the pictures', () => {+ it('opens on A to B, both ends in, a picture over the cloud ceiling left out', () => {+ expect(rangeKeys(ROWS, ROWS[3], ROWS[0])).toEqual(['2025-01-03', '2025-01-20', '2025-03-02']);+ // A side the list does not hold stands at its end.+ expect(rangeKeys(ROWS, null, ROWS[1])).toEqual(['2025-01-03', '2025-01-20']);+ expect(rangeKeys(ROWS, ROWS[3], null)).toEqual(['2025-03-02', '2026-04-09']);+ expect(defaultKeys(ROWS, ROWS[0], ROWS[3])).toEqual(['2025-01-03', '2025-01-20', '2025-03-02']);+ });++ it('opens on every usable picture when A and B show one', () => {+ expect(defaultKeys(ROWS, ROWS[1], ROWS[1])).toEqual(allKeys(ROWS));+ expect(allKeys(ROWS)).not.toContain('2025-02-11');+ });++ it('spreads a long list down to the most one export holds, both ends kept', () => {+ const keys = Array.from({ length: 100 }, (_, index) => `k${index}`);+ const spread = spreadKeys(keys);+ expect(spread).toHaveLength(MAX_EVOLUTION_FRAMES);+ expect(new Set(spread).size).toBe(MAX_EVOLUTION_FRAMES);+ expect([spread[0], spread.at(-1)]).toEqual(['k0', 'k99']);+ expect(spreadKeys(['a', 'b'])).toEqual(['a', 'b']);+ });++ it('keeps the clearest picture of each month or year', () => {+ const keys = ROWS.map((entry) => entry.key);+ expect(thinKeys(ROWS, keys, 'month')).toEqual(['2025-01-20', '2025-02-11', '2025-03-02', '2026-04-09']);+ expect(thinKeys(ROWS, keys, 'year')).toEqual(['2025-01-20', '2026-04-09']);+ // Wayback says nothing of cloud: the first of the month stands.+ const releases = [row('r1', '2024-05-01'), row('r2', '2024-05-20')];+ expect(thinKeys(releases, ['r1', 'r2'], 'month')).toEqual(['r1']);+ });++ it('plays the chosen rows by the day each was taken, however they were ticked', () => {+ expect(chosenEntries(ROWS, ['2026-04-09', '2025-01-03']).map((entry) => entry.key))+ .toEqual(['2025-01-03', '2026-04-09']);+ // A later Wayback release can carry an older picture.+ const releases = [row('r1', '2011-01-15'), row('r2', '2014-02-20'), row('r3', '2010-12-18')];+ expect(playOrder(releases).map((entry) => entry.key)).toEqual(['r3', 'r1', 'r2']);+ expect(chosenEntries(releases, ['r1', 'r3']).map((entry) => entry.key)).toEqual(['r3', 'r1']);+ });++ it('opens the Sentinel-2 picker on a month between 2015 and now', () => {+ expect(pickerMonth('2019-04', '2026-09')).toBe('2019-04');+ expect(pickerMonth('2011-01', '2026-09')).toBe('2015-06');+ expect(pickerMonth('2030-01', '2026-09')).toBe('2026-09');+ expect(pickerMonth('2019-13', '2026-09')).toBeNull();+ expect(pickerMonth('', '2026-09')).toBeNull();+ });++ it('dates a Wayback picture as Esri estimates it, or as its release', () => {+ expect(pictureLabel('esri-wayback', { date: '2023-07-02', note: 'taken' })).toBe('~2023-07-02');+ expect(pictureLabel('esri-wayback', { date: '2023-07-02', note: '' })).toBe('Release 2023-07-02');+ expect(pictureLabel('esri-wayback', { date: '', note: '' })).toBe('Release, undated');+ expect(pictureLabel('sentinel2', { date: '2023-07-02', note: '3% cloud' })).toBe('2023-07-02');+ });+});++describe('the ground of an evolution', () => {+ const VIEW = { lng: 2.35, lat: 48.85, zoom: 16, bearing: 0, width: 1200, height: 800 };++ it('is the view, with no export frame', () => {+ expect(evolutionFrame(VIEW, null)).toEqual(VIEW);+ });++ it('is the export frame at the view scale, upright as it was drawn, off screen or not', () => {+ const [x, y] = toMercator(2.35, 48.85);+ const perPixel = (2 * Math.PI * 6378137) / (512 * 2 ** 16);+ const [west, south] = [x - 150 * perPixel, y - 100 * perPixel];+ const [east, north] = [x + 150 * perPixel, y + 100 * perPixel];+ const back = (mx, my) => [(mx / 6378137) * (180 / Math.PI), (2 * Math.atan(Math.exp(my / 6378137)) - Math.PI / 2) * (180 / Math.PI)];+ const frame = evolutionFrame(VIEW, { points: [back(west, north), back(east, south)], angle: 30 });+ expect(frame.width).toBeGreaterThan(0);+ expect(frame.bearing).toBe(30);+ expect(frame.lng).toBeCloseTo(2.35, 6);+ expect(frame.lat).toBeCloseTo(48.85, 6);+ expect(frame.zoom).toBe(16);+ });++ it('is drawn at the screen density, held under the GIF edge', () => {+ expect(pictureScale({ width: 800, height: 600 }, GIF_EDGE, 1)).toBe(1);+ expect(pictureScale({ width: 800, height: 600 }, GIF_EDGE, 2)).toBe(1.6);+ expect(pictureScale({ width: 2560, height: 1400 }, GIF_EDGE, 1)).toBe(0.5);+ });++ it('shares a sheet out, and keeps a tall one under the pixels the plates route takes', () => {+ expect(sheetColumns(2)).toBe(2);+ expect(sheetColumns(12)).toBe(4);+ expect(sheetColumns(40)).toBe(6);+ const wide = { width: 1200, height: 800 };+ expect(sheetCellScale(wide, 4, 1)).toBeCloseTo((2400 - 24) / 2 / 1200, 6);+ const tall = { width: 400, height: 1400 };+ const cell = sheetCellScale(tall, 40, 2);+ const pixels = 6 * 7 * (400 * cell) * (1400 * cell);+ expect(pixels).toBeLessThanOrEqual(SHEET_PIXELS * 1.0001);+ });+});++describe('the tiles of a picture', () => {+ const PROVIDER = { tile_size: 256, max_zoom: 19 };+ const FRAME = { lng: 2.35, lat: 48.85, zoom: 16, bearing: 0, width: 600, height: 400 };++ it('asks about one tile pixel per output pixel, and lays each exactly on the ground', () => {+ const plan = pictureTiles(FRAME, PROVIDER, 1);+ // engine zoom 16 on 512 px tiles is XYZ 17 on 256 px ones+ expect(plan.z).toBe(17);+ expect([plan.width, plan.height]).toEqual([600, 400]);+ const toOutput = invert(compose(screenToMercator(FRAME), scale(1)));+ for (const tile of plan.tiles) {+ const span = (2 * Math.PI * 6378137) / 2 ** tile.z;+ const corner = [tile.x * span - Math.PI * 6378137, Math.PI * 6378137 - tile.y * span];+ const [ex, ey] = apply(toOutput, ...corner);+ const [gx, gy] = apply(tile.matrix, 0, 0);+ expect(gx).toBeCloseTo(ex, 6);+ expect(gy).toBeCloseTo(ey, 6);+ expect(tile.matrix.a).toBeCloseTo(1, 9);+ }+ // 600 × 400 output px of 256 px tiles: 3 or 4 across, 2 or 3 down+ expect(plan.tiles.length).toBeGreaterThanOrEqual(6);+ expect(plan.tiles.length).toBeLessThanOrEqual(12);+ });++ it('stops at the native level, where the proxy magnifies for free', () => {+ const plan = pictureTiles(FRAME, { tile_size: 512, max_zoom: 18, max_native_zoom: 14 }, 1);+ expect(plan.z).toBe(13);+ expect(plan.tiles.every((tile) => tile.size === 512)).toBe(true);+ });++ it('lists only the tiles a turned frame touches', () => {+ const upright = pictureTiles({ ...FRAME, width: 1200, height: 60 }, PROVIDER, 1);+ const turned = pictureTiles({ ...FRAME, width: 1200, height: 60, bearing: 45 }, PROVIDER, 1);+ const box = (Math.ceil((1200 + 60) / Math.SQRT2 / 256) + 1) ** 2;+ expect(turned.tiles.length).toBeLessThan(box);+ expect(upright.tiles.length).toBeLessThanOrEqual(8);+ });++ it('wraps a view counted past the date line', () => {+ const plan = pictureTiles({ ...FRAME, lng: 180.0001, lat: 0 }, PROVIDER, 1);+ const count = 2 ** plan.z;+ expect(plan.tiles.every((tile) => tile.x >= 0 && tile.x < count)).toBe(true);+ });+});++describe('telling pictures apart', () => {+ it('finds a repeated release by its pixels', () => {+ expect(samePixels(new Uint8ClampedArray([1, 2, 3]), new Uint8ClampedArray([1, 2, 3]))).toBe(true);+ expect(samePixels(new Uint8ClampedArray([1, 2, 3]), new Uint8ClampedArray([1, 2, 4]))).toBe(false);+ expect(samePixels(null, new Uint8ClampedArray([1]))).toBe(false);+ });++ it('places each picture on the line by its day', () => {+ expect(timelinePositions(['2020-01-01', '2020-01-11', '2020-01-21'])).toEqual([0, 0.5, 1]);+ expect(timelinePositions(['2020-01-01', '2020-01-01'])).toEqual([0, 0]);+ expect(timelinePositions(['', ''])).toEqual([0, 1]);+ });+});diff --git a/frontend/src/lib/map/evolutionExport.js b/frontend/src/lib/map/evolutionExport.jsnew file mode 100644index 0000000..ca4d6c8--- /dev/null+++ b/frontend/src/lib/map/evolutionExport.js@@ -0,0 +1,330 @@+/**+ * Drawing an evolution: each dated picture fetched from the tile proxy onto the+ * export's ground, then composed as a GIF frame or as one cell of a sheet.+ *+ * The choosing and the geometry are pure and live in `evolution.js`.+ */++import { drawAnnotations } from './compareAnnotations.js';+import {+ EXPORT_STYLE, captureProjection, drawScaleAndNorth, drawTag, signFooter, signatureRoom,+} from './compareExport.js';+import { compassAngle } from './groundFrame.js';+import { MAX_PICTURE_TILES, pictureTiles, samePixels, sheetColumns } from './evolution.js';+import { wrapLon } from '../coords.js';++const { INK, MUTED, BAND, ACCENT, FONT, MONO } = EXPORT_STYLE;+/** What shows where the archive has no pixels. */+const PAPER = '#14171d';+/** Tiles asked at once for one picture. */+const PARALLEL = 6;++const clamp = (value, min, max) => Math.min(max, Math.max(min, value));++function canvasOf(width, height, makeCanvas) {+ const canvas = makeCanvas ? makeCanvas() : document.createElement('canvas');+ canvas.width = Math.max(1, Math.round(width));+ canvas.height = Math.max(1, Math.round(height));+ return canvas;+}++function stopIfAborted(signal) {+ if (signal?.aborted) throw signal.reason ?? new DOMException('The export was cancelled', 'AbortError');+}++/**+ * One tile through the proxy. A 404 is ground the archive does not cover and+ * comes back as nothing; any other refusal (a paused quota, a key gone bad) ends+ * the export with the proxy's own sentence.+ */+export async function fetchTile(url, signal) {+ const response = await fetch(url, { signal });+ if (response.status === 404) return null;+ if (!response.ok) {+ let detail = '';+ try {+ detail = (await response.json()).detail;+ } catch {+ /* not JSON */+ }+ const error = new Error(typeof detail === 'string' && detail ? detail : `a tile answered HTTP ${response.status}`);+ error.status = response.status;+ throw error;+ }+ try {+ return await createImageBitmap(await response.blob());+ } catch {+ return null;+ }+}++/**+ * One picture of `frame`, drawn from `variant`'s tiles.+ *+ * Tiles are fetched a few at a time and painted in the plan's order once all are+ * in, so two releases holding the same pixels draw the same picture. Each tile is+ * grown by half an output pixel so a turned frame shows no seams.+ *+ * @returns {Promise<{ canvas, frame, empty: boolean }>} `empty` when no tile had imagery+ */+export async function drawPicture({+ frame, pixelScale, provider, variant, signal, loadTile = fetchTile, makeCanvas,+}) {+ const plan = pictureTiles(frame, provider, pixelScale);+ if (plan.tiles.length > MAX_PICTURE_TILES) {+ throw new Error('this frame needs too many tiles; zoom in or draw a smaller frame');+ }+ const images = new Array(plan.tiles.length).fill(null);+ let next = 0;+ let failed = null;+ const worker = async () => {+ while (next < plan.tiles.length && !failed) {+ const index = next;+ next += 1;+ const tile = plan.tiles[index];+ try {+ stopIfAborted(signal);+ images[index] = await loadTile(+ `/api/tiles/${encodeURIComponent(variant)}/${tile.z}/${tile.x}/${tile.y}`,+ signal,+ );+ } catch (error) {+ failed ??= error;+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(PARALLEL, plan.tiles.length) }, worker));+ if (failed) {+ images.forEach((image) => image?.close?.());+ throw failed;+ }++ const canvas = canvasOf(plan.width, plan.height, makeCanvas);+ const ctx = canvas.getContext('2d');+ if (!ctx) throw new Error('this browser cannot draw the evolution');+ ctx.fillStyle = PAPER;+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.imageSmoothingQuality = 'high';+ let drawn = 0;+ plan.tiles.forEach((tile, index) => {+ const image = images[index];+ if (!image) return;+ const m = tile.matrix;+ const pad = 0.5 / Math.max(1e-6, Math.hypot(m.a, m.b));+ ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);+ ctx.drawImage(image, 0, 0, image.width, image.height, -pad, -pad, tile.size + pad * 2, tile.size + pad * 2);+ image.close?.();+ drawn += 1;+ });+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ return { canvas, frame: { ...frame }, empty: drawn === 0 };+}++/** A picture's pixels, to tell a repeated release; null where the canvas cannot say. */+function pixelsOf(canvas) {+ try {+ return canvas.getContext('2d')?.getImageData?.(0, 0, canvas.width, canvas.height)?.data ?? null;+ } catch {+ return null;+ }+}++/**+ * Draw every chosen picture in order and hand each over as it is done, so a GIF+ * frame can be encoded and its picture let go before the next is fetched.+ *+ * A picture with no imagery at all, or with exactly the pixels of the one before+ * it, is left out and counted, never dropped without a word.+ *+ * @returns {Promise<{ drawn: number, empty: number, repeated: number }>}+ */+export async function drawPictures({+ entries, frame, pixelScale, provider, variantFor, signal, onprogress, onpicture, loadTile, makeCanvas,+}) {+ let previous = null;+ const tally = { drawn: 0, empty: 0, repeated: 0 };+ for (const [index, entry] of entries.entries()) {+ stopIfAborted(signal);+ onprogress?.(index, entries.length);+ const picture = await drawPicture({+ frame, pixelScale, provider, variant: variantFor(entry), signal, loadTile, makeCanvas,+ });+ if (picture.empty) {+ tally.empty += 1;+ continue;+ }+ const pixels = pixelsOf(picture.canvas);+ if (samePixels(previous, pixels)) {+ tally.repeated += 1;+ continue;+ }+ previous = pixels;+ await onpicture({ entry, picture, index });+ tally.drawn += 1;+ }+ onprogress?.(entries.length, entries.length);+ return tally;+}++/** Marks drawn on both sides stand on every picture; a mark pinned to A or B does not. */+const sharedMarks = (annotations) => (annotations ?? []).filter((mark) => mark?.side === 'both');++function drawMarks(ctx, picture, annotations, x, y, units) {+ const marks = sharedMarks(annotations);+ if (!marks.length) return;+ const pixelScale = picture.canvas.width / picture.frame.width;+ ctx.save();+ ctx.beginPath();+ ctx.rect(x, y, picture.canvas.width, picture.canvas.height);+ ctx.clip();+ drawAnnotations(ctx, marks, captureProjection(picture, x, y), { scale: pixelScale, units });+ ctx.restore();+}++function header(ctx, { title, line, right, width, scale }) {+ const left = 16 * scale;+ let offset = 0;+ if (title) {+ ctx.fillStyle = INK;+ ctx.font = `700 ${Math.round(17 * scale)}px ${FONT}`;+ ctx.fillText(title, left, 25 * scale, width * 0.6);+ offset = 20 * scale;+ }+ ctx.fillStyle = INK;+ ctx.font = `600 ${Math.round(12 * scale)}px ${FONT}`;+ ctx.fillText(line, left, 24 * scale + offset, width * 0.62);+ if (right) {+ ctx.font = `${Math.round(11 * scale)}px ${MONO}`;+ const measured = ctx.measureText(right).width;+ const taken = left + Math.min(ctx.measureText(line).width, width * 0.62);+ if (width - measured - 16 * scale > taken + 12 * scale) {+ ctx.fillStyle = MUTED;+ ctx.fillText(right, width - measured - 16 * scale, (title ? 25 : 24) * scale);+ }+ }+}++function credits(ctx, text, y, width, scale, signed) {+ const room = signed && signFooter(ctx, width - 14 * scale, y - 4 * scale, scale) ? signatureRoom(scale) : 0;+ ctx.fillStyle = MUTED;+ ctx.font = `${Math.round(10 * scale)}px ${FONT}`;+ ctx.fillText(text, 16 * scale, y, Math.max(0, width - 32 * scale - room));+}++const whereLine = (frame) => {+ const lat = Number(frame.lat);+ const lon = wrapLon(Number(frame.lng));+ return Number.isFinite(lat) && Number.isFinite(lon) ? `${lat.toFixed(5)}, ${lon.toFixed(5)}` : '';+};++/**+ * One frame of an evolution GIF: the picture under a header naming the series,+ * its date large on the imagery, and a line along the footer placing it among+ * the others by date.+ *+ * @param {object} input+ * @param {{canvas, frame}} input.picture+ * @param {number} input.current index of this picture among `positions`+ * @param {number[]} input.positions each chosen picture's place on the line, 0 to 1+ */+export function composeEvolutionFrame({+ picture, title = '', label, date, current, positions, attribution = '', annotations = [],+ units = 'metric', signed = false, makeCanvas,+}) {+ const width = picture.canvas.width;+ const s = clamp(width / 1000, 1, 2);+ const pixelScale = width / picture.frame.width;+ const top = Math.round((title ? 64 : 48) * s);+ const footer = Math.round(46 * s);+ const bottom = top + picture.canvas.height;+ const output = canvasOf(width, bottom + footer, makeCanvas);+ const ctx = output.getContext('2d');+ if (!ctx) throw new Error('this browser cannot compose the evolution');+ ctx.fillStyle = BAND;+ ctx.fillRect(0, 0, output.width, output.height);+ ctx.drawImage(picture.canvas, 0, top);+ drawMarks(ctx, picture, annotations, 0, top, units);+ drawTag(ctx, date, 12 * s, top + 12 * s, { scale: 1.4 * s, accent: true });+ drawScaleAndNorth(ctx, picture.frame, 12 * s, bottom - 12 * s, {+ scale: s, pixelScale, bearing: compassAngle(-picture.frame.bearing), units,+ });+ header(ctx, {+ title,+ line: `${label} · ${positions.length} pictures`,+ right: whereLine(picture.frame),+ width,+ scale: s,+ });++ // The line of dates: every chosen picture a tick, this one lit.+ const from = 16 * s;+ const to = width - 16 * s;+ const y = bottom + 14 * s;+ ctx.fillStyle = MUTED;+ ctx.fillRect(from, y - 0.75 * s, to - from, 1.5 * s);+ positions.forEach((position, index) => {+ if (index === current) return;+ ctx.fillRect(from + position * (to - from) - s, y - 4 * s, 2 * s, 8 * s);+ });+ const lit = positions[current];+ if (Number.isFinite(lit)) {+ ctx.fillStyle = ACCENT;+ ctx.fillRect(from + lit * (to - from) - 2 * s, y - 7 * s, 4 * s, 14 * s);+ }+ credits(ctx, attribution || label, output.height - 9 * s, width, s, signed);+ return output;+}++/**+ * The pictures of an evolution side by side on one page, oldest first, reading+ * left to right then down. One scale bar serves them all, since every cell+ * covers the same ground at the same scale.+ *+ * @param {object} input+ * @param {Array<{ picture: {canvas, frame}, date: string }>} input.cells+ */+export function composeEvolutionSheet({+ cells, title = '', label, span = '', attribution = '', annotations = [], units = 'metric',+ signed = false, makeCanvas,+}) {+ if (!cells.length) throw new Error('an evolution sheet needs its pictures');+ const columns = sheetColumns(cells.length);+ const rows = Math.ceil(cells.length / columns);+ const cellWidth = Math.max(...cells.map((cell) => cell.picture.canvas.width));+ const cellHeight = Math.max(...cells.map((cell) => cell.picture.canvas.height));+ const gap = 8;+ const width = columns * cellWidth + (columns + 1) * gap;+ const s = clamp(width / 1400, 1, 2);+ const top = Math.round((title ? 64 : 48) * s);+ const footer = Math.round(26 * s);+ const height = top + rows * cellHeight + (rows + 1) * gap + footer;+ const output = canvasOf(width, height, makeCanvas);+ const ctx = output.getContext('2d');+ if (!ctx) throw new Error('this browser cannot compose the evolution');+ ctx.fillStyle = BAND;+ ctx.fillRect(0, 0, output.width, output.height);+ const tagScale = clamp(cellWidth / 420, 0.8, 1.6);+ cells.forEach(({ picture, date }, index) => {+ const x = gap + (index % columns) * (cellWidth + gap);+ const y = top + gap + Math.floor(index / columns) * (cellHeight + gap);+ ctx.drawImage(picture.canvas, x, y);+ drawMarks(ctx, picture, annotations, x, y, units);+ drawTag(ctx, date, x + 8 * tagScale, y + 8 * tagScale, { scale: tagScale, accent: true });+ });+ const first = cells[0].picture;+ drawScaleAndNorth(ctx, first.frame, gap + 8 * tagScale, top + gap + first.canvas.height - 8 * tagScale, {+ scale: tagScale,+ pixelScale: first.canvas.width / first.frame.width,+ bearing: compassAngle(-first.frame.bearing),+ units,+ });+ header(ctx, {+ title,+ line: [label, `${cells.length} pictures`, span].filter(Boolean).join(' · '),+ right: whereLine(first.frame),+ width,+ scale: s,+ });+ credits(ctx, attribution || label, output.height - 9 * s, width, s, signed);+ return output;+}diff --git a/frontend/src/lib/map/evolutionExport.test.js b/frontend/src/lib/map/evolutionExport.test.jsnew file mode 100644index 0000000..bf391f6--- /dev/null+++ b/frontend/src/lib/map/evolutionExport.test.js@@ -0,0 +1,199 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ composeEvolutionFrame, composeEvolutionSheet, drawPicture, drawPictures, fetchTile,+} from './evolutionExport.js';++const PROVIDER = { tile_size: 256, max_zoom: 19 };+const FRAME = { lng: 2.35, lat: 48.85, zoom: 16, bearing: 0, width: 600, height: 400 };++/** A canvas whose context records what is drawn, and can say what its pixels are. */+function fakeCanvas(pixels = () => null) {+ const calls = [];+ const record = (name) => (...args) => calls.push([name, ...args]);+ const canvas = { width: 0, height: 0, calls };+ const context = {+ calls,+ measureText: (text) => ({ width: String(text).length * 6 }),+ getImageData: () => ({ data: pixels(canvas) }),+ };+ for (const name of [+ 'fillRect', 'drawImage', 'fillText', 'save', 'restore', 'beginPath', 'rect', 'roundRect', 'clip',+ 'fill', 'stroke', 'moveTo', 'lineTo', 'closePath', 'translate', 'rotate', 'scale', 'transform',+ 'setTransform', 'setLineDash', 'arcTo', 'arc',+ ]) {+ context[name] = record(name);+ }+ canvas.getContext = () => context;+ return canvas;+}++const tileImage = () => ({ width: 256, height: 256, close: vi.fn() });++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('drawing one picture', () => {+ it('asks the proxy for each tile of the variant and paints them in the plan order', async () => {+ const urls = [];+ const loadTile = vi.fn(async (url) => {+ urls.push(url);+ return tileImage();+ });+ const picture = await drawPicture({+ frame: FRAME, pixelScale: 1, provider: PROVIDER, variant: 'esri-wayback~20', loadTile, makeCanvas: () => fakeCanvas(),+ });+ expect(picture.empty).toBe(false);+ expect([picture.canvas.width, picture.canvas.height]).toEqual([600, 400]);+ expect(urls.every((url) => url.startsWith('/api/tiles/esri-wayback~20/17/'))).toBe(true);+ const painted = picture.canvas.calls.filter(([name]) => name === 'drawImage');+ expect(painted).toHaveLength(urls.length);+ // Each tile is grown by half an output pixel on every side.+ expect(painted[0].slice(6)).toEqual([-0.5, -0.5, 257, 257].map((value) => expect.closeTo(value, 6)));+ });++ it('leaves ground the archive does not cover dark, and says when none was covered', async () => {+ const picture = await drawPicture({+ frame: FRAME, pixelScale: 1, provider: PROVIDER, variant: 'sentinel2', loadTile: async () => null,+ makeCanvas: () => fakeCanvas(),+ });+ expect(picture.empty).toBe(true);+ });++ it('ends on the proxy refusing, with its own sentence', async () => {+ const refusal = new Error('Copernicus is paused');+ const loadTile = vi.fn(async (url) => {+ if (url.endsWith('/0') || loadTile.mock.calls.length > 2) throw refusal;+ return tileImage();+ });+ await expect(drawPicture({+ frame: FRAME, pixelScale: 1, provider: PROVIDER, variant: 'sentinel2', loadTile, makeCanvas: () => fakeCanvas(),+ })).rejects.toBe(refusal);+ });++ it('refuses a frame that would take too many tiles', async () => {+ await expect(drawPicture({+ frame: { ...FRAME, width: 5000, height: 5000 }, pixelScale: 1, provider: PROVIDER, variant: 'x',+ loadTile: async () => tileImage(), makeCanvas: () => fakeCanvas(),+ })).rejects.toThrow('too many tiles');+ });+});++describe('drawing the pictures', () => {+ const ENTRIES = ['a', 'b', 'c', 'd'].map((key) => ({ key, date: '2024-01-01' }));+ // The picture being drawn, so a stand-in canvas knows which pixels to report.+ let current = null;++ it('leaves out a picture with no imagery and one repeating the one before, and counts both', async () => {+ const shown = { a: 1, b: null, c: 1, d: 2 };+ const seen = [];+ const tally = await drawPictures({+ entries: ENTRIES,+ frame: { ...FRAME, width: 256, height: 256 },+ pixelScale: 1,+ provider: PROVIDER,+ variantFor: (entry) => entry.key,+ loadTile: async (url) => (shown[url.split('/')[3]] === null ? null : tileImage()),+ makeCanvas: () => {+ const canvas = fakeCanvas(() => new Uint8ClampedArray([shown[current]]));+ return canvas;+ },+ onprogress: (done) => (current = ENTRIES[done]?.key),+ onpicture: async ({ entry, index }) => seen.push([entry.key, index]),+ });+ expect(seen).toEqual([['a', 0], ['d', 3]]);+ expect(tally).toEqual({ drawn: 2, empty: 1, repeated: 1 });+ });++ it('stops between two pictures once cancelled', async () => {+ const controller = new AbortController();+ const onpicture = vi.fn(async () => controller.abort());+ await expect(drawPictures({+ entries: ENTRIES, frame: FRAME, pixelScale: 1, provider: PROVIDER, variantFor: () => 'x',+ signal: controller.signal, loadTile: async () => tileImage(), makeCanvas: () => fakeCanvas(), onpicture,+ })).rejects.toMatchObject({ name: 'AbortError' });+ expect(onpicture).toHaveBeenCalledTimes(1);+ });+});++describe('fetching a tile', () => {+ it('reads a 404 as ground with no imagery', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response('', { status: 404 })));+ expect(await fetchTile('/api/tiles/x/1/0/0')).toBeNull();+ });++ it('passes a refusal on in the proxy’s words', async () => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ detail: 'Sentinel-2 is paused' }), { status: 429 })));+ await expect(fetchTile('/api/tiles/x/1/0/0')).rejects.toMatchObject({ message: 'Sentinel-2 is paused', status: 429 });+ });+});++describe('composing', () => {+ const picture = () => {+ const canvas = fakeCanvas();+ canvas.width = 1200;+ canvas.height = 800;+ return { canvas, frame: { ...FRAME, width: 1200, height: 800 } };+ };+ const texts = (out) => out.calls.filter(([name]) => name === 'fillText').map(([, text]) => text);++ it('dates a frame on the imagery, places it on the line of dates, and credits the archive', () => {+ const out = composeEvolutionFrame({+ picture: picture(), title: 'Harbour', label: 'Esri Wayback', date: '~2021-05-02', current: 1,+ positions: [0, 0.5, 1], attribution: 'Esri, Maxar', makeCanvas: () => fakeCanvas(),+ });+ const s = 1.2;+ expect(out.width).toBe(1200);+ expect(out.height).toBe(Math.round(64 * s) + 800 + Math.round(46 * s));+ expect(texts(out)).toEqual(expect.arrayContaining(['~2021-05-02', 'Harbour', 'Esri Wayback · 3 pictures', 'Esri, Maxar']));+ // two quiet ticks and a lit one+ const ticks = out.calls.filter(([name, , , w, h]) => name === 'fillRect' && h >= 8 * s && w <= 4 * s);+ expect(ticks).toHaveLength(3);+ });++ it('only draws the marks set on both sides', () => {+ const mark = (id, side) => ({ id, side, kind: 'rect', colour: '#ef4444', points: [[2.349, 48.849], [2.351, 48.851]] });+ const out = composeEvolutionFrame({+ picture: picture(), label: 'Sentinel-2', date: '2024-01-01', current: 0, positions: [0, 1],+ annotations: [mark('shared', 'both'), mark('before', 'a')], makeCanvas: () => fakeCanvas(),+ });+ const outlines = out.calls.filter(([name]) => name === 'stroke');+ expect(outlines.length).toBeGreaterThan(0);+ const alone = composeEvolutionFrame({+ picture: picture(), label: 'Sentinel-2', date: '2024-01-01', current: 0, positions: [0, 1],+ annotations: [mark('before', 'a')], makeCanvas: () => fakeCanvas(),+ });+ expect(alone.calls.filter(([name]) => name === 'stroke').length).toBeLessThan(outlines.length);+ });++ it('signs the credits line when asked', () => {+ const paths = [];+ vi.stubGlobal('Path2D', class { constructor(d) { paths.push(d); } });+ const input = {+ picture: picture(), label: 'Sentinel-2', date: '2024-01-01', current: 0, positions: [0, 1],+ makeCanvas: () => fakeCanvas(),+ };+ composeEvolutionFrame({ ...input, signed: false });+ expect(paths).toHaveLength(0);+ composeEvolutionFrame({ ...input, signed: true });+ expect(paths).toHaveLength(9); // two flanks, seven letter strokes+ });++ it('lays a sheet out in rows, oldest first, with one date per cell', () => {+ const cells = ['2020', '2021', '2022', '2023', '2024'].map((year) => {+ const canvas = fakeCanvas();+ canvas.width = 400;+ canvas.height = 300;+ return { picture: { canvas, frame: { ...FRAME, width: 400, height: 300 } }, date: `${year}-06-01` };+ });+ const out = composeEvolutionSheet({ cells, label: 'Sentinel-2', span: '2020-06-01 to 2024-06-01', makeCanvas: () => fakeCanvas() });+ // five pictures in three columns, two rows+ expect(out.width).toBe(3 * 400 + 4 * 8);+ expect(out.height).toBe(48 + 2 * 300 + 3 * 8 + 26);+ const placed = out.calls.filter(([name]) => name === 'drawImage').map(([, , x, y]) => [x, y]);+ expect(placed).toEqual([[8, 56], [416, 56], [824, 56], [8, 364], [416, 364]]);+ expect(texts(out)).toEqual(expect.arrayContaining([+ '2020-06-01', '2024-06-01', 'Sentinel-2 · 5 pictures · 2020-06-01 to 2024-06-01',+ ]));+ });+});diff --git a/frontend/src/lib/map/layerCard.js b/frontend/src/lib/map/layerCard.jsindex e5d81fc..1886497 100644--- a/frontend/src/lib/map/layerCard.js+++ b/frontend/src/lib/map/layerCard.js@@ -1,10 +1,11 @@/*** The card a feature of an added layer opens.*- * Read-only by construction: it is built from the strings the source stated and- * offers no control at all. Nothing in an added layer enters the case.+ * Read-only by construction: it is built from the strings the source stated,+ * and its one control copies the feature's point. Nothing in an added layer+ * enters the case.*- * Two things it does beyond printing the description:+ * Three things it does beyond printing the description:** - **A labelled line is drawn as a labelled line.** A My Maps carries its* columns as `label: value`, and the backend now keeps one row per line@@ -18,7 +19,13 @@* HTML anywhere: the text belongs to whoever made the file, so it only ever* reaches the page as `textContent`, and a link's address is checked to be* http(s) before it becomes one.+ * - **A point states where it is.** The source's own coordinates, in the+ * analyst's format, copied in one click. A right-click on the pin used to be+ * the only way to them, and it read the ground under the pin's head rather+ * than the point the pin names.*/+import { paths } from '../../components/Icon.svelte';+import { formatCoords } from '../coords.js';import { UNNAMED } from './addedLayers.js';/** Where a URL starts, and how far it runs: to the first space or quote. */@@ -98,16 +105,38 @@ export function fillText(element, text) {return element;}+/** The copy glyph, built as DOM for the same reason the text is. */+function copyGlyph() {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ svg.setAttribute('viewBox', '0 0 24 24');+ svg.setAttribute('width', '11');+ svg.setAttribute('height', '11');+ svg.setAttribute('fill', 'none');+ svg.setAttribute('stroke', 'currentColor');+ svg.setAttribute('stroke-width', '2');+ svg.setAttribute('aria-hidden', 'true');+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');+ path.setAttribute('d', paths.copy);+ svg.append(path);+ return svg;+}+/*** The card builder for one layer, which is why the layer's title is bound here:* with three maps over the imagery at once, a card stating a name and a group* says nothing about *whose* map said it. The layer signs the bottom of it.** @param {string} title- * @returns {(properties: Record<string, any>) => HTMLElement}+ * @param {object} [opts]+ * @param {(lat: number, lon: number) => string} [opts.coords] the point as the+ * analyst writes coordinates; read when the card opens, so a format changed+ * in Settings is the one the next card uses+ * @param {(text: string) => void} [opts.copy] what pressing the coordinates+ * does. Absent, they are text.+ * @returns {(properties: Record<string, any>, point?: { lat: number, lon: number } | null) => HTMLElement}*/-export function layerCard(title) {- return (properties = {}) => {+export function layerCard(title, { coords = formatCoords, copy = null } = {}) {+ return (properties = {}, point = null) => {const element = document.createElement('div');element.className = 'layer-card';@@ -122,6 +151,23 @@ export function layerCard(title) {element.append(group);}+ // A line or an area has no one point, so it states none.+ const text = point ? coords(point.lat, point.lon) : '';+ if (text) {+ const where = document.createElement(copy ? 'button' : 'p');+ where.className = 'layer-card-where mono';+ const value = document.createElement('span');+ value.textContent = text;+ where.append(value);+ if (copy) {+ where.type = 'button';+ where.title = 'Copy coordinates';+ where.append(copyGlyph());+ where.addEventListener('click', () => copy(text));+ }+ element.append(where);+ }+const blocks = readBlocks(properties.description);if (blocks.length) {const body = document.createElement('div');diff --git a/frontend/src/lib/map/layerCard.test.js b/frontend/src/lib/map/layerCard.test.jsindex af8b635..dc8858f 100644--- a/frontend/src/lib/map/layerCard.test.js+++ b/frontend/src/lib/map/layerCard.test.js@@ -1,5 +1,5 @@// @vitest-environment happy-dom-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import { readBlocks, readLinks, fillText, layerCard } from './layerCard.js';describe('readBlocks', () => {@@ -110,3 +110,39 @@ describe('layerCard', () => {expect(element.querySelector('input')).toBeNull();});});++describe("a pin's point on its card", () => {+ const POINT = { lat: 48.8584, lon: 2.2945 };++ it('states where the pin stands, in the format it is given', () => {+ const coords = vi.fn(() => '48°51′30″N 2°17′40″E');+ const element = layerCard('Paris', { coords })({ name: 'Tower' }, POINT);++ expect(coords).toHaveBeenCalledWith(48.8584, 2.2945);+ expect(element.querySelector('.layer-card-where').textContent).toBe('48°51′30″N 2°17′40″E');+ });++ it('writes decimal degrees when no format was given', () => {+ const element = layerCard('Paris')({ name: 'Tower' }, POINT);+ expect(element.querySelector('.layer-card-where').textContent).toBe('48.858400, 2.294500');+ });++ it('copies those coordinates, and that is the only control it has', () => {+ const copy = vi.fn();+ const element = layerCard('Paris', { copy })({ name: 'Tower', description: 'code: UA' }, POINT);+ const buttons = element.querySelectorAll('button');++ expect(buttons).toHaveLength(1);+ expect(buttons[0].title).toBe('Copy coordinates');+ buttons[0].click();+ expect(copy).toHaveBeenCalledWith(element.querySelector('.layer-card-where span').textContent);+ // still nothing that files, confirms or saves+ expect(element.querySelector('input, form')).toBeNull();+ });++ it('states no point for a line or an area, which has no one point', () => {+ const element = layerCard('Paris', { copy: vi.fn() })({ name: 'District' }, null);+ expect(element.querySelector('.layer-card-where')).toBeNull();+ expect(element.querySelector('button')).toBeNull();+ });+});diff --git a/frontend/src/lib/map/passStrip.js b/frontend/src/lib/map/passStrip.jsindex 6c44f14..bd35c86 100644--- a/frontend/src/lib/map/passStrip.js+++ b/frontend/src/lib/map/passStrip.js@@ -89,6 +89,8 @@ export function stripEntries(archive, answer, { maxcc = 100, track = '' } = {})date: entry.acquired || entry.date || '',note: entry.acquired ? 'taken' : '',release: entry.release,+ // when the release was published, which dates a picture with no acquisition date+ released: entry.date || '',usable: true,})).reverse();diff --git a/frontend/src/tools/Compare.render.test.js b/frontend/src/tools/Compare.render.test.jsindex 97cdb7c..01fbaf9 100644--- a/frontend/src/tools/Compare.render.test.js+++ b/frontend/src/tools/Compare.render.test.js@@ -65,6 +65,9 @@ const ANALYZERS = {// Newest first. Empty by default, so the opening pair has no "then" to show.let releases = [];+// The releases that first published a picture of the point, newest first; the+// release list stands in when a test sets none.+let changes = null;const get = vi.fn(async (path) => {if (path === '/api/compare/analyzers') return structuredClone(ANALYZERS);if (path.startsWith('/api/cases/case-a/analysis/')) return [];@@ -82,6 +85,7 @@ const get = vi.fn(async (path) => {if (path.includes('/satellite/index')) return [];if (path.includes('/imagery-date')) return { supported: true, date: '2024-01-02' };if (path === '/api/satellite/wayback/releases') return { releases: structuredClone(releases) };+ if (path.startsWith('/api/satellite/wayback/changes')) return { changes: structuredClone(changes ?? releases) };if (path === '/api/cases/case-a/compare/sessions') {return [{ name: 'Harbour change', title: 'Harbour change', provider_a: 'esri-world-imagery', provider_b: 'esri-wayback', mode: 'swipe' },@@ -183,6 +187,21 @@ vi.mock('../lib/map/basemap.js', () => ({})),}));+// An evolution's pictures come from the tile proxy; here each one is a stand-in+// canvas, so the dialog's choices and the request it posts can be read.+const pictureCanvas = () => ({ width: 400, height: 300, toBlob: (done) => done(new Blob(['png'])) });+const drawPictures = vi.fn(async ({ entries, variantFor, onpicture, onprogress }) => {+ for (const [index, entry] of entries.entries()) {+ onprogress?.(index, entries.length);+ variantFor(entry);+ await onpicture({ entry, index, picture: { canvas: pictureCanvas(), frame: {} } });+ }+ return { drawn: entries.length, empty: 0, repeated: 0 };+});+const composeEvolutionFrame = vi.fn(() => pictureCanvas());+const composeEvolutionSheet = vi.fn(() => pictureCanvas());+vi.mock('../lib/map/evolutionExport.js', () => ({ drawPictures, composeEvolutionFrame, composeEvolutionSheet }));+const { default: Compare } = await import('./Compare.svelte');let live;@@ -243,6 +262,7 @@ beforeEach(() => {vi.clearAllMocks();engines.length = 0;releases = [];+ changes = null;uiState.tool = 'compare';uiState.openCompare = null;uiState.compareAt = null;@@ -541,11 +561,110 @@ describe('Compare', () => {'PNG','GIF · Blink','GIF · Slide',+ 'GIF · Evolution',+ 'PNG · Evolution sheet',]);+ // World Imagery on both sides has no history to play.+ expect([...output.querySelectorAll('input[value="evolution"], input[value="sheet"]')]+ .map((input) => input.disabled)).toEqual([true, true]);+ expect(output.textContent).toContain('Needs Sentinel-2 or Wayback on both sides');+ const sign = [...output.querySelectorAll('.keep-choice')].find((entry) => entry.textContent.includes('Sign it Azimut'));+ expect(sign.querySelector('input').checked).toBe(true);expect(output.textContent).not.toContain('Save to this case');expect(output.textContent).toContain('Export copy');});+ async function openThenAndNow() {+ releases = [+ { release: 30, date: '2026-09-01' },+ { release: 20, date: '2025-06-01' },+ { release: 10, date: '2014-02-20' },+ ];+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-23T12:00:00Z'));+ try {+ await openFresh();+ } finally {+ vi.useRealTimers();+ }+ button('Export', target).click();+ await settle();+ return document.querySelector('[role="dialog"]');+ }++ it('plays the Wayback pictures from A to B as one GIF, each shown as it will play', async () => {+ // A shows the 2025 release, which republished the 2020 picture; the newest+ // release carries an older one than 2020's, so the GIF plays it first.+ changes = [+ { release: 30, date: '2026-09-01', acquired: '2018-05-05' },+ { release: 15, date: '2020-01-01', acquired: '2019-03-02' },+ { release: 5, date: '2010-01-01' },+ ];+ const dialog = await openThenAndNow();+ // The export dialog alone reads nothing of the point's history.+ expect(get.mock.calls.some(([path]) => path.includes('/wayback/changes'))).toBe(false);+ const choice = dialog.querySelector('input[value="evolution"]');+ expect(choice.disabled).toBe(false);+ choice.click();+ await settle();+ expect(get.mock.calls.filter(([path]) => path.includes('/wayback/changes'))).toHaveLength(1);+ expect(dialog.textContent).toContain('An evolution is written out only');+ expect(dialog.textContent).not.toContain('Also keep it in this case');+ const rows = [...dialog.querySelectorAll('.cards li')];+ expect(rows.map((row) => row.querySelector('.mono').textContent)).toEqual([+ 'Release 2010-01-01', '~2018-05-05', '~2019-03-02',+ ]);+ expect(rows.map((row) => row.querySelector('small')?.textContent ?? '')).toEqual([+ '', 'release 2026-09-01', 'release 2020-01-01',+ ]);+ // A to B: the 2020 picture A shows and the newest B shows, not the 2010 one.+ expect(rows.map((row) => row.querySelector('input').checked)).toEqual([false, true, true]);+ expect(rows.map((row) => [...row.querySelectorAll('.tag')].map((tag) => tag.textContent).join(''))).toEqual(['', 'B', 'A']);+ // Each row shows its picture, drawn from its own release.+ expect(rows[0].querySelector('.thumb img').getAttribute('src')).toMatch(/^\/api\/tiles\/esri-wayback~5\//);+ button('All', dialog.querySelector('.presets')).click();+ flushSync();+ expect(dialog.textContent).toContain('3 chosen');+ button('A to B', dialog.querySelector('.presets')).click();+ flushSync();+ expect(dialog.textContent).toContain('2 chosen');++ button('Export copy', dialog).click();+ await settle();+ const asked = drawPictures.mock.calls[0][0];+ expect(asked.entries.map((entry) => entry.release)).toEqual([30, 15]);+ expect(asked.variantFor(asked.entries[0])).toBe('esri-wayback~30');+ expect(composeEvolutionFrame.mock.calls.map(([input]) => [input.date, input.current, input.signed])).toEqual([+ ['~2018-05-05', 0, true], ['~2019-03-02', 1, true],+ ]);+ const [, form] = post.mock.calls.find(([path]) => path === '/api/cases/case-a/compare/sequence');+ expect(form.getAll('frames')).toHaveLength(2);+ expect(form.get('interval')).toBe('800');+ expect(form.get('filename')).toContain('2018-05-05_2019-03-02');+ expect(form.get('keep').split(',')).toEqual(expect.arrayContaining(['#e8a33d', '#e3e3e3']));+ expect(toast).toHaveBeenCalledWith(expect.stringContaining('written to'), 'ok', expect.any(Number), expect.any(Object));+ });++ it('lays an evolution out as one sheet, unsigned when asked', async () => {+ const dialog = await openThenAndNow();+ dialog.querySelector('input[value="sheet"]').click();+ await settle();+ button('All', dialog.querySelector('.presets')).click();+ flushSync();+ const sign = [...dialog.querySelectorAll('.keep-choice')].find((entry) => entry.textContent.includes('Sign it Azimut'));+ sign.querySelector('input').click();+ flushSync();+ button('Export copy', dialog).click();+ await settle();+ const [input] = composeEvolutionSheet.mock.calls[0];+ expect(input.cells.map((cell) => cell.date)).toEqual(['Release 2014-02-20', 'Release 2025-06-01', 'Release 2026-09-01']);+ expect(input.signed).toBe(false);+ expect(input.span).toBe('2014-02-20 to 2026-09-01');+ const [, body] = post.mock.calls.find(([path]) => path === '/api/cases/case-a/plates');+ expect(body).toMatchObject({ format: 'png', overwrite: false });+ expect(body.filename).toMatch(/2014-02-20_2026-09-01 evolution$/);+ });+it('frames an export on the ground and keeps the frame with the comparison', async () => {await open();await add('A');diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelteindex 83fc6c0..411f92e 100644--- a/frontend/src/tools/Compare.svelte+++ b/frontend/src/tools/Compare.svelte@@ -22,6 +22,7 @@import { saveRelation } from '../lib/relations.svelte.js';import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';import { openMapAt } from '../lib/navigate.js';+ import { wrapLon } from '../lib/coords.js';import {COMPARE_LAYERS,COMPARE_MODES,@@ -42,8 +43,22 @@canvasBlob,comparisonFilename,composeComparison,+ gifColours,pictureDateFields,} from '../lib/map/compareExport.js';+ import {+ DEFAULT_INTERVAL,+ GIF_EDGE,+ MAX_EVOLUTION_FRAMES,+ evolutionArchive,+ evolutionFrame,+ pictureLabel,+ pictureScale,+ pictureTiles,+ sheetCellScale,+ timelinePositions,+ } from '../lib/map/evolution.js';+ import { composeEvolutionFrame, composeEvolutionSheet, drawPictures } from '../lib/map/evolutionExport.js';import {changeCompatibility,changeNeedsFrames,@@ -94,6 +109,7 @@import DifferenceBar from './compare/DifferenceBar.svelte';import { fromDifference } from '../lib/map/analyzerRules.js';import PassStrip from './compare/PassStrip.svelte';+ import EvolutionPicker from './compare/EvolutionPicker.svelte';import CopernicusNeeded from '../components/CopernicusNeeded.svelte';import { copernicusNeed } from '../lib/copernicusSetup.js';import { stripArchive } from '../lib/map/passStrip.js';@@ -138,7 +154,15 @@let rightPanel = $state(null); // 'export' | 'layers' | nulllet grabbing = $state(false);let captureSide = $state(null); // surface visible during an extension frame- let exportKind = $state('png'); // 'png' | 'blink' | 'slide'+ let exportKind = $state('png'); // 'png' | 'blink' | 'slide' | 'evolution' | 'sheet'+ // Every export is signed with the Azimut lockup unless this is unticked.+ let signExport = $state(true);+ // The pictures an evolution plays, as the picker has them ticked, and how far+ // a running one has got. Aborting the controller stops it between two tiles.+ let evolutionChosen = $state([]);+ let evolutionInterval = $state(DEFAULT_INTERVAL);+ let evolutionProgress = $state(null); // { done, total } | null+ let evolutionAbort = null;// What an export is cut to, as two ground corners, and whether one is being// drawn right now. No frame means the whole view, which is the default.let exportFrame = $state(null);@@ -351,6 +375,14 @@if (!archive) stripOpen = false;});+ // The archive an evolution plays, which Then and now also has: World Imagery's+ // history is Wayback.+ const evolution = $derived(evolutionArchive(sideSpec(a, s2a, wba, s1a), sideSpec(b, s2b, wbb, s1b)));+ const evolutionKind = $derived(exportKind === 'evolution' || exportKind === 'sheet');+ $effect(() => {+ if (!evolution && (exportKind === 'evolution' || exportKind === 'sheet')) exportKind = 'png';+ });+/** Show one of the strip's pictures on a side. */function assignFromStrip(letter, entry) {const [target, sentinel, wayback, radar] = letter === 'a' ? [a, s2a, wba, s1a] : [b, s2b, wbb, s1b];@@ -368,6 +400,12 @@return variantId(SENTINEL_ID, { layer: s2b.layer, from: entry.date, to: entry.date });}+ /** The provider id one picture of an evolution is drawn from: B's layer, on that row's date. */+ function evolutionVariant(entry) {+ if (evolution === WAYBACK_ID) return waybackId(WAYBACK_ID, entry.release);+ return variantId(SENTINEL_ID, { layer: s2b.layer, from: entry.date, to: entry.date });+ }+const changeStatus = $derived(changeCompatibility(changeSide(a, s2a, wba, shownA, s1a), changeSide(b, s2b, wbb, shownB, s1b)));@@ -1741,7 +1779,7 @@function compose(sources,- { renderMode = mode, renderBlinkB = blinkB, renderChangeMap = null } = {}+ { renderMode = mode, renderBlinkB = blinkB, renderChangeMap = null, renderSigned = false } = {}) {const provenanceA = a.surface?.provenance?.() ?? {};const provenanceB = b.surface?.provenance?.() ?? {};@@ -1762,6 +1800,7 @@attributionA: shownA.provider?.attribution,attributionB: shownB.provider?.attribution,view,+ signed: renderSigned,// A framed export comes out upright at the bearing its frame was drawn at.// A frame counts the compass direction that is up; the app counts the// map's clockwise turn, the same angle the other way.@@ -1783,10 +1822,10 @@return changeResult;}- async function comparisonBlob() {+ async function comparisonBlob({ signed = false } = {}) {const renderChangeMap = await exportedChange();const sources = await exportSources();- return canvasBlob(compose(sources, { renderChangeMap }));+ return canvasBlob(compose(sources, { renderChangeMap, renderSigned: signed }));}/** When each picture on screen was taken, as the surfaces that drew them say. */@@ -1813,6 +1852,7 @@form.append('image_b', frameB, 'comparison-b.png');form.append('format', 'blink');form.append('interval', String(blinkInterval));+ form.append('keep', gifColours(annotations));} else {form.append('image_a', await comparisonBlob(), 'comparison.png');form.append('format', 'png');@@ -1848,6 +1888,7 @@if (imageB) form.append('image_b', imageB, 'comparison-b.png');form.append('format', format);form.append('interval', String(blinkInterval));+ if (format !== 'png') form.append('keep', gifColours(annotations, { signed: signExport }));form.append('filename', exportName());form.append('spec', JSON.stringify(sessionSpec()));for (const [field, value] of pictureDateFields(pictureDates())) form.append(field, value);@@ -1869,7 +1910,7 @@outputBusy = 'png';try {const owner = await ensureCase();- const blob = await comparisonBlob();+ const blob = await comparisonBlob({ signed: signExport });const result = await api.post(`/api/cases/${owner.id}/plates`, {filename: exportName(),format: 'png',@@ -1897,13 +1938,15 @@const owner = await ensureCase();const renderChangeMap = await exportedChange();const sources = await exportSources();- const frameA = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: false, renderChangeMap }));- const frameB = await canvasBlob(compose(sources, { renderMode: 'blink', renderBlinkB: true, renderChangeMap }));+ const blink = { renderMode: 'blink', renderChangeMap, renderSigned: signExport };+ const frameA = await canvasBlob(compose(sources, { ...blink, renderBlinkB: false }));+ const frameB = await canvasBlob(compose(sources, { ...blink, renderBlinkB: true }));const form = new FormData();form.append('image_a', frameA, 'comparison-a.png');form.append('image_b', frameB, 'comparison-b.png');form.append('animation', animation);form.append('interval', String(blinkInterval));+ form.append('keep', gifColours(annotations, { signed: signExport }));form.append('filename', exportName());const result = await api.post(`/api/cases/${owner.id}/compare/gif`, form);const kept = await keepExport(owner.id, animation, frameA, frameB);@@ -1919,7 +1962,151 @@}}+ /**+ * The ground and scale an evolution is drawn at: the export frame, or A's view,+ * at the screen's density held under the GIF's edge, or shared out across a sheet.+ */+ function evolutionPlan(kind, count) {+ const target = a.engine ? a : b.engine ? b : null;+ if (!target) return null;+ const frame = evolutionFrame(surfaceFrame(target), exportFrame);+ const density = window.devicePixelRatio || 1;+ const pixelScale = kind === 'sheet'+ ? sheetCellScale(frame, count, density)+ : pictureScale(frame, GIF_EDGE, density);+ return { frame, pixelScale };+ }++ /**+ * A side as the evolution picker reads it: with its Wayback release's date, and+ * a Sentinel-2 side on its latest pass named by that pass's day.+ */+ 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 || '' } };+ }++ /** The ground a picker row's picture shows: the evolution's centre, at its scale. */+ const evolutionThumbView = $derived.by(() => {+ if (!evolutionKind || rightPanel !== 'export' || !evolution) return null;+ void [view, bearing, exportFrame];+ const plan = evolutionPlan('evolution', 2);+ if (!plan) return null;+ // The frame counts the engine's zoom, one level short of the app's.+ return { lat: plan.frame.lat, lon: wrapLon(plan.frame.lng), zoom: plan.frame.zoom + 1, viewWidth: plan.frame.width };+ });++ /** Tiles one picture of the evolution takes as the export stands, for its price. */+ const evolutionTiles = $derived.by(() => {+ if (!evolutionKind || rightPanel !== 'export' || !evolution) return 0;+ void [view, bearing, exportFrame];+ const plan = evolutionPlan(exportKind, Math.max(2, evolutionChosen.length));+ return plan ? pictureTiles(plan.frame, imagery.find(evolution), plan.pixelScale).tiles.length : 0;+ });++ function closeExport() {+ evolutionAbort?.abort();+ rightPanel = null;+ }++ $effect(() => () => evolutionAbort?.abort());++ /** What was left out of an evolution, said in the toast that reports it. */+ function leftOut({ empty, repeated }) {+ const parts = [];+ if (repeated) parts.push(`${repeated} repeated ${repeated === 1 ? 'picture' : 'pictures'}`);+ if (empty) parts.push(`${empty} with no imagery here`);+ return parts.length ? ` (left out: ${parts.join(', ')})` : '';+ }++ async function exportEvolution(kind) {+ if (outputBusy || !evolution) return;+ const pictures = [...evolutionChosen];+ if (pictures.length < 2 || pictures.length > MAX_EVOLUTION_FRAMES) {+ toast(`An evolution plays 2 to ${MAX_EVOLUTION_FRAMES} pictures`, 'warn');+ return;+ }+ const plan = evolutionPlan(kind, pictures.length);+ if (!plan) {+ toast('Open a map before exporting', 'warn');+ return;+ }+ const controller = new AbortController();+ evolutionAbort = controller;+ outputBusy = 'evolution';+ evolutionProgress = { done: 0, total: pictures.length };+ const archiveId = evolution;+ const provider = imagery.find(archiveId);+ const label = provider?.label ?? (archiveId === WAYBACK_ID ? 'Esri Wayback' : 'Sentinel-2');+ const common = {+ title: sessionName,+ label,+ attribution: provider?.attribution,+ annotations,+ units: prefs.units,+ signed: signExport,+ };+ const positions = timelinePositions(pictures.map((entry) => entry.date));+ const frames = [];+ const cells = [];+ try {+ const owner = await ensureCase();+ const tally = await drawPictures({+ entries: pictures,+ frame: plan.frame,+ pixelScale: plan.pixelScale,+ provider,+ variantFor: evolutionVariant,+ signal: controller.signal,+ onprogress: (done, total) => (evolutionProgress = { done, total }),+ onpicture: async ({ entry, picture, index }) => {+ const date = pictureLabel(archiveId, entry);+ if (kind === 'sheet') cells.push({ picture, date });+ else frames.push(await canvasBlob(composeEvolutionFrame({ ...common, picture, date, current: index, positions })));+ },+ });+ if (tally.drawn < 2) throw new Error(`fewer than two distinct pictures of this ground came back${leftOut(tally)}`);+ const name = comparisonFilename(sessionName, { a: pictures[0].date, b: pictures.at(-1).date });+ let result;+ if (kind === 'sheet') {+ const span = `${pictures[0].date} to ${pictures.at(-1).date}`;+ const blob = await canvasBlob(composeEvolutionSheet({ ...common, cells, span }));+ result = await api.post(`/api/cases/${owner.id}/plates`, {+ filename: `${name} evolution`,+ format: 'png',+ png: await blobBase64(blob),+ overwrite: false,+ }, { signal: controller.signal });+ } else {+ const form = new FormData();+ frames.forEach((blob, index) => form.append('frames', blob, `evolution-${index + 1}.png`));+ form.append('interval', String(evolutionInterval));+ form.append('filename', name);+ form.append('keep', gifColours(annotations.filter((mark) => mark.side === 'both'), { signed: signExport }));+ result = await api.post(`/api/cases/${owner.id}/compare/sequence`, form, { signal: controller.signal });+ }+ rightPanel = null;+ toast(`${result.file} written to ${destinationLabel(result.path)}${leftOut(tally)}`, 'ok', 7000, {+ label: 'Show',+ onClick: () => showExports(),+ });+ } catch (error) {+ if (error?.name === 'AbortError') toast('Evolution export stopped', 'info');+ else outputError('Evolution export failed', error);+ } finally {+ if (archiveId !== WAYBACK_ID) imagery.refreshUsage();+ if (evolutionAbort === controller) evolutionAbort = null;+ outputBusy = '';+ evolutionProgress = null;+ }+ }+async function runExport() {+ if (evolutionKind) {+ await exportEvolution(exportKind);+ return;+ }if (keepInCase && !openedSession) {exportAfterSave = true;saveDialog = true;@@ -1945,7 +2132,7 @@if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {throw new Error('this browser cannot copy an image');}- const blob = await comparisonBlob();+ const blob = await comparisonBlob({ signed: signExport });await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);toast('Comparison copied as an image', 'ok');} catch (error) {@@ -2372,7 +2559,7 @@</div>{/if}{#if rightPanel === 'export'}- <Modal title="Export a copy" onclose={() => (rightPanel = null)} width="540px">+ <Modal title="Export a copy" onclose={closeExport} width="540px"><div class="export-dialog"><div class="output-list"><label class="output-choice" class:selected={exportKind === 'png'}>@@ -2390,8 +2577,40 @@<Icon name="panelRight" size={17} /><span><strong>GIF · Slide</strong><small>Sweeps the divider across the image.</small></span></label>+ <label class="output-choice" class:selected={exportKind === 'evolution'} class:locked={!evolution}>+ <input type="radio" bind:group={exportKind} value="evolution" disabled={!evolution || !!outputBusy} />+ <Icon name="video" size={17} />+ <span><strong>GIF · Evolution</strong><small>{evolution+ ? 'Every picture you tick, oldest to newest.'+ : 'Needs Sentinel-2 or Wayback on both sides, or Wayback against World Imagery.'}</small></span>+ </label>+ <label class="output-choice" class:selected={exportKind === 'sheet'} class:locked={!evolution}>+ <input type="radio" bind:group={exportKind} value="sheet" disabled={!evolution || !!outputBusy} />+ <Icon name="grid" size={17} />+ <span><strong>PNG · Evolution sheet</strong><small>The same pictures side by side on one page.</small></span>+ </label></div>+ {#if evolutionKind && evolution}+ {#key evolution}+ <EvolutionPicker archive={evolution} a={evolutionSide(a, s2a, wba, s1a)} b={evolutionSide(b, s2b, wbb, s1b)}+ {view} maxcc={s2b.maxcc} perPicture={evolutionTiles} disabled={!!outputBusy}+ provider={imagery.find(evolution)} variantFor={evolutionVariant} thumbView={evolutionThumbView}+ onchoose={(chosen) => (evolutionChosen = chosen)} onbilled={() => imagery.refreshUsage()} />+ {/key}+ {#if exportKind === 'evolution'}+ <label class="pace">+ <span class="field-label">Pace</span>+ <input type="range" min="300" max="3000" step="100" bind:value={evolutionInterval}+ disabled={!!outputBusy} aria-label="Time each picture stays up" />+ <span class="mono">{(evolutionInterval / 1000).toFixed(1)} s a picture</span>+ </label>+ {/if}+ {#if difference}+ <p class="panel-note"><Icon name="info" size={13} /> Difference highlights stay out of an evolution; they read one pair.</p>+ {/if}+ {/if}+<div class="destination"><span class="field-label">Frame</span><strong>{exportFrame ? frameLabel(exportFrame) : 'Full view'}</strong>@@ -2411,13 +2630,25 @@<button class="link" onclick={() => (exportPicker = true)}>Change…</button></div>+ {#if evolutionKind}+ <p class="panel-note"><Icon name="info" size={13} /> An evolution is written out only, not kept in the case.</p>+ {:else}+ <label class="keep-choice">+ <input type="checkbox" bind:checked={keepInCase} />+ <span>+ <strong>Also keep it in this case</strong>+ <small>{openedSession+ ? `Filed under ${openedSession.title}, with its dates and point.`+ : 'Saves the comparison first, then files the image under it.'}</small>+ </span>+ </label>+ {/if}+<label class="keep-choice">- <input type="checkbox" bind:checked={keepInCase} />+ <input type="checkbox" bind:checked={signExport} /><span>- <strong>Also keep it in this case</strong>- <small>{openedSession- ? `Filed under ${openedSession.title}, with its dates and point.`- : 'Saves the comparison first, then files the image under it.'}</small>+ <strong>Sign it Azimut</strong>+ <small>The logo and name close the credits line, under the imagery.</small></span></label>@@ -2429,8 +2660,21 @@<button class="btn" disabled={!!outputBusy} onclick={copyComparison}><Icon name="copy" size={13} /> {outputBusy === 'copy' ? 'Copying…' : 'Copy current PNG'}</button>- <button class="btn btn-primary" disabled={!!outputBusy} onclick={runExport}>- <Icon name="download" size={13} /> {outputBusy === 'png' || outputBusy === 'gif' ? 'Exporting…' : 'Export copy'}+ {#if outputBusy === 'evolution'}+ <button class="btn" onclick={() => evolutionAbort?.abort()}>+ <Icon name="x" size={13} /> Stop+ </button>+ {/if}+ <button class="btn btn-primary" onclick={runExport}+ disabled={!!outputBusy || (evolutionKind && (evolutionChosen.length < 2 || evolutionChosen.length > MAX_EVOLUTION_FRAMES))}>+ <Icon name="download" size={13} />+ {#if outputBusy === 'evolution' && evolutionProgress}+ {evolutionProgress.done < evolutionProgress.total+ ? `Drawing ${evolutionProgress.done + 1} of ${evolutionProgress.total}…`+ : 'Writing…'}+ {:else}+ {outputBusy === 'png' || outputBusy === 'gif' ? 'Exporting…' : 'Export copy'}+ {/if}</button></div>@@ -2909,6 +3153,10 @@.output-choice small { display: block; }.output-choice strong { color: var(--text-1); font-size: var(--fs-sm); }.output-choice small { margin-top: 2px; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.35; }+ .output-choice.locked { cursor: default; opacity: .6; }+ .output-choice.locked:hover { border-color: var(--border); color: inherit; background: none; }+ .pace { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: 10px; }+ .pace .mono { color: var(--text-2); font-size: var(--fs-xs); }.destination { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 10px; align-items: center; padding-top: 13px; border-top: 1px solid var(--border); }.destination .field-label { grid-column: 1 / -1; }.keep-choice { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: flex-start; gap: 9px; padding-top: 13px; border-top: 1px solid var(--border); cursor: pointer; }diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 0a84a81..18ac7d7 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -886,9 +886,10 @@// --- the right-click menu: acts on the point under the cursor -------------//// Every act here already exists for the map centre; the menu hands each one- // the clicked point instead (lib/map/contextMenu.js). Session chrome, never- // part of a capture.- let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup }+ // the clicked point instead (lib/map/contextMenu.js). On a pin of an added+ // layer the point is the pin's, and `feature` and `layer` name it. Session+ // chrome, never part of a capture.+ let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup, feature?, layer? }let pointLookupSeq = 0;const pointActions = actionsFor(['lookup', 'place', 'measure', 'sky', 'history', 'centre']);const pointTools = otherMapTools('satellite');@@ -2221,6 +2222,7 @@layers={addedLayers.drawn}drawing={addedLayers.drawing}picked={addedLayers.picked}+ onmenu={onMapContextMenu}/>{#if sheetPoints && sheetShown}diff --git a/frontend/src/tools/compare/EvolutionPicker.svelte b/frontend/src/tools/compare/EvolutionPicker.sveltenew file mode 100644index 0000000..14c3b33--- /dev/null+++ b/frontend/src/tools/compare/EvolutionPicker.svelte@@ -0,0 +1,397 @@+<script>+ /**+ * Which pictures an evolution plays, chosen by hand in the export dialog, each+ * row with its picture of the export's ground.+ *+ * Wayback lists the whole history of the crosshair at once, as the pictures+ * strip reads it, in the order the pictures were taken, and opens on A to B.+ * Sentinel-2 passes every few days since mid-2015, far more than one list+ * holds, so it is read a month at a time: the picker opens on A's month and+ * B's with both passes ticked, and the analyst pages or jumps to any month+ * back to 2015 to tick more. Ticks are kept across months.+ *+ * What is read is what the analyst opened: the Wayback walk is free, and each+ * Sentinel-2 month is one Copernicus request, as in the Sentinel-2 day picker.+ * A picture is a tile or two through the proxy, cached once read.+ */+ import { onMount } from 'svelte';+ import { api } from '../../lib/api.js';+ import Icon from '../../components/Icon.svelte';+ import { addMonths, isoDay, monthBounds, monthLabel, monthOf } from '../../lib/sentinel.js';+ import { THUMB, lookupPath, stripEntries, thumbTiles } from '../../lib/map/passStrip.js';+ import {+ MAX_EVOLUTION_FRAMES,+ SENTINEL2_FIRST_MONTH,+ allKeys,+ chosenEntries,+ defaultKeys,+ pickerMonth,+ pictureLabel,+ playOrder,+ rangeKeys,+ sideEntry,+ thinKeys,+ } from '../../lib/map/evolution.js';++ let {+ /** 'sentinel2' | 'esri-wayback' */+ archive,+ /** Both sides as a saved comparison keeps them, with the day each shows. */+ a,+ b,+ view,+ maxcc = 100,+ /** Tiles one picture takes at the export's frame, for the price. */+ perPicture = 0,+ /** The provider the pictures are drawn from, and the id each row's is asked as. */+ provider = null,+ variantFor = () => '',+ /** The ground a row's picture shows: `{ lat, lon, zoom, viewWidth }`. */+ thumbView = null,+ disabled = false,+ onchoose = () => {},+ onbilled = () => {},+ } = $props();++ const monthly = $derived(archive === 'sentinel2');+ const today = monthOf(isoDay(new Date()));++ // What each read answered: the whole history under 'all', or one answer per month.+ let answers = $state({});+ let readAt = $state(null);+ let busy = $state(false);+ let note = $state('');+ let picked = $state([]);+ let month = $state(today);+ let monthInput = $state(today);+ // The rows whose picture has arrived; the others shimmer until it does.+ let ready = $state({});++ const entries = $derived(monthly+ ? stripEntries(archive, { dates: Object.values(answers).flatMap((answer) => answer?.dates ?? []) }, { maxcc })+ : stripEntries(archive, answers.all ?? null, { maxcc }));+ const first = $derived(sideEntry(entries, archive, a));+ const last = $derived(sideEntry(entries, archive, b));+ const shown = $derived(monthly+ ? entries.filter((entry) => entry.date.startsWith(month))+ : playOrder(entries));+ const chosen = $derived(chosenEntries(entries, picked));+ const thumbs = $derived(thumbView ? thumbTiles(thumbView, provider) : []);+ const monthsRead = $derived(Object.keys(answers).length);+ const over = $derived(chosen.length > MAX_EVOLUTION_FRAMES);+ const moved = $derived(!!readAt && distance(readAt, view) > 1000);+ const read = $derived(monthly ? month in answers : 'all' in answers);++ $effect(() => {+ onchoose(chosen);+ });++ onMount(() => {+ void open();+ });++ function distance(from, to) {+ const dy = (to.lat - from.lat) * 111_320;+ const dx = (to.lon - from.lon) * 111_320 * Math.cos((from.lat * Math.PI) / 180);+ return Math.hypot(dx, dy);+ }++ const dayOf = (side) => side?.sentinel?.date ?? '';++ /** Read what the picker opens on, and tick A to B, or A's pass and B's. */+ async function open() {+ answers = {};+ picked = [];+ note = '';+ readAt = { lat: view.lat, lon: view.lon, zoom: view.zoom };+ if (!monthly) {+ if (await ask('all')) picked = defaultKeys(entries, first, last);+ return;+ }+ const opening = [dayOf(a), dayOf(b)].filter(Boolean).map(monthOf);+ month = opening[0] ?? today;+ monthInput = month;+ for (const each of new Set(opening.length ? opening : [today])) {+ if (!(await ask(each))) return;+ }+ picked = [...new Set([first, last].filter(Boolean).map((entry) => entry.key))];+ }++ /** One read: the history, or one month of passes. False when it failed. */+ async function ask(which) {+ if (which in answers) return true;+ busy = true;+ note = '';+ const at = readAt ?? { lat: view.lat, lon: view.lon, zoom: view.zoom };+ try {+ const bounds = which === 'all' ? null : monthBounds(which);+ const window = bounds ? { start: bounds.from, end: bounds.to } : null;+ const reply = await api.get(lookupPath(archive, at, window));+ answers = { ...answers, [which]: reply };+ if (monthly) onbilled();+ return true;+ } catch (error) {+ note = `Could not read the pictures of this point: ${error.message}`;+ return false;+ } finally {+ busy = false;+ }+ }++ function goTo(next) {+ const held = pickerMonth(next, today);+ if (!held) return;+ month = held;+ monthInput = month;+ void ask(month);+ }++ function toggle(key) {+ picked = picked.includes(key) ? picked.filter((entry) => entry !== key) : [...picked, key];+ }++ /** The clearest usable pass of the month on screen, ticked beside what is. */+ function clearest() {+ const [best] = thinKeys(shown, shown.filter((entry) => entry.usable).map((entry) => entry.key), 'month');+ if (best && !picked.includes(best)) picked = [...picked, best];+ }++ const range = () => rangeKeys(entries, first, last);+ const PRESETS = [+ { label: 'A to B', keys: () => range() },+ { label: 'One a month', keys: () => thinKeys(entries, range(), 'month') },+ { label: 'One a year', keys: () => thinKeys(entries, range(), 'year') },+ { label: 'All', keys: () => allKeys(entries) },+ ];++ const tileUrl = (entry, tile) =>+ `/api/tiles/${encodeURIComponent(variantFor(entry))}/${tile.z}/${tile.x}/${tile.y}`;++ /** What a row adds under its date: a Wayback picture's release, a pass's cloud. */+ function detail(entry) {+ if (!entry.usable) return `${entry.note ? `${entry.note}, ` : ''}over the cloud ceiling`;+ if (!monthly) return entry.note === 'taken' && entry.released ? `release ${entry.released}` : '';+ return entry.note ?? '';+ }+</script>++<div class="evolution" aria-label="Pictures of the evolution">+ <div class="head">+ <span class="field-label">Pictures</span>+ <span class="count">{chosen.length} chosen</span>+ <span class="grow"></span>+ {#if moved}+ <button type="button" class="link" onclick={open} disabled={busy || disabled}>The map moved · read here</button>+ {/if}+ </div>++ {#if monthly}+ <div class="months">+ <button type="button" class="cmp-icon" aria-label="Previous month" title="Previous month"+ disabled={busy || disabled || month <= SENTINEL2_FIRST_MONTH} onclick={() => goTo(addMonths(month, -1))}>+ <Icon name="chevronLeft" size={14} />+ </button>+ <strong>{monthLabel(month)}</strong>+ <button type="button" class="cmp-icon" aria-label="Next month" title="Next month"+ disabled={busy || disabled || month >= today} onclick={() => goTo(addMonths(month, 1))}>+ <Icon name="chevronRight" size={14} />+ </button>+ <input class="input" type="month" aria-label="Go to a month" min={SENTINEL2_FIRST_MONTH} max={today}+ bind:value={monthInput} onchange={(event) => goTo(event.currentTarget.value)} disabled={busy || disabled} />+ <span class="grow"></span>+ {#if shown.length}+ <button type="button" class="btn btn-sm" onclick={clearest} {disabled}>Clearest of the month</button>+ {/if}+ </div>+ {:else if entries.length}+ <div class="presets">+ {#each PRESETS as preset (preset.label)}+ <button type="button" class="btn btn-sm" {disabled} onclick={() => (picked = preset.keys())}>{preset.label}</button>+ {/each}+ </div>+ {/if}++ {#if busy}+ <div class="loading" role="status">+ <span class="spinner" aria-hidden="true"></span>+ <span>+ <strong>Loading the pictures…</strong>+ <small>{monthly+ ? `Asking Copernicus for the passes of ${monthLabel(month)}.`+ : 'Esri’s history of this point is read picture by picture, which takes a few seconds.'}</small>+ </span>+ </div>+ {#if !shown.length}+ <ol class="cards" aria-hidden="true">+ {#each [0, 1, 2, 3, 4, 5] as ghost (ghost)}+ <li class="ghost"><span class="thumb" style:height={`${THUMB.height}px`}></span><span class="bar"></span></li>+ {/each}+ </ol>+ {/if}+ {:else if note}+ <p class="warn" role="alert">+ {note}+ <button type="button" class="link" onclick={() => (monthly ? ask(month) : open())}>Try again</button>+ </p>+ {:else if read && !shown.length}+ <p class="hint">{monthly ? 'No Sentinel-2 pass over this point that month.' : 'The archive holds no picture of this point.'}</p>+ {/if}++ {#if shown.length}+ <ol class="cards">+ {#each shown as entry (entry.key)}+ <li class:off={!entry.usable} class:picked={picked.includes(entry.key)}>+ <label>+ <span class="thumb" class:ready={ready[entry.key]}+ style:width={`${THUMB.width}px`} style:height={`${THUMB.height}px`}>+ {#each thumbs as tile (`${tile.z}/${tile.x}/${tile.y}`)}+ <img alt="" loading="lazy" src={tileUrl(entry, tile)} style:left={`${tile.left}px`}+ style:top={`${tile.top}px`} style:width={`${tile.size}px`} style:height={`${tile.size}px`}+ onload={() => (ready[entry.key] = true)} onerror={() => (ready[entry.key] = true)} />+ {/each}+ </span>+ <span class="line">+ <input type="checkbox" checked={picked.includes(entry.key)} {disabled}+ onchange={() => toggle(entry.key)} />+ <span class="mono">{pictureLabel(archive, entry)}</span>+ <span class="grow"></span>+ {#if first?.key === entry.key}<span class="tag">A</span>{/if}+ {#if last?.key === entry.key}<span class="tag">B</span>{/if}+ </span>+ {#if detail(entry)}<small>{detail(entry)}</small>{/if}+ </label>+ </li>+ {/each}+ </ol>+ {/if}++ {#if monthly && chosen.length}+ <ul class="chosen" aria-label="Chosen passes">+ {#each chosen as entry (entry.key)}+ <li>+ <button type="button" class="chip" onclick={() => goTo(monthOf(entry.date))} title="Show its month">{entry.date}</button>+ <button type="button" class="unpick" aria-label={`Untick ${entry.date}`} title="Untick" {disabled}+ onclick={() => toggle(entry.key)}><Icon name="x" size={11} /></button>+ </li>+ {/each}+ </ul>+ {/if}++ {#if over}+ <p class="warn" role="alert">At most {MAX_EVOLUTION_FRAMES} pictures in one export. Untick some.</p>+ {:else if chosen.length < 2 && (read || monthsRead)}+ <p class="hint">Tick at least two pictures{monthly ? ', in this month or another' : ''}.</p>+ {:else if monthly && chosen.length}+ <p class="hint">+ {monthsRead} {monthsRead === 1 ? 'month' : 'months'} read, one Copernicus request each. The export takes up to+ {chosen.length * perPicture} more, a preview one to four; tiles already read are free.+ </p>+ {/if}+</div>++<style>+ .evolution { display: grid; gap: 7px; padding-top: 13px; border-top: 1px solid var(--border); }+ .head, .months, .presets { display: flex; align-items: center; gap: 6px; }+ .presets { flex-wrap: wrap; }+ .grow { flex: 1; }+ .count { color: var(--text-3); font-size: var(--fs-xs); }+ .field-label {+ color: var(--text-3);+ font-size: 10px;+ font-weight: 700;+ letter-spacing: .08em;+ text-transform: uppercase;+ }+ .months strong { min-width: 118px; text-align: center; font-size: var(--fs-sm); }+ .months input { width: 132px; padding: 3px 6px; font-size: var(--fs-xs); }+ .link { color: var(--accent); font-size: var(--fs-xs); }+ .link:disabled { color: var(--text-3); }+ .hint, .warn { margin: 0; font-size: var(--fs-xs); line-height: 1.4; }+ .hint { color: var(--text-3); }+ .warn { color: var(--warn, #e2a03f); }+ .cards {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(148px, 1fr));+ gap: 6px;+ max-height: 320px;+ margin: 0;+ padding: 6px;+ overflow-y: auto;+ list-style: none;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ }+ .cards label {+ display: grid;+ gap: 2px;+ padding: 4px;+ border: 1px solid transparent;+ border-radius: var(--r-sm);+ font-size: var(--fs-xs);+ cursor: pointer;+ }+ .cards label:hover { background: var(--bg-2); }+ .cards li.picked label { border-color: var(--accent); }+ .line { display: flex; align-items: center; gap: 6px; }+ .cards small { color: var(--text-3); }+ .thumb {+ position: relative;+ display: block;+ overflow: hidden;+ border-radius: 3px;+ background: #14171d;+ }+ /* A picture on its way shimmers, so an empty box reads as loading. */+ .thumb:not(.ready) {+ background: linear-gradient(90deg, #14171d 30%, #232833 50%, #14171d 70%) 0 0 / 300% 100%;+ animation: shimmer 1.3s linear infinite;+ }+ /* A tile is drawn larger than the box and placed by its offset: the global+ img rule would shrink it to the box and push it out of view. */+ .thumb img { position: absolute; max-width: none; }+ .loading { display: flex; align-items: flex-start; gap: 9px; padding: 8px 10px; border: 1px solid var(--border);+ border-radius: var(--r-sm); background: var(--bg-2); font-size: var(--fs-xs); }+ .loading strong, .loading small { display: block; }+ .loading strong { color: var(--text-1); }+ .loading small { margin-top: 2px; color: var(--text-3); line-height: 1.35; }+ .spinner {+ flex: none;+ width: 13px;+ height: 13px;+ margin-top: 1px;+ border: 2px solid var(--accent);+ border-top-color: transparent;+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ }+ .ghost { display: grid; gap: 6px; padding: 4px; }+ .ghost .bar { width: 70%; height: 9px; border-radius: 3px; background: var(--bg-2); }+ @keyframes spin { to { transform: rotate(360deg); } }+ @keyframes shimmer { to { background-position: -300% 0; } }+ @media (prefers-reduced-motion: reduce) {+ .spinner, .thumb:not(.ready) { animation: none; }+ }+ li.off .thumb { opacity: 0.45; }+ li.off .mono { color: var(--text-3); }+ .tag {+ padding: 0 4px;+ border-radius: 3px;+ background: var(--accent);+ color: #0b0d11;+ font-size: 9.5px;+ font-weight: 700;+ line-height: 14px;+ }+ .chosen { display: flex; flex-wrap: wrap; gap: 4px; margin: 0; padding: 0; list-style: none; }+ .chosen li {+ display: flex;+ align-items: center;+ border: 1px solid var(--border);+ border-radius: 999px;+ font-size: var(--fs-xs);+ }+ .chip { padding: 1px 4px 1px 8px; font-family: var(--font-mono, monospace); color: var(--text-2); }+ .chip:hover { color: var(--text-1); }+ .unpick { display: flex; padding: 3px 6px 3px 2px; color: var(--text-3); }+ .unpick:hover:not(:disabled) { color: var(--text-1); }+</style>diff --git a/frontend/src/tools/compare/EvolutionPicker.test.js b/frontend/src/tools/compare/EvolutionPicker.test.jsnew file mode 100644index 0000000..e50f6a1--- /dev/null+++ b/frontend/src/tools/compare/EvolutionPicker.test.js@@ -0,0 +1,152 @@+// @vitest-environment happy-dom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { flushSync, mount, unmount } from 'svelte';++// One answer per month asked, as the Sentinel-2 catalogue gives it: newest first.+const MONTHS = {+ '2017-03': [{ date: '2017-03-21', cloud: 64 }, { date: '2017-03-04', cloud: 2 }],+ '2024-05': [{ date: '2024-05-18', cloud: 8 }, { date: '2024-05-03', cloud: 0 }],+ '2026-08': [{ date: '2026-08-27', cloud: 12 }],+};+const get = vi.fn(async (path) => {+ const start = /start=(\d{4}-\d{2})-01/.exec(path)?.[1];+ return { dates: structuredClone(MONTHS[start] ?? []) };+});+vi.mock('../../lib/api.js', () => ({ api: { get } }));++const { default: EvolutionPicker } = await import('./EvolutionPicker.svelte');++const side = (date) => ({ present: true, provider: 'sentinel2', sentinel: { layer: 'TRUE_COLOR', date, maxcc: 100 } });+const PROVIDER = { id: 'sentinel2', tile_size: 512, max_zoom: 18, max_native_zoom: 14 };++let live;+let target;+let chosen = [];+const onbilled = vi.fn();++async function settle() {+ for (let index = 0; index < 40; index += 1) await Promise.resolve();+ flushSync();+}++async function open(props = {}) {+ target = document.createElement('div');+ document.body.append(target);+ live = mount(EvolutionPicker, {+ target,+ props: {+ archive: 'sentinel2',+ a: side('2024-05-03'),+ b: side('2026-08-27'),+ view: { lat: 48.85, lon: 2.35, zoom: 16 },+ maxcc: 30,+ perPicture: 2,+ provider: PROVIDER,+ variantFor: (entry) => `sentinel2~TRUE_COLOR~${entry.date}~${entry.date}`,+ thumbView: { lat: 48.85, lon: 2.35, zoom: 16, viewWidth: 900 },+ onchoose: (next) => (chosen = next),+ onbilled,+ ...props,+ },+ });+ flushSync();+ await settle();+}++const button = (label) => [...target.querySelectorAll('button')].find((entry) => entry.textContent.trim() === label+ || entry.getAttribute('aria-label') === label);+const cards = () => [...target.querySelectorAll('.cards li')];+const months = () => get.mock.calls.map(([path]) => /start=(\d{4}-\d{2})/.exec(path)?.[1]);++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-09-25T10:00:00Z'));+ get.mockClear();+ onbilled.mockClear();+ chosen = [];+});++afterEach(() => {+ vi.useRealTimers();+ if (live) unmount(live);+ live = null;+ target?.remove();+});++describe('choosing Sentinel-2 passes by hand', () => {+ it('opens on A’s month, reads B’s too, and ticks both passes', async () => {+ await open();+ expect(months()).toEqual(['2024-05', '2026-08']);+ expect(onbilled).toHaveBeenCalledTimes(2);+ expect(target.textContent).toContain('May 2024');+ expect(cards().map((card) => card.querySelector('.mono').textContent)).toEqual(['2024-05-03', '2024-05-18']);+ expect(chosen.map((entry) => entry.date)).toEqual(['2024-05-03', '2026-08-27']);+ // each pass shows its own picture of the ground+ expect(cards()[0].querySelector('.thumb img').getAttribute('src'))+ .toMatch(/^\/api\/tiles\/sentinel2~TRUE_COLOR~2024-05-03~2024-05-03\//);+ expect(target.textContent).toContain('2 months read');+ });++ it('goes back to any month since 2015, keeps what was ticked, and adds from there', async () => {+ await open();+ const input = target.querySelector('input[type="month"]');+ input.value = '2017-03';+ input.dispatchEvent(new Event('input', { bubbles: true }));+ input.dispatchEvent(new Event('change', { bubbles: true }));+ await settle();+ expect(target.textContent).toContain('March 2017');+ const [early, cloudy] = cards();+ expect(early.querySelector('small').textContent).toBe('2% cloud');+ // over the ceiling, shown and still tickable by hand+ expect(cloudy.querySelector('small').textContent).toBe('64% cloud, over the cloud ceiling');+ button('Clearest of the month').click();+ flushSync();+ expect(chosen.map((entry) => entry.date)).toEqual(['2017-03-04', '2024-05-03', '2026-08-27']);+ // the chips untick a pass read in another month+ button('Untick 2026-08-27').click();+ flushSync();+ expect(chosen.map((entry) => entry.date)).toEqual(['2017-03-04', '2024-05-03']);+ expect(target.textContent).toContain('3 months read');+ input.value = '2015-07';+ input.dispatchEvent(new Event('change', { bubbles: true }));+ await settle();+ button('Previous month').click();+ await settle();+ // Sentinel-2 began in June 2015: nothing is asked before it.+ expect(target.textContent).toContain('June 2015');+ expect(months().at(-1)).toBe('2015-06');+ expect(button('Previous month').disabled).toBe(true);+ // a month already read is not asked twice+ button('Next month').click();+ await settle();+ button('Previous month').click();+ await settle();+ expect(months().filter((entry) => entry === '2015-06')).toHaveLength(1);+ });++ it('says it is loading while the archive answers, with cards on their way', async () => {+ let answer;+ get.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));+ await open();+ const status = target.querySelector('[role="status"]');+ expect(status.textContent).toContain('Loading the pictures…');+ expect(status.textContent).toContain('May 2024');+ expect(target.querySelectorAll('.cards .ghost')).toHaveLength(6);+ answer({ dates: structuredClone(MONTHS['2024-05']) });+ await settle();+ expect(target.querySelector('.ghost')).toBeNull();+ // each picture shimmers until one of its tiles is in+ const thumb = cards()[0].querySelector('.thumb');+ expect(thumb.classList.contains('ready')).toBe(false);+ thumb.querySelector('img').dispatchEvent(new Event('load'));+ flushSync();+ expect(thumb.classList.contains('ready')).toBe(true);+ });++ it('opens on this month when both sides show their latest pass and none is known', async () => {+ await open({ a: side(''), b: side('') });+ expect(months()).toEqual(['2026-09']);+ expect(target.textContent).toContain('No Sentinel-2 pass over this point that month.');+ expect(button('Next month').disabled).toBe(true);+ });+});diff --git a/frontend/src/tools/compare/PassStrip.svelte b/frontend/src/tools/compare/PassStrip.svelteindex cef722a..f6327e6 100644--- a/frontend/src/tools/compare/PassStrip.svelte+++ b/frontend/src/tools/compare/PassStrip.svelte@@ -288,7 +288,8 @@border-radius: 3px;background: #14171d;}- .thumb img { position: absolute; image-rendering: auto; }+ /* larger than the box and placed by its offset, so the global img rule must not shrink it */+ .thumb img { position: absolute; max-width: none; image-rendering: auto; }.note { color: var(--glass-muted, var(--text-3)); font-size: 10px; }.tags {position: absolute;diff --git a/frontend/src/tools/satellite/AddedLayersOverlay.svelte b/frontend/src/tools/satellite/AddedLayersOverlay.svelteindex aac93a1..e8a6375 100644--- a/frontend/src/tools/satellite/AddedLayersOverlay.svelte+++ b/frontend/src/tools/satellite/AddedLayersOverlay.svelte@@ -4,17 +4,21 @@** Thin on purpose: `lib/map/addedLayer.js` owns the engine side, this owns the* lifecycle — which layers are drawn right now, which have to be torn down,- * and what a click on one of their features opens.+ * and what a click or a right-click on one of their features opens.** That card is **read-only, by construction rather than by restraint**: it is- * built from the strings the source stated and offers no control at all. There- * is no route from a feature into the case, because a feature here is somebody- * else's claim and the case is this analyst's work. How it is laid out lives in- * `lib/map/layerCard.js`; only its lifecycle lives here.+ * built from the strings the source stated, and its one control copies the+ * feature's point. There is no route from a feature into the case, because a+ * feature here is somebody else's claim and the case is this analyst's work.+ * The right-click opens the map's own point menu on the pin's point: a place+ * saved from it is the analyst's, and carries nothing of the feature. How the+ * card is laid out lives in `lib/map/layerCard.js`; only its lifecycle lives+ * here.*/import { createAddedLayer } from '../../lib/map/addedLayer.js';- import { attribution } from '../../lib/map/addedLayers.js';+ import { attribution, UNNAMED } from '../../lib/map/addedLayers.js';import { layerCard } from '../../lib/map/layerCard.js';+ import { fmtCoords, toast } from '../../lib/state.svelte.js';let {engine = null,@@ -23,8 +27,20 @@drawing,/** The search result the panel sent here: `{ name, index, at }`, or null. */picked = null,+ /** `({ lat, lon, x, y, feature?, layer? })`: the map's point menu, opened on+ * a feature. `feature` and `layer` name a pin whose point the menu is on. */+ onmenu = null,} = $props();+ async function copy(text) {+ try {+ await navigator.clipboard.writeText(text);+ toast('Coordinates copied', 'ok', 1600);+ } catch {+ toast('The browser refused the clipboard', 'warn');+ }+ }+/** name → { layer, sha } so a refreshed snapshot redraws and nothing else does. */const live = new Map();@@ -62,8 +78,10 @@}if (existing) drop(row.name);const layer = createAddedLayer(engine, {- card: layerCard(row.title),+ card: layerCard(row.title, { coords: fmtCoords, copy }),iconUrl: iconUrlFor(row),+ menu: (at, properties) =>+ onmenu?.(properties ? { ...at, feature: properties.name || UNNAMED, layer: row.title } : at),});live.set(row.name, { layer, sha: row.sha256 });drawing(caseId, row.name)@@ -116,6 +134,27 @@color: var(--text-3);font-size: 10px;}+ /* The point, read like the Saved card's and pressed to copy: text first,+ the glyph only saying that it can be pressed. */+ :global(.layer-card-where) {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ margin: 4px 0 0;+ padding: 0;+ border: 0;+ background: none;+ color: var(--text-2);+ font-size: var(--fs-xs);+ text-align: left;+ }+ :global(button.layer-card-where) {+ cursor: pointer;+ }+ :global(button.layer-card-where:hover),+ :global(button.layer-card-where:focus-visible) {+ color: var(--text-1);+ }:global(.layer-card-body) {margin: 6px 0 0;max-height: 220px;diff --git a/frontend/src/tools/satellite/MapContextMenu.svelte b/frontend/src/tools/satellite/MapContextMenu.svelteindex 076aedc..152fc81 100644--- a/frontend/src/tools/satellite/MapContextMenu.svelte+++ b/frontend/src/tools/satellite/MapContextMenu.svelte@@ -19,7 +19,9 @@} from '../../lib/map/contextMenu.js';let {- /** `{ lat, lon, x, y }`: the point, and where it was clicked in the map. */+ /** `{ lat, lon, x, y }`: the point, and where it was clicked in the map.+ * Opened on a pin of an added layer, `feature` and `layer` name it: the+ * point is then the pin's own, not the ground under the cursor. */at,/** The map's own size, which the menu must stay inside. */frame = { width: 0, height: 0 },@@ -178,6 +180,14 @@{onkeydown}oncontextmenu={(event) => event.preventDefault()}>+ {#if at.feature}+ <p class="snap" title="The menu acts on this pin's point">+ <span class="snap-name">{at.feature}</span>+ {#if at.layer}<small>{at.layer}</small>{/if}+ </p>+ <div class="rule" role="separator"></div>+ {/if}+{#each copies as row (row.id)}<buttonclass="item copy"@@ -359,6 +369,30 @@overflow: hidden;text-overflow: ellipsis;}+ /* Whose point this is, when it is a pin's: stated above the copies, which+ would otherwise read as the ground under the cursor. */+ .snap {+ display: grid;+ gap: 1px;+ margin: 0;+ padding: 4px 8px 2px;+ font-size: var(--fs-sm);+ color: var(--text-1);+ white-space: normal;+ }+ /* A GeoConfirmed event is named by its first line, which can run long. */+ .snap-name {+ display: -webkit-box;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ overflow-wrap: anywhere;+ }+ .snap small {+ color: var(--text-3);+ font-size: var(--fs-xs);+ }.rule {height: 1px;margin: 4px 6px;diff --git a/frontend/src/tools/satellite/MapContextMenu.test.js b/frontend/src/tools/satellite/MapContextMenu.test.jsindex 4f4a318..45734dd 100644--- a/frontend/src/tools/satellite/MapContextMenu.test.js+++ b/frontend/src/tools/satellite/MapContextMenu.test.js@@ -95,4 +95,23 @@ describe('the right-click menu', () => {expect(body).toContain('DMS');expect(body).toContain('Open in…');});++ it('names the pin it was opened on, whose point the copies are', () => {+ const { body } = render(MapContextMenu, {+ props: props({+ at: { lat: 48.85, lon: 2.35, x: 10, y: 10, feature: 'North gate', layer: 'Checkpoints map' },+ }),+ });+ expect(body).toContain('North gate');+ expect(body).toContain('Checkpoints map');+ expect(body).toContain('48.850000, 2.350000');+ // everything the ground menu offers, on that point+ expect(body).toContain('Save place here…');+ expect(body).toContain('Open in…');+ });++ it('names nothing on the ground', () => {+ const { body } = render(MapContextMenu, { props: props() });+ expect(body).not.toContain('class="snap');+ });});diff --git a/src/azimut/api/compare.py b/src/azimut/api/compare.pyindex 444ff55..eae7407 100644--- a/src/azimut/api/compare.py+++ b/src/azimut/api/compare.py@@ -21,7 +21,8 @@ Finished copies go to the configured export destination and are not case state.They are named by those dates, so two comparisons of one pair would share a name,and none ever overwrites another. An export may also be kept in the case: it is thena media file of its own, stamped with the reading it shows and never replaced-(`engine/comparisons.py`).+(`engine/comparisons.py`). An evolution, the dated pictures of one archive played+in order, is only ever a finished copy.A saved comparison stands on the map as saved work, at its frame's centre or itsview's, and is listed with the captures in the Saved panel.@@ -62,6 +63,15 @@ MAX_GIF_PIXELS = 16_000_000MAX_GIF_EDGE = 1280#: Two PNGs plus multipart framing, enforced before uploads are materialised.MAX_GIF_BODY_BYTES = MAX_FRAME_BYTES * 2 + 1_000_000+#: An evolution: the pictures of one point, one after another. The browser draws+#: each at most `MAX_GIF_EDGE` across plus its header band, so a frame is a few+#: megabytes at most and its pixel count is checked before it is decoded.+MAX_SEQUENCE_FRAMES = 40+MAX_SEQUENCE_FRAME_BYTES = 8_000_000+MAX_SEQUENCE_FRAME_PIXELS = MAX_GIF_EDGE * MAX_GIF_EDGE * 2+MAX_SEQUENCE_BODY_BYTES = MAX_SEQUENCE_FRAMES * MAX_SEQUENCE_FRAME_BYTES + 1_000_000+#: How many intervals the last picture stays up, so the loop reads as an ending.+SEQUENCE_HOLD = 3#: What a saved comparison's media sidecar records as its producer.SOURCE_TYPE = "compare"#: The reading a kept image carries, as JSON. A session holds at most 200@@ -71,6 +81,13 @@ MAX_SPEC_CHARS = 400_000_DAY = r"^(|\d{4}-\d{2}-\d{2})$"#: A picture's date as the browser states it: a day, or a radar pass's UTC instant._PICTURE_DATE = r"^(|\d{4}-\d{2}-\d{2}(T([01]\d|2[0-3]):[0-5]\d:[0-5]\dZ)?)$"+#: The colours a GIF keeps exactly, comma-separated: the marks drawn on the+#: pictures and the export's own inks. Median cut spends a palette on the+#: imagery, so a thin red outline over fields came out a dull brown and a green+#: and a blue mark came out one teal.+GIF_COLOURS = 192+MAX_KEPT_COLOURS = 32+_KEPT_COLOURS = r"^(#[0-9a-fA-F]{6}(,#[0-9a-fA-F]{6}){0,31})?$"class CompareCamera(BaseModel):@@ -544,12 +561,44 @@ def _save_session(return {"name": name, "title": name, "spec_path": rel}, located-def _gif_bytes(a: Image.Image, b: Image.Image, animation: str, interval: int = 700) -> bytes:+def _kept_colours(text: str) -> list[tuple[int, int, int]]:+ """The validated `keep` field as RGB triples, each once, in order."""+ kept: list[tuple[int, int, int]] = []+ for entry in filter(None, text.split(",")):+ rgb = (int(entry[1:3], 16), int(entry[3:5], 16), int(entry[5:7], 16))+ if rgb not in kept:+ kept.append(rgb)+ return kept[:MAX_KEPT_COLOURS]+++def _quantize(frame: Image.Image, kept: list[tuple[int, int, int]]) -> Image.Image:+ """One frame in 192 colours, the kept ones among them exactly.++ The rest of the palette is median cut's answer for the imagery. Mapping onto a+ fixed palette dithers by default, which would speckle the marks' edges and change+ how the imagery has always looked, so it maps to the nearest entry instead.+ """+ if not kept:+ return frame.quantize(colors=GIF_COLOURS, method=Image.Quantize.MEDIANCUT)+ base = frame.quantize(colors=GIF_COLOURS - len(kept), method=Image.Quantize.MEDIANCUT)+ ground = (base.getpalette() or [])[: 3 * (GIF_COLOURS - len(kept))]+ entries = [channel for rgb in kept for channel in rgb] + ground+ # A palette image holds 256 entries; the spare ones repeat the first kept colour.+ entries += list(kept[0]) * ((768 - len(entries)) // 3)+ palette = Image.new("P", (1, 1))+ palette.putpalette(entries)+ return frame.quantize(palette=palette, dither=Image.Dither.NONE)+++def _gif_bytes(+ a: Image.Image,+ b: Image.Image,+ animation: str,+ interval: int = 700,+ kept: list[tuple[int, int, int]] | None = None,+) -> bytes:frames = _gif_frames(a, b, animation)- palette = [- frame.quantize(colors=192, method=Image.Quantize.MEDIANCUT)- for frame in frames- ]+ palette = [_quantize(frame, kept or []) for frame in frames]buf = io.BytesIO()palette[0].save(buf,@@ -582,6 +631,7 @@ async def save_session_preview(image_b: UploadFile | None = File(default=None),format_: Literal["png", "blink"] = Form(alias="format"),interval: int = Form(default=800, ge=200, le=4000),+ keep: str = Form(default="", pattern=_KEPT_COLOURS),imagery_a: str = Form(default="", pattern=_PICTURE_DATE),imagery_b: str = Form(default="", pattern=_PICTURE_DATE),imagery_a_exact: bool = Form(default=True),@@ -606,7 +656,7 @@ async def save_session_preview(if image_b is None:raise HTTPException(status_code=422, detail="a blink preview needs image B")b = await _read_png(image_b, "B")- data = _gif_bytes(a, b, "blink", interval)+ data = _gif_bytes(a, b, "blink", interval, _kept_colours(keep))suffix = ".gif"else:out = io.BytesIO()@@ -677,6 +727,7 @@ async def keep_image(image_b: UploadFile | None = File(default=None),format_: Literal["png", "blink", "slide"] = Form(alias="format"),interval: int = Form(default=800, ge=200, le=4000),+ keep: str = Form(default="", pattern=_KEPT_COLOURS),filename: str = Form(min_length=1, max_length=120),spec: str = Form(min_length=2, max_length=MAX_SPEC_CHARS),imagery_a: str = Form(default="", pattern=_PICTURE_DATE),@@ -710,7 +761,7 @@ async def keep_image(if image_b is None:raise HTTPException(status_code=422, detail="an animated image needs image B")b = await _read_png(image_b, "B")- data, suffix = _gif_bytes(a, b, format_, interval), ".gif"+ data, suffix = _gif_bytes(a, b, format_, interval, _kept_colours(keep)), ".gif"placed = comparisons.placement(reading)source: dict[str, Any] = {@@ -760,9 +811,15 @@ def delete_session(case_id: str, name: str) -> dict[str, Any]:return result-async def _read_png(upload: UploadFile, side: str) -> Image.Image:- raw = await upload.read(MAX_FRAME_BYTES + 1)- if len(raw) > MAX_FRAME_BYTES:+async def _read_png(+ upload: UploadFile,+ side: str,+ *,+ max_bytes: int = MAX_FRAME_BYTES,+ max_pixels: int = MAX_GIF_PIXELS,+) -> Image.Image:+ raw = await upload.read(max_bytes + 1)+ if len(raw) > max_bytes:raise HTTPException(status_code=413, detail=f"comparison frame {side} is too large")try:with warnings.catch_warnings():@@ -770,23 +827,36 @@ async def _read_png(upload: UploadFile, side: str) -> Image.Image:opened = Image.open(io.BytesIO(raw))if opened.format != "PNG":raise ValueError("not a PNG")+ # The header states the size, so an oversized frame is refused+ # before its pixels are decoded.+ if opened.width * opened.height > max_pixels:+ raise _TooManyPixelsframe = opened.convert("RGB")+ except _TooManyPixels as exc:+ raise HTTPException(status_code=413, detail=f"comparison frame {side} has too many pixels") from excexcept (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:raise HTTPException(status_code=413, detail=f"comparison frame {side} is too large") from excexcept Exception as exc:raise HTTPException(status_code=422, detail=f"comparison frame {side} is unreadable") from exc- if frame.width * frame.height > MAX_GIF_PIXELS:- raise HTTPException(status_code=413, detail=f"comparison frame {side} has too many pixels")return frame+class _TooManyPixels(Exception):+ """A frame whose header states more pixels than the route accepts."""+++def _fit_edge(frame: Image.Image, edge: int = MAX_GIF_EDGE) -> Image.Image:+ if max(frame.size) <= edge:+ return frame+ scale = edge / max(frame.size)+ return frame.resize(+ (max(1, round(frame.width * scale)), max(1, round(frame.height * scale))),+ Image.Resampling.LANCZOS,+ )++def _gif_frames(a: Image.Image, b: Image.Image, animation: str) -> list[Image.Image]:- if max(a.size) > MAX_GIF_EDGE:- scale = MAX_GIF_EDGE / max(a.size)- a = a.resize(- (max(1, round(a.width * scale)), max(1, round(a.height * scale))),- Image.Resampling.LANCZOS,- )+ a = _fit_edge(a)if b.size != a.size:b = b.resize(a.size, Image.Resampling.LANCZOS)if animation == "blink":@@ -809,13 +879,14 @@ async def export_gif(image_b: UploadFile,animation: Literal["blink", "slide"] = Form(),interval: int = Form(default=800, ge=200, le=4000),+ keep: str = Form(default="", pattern=_KEPT_COLOURS),filename: str = Form(default="comparison", min_length=1, max_length=120),) -> dict[str, str]:"""Write a bounded animation to the configured export destination."""case = get_case(case_id)a = await _read_png(image_a, "A")b = await _read_png(image_b, "B")- data = _gif_bytes(a, b, animation, interval)+ data = _gif_bytes(a, b, animation, interval, _kept_colours(keep))name = f"{layout.slugify(filename, 'comparison')}-{animation}.gif"try:export_destination = exportdir.destination("views", case.path)@@ -825,6 +896,67 @@ async def export_gif(return {"file": path.name, "path": str(export_destination), "animation": animation}+def _sequence_bytes(frames: list[Image.Image], interval: int) -> bytes:+ """One looping GIF of already-quantized frames, the last held longer."""+ durations = [interval] * (len(frames) - 1) + [interval * SEQUENCE_HOLD]+ buf = io.BytesIO()+ frames[0].save(+ buf,+ "GIF",+ save_all=True,+ append_images=frames[1:],+ duration=durations,+ loop=0,+ optimize=True,+ disposal=2,+ )+ return buf.getvalue()++[email protected]("/cases/{case_id}/compare/sequence")+async def export_sequence(+ case_id: str,+ frames: list[UploadFile] = File(),+ interval: int = Form(default=800, ge=200, le=4000),+ keep: str = Form(default="", pattern=_KEPT_COLOURS),+ filename: str = Form(default="comparison", min_length=1, max_length=120),+) -> dict[str, Any]:+ """Write an evolution, several dated pictures of one point in order, as a GIF.++ Each frame is quantized as soon as it is read, so the pictures wait at one byte+ a pixel rather than three. Every frame takes the first one's size.+ """+ case = get_case(case_id)+ if not 2 <= len(frames) <= MAX_SEQUENCE_FRAMES:+ raise HTTPException(+ status_code=422,+ detail=f"an evolution holds 2 to {MAX_SEQUENCE_FRAMES} pictures",+ )+ kept = _kept_colours(keep)+ shown: list[Image.Image] = []+ size: tuple[int, int] | None = None+ for index, upload in enumerate(frames, start=1):+ frame = await _read_png(+ upload,+ str(index),+ max_bytes=MAX_SEQUENCE_FRAME_BYTES,+ max_pixels=MAX_SEQUENCE_FRAME_PIXELS,+ )+ frame = _fit_edge(frame) if size is None else frame+ if size is not None and frame.size != size:+ frame = frame.resize(size, Image.Resampling.LANCZOS)+ size = frame.size+ shown.append(_quantize(frame, kept))+ data = _sequence_bytes(shown, interval)+ name = f"{layout.slugify(filename, 'comparison')}-evolution.gif"+ try:+ export_destination = exportdir.destination("views", case.path)+ path = exportdir.write_out(data, export_destination, name)+ except (OSError, exportdir.ExportDirError) as exc:+ raise HTTPException(status_code=409, detail=f"could not write the GIF: {exc}") from exc+ return {"file": path.name, "path": str(export_destination), "frames": len(shown)}++class BandFrameIn(BaseModel):"""A Web Mercator box, its pixel size, and the pass to read a band frame from."""diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex 206e44f..98f43d7 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -433,19 +433,27 @@ def wayback_changes(zoom: int = Query(ge=1, le=22),) -> dict[str, Any]:"""The distinct pictures of a point, newest first, each with the release- that first published it and when it was taken.+ that first published it, that release's date, and when it was taken.A few small requests per picture found, so it is asked only when theanalyst asks for the changes, and answered from memory for the same tile- afterwards.+ afterwards. The release dates come from the list the walk has just read."""try:found = wayback.local_changes(lat, lon, zoom)+ listed = wayback.releases()except Exception as exc:raise HTTPException(status_code=502, detail=f"could not read this point's history: {tiles.upstream_failure(exc)}") from exc+ published = {release.number: release.date for release in listed}return {"changes": [- {"release": c.release, "acquired": c.acquired, "source": c.source} for c in found+ {+ "release": c.release,+ "date": published.get(c.release),+ "acquired": c.acquired,+ "source": c.source,+ }+ for c in found],"zoom": min(zoom, wayback.MAX_ZOOM),}diff --git a/src/azimut/server.py b/src/azimut/server.pyindex ca00241..3ab1a37 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -74,6 +74,7 @@ class BulkBodyLimit:("PUT", ("notes", "*"), "notes", "MAX_NOTE_BODY_BYTES"),("POST", ("plates",), "plates", "MAX_PLATE_BODY_BYTES"),("POST", ("compare", "gif"), "compare", "MAX_GIF_BODY_BYTES"),+ ("POST", ("compare", "sequence"), "compare", "MAX_SEQUENCE_BODY_BYTES"),("POST", ("compare", "sessions", "*", "preview"), "compare", "MAX_GIF_BODY_BYTES"),("POST", ("compare", "sessions", "*", "images"), "compare", "MAX_GIF_BODY_BYTES"),("POST", ("proofs",), "proofs", "MAX_PROOF_BODY_BYTES"),diff --git a/tests/test_compare_api.py b/tests/test_compare_api.pyindex 03ffc57..24b9078 100644--- a/tests/test_compare_api.py+++ b/tests/test_compare_api.py@@ -551,6 +551,77 @@ def test_compare_gif_scales_large_frames_before_building_the_animation():assert frames[0].size == (MAX_GIF_EDGE, 150)+# -- evolutions -------------------------------------------------------------------+++def _sequence(client, cid: str, frames: list[bytes], **data):+ return client.post(+ f"/api/cases/{cid}/compare/sequence",+ files=[("frames", (f"{index}.png", frame, "image/png")) for index, frame in enumerate(frames)],+ data={"filename": "Harbour 2024-05-03_2026-09-02", **data},+ )+++def test_an_evolution_is_one_gif_of_every_picture_in_order_with_the_last_held(client):+ cid = _case(client, "Compare evolution")+ colours = [(220, 30, 30), (30, 220, 30), (20, 40, 220), (240, 240, 20)]+ response = _sequence(client, cid, [_png(colour) for colour in colours], interval="600")+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["file"] == "Harbour 2024-05-03_2026-09-02-evolution.gif"+ assert body["frames"] == 4+ with Image.open(Path(body["path"]) / body["file"]) as gif:+ assert gif.n_frames == 4+ durations, firsts = [], []+ for index in range(gif.n_frames):+ gif.seek(index)+ durations.append(gif.info["duration"])+ firsts.append(gif.convert("RGB").getpixel((5, 5)))+ assert durations == [600, 600, 600, 600 * compare_api.SEQUENCE_HOLD]+ for seen, colour in zip(firsts, colours):+ assert all(abs(a - b) < 12 for a, b in zip(seen, colour))+++def test_an_evolution_takes_the_first_pictures_size_and_the_gif_edge(client):+ cid = _case(client, "Compare evolution sizes")+ wide = (MAX_GIF_EDGE * 2, 200)+ response = _sequence(client, cid, [_png((0, 0, 0), wide), _png((255, 255, 255), (40, 40))])+ assert response.status_code == 200, response.text+ with Image.open(Path(response.json()["path"]) / response.json()["file"]) as gif:+ assert gif.size == (MAX_GIF_EDGE, 100)+++def test_an_evolution_is_refused_outside_its_bounds(client, monkeypatch):+ cid = _case(client, "Compare evolution bounds")+ one = _sequence(client, cid, [_png((0, 0, 0))])+ assert one.status_code == 422+ assert "2 to" in one.json()["detail"]+ monkeypatch.setattr(compare_api, "MAX_SEQUENCE_FRAMES", 3)+ assert _sequence(client, cid, [_png((index, 0, 0)) for index in range(4)]).status_code == 422+ unreadable = _sequence(client, cid, [_png((0, 0, 0)), b"not an image"])+ assert unreadable.status_code == 422+ assert unreadable.json()["detail"] == "comparison frame 2 is unreadable"+ assert _sequence(client, cid, [_png((0, 0, 0))] * 2, interval="50").status_code == 422+++def test_an_evolution_frame_is_refused_by_its_header_before_it_is_decoded(client, monkeypatch):+ cid = _case(client, "Compare evolution pixels")+ monkeypatch.setattr(compare_api, "MAX_SEQUENCE_FRAME_PIXELS", 96 * 64 - 1)+ response = _sequence(client, cid, [_png((0, 0, 0)), _png((9, 9, 9))])+ assert response.status_code == 413+ assert response.json()["detail"] == "comparison frame 1 has too many pixels"+ monkeypatch.setattr(compare_api, "MAX_SEQUENCE_FRAME_BYTES", 20)+ assert _sequence(client, cid, [_png((0, 0, 0)), _png((9, 9, 9))]).status_code == 413+++def test_the_body_limit_covers_the_evolution_route(client, monkeypatch):+ cid = _case(client, "Compare evolution body")+ monkeypatch.setattr(compare_api, "MAX_SEQUENCE_BODY_BYTES", 200)+ response = _sequence(client, cid, [_png((0, 0, 0)), _png((9, 9, 9))])+ assert response.status_code == 413+ assert response.json()["detail"] == "request body too large"++# -- Sentinel-2 band frames ------------------------------------------------------@@ -632,3 +703,77 @@ def test_two_comparisons_differing_only_by_case_cannot_both_be_saved(client):assert _save(client, cid, "harbour").status_code == 409_save(client, cid, "Quay")assert _save(client, cid, "harbour", rename_from="Quay").status_code == 409+++# -- mark colours in a GIF -------------------------------------------------------------++MARKS = {"red": (0xEF, 0x44, 0x44), "blue": (0x38, 0xBD, 0xF8), "green": (0x22, 0xC5, 0x5E)}+++def _marked_imagery() -> bytes:+ """Grey-green fields with three thin outlines, the case median cut got wrong."""+ import random++ from PIL import ImageDraw++ rng = random.Random(1)+ image = Image.new("RGB", (800, 500))+ image.putdata([+ (g, g + rng.randint(-10, 20), g - rng.randint(0, 25))+ for g in (rng.randint(60, 140) for _ in range(800 * 500))+ ])+ draw = ImageDraw.Draw(image)+ for index, colour in enumerate(MARKS.values()):+ draw.rectangle((50 + index * 150, 200, 150 + index * 150, 300), outline=colour, width=3)+ out = io.BytesIO()+ image.save(out, "PNG")+ return out.getvalue()+++def _first_frame_marks(path: Path) -> list[tuple[int, int, int]]:+ with Image.open(path) as gif:+ gif.seek(0)+ frame = gif.convert("RGB")+ return [frame.getpixel((51 + index * 150, 250)) for index in range(len(MARKS))]+++def test_a_gif_keeps_the_colours_it_is_asked_to_keep(client):+ cid = _case(client, "Compare GIF colours")+ keep = ",".join("#%02x%02x%02x" % colour for colour in MARKS.values())+ written = {}+ for asked in ("", keep):+ response = client.post(+ f"/api/cases/{cid}/compare/gif",+ files={+ "image_a": ("a.png", _marked_imagery(), "image/png"),+ "image_b": ("b.png", _marked_imagery(), "image/png"),+ },+ data={"animation": "blink", "filename": f"Colours {len(asked)}", "keep": asked},+ )+ assert response.status_code == 200, response.text+ written[asked] = _first_frame_marks(Path(response.json()["path"]) / response.json()["file"])+ assert written[keep] == list(MARKS.values())+ # Without the list, median cut spends the palette on the fields.+ assert written[""] != list(MARKS.values())+++def test_an_evolution_keeps_its_mark_colours_too(client):+ cid = _case(client, "Compare evolution colours")+ keep = ",".join("#%02x%02x%02x" % colour for colour in MARKS.values())+ response = _sequence(client, cid, [_marked_imagery(), _marked_imagery()], keep=keep)+ assert response.status_code == 200, response.text+ assert _first_frame_marks(Path(response.json()["path"]) / response.json()["file"]) == list(MARKS.values())++[email protected]("keep", ["red", "#12345", "#123456,", ",".join(["#123456"] * 33)])+def test_a_colour_list_the_app_never_writes_is_refused(client, keep):+ cid = _case(client, "Compare GIF bad colours")+ response = client.post(+ f"/api/cases/{cid}/compare/gif",+ files={+ "image_a": ("a.png", _png((0, 0, 0)), "image/png"),+ "image_b": ("b.png", _png((9, 9, 9)), "image/png"),+ },+ data={"animation": "blink", "filename": "Bad", "keep": keep},+ )+ assert response.status_code == 422diff --git a/tests/test_wayback.py b/tests/test_wayback.pyindex ee97905..dd84933 100644--- a/tests/test_wayback.py+++ b/tests/test_wayback.py@@ -455,6 +455,10 @@ def test_the_change_route_answers_for_a_point(client, monkeypatch):).json()assert [change["release"] for change in body["changes"]] == [64776, 25982]assert body["changes"][0]["acquired"] and body["changes"][0]["source"] == "Maxar WV03"+ # Each picture carries its release's date, for the rows that have no acquisition date.+ listed = {release.number: release.date for release in wayback.releases()}+ assert [change["date"] for change in body["changes"]] == [listed[64776], listed[25982]]+ assert all(change["date"] for change in body["changes"])assert body["zoom"] == 16